local HttpService = game:GetService("HttpService") local API_BASE = "https://api.luaprotect.dev" local LuaProtectMCP = {} LuaProtectMCP.Running = false LuaProtectMCP.PollInterval = 0.5 LuaProtectMCP.HotPollInterval = 0.1 LuaProtectMCP.IdlePollInterval = 1.0 local function resolveToken() local t = nil if getgenv and type(getgenv) == "function" then local g = getgenv() t = g.LUAPROTECT_MCP_TOKEN or g.MCP_TOKEN or g.LuaProtectToken end if not t and _G then t = _G.LUAPROTECT_MCP_TOKEN or _G.MCP_TOKEN or _G.LuaProtectToken end if not t and shared then t = shared.LUAPROTECT_MCP_TOKEN or shared.MCP_TOKEN or shared.LuaProtectToken end return t end LuaProtectMCP.Token = resolveToken() local requestFunc = (syn and syn.request) or (http and http.request) or http_request or (fluxus and fluxus.request) or request if not requestFunc then error("[LuaProtect MCP] Unsupported executor HTTP environment.") end local function httpRequest(endpoint, method, payload) local tok = LuaProtectMCP.Token or resolveToken() local headers = { ["Authorization"] = "Bearer " .. tostring(tok), ["Content-Type"] = "application/json", ["User-Agent"] = "LuaProtect-Roblox-MCP/1.0" } local bodyData = nil if payload then local encodeOk, encoded = pcall(function() return HttpService:JSONEncode(payload) end) if encodeOk then bodyData = encoded else return false, "JSON encode failed" end end local response = nil local reqOk, reqErr = pcall(function() response = requestFunc({ Url = API_BASE .. endpoint, Method = method or "GET", Headers = headers, Body = bodyData }) end) if not reqOk or not response then return false, reqErr or "No response" end local statusCode = response.StatusCode or response.Status if statusCode == 200 or statusCode == 201 then local decodeOk, data = pcall(function() return HttpService:JSONDecode(response.Body) end) if decodeOk then return true, data else return true, response.Body end else return false, response.Body or ("HTTP " .. tostring(statusCode)) end end function LuaProtectMCP.ExecutePayload(commandId, sourceCode) local startTime = os.clock() local capturedOutputs = {} local function recordOutput(prefix, ...) local parts = {...} local strParts = {} for i = 1, select("#", ...) do local v = parts[i] if type(v) == "table" then local encOk, encStr = pcall(function() return HttpService:JSONEncode(v) end) table.insert(strParts, encOk and encStr or tostring(v)) else table.insert(strParts, tostring(v)) end end local msg = table.concat(strParts, " ") table.insert(capturedOutputs, prefix .. msg) end local env = (getgenv and type(getgenv) == "function" and getgenv()) or _G or {} local oldPrint = env.print or print local oldWarn = env.warn or warn local customPrint = function(...) recordOutput("", ...) end local customWarn = function(...) recordOutput("[warn] ", ...) end local fn, parseErr = loadstring(sourceCode) if not fn then httpRequest("/mcp/roblox/result", "POST", { commandId = commandId, success = false, error = tostring(parseErr), output = "Syntax Error: " .. tostring(parseErr), executionTimeMs = math.floor((os.clock() - startTime) * 1000) }) return end pcall(function() env.print = customPrint env.warn = customWarn end) local success, runtimeResult = pcall(fn) local elapsed = math.floor((os.clock() - startTime) * 1000) pcall(function() env.print = oldPrint env.warn = oldWarn end) local finalOutputText = "" if #capturedOutputs > 0 then finalOutputText = table.concat(capturedOutputs, "\n") elseif runtimeResult ~= nil then if type(runtimeResult) == "table" then local ok, str = pcall(function() return HttpService:JSONEncode(runtimeResult) end) finalOutputText = ok and str or tostring(runtimeResult) else finalOutputText = tostring(runtimeResult) end else finalOutputText = "Execution finished with 0 output." end local postOk, postErr = httpRequest("/mcp/roblox/result", "POST", { commandId = commandId, success = success, output = finalOutputText, error = success and nil or tostring(runtimeResult), executionTimeMs = elapsed }) end function LuaProtectMCP.Start(token) if LuaProtectMCP.Running then LuaProtectMCP.Stop() task.wait(0.1) end if token and token ~= "" then LuaProtectMCP.Token = token end if not LuaProtectMCP.Token then LuaProtectMCP.Token = resolveToken() end if not LuaProtectMCP.Token or LuaProtectMCP.Token == "" then warn("[LuaProtect MCP] No token found. Set getgenv().LUAPROTECT_MCP_TOKEN before running.") return false end local authOk, authData = httpRequest("/mcp/me", "GET") if not authOk then warn("[LuaProtect MCP] Failed to authenticate with MCP: " .. tostring(authData)) return false end LuaProtectMCP.Running = true LuaProtectMCP._startedAt = os.clock() print("[LuaProtect MCP] Connected to the MCP") pcall(function() game:GetService("StarterGui"):SetCore("SendNotification", { Title = "LuaProtect MCP", Text = "Connected to the MCP", Duration = 5 }) end) task.spawn(function() local Players = game:GetService("Players") local localPlayer = Players.LocalPlayer local execName = (identifyexecutor and identifyexecutor()) or "Roblox Executor" while LuaProtectMCP.Running do pcall(function() local playerData = nil if localPlayer then playerData = { name = localPlayer.Name, displayName = localPlayer.DisplayName, userId = localPlayer.UserId, accountAge = localPlayer.AccountAge } end local gameData = { name = "Active Roblox Game", placeId = game.PlaceId, placeVersion = game.PlaceVersion, jobId = game.JobId or "", playerCount = #Players:GetPlayers() } local pollOk, pollData = httpRequest("/mcp/roblox/poll", "POST", { executorInfo = execName, player = playerData, game = gameData }) if pollOk and type(pollData) == "table" and pollData.disconnect then LuaProtectMCP.Running = false elseif pollOk and type(pollData) == "table" and pollData.hasCommand and pollData.command then local cmd = pollData.command task.spawn(function() LuaProtectMCP.ExecutePayload(cmd.id, cmd.source) end) elseif not pollOk and type(pollData) == "string" and (string.find(pollData, "429") or string.find(pollData, "rate limit")) then task.wait(2) end end) -- Adaptive polling: poll fast right after startup (commands tend -- to arrive immediately after the bridge comes online), then -- settle into the idle interval. Cuts mean dispatch latency from -- ~150ms to ~25ms during the hot window without extra load. -- Back off while idle and wake quickly only during the brief -- post-connect window. This reduces idle request volume by ~3x -- across large player populations without making executions slow. local interval = LuaProtectMCP.IdlePollInterval if os.clock() - LuaProtectMCP._startedAt < 10 then interval = LuaProtectMCP.HotPollInterval end task.wait(interval) end end) return true end function LuaProtectMCP.Stop() LuaProtectMCP.Running = false end if LuaProtectMCP.Token and LuaProtectMCP.Token ~= "" then LuaProtectMCP.Start() else warn("[LuaProtect MCP] No token configured. Please set getgenv().LUAPROTECT_MCP_TOKEN before loading.") end return LuaProtectMCP