Skip to main content

adk_tool/code_execution/
monty_python_code_tool.rs

1//! `MontyPythonCodeTool` — in-process Python execution via the Monty interpreter.
2//!
3//! This tool wraps the `adk-code` Monty executors (`MontyOneShotExecutor` /
4//! `MontyReplExecutor`) to run Python snippets in-process — no container, no
5//! subprocess, microsecond startup. It supports two modes:
6//!
7//! - **One-shot** (default): each call runs in a fresh interpreter.
8//! - **REPL**: interpreter state (variables, functions, imports) persists
9//!   across calls, scoped per ADK session.
10//!
11//! It complements [`PythonCodeTool`](super::PythonCodeTool), which runs full
12//! CPython in an isolated container — use that when scripts need the real
13//! Python ecosystem (pip packages, C extensions, the complete standard
14//! library). Monty implements a subset of Python, in exchange for in-process
15//! speed, serializable interpreter state, and a no-network/no-subprocess
16//! guarantee that holds by construction.
17//!
18//! When the `code-embedded-python` feature is not enabled, the tool returns a
19//! structured `"rejected"` result explaining how to enable it.
20//!
21//! # Required Scopes
22//!
23//! This tool declares `["code:execute"]` as its required scope. Embedded
24//! Python runs in-process with only the OS access granted at construction, so
25//! no elevated container or host scopes are needed.
26
27use adk_core::{Result, Tool, ToolContext};
28use async_trait::async_trait;
29use serde_json::{Value, json};
30use std::sync::Arc;
31
32/// Default `timeout_secs` when the model omits it.
33const DEFAULT_TIMEOUT_SECS: u64 = 30;
34/// Bounds for the model-supplied `timeout_secs` (values outside are clamped).
35const MIN_TIMEOUT_SECS: u64 = 1;
36const MAX_TIMEOUT_SECS: u64 = 300;
37
38/// The short base contract; the executor's own `prompt_snippet()` is appended
39/// at construction, so the description always reflects the built environment.
40const BASE_DESCRIPTION: &str = "Execute Python code in a sandboxed interpreter.";
41
42/// Embedded Python code execution tool backed by the Monty interpreter.
43///
44/// The LLM-facing description is **composed, not authored**: a short base
45/// contract followed by the executor's own
46/// [`prompt_snippet`](adk_code::CodeExecutor::prompt_snippet), which describes
47/// mode semantics, granted filesystem roots, environment variable names
48/// (never values), clock availability, the no-network/no-subprocess
49/// guarantee, and registered host functions. Because both the description and
50/// the in-interpreter behavior derive from the same configuration, they
51/// cannot drift.
52///
53/// In REPL mode, interpreter sessions are keyed by the full ADK session
54/// identity — app name, user id, and session id — so state never leaks
55/// between users even when session id strings repeat across users. The
56/// session map is bounded by an LRU cap (default 100); an evicted session's
57/// next call transparently starts a fresh interpreter.
58///
59/// For container-backed CPython (pip packages, C extensions, the complete
60/// standard library), use [`PythonCodeTool`](super::PythonCodeTool) instead.
61///
62/// Requires the `code-embedded-python` feature. Without it, the tool returns
63/// a structured `"rejected"` result.
64///
65/// # Required Scopes
66///
67/// Returns `["code:execute"]`. No elevated scopes needed.
68///
69/// # Example
70///
71/// ```rust
72/// use adk_tool::{MontyPythonCodeTool, Tool};
73///
74/// let tool = MontyPythonCodeTool::new();
75/// assert_eq!(tool.name(), "monty_python_code");
76/// assert_eq!(tool.required_scopes(), &["code:execute"]);
77/// ```
78pub struct MontyPythonCodeTool {
79    repl: bool,
80    description: String,
81    #[cfg(feature = "code-embedded-python")]
82    inner: enabled::Inner,
83}
84
85impl MontyPythonCodeTool {
86    /// Create a one-shot tool with a fully sandboxed interpreter: no
87    /// filesystem, no environment variables, no clock, no host functions.
88    pub fn new() -> Self {
89        Self::sandboxed(false)
90    }
91
92    /// Create a REPL-mode tool with a fully sandboxed interpreter. Variables,
93    /// functions, and imports persist across calls within an ADK session.
94    pub fn repl() -> Self {
95        Self::sandboxed(true)
96    }
97
98    #[cfg(feature = "code-embedded-python")]
99    fn sandboxed(repl: bool) -> Self {
100        // A fully sandboxed builder has no host functions, so registry
101        // validation cannot fail.
102        let builder = MontyPythonCodeToolBuilder::new();
103        let built = if repl { builder.build_repl() } else { builder.build_one_shot() };
104        built.expect("an empty host-function registry always validates")
105    }
106
107    #[cfg(not(feature = "code-embedded-python"))]
108    fn sandboxed(repl: bool) -> Self {
109        Self { repl, description: BASE_DESCRIPTION.to_string() }
110    }
111
112    /// Start configuring a tool with OS-access grants, host functions, and
113    /// limits (forwarded to
114    /// [`MontyExecutorBuilder`](adk_code::MontyExecutorBuilder)).
115    ///
116    /// # Example
117    ///
118    /// ```rust,ignore
119    /// use adk_code::PathAccess;
120    /// use adk_tool::MontyPythonCodeTool;
121    ///
122    /// let tool = MontyPythonCodeTool::builder()
123    ///     .allow_path("/data", "/srv/agent/data", PathAccess::ReadOnly)
124    ///     .environ_var("PROJECT", "acme")
125    ///     .system_clock()
126    ///     .build_repl()?;
127    /// ```
128    #[cfg(feature = "code-embedded-python")]
129    pub fn builder() -> MontyPythonCodeToolBuilder {
130        MontyPythonCodeToolBuilder::new()
131    }
132}
133
134impl Default for MontyPythonCodeTool {
135    fn default() -> Self {
136        Self::new()
137    }
138}
139
140#[async_trait]
141impl Tool for MontyPythonCodeTool {
142    fn name(&self) -> &str {
143        "monty_python_code"
144    }
145
146    fn description(&self) -> &str {
147        &self.description
148    }
149
150    fn required_scopes(&self) -> &[&str] {
151        &["code:execute"]
152    }
153
154    /// The schema is built from configuration: `reset` exists only in REPL
155    /// mode, where it discards the persistent session before executing.
156    fn parameters_schema(&self) -> Option<Value> {
157        let mut properties = json!({
158            "code": {
159                "type": "string",
160                "description": "Python source to execute."
161            },
162            "input": {
163                "description": "Optional JSON value bound to the `input` variable."
164            },
165            "timeout_secs": {
166                "type": "integer",
167                "default": DEFAULT_TIMEOUT_SECS,
168                "minimum": MIN_TIMEOUT_SECS,
169                "maximum": MAX_TIMEOUT_SECS,
170                "description": "Time budget in seconds (default 30; values outside 1-300 \
171                                are clamped)."
172            }
173        });
174        if self.repl {
175            properties["reset"] = json!({
176                "type": "boolean",
177                "default": false,
178                "description": "REPL mode only: discard the persistent session before executing."
179            });
180        }
181        Some(json!({
182            "type": "object",
183            "properties": properties,
184            "required": ["code"]
185        }))
186    }
187
188    /// The response envelope is fixed across both modes (and the feature-off
189    /// fallback), so the schema is declared for the model. Script-level
190    /// failures are data in this envelope, never a `ToolError`.
191    fn response_schema(&self) -> Option<Value> {
192        Some(json!({
193            "type": "object",
194            "properties": {
195                "status": {
196                    "type": "string",
197                    "enum": ["success", "failed", "timeout", "rejected"],
198                    "description": "'success': the script completed. 'failed': a Python \
199                                    exception propagated (traceback in stderr). 'timeout': \
200                                    the time budget was exceeded. 'rejected': bad arguments \
201                                    or the feature is disabled."
202                },
203                "stdout": {
204                    "type": "string",
205                    "description": "Captured print() output."
206                },
207                "stderr": {
208                    "type": "string",
209                    "description": "Python traceback or rejection reason; empty on success."
210                },
211                "output": {
212                    "description": "JSON value of the script's final expression; null unless \
213                                    status is 'success'."
214                },
215                "stdoutTruncated": {
216                    "type": "boolean",
217                    "description": "True when stdout was cut at the policy limit."
218                },
219                "stderrTruncated": {
220                    "type": "boolean",
221                    "description": "True when stderr was cut at the policy limit."
222                },
223                "durationMs": {
224                    "type": "integer",
225                    "description": "Wall-clock execution time in milliseconds."
226                }
227            },
228            "required": ["status", "stdout", "stderr", "output", "stdoutTruncated",
229                         "stderrTruncated", "durationMs"]
230        }))
231    }
232
233    fn is_read_only(&self) -> bool {
234        // Scripts can write to granted mounts; host functions may have side
235        // effects.
236        false
237    }
238
239    fn is_concurrency_safe(&self) -> bool {
240        // REPL snippet ordering within a session is meaningful; the
241        // per-executor Mutex guarantees serialization, but parallel dispatch
242        // would make ordering nondeterministic.
243        !self.repl
244    }
245
246    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
247        let Some(code) = args.get("code").and_then(Value::as_str) else {
248            return Ok(rejected("missing required field: code"));
249        };
250        let input = args.get("input").cloned();
251        let timeout_secs = args
252            .get("timeout_secs")
253            .and_then(Value::as_u64)
254            .unwrap_or(DEFAULT_TIMEOUT_SECS)
255            .clamp(MIN_TIMEOUT_SECS, MAX_TIMEOUT_SECS);
256        let reset = args.get("reset").and_then(Value::as_bool).unwrap_or(false);
257
258        self.execute_python(ctx, code, input, timeout_secs, reset).await
259    }
260}
261
262/// A structured rejection envelope (bad arguments or feature disabled).
263/// Never a `ToolError` — errors are information the model can react to.
264fn rejected(message: &str) -> Value {
265    json!({
266        "status": "rejected",
267        "stdout": "",
268        "stderr": message,
269        "output": null,
270        "stdoutTruncated": false,
271        "stderrTruncated": false,
272        "durationMs": 0,
273    })
274}
275
276#[cfg(feature = "code-embedded-python")]
277pub use enabled::MontyPythonCodeToolBuilder;
278
279#[cfg(feature = "code-embedded-python")]
280mod enabled {
281    use super::*;
282    use adk_code::{
283        CodeExecutor, ExecutionError, ExecutionLanguage, ExecutionPayload, ExecutionRequest,
284        ExecutionResult, HostFunction, HostFunctionError, MontyBuildError, MontyExecutorBuilder,
285        MontyOneShotExecutor, MontyReplExecutor, PathAccess,
286    };
287    use serde_json::Map;
288    use std::collections::HashMap;
289    use std::future::Future;
290    use std::path::PathBuf;
291    use std::time::Duration;
292    use tokio::sync::RwLock;
293    use tracing::debug;
294
295    /// Default cap on concurrently retained REPL sessions.
296    const DEFAULT_MAX_SESSIONS: usize = 100;
297
298    /// The full ADK session identity. Session id strings are only unique per
299    /// user, so REPL interpreter state is keyed by the whole triple — two
300    /// users with the same session id never share an interpreter.
301    #[derive(Clone, PartialEq, Eq, Hash)]
302    pub(super) struct SessionKey {
303        app: String,
304        user: String,
305        session: String,
306    }
307
308    impl SessionKey {
309        pub(super) fn new(ctx: &dyn ToolContext) -> Self {
310            Self {
311                app: ctx.app_name().to_string(),
312                user: ctx.user_id().to_string(),
313                session: ctx.session_id().to_string(),
314            }
315        }
316    }
317
318    /// The live (feature-enabled) tool internals.
319    pub(super) struct Inner {
320        /// Grants, registry, limits — cheaply cloneable; mints per-session
321        /// REPL executors.
322        builder: MontyExecutorBuilder,
323        /// A policy requesting exactly the tool's grants; the model controls
324        /// only the code, the input, and the time budget.
325        granted: adk_code::SandboxPolicy,
326        /// One-shot mode: a single shared stateless executor.
327        oneshot: Option<Arc<MontyOneShotExecutor>>,
328        /// REPL mode: one interpreter session per ADK session identity,
329        /// LRU-bounded.
330        sessions: RwLock<LruSessions>,
331    }
332
333    /// A small LRU map: session identity → REPL executor, evicting the least
334    /// recently used entry once `capacity` is reached. O(n) eviction is fine
335    /// at the default capacity of 100.
336    pub(super) struct LruSessions {
337        capacity: usize,
338        clock: u64,
339        entries: HashMap<SessionKey, (Arc<MontyReplExecutor>, u64)>,
340    }
341
342    impl LruSessions {
343        fn new(capacity: usize) -> Self {
344            Self { capacity: capacity.max(1), clock: 0, entries: HashMap::new() }
345        }
346
347        fn get(&mut self, key: &SessionKey) -> Option<Arc<MontyReplExecutor>> {
348            self.clock += 1;
349            let clock = self.clock;
350            self.entries.get_mut(key).map(|(executor, used)| {
351                *used = clock;
352                executor.clone()
353            })
354        }
355
356        fn insert(&mut self, key: SessionKey, executor: Arc<MontyReplExecutor>) {
357            self.clock += 1;
358            if !self.entries.contains_key(&key) && self.entries.len() >= self.capacity {
359                // Evict the least recently used entry; its session's next
360                // call transparently starts a fresh interpreter.
361                if let Some(evict) = self
362                    .entries
363                    .iter()
364                    .min_by_key(|(_, (_, used))| *used)
365                    .map(|(key, _)| key.clone())
366                {
367                    debug!(
368                        session.app = %evict.app,
369                        session.user = %evict.user,
370                        session.id = %evict.session,
371                        "evicting lru repl session"
372                    );
373                    self.entries.remove(&evict);
374                }
375            }
376            self.entries.insert(key, (executor, self.clock));
377        }
378
379        fn remove(&mut self, key: &SessionKey) {
380            self.entries.remove(key);
381        }
382
383        #[cfg(test)]
384        fn contains(&self, key: &SessionKey) -> bool {
385            self.entries.contains_key(key)
386        }
387    }
388
389    /// Configures a [`MontyPythonCodeTool`]: OS-access grants, host
390    /// functions, and limits are forwarded to [`MontyExecutorBuilder`]; the
391    /// terminal methods select the mode.
392    ///
393    /// # Example
394    ///
395    /// ```rust
396    /// use adk_code::PathAccess;
397    /// use adk_tool::{MontyPythonCodeTool, Tool};
398    ///
399    /// # fn main() -> Result<(), adk_code::MontyBuildError> {
400    /// let tool = MontyPythonCodeTool::builder()
401    ///     .environ_var("PROJECT", "acme")
402    ///     .system_clock()
403    ///     .build_repl()?;
404    /// assert!(tool.description().contains("PROJECT"));
405    /// # Ok(())
406    /// # }
407    /// ```
408    pub struct MontyPythonCodeToolBuilder {
409        builder: MontyExecutorBuilder,
410        max_sessions: usize,
411    }
412
413    impl Default for MontyPythonCodeToolBuilder {
414        fn default() -> Self {
415            Self::new()
416        }
417    }
418
419    impl MontyPythonCodeToolBuilder {
420        /// Start with the fully sandboxed defaults.
421        #[must_use]
422        pub fn new() -> Self {
423            Self {
424                builder: MontyExecutorBuilder::new().script_name("agent_snippet"),
425                max_sessions: DEFAULT_MAX_SESSIONS,
426            }
427        }
428
429        /// Make a host directory available to scripts at `virtual_path`.
430        /// See [`MontyExecutorBuilder::allow_path`].
431        #[must_use]
432        pub fn allow_path(
433            mut self,
434            virtual_path: impl Into<String>,
435            host_path: impl Into<PathBuf>,
436            access: PathAccess,
437        ) -> Self {
438            self.builder = self.builder.allow_path(virtual_path, host_path, access);
439            self
440        }
441
442        /// Replace the environment map exposed via `os.getenv` / `os.environ`.
443        /// See [`MontyExecutorBuilder::environ`].
444        #[must_use]
445        pub fn environ<K, V>(mut self, vars: impl IntoIterator<Item = (K, V)>) -> Self
446        where
447            K: Into<String>,
448            V: Into<String>,
449        {
450            self.builder = self.builder.environ(vars);
451            self
452        }
453
454        /// Add or overwrite a single environment variable.
455        /// See [`MontyExecutorBuilder::environ_var`].
456        #[must_use]
457        pub fn environ_var(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
458            self.builder = self.builder.environ_var(key, value);
459            self
460        }
461
462        /// Grant host-clock access (`date.today()` / `datetime.now()`).
463        /// See [`MontyExecutorBuilder::system_clock`].
464        #[must_use]
465        pub fn system_clock(mut self) -> Self {
466            self.builder = self.builder.system_clock();
467            self
468        }
469
470        /// Register a host function callable from Python by bare name.
471        /// See [`MontyExecutorBuilder::function`].
472        #[must_use]
473        pub fn function(mut self, function: Arc<dyn HostFunction>) -> Self {
474            self.builder = self.builder.function(function);
475            self
476        }
477
478        /// Register a closure as a host function.
479        /// See [`MontyExecutorBuilder::function_fn`].
480        #[must_use]
481        pub fn function_fn<F, Fut>(
482            mut self,
483            name: impl Into<String>,
484            description: impl Into<String>,
485            func: F,
486        ) -> Self
487        where
488            F: Fn(Vec<Value>, Map<String, Value>) -> Fut + Send + Sync + 'static,
489            Fut: Future<Output = std::result::Result<Value, HostFunctionError>> + Send + 'static,
490        {
491            self.builder = self.builder.function_fn(name, description, func);
492            self
493        }
494
495        /// Cap the interpreter's memory use in bytes.
496        /// See [`MontyExecutorBuilder::max_memory`].
497        #[must_use]
498        pub fn max_memory(mut self, bytes: usize) -> Self {
499            self.builder = self.builder.max_memory(bytes);
500            self
501        }
502
503        /// Wall-clock bound for a single host-function call.
504        /// See [`MontyExecutorBuilder::host_function_timeout`].
505        #[must_use]
506        pub fn host_function_timeout(mut self, timeout: Duration) -> Self {
507            self.builder = self.builder.host_function_timeout(timeout);
508            self
509        }
510
511        /// Cap on concurrently retained REPL sessions (default 100). The
512        /// least recently used session is evicted at the cap; its next call
513        /// starts a fresh interpreter. A value of 0 is treated as 1.
514        #[must_use]
515        pub fn max_sessions(mut self, max_sessions: usize) -> Self {
516            self.max_sessions = max_sessions;
517            self
518        }
519
520        /// Build a one-shot tool: each call runs in a fresh interpreter.
521        ///
522        /// # Errors
523        ///
524        /// Returns a [`MontyBuildError`] when the host-function registry is
525        /// invalid.
526        pub fn build_one_shot(self) -> std::result::Result<MontyPythonCodeTool, MontyBuildError> {
527            let executor = Arc::new(self.builder.clone().build_one_shot()?);
528            Ok(MontyPythonCodeTool {
529                repl: false,
530                description: compose_description(executor.prompt_snippet()),
531                inner: Inner {
532                    builder: self.builder,
533                    granted: executor.granted_policy(),
534                    oneshot: Some(executor),
535                    sessions: RwLock::new(LruSessions::new(self.max_sessions)),
536                },
537            })
538        }
539
540        /// Build a REPL tool: interpreter state persists across calls, scoped
541        /// per ADK session.
542        ///
543        /// # Errors
544        ///
545        /// Returns a [`MontyBuildError`] when the host-function registry is
546        /// invalid.
547        pub fn build_repl(self) -> std::result::Result<MontyPythonCodeTool, MontyBuildError> {
548            // A probe executor renders the snippet; all sessions share the
549            // same grants and registry, so the description is identical
550            // across sessions and stays valid.
551            let probe = self.builder.clone().build_repl()?;
552            Ok(MontyPythonCodeTool {
553                repl: true,
554                description: compose_description(probe.prompt_snippet()),
555                inner: Inner {
556                    builder: self.builder,
557                    granted: probe.granted_policy(),
558                    oneshot: None,
559                    sessions: RwLock::new(LruSessions::new(self.max_sessions)),
560                },
561            })
562        }
563    }
564
565    fn compose_description(snippet: Option<String>) -> String {
566        match snippet {
567            Some(snippet) => format!("{BASE_DESCRIPTION}\n\n{snippet}"),
568            None => BASE_DESCRIPTION.to_string(),
569        }
570    }
571
572    impl MontyPythonCodeTool {
573        /// The live execution path: dispatch to the shared one-shot executor,
574        /// or to the calling session's REPL executor.
575        pub(super) async fn execute_python(
576            &self,
577            ctx: Arc<dyn ToolContext>,
578            code: &str,
579            input: Option<Value>,
580            timeout_secs: u64,
581            reset: bool,
582        ) -> Result<Value> {
583            let executor: Arc<dyn CodeExecutor> = if let Some(oneshot) = &self.inner.oneshot {
584                oneshot.clone()
585            } else {
586                match self.repl_executor(SessionKey::new(ctx.as_ref()), reset).await {
587                    Ok(executor) => executor,
588                    Err(err) => return Ok(render_error(err)),
589                }
590            };
591
592            // Request exactly the tool's grants; the model controls only the
593            // code, the input, and the time budget.
594            let mut sandbox = self.inner.granted.clone();
595            sandbox.timeout = Duration::from_secs(timeout_secs);
596
597            let request = ExecutionRequest {
598                language: ExecutionLanguage::Python,
599                payload: ExecutionPayload::Source { code: code.to_string() },
600                argv: vec![],
601                stdin: None,
602                input,
603                sandbox,
604                identity: None,
605            };
606
607            match executor.execute(request).await {
608                Ok(result) => Ok(render_result(result)),
609                Err(err) => Ok(render_error(err)),
610            }
611        }
612
613        /// Get (or lazily create) the REPL executor for `key`; `reset`
614        /// discards any existing session first. A build failure is an
615        /// [`ExecutionError`] so the caller renders it as envelope data,
616        /// never a `ToolError`.
617        async fn repl_executor(
618            &self,
619            key: SessionKey,
620            reset: bool,
621        ) -> std::result::Result<Arc<MontyReplExecutor>, ExecutionError> {
622            let mut sessions = self.inner.sessions.write().await;
623            if reset {
624                sessions.remove(&key);
625            }
626            if let Some(executor) = sessions.get(&key) {
627                return Ok(executor);
628            }
629            let executor = Arc::new(self.inner.builder.clone().build_repl().map_err(|err| {
630                ExecutionError::InternalError(format!("failed to build repl session: {err}"))
631            })?);
632            debug!(
633                session.app = %key.app,
634                session.user = %key.user,
635                session.id = %key.session,
636                "created repl session"
637            );
638            sessions.insert(key, executor.clone());
639            Ok(executor)
640        }
641
642        /// Whether a REPL session currently exists for the calling context's
643        /// session identity (test support).
644        #[cfg(test)]
645        pub(super) async fn has_session(&self, ctx: &dyn ToolContext) -> bool {
646            self.inner.sessions.read().await.contains(&SessionKey::new(ctx))
647        }
648    }
649
650    // Execution is in-process — no process is spawned, so the envelope has no
651    // `exitCode` (unlike the container-backed code tools). `status` is the
652    // success/failure signal.
653    fn render_result(result: ExecutionResult) -> Value {
654        json!({
655            "status": result.status,
656            "stdout": result.stdout,
657            "stderr": result.stderr,
658            "output": result.output,
659            "stdoutTruncated": result.stdout_truncated,
660            "stderrTruncated": result.stderr_truncated,
661            "durationMs": result.duration_ms,
662        })
663    }
664
665    /// Executor-level errors (policy, internal) are information for the
666    /// model, never a `ToolError`.
667    fn render_error(err: ExecutionError) -> Value {
668        let status = match err {
669            ExecutionError::InvalidRequest(_)
670            | ExecutionError::UnsupportedPolicy(_)
671            | ExecutionError::Rejected(_) => "rejected",
672            ExecutionError::Timeout(_) => "timeout",
673            ExecutionError::UnsupportedLanguage(_)
674            | ExecutionError::CompileFailed(_)
675            | ExecutionError::ExecutionFailed(_)
676            | ExecutionError::InternalError(_) => "failed",
677        };
678        json!({
679            "status": status,
680            "stdout": "",
681            "stderr": err.to_string(),
682            "output": null,
683            "stdoutTruncated": false,
684            "stderrTruncated": false,
685            "durationMs": 0,
686        })
687    }
688}
689
690/// Fallback when the `code-embedded-python` feature is not enabled.
691#[cfg(not(feature = "code-embedded-python"))]
692impl MontyPythonCodeTool {
693    pub(super) async fn execute_python(
694        &self,
695        _ctx: Arc<dyn ToolContext>,
696        _code: &str,
697        _input: Option<Value>,
698        _timeout_secs: u64,
699        _reset: bool,
700    ) -> Result<Value> {
701        Ok(rejected(
702            "Python execution requires the 'code-embedded-python' feature. \
703             Enable it with: adk-tool = { features = [\"code-embedded-python\"] }",
704        ))
705    }
706}
707
708#[cfg(all(test, feature = "code-embedded-python"))]
709mod tests {
710    use super::*;
711    use adk_core::{CallbackContext, Content, EventActions, ReadonlyContext};
712    use std::sync::Mutex;
713
714    struct MockToolContext {
715        user: String,
716        session: String,
717        actions: Mutex<EventActions>,
718        content: Content,
719    }
720
721    impl MockToolContext {
722        fn new(session: &str) -> Arc<Self> {
723            Self::for_user("user-1", session)
724        }
725
726        fn for_user(user: &str, session: &str) -> Arc<Self> {
727            Arc::new(Self {
728                user: user.to_string(),
729                session: session.to_string(),
730                actions: Mutex::new(EventActions::default()),
731                content: Content::new("user"),
732            })
733        }
734    }
735
736    #[async_trait]
737    impl ReadonlyContext for MockToolContext {
738        fn invocation_id(&self) -> &str {
739            "inv-test"
740        }
741        fn agent_name(&self) -> &str {
742            "test-agent"
743        }
744        fn user_id(&self) -> &str {
745            &self.user
746        }
747        fn app_name(&self) -> &str {
748            "test-app"
749        }
750        fn session_id(&self) -> &str {
751            &self.session
752        }
753        fn branch(&self) -> &str {
754            ""
755        }
756        fn user_content(&self) -> &Content {
757            &self.content
758        }
759    }
760
761    #[async_trait]
762    impl CallbackContext for MockToolContext {
763        fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
764            None
765        }
766    }
767
768    #[async_trait]
769    impl ToolContext for MockToolContext {
770        fn function_call_id(&self) -> &str {
771            "call-test"
772        }
773        fn actions(&self) -> EventActions {
774            self.actions.lock().unwrap().clone()
775        }
776        fn set_actions(&self, actions: EventActions) {
777            *self.actions.lock().unwrap() = actions;
778        }
779        async fn search_memory(&self, _query: &str) -> Result<Vec<adk_core::MemoryEntry>> {
780            Ok(vec![])
781        }
782    }
783
784    #[test]
785    fn schema_includes_reset_only_in_repl_mode() {
786        let one_shot = MontyPythonCodeTool::new();
787        let schema = one_shot.parameters_schema().unwrap();
788        assert!(schema["properties"]["code"].is_object());
789        assert!(schema["properties"]["timeout_secs"].is_object());
790        assert!(schema["properties"].get("reset").is_none());
791        assert_eq!(schema["required"], json!(["code"]));
792
793        let repl = MontyPythonCodeTool::repl();
794        let schema = repl.parameters_schema().unwrap();
795        assert!(schema["properties"]["reset"].is_object());
796    }
797
798    #[test]
799    fn description_is_base_contract_plus_prompt_snippet() {
800        let tool = MontyPythonCodeTool::builder()
801            .environ_var("PROJECT", "secret-value")
802            .function_fn("noop", "Do nothing.", |_args, _kwargs| async move { Ok(json!(null)) })
803            .build_repl()
804            .unwrap();
805        let description = tool.description();
806        assert!(description.starts_with(BASE_DESCRIPTION));
807        assert!(description.contains("## Python execution environment"));
808        assert!(description.contains("persistent REPL session"));
809        assert!(description.contains("PROJECT"));
810        assert!(!description.contains("secret-value"));
811        assert!(description.contains("def noop(...):"));
812    }
813
814    #[tokio::test]
815    async fn response_schema_matches_the_actual_envelope() {
816        let tool = MontyPythonCodeTool::new();
817        let schema = tool.response_schema().expect("the envelope is fixed, so it is declared");
818
819        // Every declared property is required, and the live envelope carries
820        // exactly those keys — in success, failure, and rejection shapes.
821        let mut declared: Vec<&str> =
822            schema["properties"].as_object().unwrap().keys().map(String::as_str).collect();
823        let mut required: Vec<&str> =
824            schema["required"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
825        declared.sort_unstable();
826        required.sort_unstable();
827        assert_eq!(declared, required);
828
829        for args in [json!({"code": "21 * 2"}), json!({"code": "1 / 0"}), json!({})] {
830            let result = tool.execute(MockToolContext::new("s1"), args).await.unwrap();
831            let mut actual: Vec<&str> =
832                result.as_object().unwrap().keys().map(String::as_str).collect();
833            actual.sort_unstable();
834            assert_eq!(actual, declared);
835
836            let status = result["status"].as_str().unwrap();
837            let allowed: Vec<&str> = schema["properties"]["status"]["enum"]
838                .as_array()
839                .unwrap()
840                .iter()
841                .filter_map(Value::as_str)
842                .collect();
843            assert!(allowed.contains(&status), "undeclared status: {status}");
844        }
845    }
846
847    #[test]
848    fn declaration_includes_parameters_and_response() {
849        let tool = MontyPythonCodeTool::new();
850        let declaration = tool.declaration();
851        assert_eq!(declaration["name"], "monty_python_code");
852        assert!(declaration["parameters"].is_object());
853        assert!(declaration["response"].is_object());
854    }
855
856    #[test]
857    fn concurrency_metadata_tracks_the_mode() {
858        assert!(MontyPythonCodeTool::new().is_concurrency_safe());
859        assert!(!MontyPythonCodeTool::repl().is_concurrency_safe());
860        assert!(!MontyPythonCodeTool::new().is_read_only());
861    }
862
863    #[tokio::test]
864    async fn missing_code_is_rejected() {
865        let tool = MontyPythonCodeTool::new();
866        let result = tool.execute(MockToolContext::new("s1"), json!({})).await.unwrap();
867        assert_eq!(result["status"], "rejected");
868        assert!(result["stderr"].as_str().unwrap().contains("code"));
869    }
870
871    #[tokio::test]
872    async fn one_shot_executes_and_reports_camel_case_envelope() {
873        let tool = MontyPythonCodeTool::new();
874        let result =
875            tool.execute(MockToolContext::new("s1"), json!({"code": "21 * 2"})).await.unwrap();
876        assert_eq!(result["status"], "success");
877        assert_eq!(result["output"], json!(42));
878        assert!(result.get("exitCode").is_none());
879        assert!(result.get("durationMs").is_some());
880        assert_eq!(result["stdoutTruncated"], json!(false));
881        assert_eq!(result["stderrTruncated"], json!(false));
882    }
883
884    #[tokio::test]
885    async fn python_exception_reports_failed_with_traceback() {
886        let tool = MontyPythonCodeTool::new();
887        let result =
888            tool.execute(MockToolContext::new("s1"), json!({"code": "1 / 0"})).await.unwrap();
889        assert_eq!(result["status"], "failed");
890        assert!(result["stderr"].as_str().unwrap().contains("ZeroDivisionError"));
891    }
892
893    #[tokio::test]
894    async fn repl_sessions_are_isolated_per_session_id() {
895        let tool = MontyPythonCodeTool::repl();
896
897        tool.execute(MockToolContext::new("alice"), json!({"code": "x = 1"})).await.unwrap();
898
899        // Bob's session has no `x`.
900        let bob = tool.execute(MockToolContext::new("bob"), json!({"code": "x"})).await.unwrap();
901        assert_eq!(bob["status"], "failed");
902        assert!(bob["stderr"].as_str().unwrap().contains("NameError"));
903
904        // Alice's session still does.
905        let alice =
906            tool.execute(MockToolContext::new("alice"), json!({"code": "x + 1"})).await.unwrap();
907        assert_eq!(alice["output"], json!(2));
908    }
909
910    #[tokio::test]
911    async fn same_session_id_for_different_users_gets_isolated_interpreters() {
912        let tool = MontyPythonCodeTool::repl();
913
914        // Two users independently chose the session id "s1".
915        let alice = MockToolContext::for_user("alice", "s1");
916        let bob = MockToolContext::for_user("bob", "s1");
917
918        tool.execute(alice.clone(), json!({"code": "x = 1"})).await.unwrap();
919
920        // Bob's interpreter has no `x` — the key is the full session identity.
921        let result = tool.execute(bob.clone(), json!({"code": "x"})).await.unwrap();
922        assert_eq!(result["status"], "failed");
923        assert!(result["stderr"].as_str().unwrap().contains("NameError"));
924        assert!(tool.has_session(alice.as_ref()).await);
925        assert!(tool.has_session(bob.as_ref()).await);
926    }
927
928    #[tokio::test]
929    async fn reset_true_clears_the_session_state() {
930        let tool = MontyPythonCodeTool::repl();
931        let ctx = MockToolContext::new("s1");
932
933        tool.execute(ctx.clone(), json!({"code": "x = 1"})).await.unwrap();
934        let result = tool.execute(ctx, json!({"code": "x", "reset": true})).await.unwrap();
935        assert_eq!(result["status"], "failed");
936        assert!(result["stderr"].as_str().unwrap().contains("NameError"));
937    }
938
939    #[tokio::test]
940    async fn lru_evicts_the_least_recently_used_session() {
941        let tool = MontyPythonCodeTool::builder().max_sessions(2).build_repl().unwrap();
942
943        tool.execute(MockToolContext::new("a"), json!({"code": "x = 1"})).await.unwrap();
944        tool.execute(MockToolContext::new("b"), json!({"code": "x = 2"})).await.unwrap();
945        // Touch `a` so `b` becomes the LRU entry.
946        tool.execute(MockToolContext::new("a"), json!({"code": "x"})).await.unwrap();
947        // A third session evicts `b`.
948        tool.execute(MockToolContext::new("c"), json!({"code": "x = 3"})).await.unwrap();
949
950        assert!(tool.has_session(MockToolContext::new("a").as_ref()).await);
951        assert!(!tool.has_session(MockToolContext::new("b").as_ref()).await);
952        assert!(tool.has_session(MockToolContext::new("c").as_ref()).await);
953
954        // The evicted session's next call transparently starts fresh.
955        let result = tool.execute(MockToolContext::new("b"), json!({"code": "x"})).await.unwrap();
956        assert_eq!(result["status"], "failed");
957    }
958
959    #[tokio::test]
960    async fn granted_input_and_host_function_flow_through_the_tool() {
961        let tool = MontyPythonCodeTool::builder()
962            .environ_var("PROJECT", "acme")
963            .function_fn("double", "Double a number.", |args, _kwargs| async move {
964                let n = args.first().and_then(Value::as_i64).unwrap_or(0);
965                Ok(json!(n * 2))
966            })
967            .build_one_shot()
968            .unwrap();
969
970        let result = tool
971            .execute(
972                MockToolContext::new("s1"),
973                json!({
974                    "code": "import os\n[double(input['n']), os.getenv('PROJECT')]",
975                    "input": {"n": 21}
976                }),
977            )
978            .await
979            .unwrap();
980        assert_eq!(result["status"], "success");
981        assert_eq!(result["output"], json!([42, "acme"]));
982    }
983}