MCPcopy Create free account
hub / github.com/Fosowl/agenticSeek / JavaInterpreter

Class JavaInterpreter

sources/tools/JavaInterpreter.py:11–98  ·  view source on GitHub ↗

This class is a tool to allow execution of Java code.

Source from the content-addressed store, hash-verified

9from sources.tools.tools import Tools
10
11class JavaInterpreter(Tools):
12 """
13 This class is a tool to allow execution of Java code.
14 """
15 def __init__(self):
16 super().__init__()
17 self.tag = "java"
18 self.name = "Java Interpreter"
19 self.description = "This tool allows you to execute Java code."
20
21 def execute(self, codes: str, safety=False) -> str:
22 """
23 Execute Java code by compiling and running it.
24 """
25 output = ""
26 code = '\n'.join(codes) if isinstance(codes, list) else codes
27
28 if safety and input("Execute code? y/n ") != "y":
29 return "Code rejected by user."
30
31 with tempfile.TemporaryDirectory() as tmpdirname:
32 source_file = os.path.join(tmpdirname, "Main.java")
33 class_dir = tmpdirname
34 with open(source_file, 'w') as f:
35 f.write(code)
36
37 try:
38 compile_command = ["javac", "-d", class_dir, source_file]
39 compile_result = subprocess.run(
40 compile_command,
41 capture_output=True,
42 text=True,
43 timeout=10
44 )
45
46 if compile_result.returncode != 0:
47 return f"Compilation failed: {compile_result.stderr}"
48
49 run_command = ["java", "-cp", class_dir, "Main"]
50 run_result = subprocess.run(
51 run_command,
52 capture_output=True,
53 text=True,
54 timeout=10
55 )
56
57 if run_result.returncode != 0:
58 return f"Execution failed: {run_result.stderr}"
59 output = run_result.stdout
60
61 except subprocess.TimeoutExpired as e:
62 return f"Execution timed out: {str(e)}"
63 except FileNotFoundError:
64 return "Error: 'java' or 'javac' not found. Ensure Java is installed and in PATH."
65 except Exception as e:
66 return f"Code execution failed: {str(e)}"
67
68 return output

Callers 2

__init__Method · 0.90
JavaInterpreter.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected