from __future__ import annotations import json import os import subprocess import tempfile from typing import Any, Dict from .registry import ToolRegistry def t_py_run(args: Dict[str, Any]) -> str: code = args.get("code") if not isinstance(code, str) or not code: return json.dumps({"error": "code required"}) env = os.environ.copy() try: with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as tf: tf.write(code) path = tf.name proc = subprocess.run(["python3", path], capture_output=True, text=True, timeout=int(args.get("timeout", 180))) return json.dumps({"returncode": proc.returncode, "stdout": proc.stdout[-8000:], "stderr": proc.stderr[-8000:]}) except Exception as e: return json.dumps({"error": str(e)}) def register_tools(reg: ToolRegistry) -> None: reg.register( name="py_run", description="Execute a Python snippet in-process (separate file).", parameters={"type": "object", "properties": {"code": {"type": "string"}, "timeout": {"type": "integer"}}, "required": ["code"]}, handler=t_py_run, )