Skip to main content

adk_tool/code_execution/
python_code_tool.rs

1//! `PythonCodeTool` — container-backed Python execution preset.
2//!
3//! This tool wraps the `adk-code` execution substrate with defaults
4//! appropriate for isolated Python execution. It supports two backends:
5//!
6//! - [`DockerExecutor`] (persistent container, recommended) — requires `docker` feature
7//! - [`ContainerCommandExecutor`] (ephemeral, CLI-based fallback)
8//!
9//! # Required Scopes
10//!
11//! This tool declares `["code:execute", "code:execute:container"]` as
12//! required scopes. Container-backed execution is an elevated mode.
13
14use adk_code::{
15    CodeExecutor, ContainerCommandExecutor, ContainerConfig, ExecutionLanguage, ExecutionPayload,
16    ExecutionRequest, SandboxPolicy,
17};
18use adk_core::{Result, Tool, ToolContext};
19use async_trait::async_trait;
20use serde_json::{Value, json};
21use std::sync::Arc;
22
23/// Container-backed Python code execution tool.
24///
25/// # Required Scopes
26///
27/// Returns `["code:execute", "code:execute:container"]`.
28///
29/// # Example
30///
31/// ```rust
32/// use adk_tool::{PythonCodeTool, Tool};
33///
34/// let tool = PythonCodeTool::new();
35/// assert_eq!(tool.name(), "python_code");
36/// assert_eq!(tool.required_scopes(), &["code:execute", "code:execute:container"]);
37/// ```
38pub struct PythonCodeTool {
39    executor: Arc<dyn CodeExecutor>,
40}
41
42impl PythonCodeTool {
43    /// Create a new `PythonCodeTool` with the CLI-based container executor.
44    pub fn new() -> Self {
45        Self {
46            executor: Arc::new(ContainerCommandExecutor::new(ContainerConfig {
47                default_image: "python:3.12-slim".to_string(),
48                ..ContainerConfig::default()
49            })),
50        }
51    }
52
53    /// Create with a custom executor (e.g., `DockerExecutor` for persistent containers).
54    pub fn with_executor(executor: Arc<dyn CodeExecutor>) -> Self {
55        Self { executor }
56    }
57
58    /// Create with a custom CLI container configuration.
59    pub fn with_config(config: ContainerConfig) -> Self {
60        Self { executor: Arc::new(ContainerCommandExecutor::new(config)) }
61    }
62}
63
64impl Default for PythonCodeTool {
65    fn default() -> Self {
66        Self::new()
67    }
68}
69
70#[async_trait]
71impl Tool for PythonCodeTool {
72    fn name(&self) -> &str {
73        "python_code"
74    }
75
76    fn description(&self) -> &str {
77        "Execute Python code in an isolated container. \
78         Suitable for data processing, scripting, and general-purpose computation. \
79         Print results as JSON to stdout using json.dumps()."
80    }
81
82    fn required_scopes(&self) -> &[&str] {
83        &["code:execute", "code:execute:container"]
84    }
85
86    fn parameters_schema(&self) -> Option<Value> {
87        Some(json!({
88            "type": "object",
89            "properties": {
90                "code": {
91                    "type": "string",
92                    "description": "Python source code to execute."
93                },
94                "input": {
95                    "description": "Optional JSON value passed via stdin."
96                }
97            },
98            "required": ["code"]
99        }))
100    }
101
102    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
103        let code = args["code"]
104            .as_str()
105            .ok_or_else(|| adk_core::AdkError::tool("missing 'code' parameter"))?
106            .to_string();
107
108        let input = args.get("input").cloned();
109
110        let request = ExecutionRequest {
111            language: ExecutionLanguage::Python,
112            payload: ExecutionPayload::Source { code },
113            argv: vec![],
114            stdin: None,
115            input,
116            sandbox: SandboxPolicy::strict_rust(),
117            identity: None,
118        };
119
120        let result = self
121            .executor
122            .execute(request)
123            .await
124            .map_err(|e| adk_core::AdkError::tool(format!("Python execution failed: {e}")))?;
125
126        Ok(json!({
127            "status": result.status,
128            "stdout": result.stdout,
129            "stderr": result.stderr,
130            "output": result.output,
131            "exitCode": result.exit_code,
132            "durationMs": result.duration_ms,
133        }))
134    }
135}