|
| 1 | +# SPDX-FileCopyrightText: GitHub, Inc. |
| 2 | +# SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +import atexit |
| 5 | +import logging |
| 6 | +import os |
| 7 | +import subprocess |
| 8 | +import uuid |
| 9 | +from typing import Annotated |
| 10 | + |
| 11 | +from fastmcp import FastMCP |
| 12 | +from pydantic import Field |
| 13 | +from seclab_taskflow_agent.path_utils import log_file_name |
| 14 | + |
| 15 | +logging.basicConfig( |
| 16 | + level=logging.DEBUG, |
| 17 | + format="%(asctime)s - %(levelname)s - %(message)s", |
| 18 | + filename=log_file_name("container_shell.log"), |
| 19 | + filemode="a", |
| 20 | +) |
| 21 | + |
| 22 | +mcp = FastMCP("ContainerShell") |
| 23 | + |
| 24 | +_container_name: str | None = None |
| 25 | + |
| 26 | +CONTAINER_IMAGE = os.environ.get("CONTAINER_IMAGE", "") |
| 27 | +CONTAINER_WORKSPACE = os.environ.get("CONTAINER_WORKSPACE", "") |
| 28 | +CONTAINER_TIMEOUT = int(os.environ.get("CONTAINER_TIMEOUT", "30")) |
| 29 | + |
| 30 | +_DEFAULT_WORKDIR = "/workspace" |
| 31 | + |
| 32 | + |
| 33 | +def _start_container() -> str: |
| 34 | + """Start the Docker container and return its name.""" |
| 35 | + if not CONTAINER_IMAGE: |
| 36 | + msg = "CONTAINER_IMAGE is not set — cannot start container" |
| 37 | + raise RuntimeError(msg) |
| 38 | + if CONTAINER_WORKSPACE and ":" in CONTAINER_WORKSPACE: |
| 39 | + msg = f"CONTAINER_WORKSPACE must not contain a colon: {CONTAINER_WORKSPACE!r}" |
| 40 | + raise RuntimeError(msg) |
| 41 | + name = f"seclab-shell-{uuid.uuid4().hex[:8]}" |
| 42 | + cmd = ["docker", "run", "-d", "--rm", "--name", name] |
| 43 | + if CONTAINER_WORKSPACE: |
| 44 | + cmd += ["-v", f"{CONTAINER_WORKSPACE}:/workspace"] |
| 45 | + cmd += [CONTAINER_IMAGE, "tail", "-f", "/dev/null"] |
| 46 | + logging.debug(f"Starting container: {' '.join(cmd)}") |
| 47 | + result = subprocess.run(cmd, capture_output=True, text=True, timeout=30) |
| 48 | + if result.returncode != 0: |
| 49 | + msg = f"docker run failed: {result.stderr.strip()}" |
| 50 | + raise RuntimeError(msg) |
| 51 | + logging.debug(f"Container started: {name}") |
| 52 | + return name |
| 53 | + |
| 54 | + |
| 55 | +def _stop_container() -> None: |
| 56 | + """Stop the running container.""" |
| 57 | + global _container_name |
| 58 | + if _container_name is None: |
| 59 | + return |
| 60 | + logging.debug(f"Stopping container: {_container_name}") |
| 61 | + result = subprocess.run( |
| 62 | + ["docker", "stop", "--time", "5", _container_name], |
| 63 | + capture_output=True, |
| 64 | + text=True, |
| 65 | + ) |
| 66 | + if result.returncode != 0: |
| 67 | + logging.warning( |
| 68 | + "docker stop failed for container %s: %s", |
| 69 | + _container_name, |
| 70 | + result.stderr.strip(), |
| 71 | + ) |
| 72 | + _container_name = None |
| 73 | + |
| 74 | + |
| 75 | +atexit.register(_stop_container) |
| 76 | + |
| 77 | + |
| 78 | +@mcp.tool() |
| 79 | +def shell_exec( |
| 80 | + command: Annotated[str, Field(description="Shell command to execute inside the container")], |
| 81 | + timeout: Annotated[int, Field(description="Timeout in seconds")] = CONTAINER_TIMEOUT, |
| 82 | + workdir: Annotated[str, Field(description="Working directory inside the container")] = _DEFAULT_WORKDIR, |
| 83 | +) -> str: |
| 84 | + """Execute a shell command inside the managed Docker container.""" |
| 85 | + global _container_name |
| 86 | + if _container_name is None: |
| 87 | + try: |
| 88 | + _container_name = _start_container() |
| 89 | + except RuntimeError as e: |
| 90 | + return f"Failed to start container: {e}" |
| 91 | + |
| 92 | + cmd = ["docker", "exec", "-w", workdir, _container_name, "bash", "-c", command] |
| 93 | + logging.debug(f"Executing: {' '.join(cmd)}") |
| 94 | + try: |
| 95 | + result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) |
| 96 | + except subprocess.TimeoutExpired: |
| 97 | + return f"[exit code: timeout after {timeout}s]" |
| 98 | + |
| 99 | + output = result.stdout |
| 100 | + if result.stderr: |
| 101 | + output += result.stderr |
| 102 | + output += f"[exit code: {result.returncode}]" |
| 103 | + return output |
| 104 | + |
| 105 | + |
| 106 | +if __name__ == "__main__": |
| 107 | + mcp.run(show_banner=False) |
0 commit comments