File size: 1,151 Bytes
93be2a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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,
    )