import asyncio
import sys
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("bounded-demo")

@mcp.tool()
async def check_local_python(timeout_seconds: int = 3) -> str:
    """Run one fixed Python check, not a caller-supplied shell command."""
    if not 1 <= timeout_seconds <= 5:
        return "timeout_seconds must be between 1 and 5"

    proc = await asyncio.create_subprocess_exec(
        sys.executable, "-c", "print('python check OK')",
        stdin=asyncio.subprocess.DEVNULL,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    try:
        stdout, stderr = await asyncio.wait_for(
            proc.communicate(), timeout=timeout_seconds
        )
    except asyncio.TimeoutError:
        if proc.returncode is None:
            proc.kill()
        await proc.communicate()
        return "Fixed local check timed out; child process reaped"

    if proc.returncode != 0:
        return f"Fixed check failed with exit status {proc.returncode}"
    if len(stdout) + len(stderr) > 4096:
        return "Unexpected output size; review locally"
    return stdout.decode("utf-8", errors="replace").strip()

if __name__ == "__main__":
    mcp.run(transport="stdio")
