# server.py import sys import io import contextlib from mcp.server.fastmcp import FastMCP mcp = FastMCP("Sandbox-Python") @mcp.tool() def execute_python_code(code: str) -> str: """ Executes arbitrary Python 3 code in this isolated sandbox container. Returns the standard output (stdout) and error streams (stderr). """ stdout_buffer = io.StringIO() stderr_buffer = io.StringIO() with contextlib.redirect_stdout(stdout_buffer), contextlib.redirect_stderr(stderr_buffer): try: # Execute within isolated global/local frames exec(code, {}, {}) except Exception as e: sys.stderr.write(f"Runtime Error: {str(e)}") output = stdout_buffer.getvalue() errors = stderr_buffer.getvalue() if errors: return f"Errors caught during execution:\n{errors}\nPartial Output:\n{output}" return output if output else "Code executed successfully with no returned stdout." if __name__ == "__main__": # Override standard stdio pipes to expose an HTTP/SSE server mcp.run(transport="sse", host="0.0.0.0", port=8000)