1use adk_core::{Result, Tool, ToolContext};
28use async_trait::async_trait;
29use serde_json::{Value, json};
30use std::sync::Arc;
31
32const DEFAULT_TIMEOUT_SECS: u64 = 30;
34const MIN_TIMEOUT_SECS: u64 = 1;
36const MAX_TIMEOUT_SECS: u64 = 300;
37
38const BASE_DESCRIPTION: &str = "Execute Python code in a sandboxed interpreter.";
41
42pub struct MontyPythonCodeTool {
79 repl: bool,
80 description: String,
81 #[cfg(feature = "code-embedded-python")]
82 inner: enabled::Inner,
83}
84
85impl MontyPythonCodeTool {
86 pub fn new() -> Self {
89 Self::sandboxed(false)
90 }
91
92 pub fn repl() -> Self {
95 Self::sandboxed(true)
96 }
97
98 #[cfg(feature = "code-embedded-python")]
99 fn sandboxed(repl: bool) -> Self {
100 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 #[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 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 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 false
237 }
238
239 fn is_concurrency_safe(&self) -> bool {
240 !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
262fn 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 const DEFAULT_MAX_SESSIONS: usize = 100;
297
298 #[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 pub(super) struct Inner {
320 builder: MontyExecutorBuilder,
323 granted: adk_code::SandboxPolicy,
326 oneshot: Option<Arc<MontyOneShotExecutor>>,
328 sessions: RwLock<LruSessions>,
331 }
332
333 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 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 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 #[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 #[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 #[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 #[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 #[must_use]
465 pub fn system_clock(mut self) -> Self {
466 self.builder = self.builder.system_clock();
467 self
468 }
469
470 #[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 #[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 #[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 #[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 #[must_use]
515 pub fn max_sessions(mut self, max_sessions: usize) -> Self {
516 self.max_sessions = max_sessions;
517 self
518 }
519
520 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 pub fn build_repl(self) -> std::result::Result<MontyPythonCodeTool, MontyBuildError> {
548 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 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 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 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 #[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 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 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#[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 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 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 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 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 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 tool.execute(MockToolContext::new("a"), json!({"code": "x"})).await.unwrap();
947 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 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}