rcdebug 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,796 @@
1
+ """
2
+ Roblox Studio MCP Inspector (rcdebug --server):
3
+ - Automatically discovers Roblox Studio MCP configuration on macOS
4
+ - Prompts & persists to ~/.rcdebug/config.json if none is found
5
+ - Connects to Studio MCP over JSON-RPC (stdio or HTTP) to perform static scene & script audits
6
+ - Also supports offline static auditing of .rbxlx/.rbxmx place files and .luau/.lua script directories
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import re
14
+ import select
15
+ import subprocess
16
+ import sys
17
+ import time
18
+ import xml.etree.ElementTree as ET
19
+ from concurrent.futures import ThreadPoolExecutor
20
+ from pathlib import Path
21
+ from typing import Any
22
+ from urllib.request import Request, urlopen
23
+
24
+ from .debugger_pack import get_debugger_pack
25
+ from .exporter import export_markdown_report
26
+ from .flaw_catalog import get_catalog
27
+ from .models import AuditSession, Finding
28
+ from .terminal import (
29
+ BOLD,
30
+ CYAN,
31
+ DIM,
32
+ GREEN,
33
+ MAGENTA,
34
+ RED,
35
+ RESET,
36
+ WHITE,
37
+ YELLOW,
38
+ normalize_filter_label,
39
+ print_banner,
40
+ print_finding,
41
+ print_session_summary,
42
+ )
43
+
44
+ CONFIG_DIR = Path.home() / ".rcdebug"
45
+ CONFIG_FILE = CONFIG_DIR / "config.json"
46
+
47
+
48
+ def candidate_mcp_config_paths() -> list[Path]:
49
+ home = Path.home()
50
+ return [
51
+ CONFIG_FILE,
52
+ home / ".gemini" / "config" / "mcp_config.json",
53
+ home / ".gemini" / "antigravity" / "mcp_config.json",
54
+ home / ".cursor" / "mcp.json",
55
+ home / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json",
56
+ home / "Library" / "Application Support" / "Cursor" / "User" / "globalStorage" / "mcp.json",
57
+ home / "Library" / "Application Support" / "Code" / "User" / "globalStorage" / "mcp.json",
58
+ ]
59
+
60
+
61
+ def find_studio_mcp(custom_paths: list[Path] | None = None) -> dict[str, Any] | None:
62
+ """
63
+ Searches common macOS configuration paths for an active Roblox Studio MCP server configuration.
64
+ """
65
+ paths = custom_paths if custom_paths is not None else candidate_mcp_config_paths()
66
+
67
+ for path in paths:
68
+ if not path.exists():
69
+ continue
70
+ try:
71
+ content = json.loads(path.read_text(encoding="utf-8"))
72
+ if not isinstance(content, dict):
73
+ continue
74
+
75
+ # 1. Check saved rcdebug config format
76
+ if "roblox_studio_mcp" in content and isinstance(content["roblox_studio_mcp"], dict):
77
+ return {
78
+ "source": str(path),
79
+ "name": content["roblox_studio_mcp"].get("name", "roblox_studio_mcp"),
80
+ "config": content["roblox_studio_mcp"],
81
+ }
82
+
83
+ # 2. Check standard mcpServers dictionary
84
+ servers = content.get("mcpServers", {})
85
+ if isinstance(servers, dict):
86
+ for name, cfg in servers.items():
87
+ if not isinstance(cfg, dict):
88
+ continue
89
+ cmd_str = str(cfg.get("command", ""))
90
+ if (
91
+ "roblox" in name.lower()
92
+ or "studio" in name.lower()
93
+ or "studiomcp" in cmd_str.lower()
94
+ ):
95
+ return {
96
+ "source": str(path),
97
+ "name": name,
98
+ "config": cfg,
99
+ }
100
+ except Exception:
101
+ continue
102
+
103
+ return None
104
+
105
+
106
+ def prompt_and_save_mcp_config(config_file: Path = CONFIG_FILE) -> dict[str, Any]:
107
+ """
108
+ Interactively prompts the user for the MCP endpoint URL or stdio command
109
+ and saves it to ~/.rcdebug/config.json for future runs.
110
+ """
111
+ print(f"{YELLOW}✖ No Roblox Studio MCP configuration found in standard macOS paths.{RESET}")
112
+ default_bin = "/Applications/RobloxStudio.app/Contents/MacOS/StudioMCP"
113
+ hint = f" (e.g. {default_bin} or http://127.0.0.1:3000/mcp)"
114
+ try:
115
+ mcp_target = input(
116
+ f"{BOLD}Enter your Roblox Studio MCP URL or stdio command path{hint}:{RESET} "
117
+ ).strip()
118
+ except EOFError:
119
+ mcp_target = ""
120
+
121
+ if not mcp_target:
122
+ print(f"{RED}No MCP input provided. Exiting.{RESET}")
123
+ sys.exit(1)
124
+
125
+ config_file.parent.mkdir(parents=True, exist_ok=True)
126
+ if mcp_target.startswith("http://") or mcp_target.startswith("https://"):
127
+ cfg_obj: dict[str, Any] = {"url": mcp_target, "endpoint_or_command": mcp_target}
128
+ else:
129
+ parts = mcp_target.split()
130
+ cfg_obj = {
131
+ "command": parts[0],
132
+ "args": parts[1:],
133
+ "endpoint_or_command": mcp_target,
134
+ }
135
+
136
+ saved_data = {"roblox_studio_mcp": cfg_obj}
137
+ config_file.write_text(json.dumps(saved_data, indent=2), encoding="utf-8")
138
+ print(f"{GREEN}✔ Saved MCP configuration to {config_file}{RESET}")
139
+ return {"source": str(config_file), "name": "roblox_studio_mcp", "config": cfg_obj}
140
+
141
+
142
+ class StdioMCPClient:
143
+ """
144
+ Lightweight JSON-RPC 2.0 client over stdio for communicating with StudioMCP.
145
+ """
146
+
147
+ def __init__(self, command: str, args: list[str] | None = None, env: dict[str, str] | None = None) -> None:
148
+ self.command = command
149
+ self.args = args or []
150
+ self.env = {**os.environ, **(env or {})}
151
+ self.proc: subprocess.Popen[bytes] | None = None
152
+ self._msg_id = 0
153
+
154
+ def __enter__(self) -> StdioMCPClient:
155
+ self.proc = subprocess.Popen(
156
+ [self.command, *self.args],
157
+ stdin=subprocess.PIPE,
158
+ stdout=subprocess.PIPE,
159
+ stderr=subprocess.PIPE,
160
+ env=self.env,
161
+ )
162
+ self.initialize()
163
+ return self
164
+
165
+ def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
166
+ if self.proc:
167
+ try:
168
+ self.proc.terminate()
169
+ self.proc.wait(timeout=1.5)
170
+ except Exception:
171
+ try:
172
+ self.proc.kill()
173
+ except Exception:
174
+ pass
175
+
176
+ def _next_id(self) -> int:
177
+ self._msg_id += 1
178
+ return self._msg_id
179
+
180
+ def send_request(self, method: str, params: dict[str, Any] | None = None, timeout: float = 4.0) -> dict[str, Any]:
181
+ if not self.proc or not self.proc.stdin or not self.proc.stdout:
182
+ raise RuntimeError("MCP process not running")
183
+
184
+ req_id = self._next_id()
185
+ payload = {
186
+ "jsonrpc": "2.0",
187
+ "id": req_id,
188
+ "method": method,
189
+ "params": params or {},
190
+ }
191
+ line = (json.dumps(payload) + "\n").encode("utf-8")
192
+ self.proc.stdin.write(line)
193
+ self.proc.stdin.flush()
194
+
195
+ deadline = time.time() + timeout
196
+ while time.time() < deadline:
197
+ remaining = max(0.05, deadline - time.time())
198
+ ready, _, _ = select.select([self.proc.stdout], [], [], remaining)
199
+ if not ready:
200
+ continue
201
+ raw_line = self.proc.stdout.readline()
202
+ if not raw_line:
203
+ break
204
+ text = raw_line.decode("utf-8", errors="replace").strip()
205
+ if not text:
206
+ continue
207
+ try:
208
+ msg = json.loads(text)
209
+ except json.JSONDecodeError:
210
+ continue
211
+ if isinstance(msg, dict) and msg.get("id") == req_id:
212
+ return msg
213
+ raise TimeoutError(f"Timed out waiting for MCP response to {method}")
214
+
215
+ def send_notification(self, method: str, params: dict[str, Any] | None = None) -> None:
216
+ if not self.proc or not self.proc.stdin:
217
+ return
218
+ payload = {
219
+ "jsonrpc": "2.0",
220
+ "method": method,
221
+ "params": params or {},
222
+ }
223
+ self.proc.stdin.write((json.dumps(payload) + "\n").encode("utf-8"))
224
+ self.proc.stdin.flush()
225
+
226
+ def initialize(self) -> dict[str, Any]:
227
+ resp = self.send_request(
228
+ "initialize",
229
+ {
230
+ "protocolVersion": "2024-11-05",
231
+ "capabilities": {},
232
+ "clientInfo": {"name": "rcdebug", "version": "1.0.0"},
233
+ },
234
+ timeout=3.5,
235
+ )
236
+ self.send_notification("notifications/initialized", {})
237
+ return resp
238
+
239
+ def call_tool(self, name: str, arguments: dict[str, Any] | None = None, timeout: float = 6.0) -> Any:
240
+ resp = self.send_request(
241
+ "tools/call",
242
+ {"name": name, "arguments": arguments or {}},
243
+ timeout=timeout,
244
+ )
245
+ if "error" in resp:
246
+ raise RuntimeError(str(resp["error"]))
247
+ result = resp.get("result", {})
248
+ content = result.get("content", [])
249
+ if isinstance(content, list) and content:
250
+ texts = [c.get("text", "") for c in content if isinstance(c, dict) and "text" in c]
251
+ joined = "\n".join(texts).strip()
252
+ try:
253
+ return json.loads(joined)
254
+ except Exception:
255
+ return joined
256
+ return result
257
+
258
+
259
+ STATIC_AUDIT_LUAU = r"""
260
+ local findings = {}
261
+ local HttpService = game:GetService("HttpService")
262
+ local ServerScriptService = game:GetService("ServerScriptService")
263
+ local ReplicatedStorage = game:GetService("ReplicatedStorage")
264
+ local Workspace = game:GetService("Workspace")
265
+ local StarterPlayer = game:GetService("StarterPlayer")
266
+ local StarterGui = game:GetService("StarterGui")
267
+
268
+ local function add(sev, cat, title, path, flaw, abuse, fix, code)
269
+ table.insert(findings, {
270
+ severity = sev,
271
+ category = cat,
272
+ title = title,
273
+ path = path,
274
+ flaw = flaw,
275
+ abuse = abuse,
276
+ fix = fix,
277
+ code_example = code or ""
278
+ })
279
+ end
280
+
281
+ pcall(function()
282
+ if ServerScriptService.LoadStringEnabled then
283
+ add(
284
+ "CRITICAL",
285
+ "StaticSceneAudit",
286
+ "ServerScriptService.LoadStringEnabled is Enabled",
287
+ "ServerScriptService.LoadStringEnabled",
288
+ "ServerScriptService allows runtime compilation of arbitrary Luau strings via loadstring().",
289
+ "Any script injection flaw or infected free-model script can execute arbitrary server code.",
290
+ "Set ServerScriptService.LoadStringEnabled = false in Studio Properties.",
291
+ "ServerScriptService.LoadStringEnabled = false"
292
+ )
293
+ end
294
+ end)
295
+
296
+ pcall(function()
297
+ if HttpService.HttpEnabled then
298
+ add(
299
+ "INFO",
300
+ "HttpSecurity",
301
+ "HttpService.HttpEnabled is Active",
302
+ "HttpService.HttpEnabled",
303
+ "Outbound HTTP requests are enabled for this place.",
304
+ "If scripts pass unsanitized player data to external webhooks or third-party scripts exfiltrate place assets, external network calls will succeed.",
305
+ "Keep HttpEnabled = false unless external APIs are required, and route all webhook calls through a rate-limited server proxy."
306
+ )
307
+ end
308
+ end)
309
+
310
+ local unanchored = 0
311
+ for _, desc in ipairs(Workspace:GetDescendants()) do
312
+ if desc:IsA("BasePart") and not desc.Anchored and not desc:IsDescendantOf(Workspace.CurrentCamera) then
313
+ unanchored += 1
314
+ if unanchored <= 3 then
315
+ add(
316
+ "WARN",
317
+ "PhysicsAudit",
318
+ "Unanchored Workspace Part: " .. desc.Name,
319
+ desc:GetFullName(),
320
+ "BasePart in Workspace is unanchored at edit time.",
321
+ "Unanchored parts default to automatic client network ownership, allowing nearby exploiters to teleport or fling them.",
322
+ "Set Anchored = true on static geometry or call part:SetNetworkOwner(nil) in a server script."
323
+ )
324
+ end
325
+ elseif desc:IsA("RemoteEvent") or desc:IsA("RemoteFunction") then
326
+ add(
327
+ "WARN",
328
+ "RemoteArchitecture",
329
+ "Remote Endpoint Inside Workspace: " .. desc.Name,
330
+ desc:GetFullName(),
331
+ desc.ClassName .. " is parented under Workspace instead of ReplicatedStorage.",
332
+ "Scattering remotes inside Workspace models complicates access auditing and often pairs with unvalidated tool/vehicle scripts.",
333
+ "Centralize network endpoints inside ReplicatedStorage.Remotes with unified server middleware validation."
334
+ )
335
+ end
336
+ end
337
+
338
+ for _, desc in ipairs(ReplicatedStorage:GetDescendants()) do
339
+ if desc:IsA("RemoteEvent") or desc:IsA("RemoteFunction") then
340
+ add(
341
+ "INFO",
342
+ "RemoteInventory",
343
+ "ReplicatedStorage Remote Endpoint: " .. desc.Name,
344
+ desc:GetFullName(),
345
+ "Client-callable " .. desc.ClassName .. " discovered during static place inspection.",
346
+ "Any client can invoke this endpoint with crafted arguments at any time.",
347
+ "Verify that the corresponding OnServerEvent/OnServerInvoke handler enforces typeof() checks and rate limiting."
348
+ )
349
+ end
350
+ end
351
+
352
+ return HttpService:JSONEncode(findings)
353
+ """
354
+
355
+
356
+ def audit_luau_script_source(script_path: str, source: str) -> list[Finding]:
357
+ """
358
+ Static analyzer for a Luau script's source code:
359
+ - Evaluates all precompiled rules in FlawCatalog (loadstring, webhooks, HttpService,
360
+ DataStore races, Marketplace ProcessReceipt, ProximityPrompt, Touched, Teleport, etc.)
361
+ - Audits OnServerEvent / OnServerInvoke handlers for typeof() validation & cooldowns
362
+ """
363
+ catalog = get_catalog()
364
+ pack = get_debugger_pack()
365
+ findings: list[Finding] = catalog.match_source(script_path, source)
366
+ findings.extend(pack.scan_source(script_path, source))
367
+
368
+ # Check OnServerEvent / OnServerInvoke handlers for missing typeof/type checks & cooldowns
369
+ remote_handler_pattern = re.compile(
370
+ r"([\w\.\:\[\]\"']+)\.(OnServerEvent\s*:\s*Connect|OnServerInvoke\s*=)\s*\(?\s*function\s*\(([^)]*)\)(.*?)(?=\bend\s*\))",
371
+ re.DOTALL,
372
+ )
373
+ for match in remote_handler_pattern.finditer(source):
374
+ remote_expr = match.group(1).strip()
375
+ params_raw = match.group(3).strip()
376
+ body = match.group(4)
377
+
378
+ params = [p.strip().split(":")[0].strip() for p in params_raw.split(",") if p.strip()]
379
+ # First parameter is always the firing Player
380
+ client_params = params[1:] if len(params) > 1 else []
381
+
382
+ has_type_check = bool(re.search(r"\b(typeof|type|tonumber)\s*\(", body))
383
+ has_cooldown = bool(re.search(r"\b(os\.clock|tick|time|debounce|cooldown|lastFired|rateLimit)\b", body, re.IGNORECASE))
384
+
385
+ if client_params and not has_type_check:
386
+ f = Finding(
387
+ severity="CRITICAL",
388
+ category="RemoteValidation",
389
+ title=f"Missing Parameter Type Validation on {remote_expr}",
390
+ path=script_path,
391
+ flaw=(
392
+ f"Server remote handler accepts client arguments ({', '.join(client_params)}) "
393
+ f"without validating parameter types via typeof() or type()."
394
+ ),
395
+ abuse=(
396
+ "A malicious client can pass nil, tables, Instances, negative numbers, or NaN for "
397
+ f"({', '.join(client_params)}), causing server script errors or bypassing price/quantity logic."
398
+ ),
399
+ fix=f"Validate typeof() for every client parameter ({', '.join(client_params)}) at the first line of the handler.",
400
+ code_example=(
401
+ f"{remote_expr}.OnServerEvent:Connect(function({params_raw})\n"
402
+ + "\n".join(
403
+ f' if typeof({p}) ~= "number" or {p} ~= {p} then return end'
404
+ for p in client_params[:2]
405
+ )
406
+ + "\n -- Proceed with verified server state\nend)"
407
+ ),
408
+ )
409
+ findings.append(catalog.enrich_finding(f))
410
+ elif not has_cooldown:
411
+ f = Finding(
412
+ severity="WARN",
413
+ category="RemoteValidation",
414
+ title=f"Missing Server-Side Cooldown/Debounce on {remote_expr}",
415
+ path=script_path,
416
+ flaw=f"Remote handler for '{remote_expr}' has no visible per-player rate limit or cooldown check.",
417
+ abuse="Clients can fire this remote dozens of times per frame to trigger race conditions or lag the server.",
418
+ fix="Track last invocation time per Player using os.clock() and drop requests that arrive faster than the cooldown threshold.",
419
+ )
420
+ findings.append(catalog.enrich_finding(f))
421
+
422
+ findings.sort(key=lambda f: f.sort_key())
423
+ return findings
424
+
425
+
426
+ def _scan_single_luau_file(file_path: Path) -> list[Finding]:
427
+ try:
428
+ src = file_path.read_text(encoding="utf-8", errors="replace")
429
+ return audit_luau_script_source(str(file_path), src)
430
+ except Exception:
431
+ return []
432
+
433
+
434
+ def audit_local_path(target_path: Path, session: AuditSession, filter_level: str | None = None) -> None:
435
+ """
436
+ Audits a local .luau/.lua file, directory of scripts, or .rbxlx/.rbxmx XML place file
437
+ using parallel worker threads for multi-file directories.
438
+ """
439
+ if target_path.is_file():
440
+ files = [target_path]
441
+ else:
442
+ files = sorted(
443
+ [
444
+ p
445
+ for p in target_path.rglob("*")
446
+ if p.is_file() and p.suffix.lower() in (".luau", ".lua", ".rbxlx", ".rbxmx")
447
+ ]
448
+ )
449
+
450
+ luau_files = [f for f in files if f.suffix.lower() in (".luau", ".lua")]
451
+ xml_files = [f for f in files if f.suffix.lower() in (".rbxlx", ".rbxmx")]
452
+
453
+ if len(luau_files) > 1:
454
+ with ThreadPoolExecutor(max_workers=min(8, len(luau_files))) as pool:
455
+ for file_findings in pool.map(_scan_single_luau_file, luau_files):
456
+ for finding in file_findings:
457
+ if session.add_finding(finding):
458
+ print_finding(finding, filter_level=filter_level)
459
+ else:
460
+ for fpath in luau_files:
461
+ for finding in _scan_single_luau_file(fpath):
462
+ if session.add_finding(finding):
463
+ print_finding(finding, filter_level=filter_level)
464
+
465
+ for file_path in xml_files:
466
+ _audit_rbxlx_file(file_path, session, filter_level=filter_level)
467
+
468
+
469
+ def _audit_rbxlx_file(xml_path: Path, session: AuditSession, filter_level: str | None = None) -> None:
470
+ try:
471
+ tree = ET.parse(xml_path)
472
+ root = tree.getroot()
473
+ except Exception:
474
+ return
475
+
476
+ for item in root.iter("Item"):
477
+ cls = item.attrib.get("class", "")
478
+ props = item.find("Properties")
479
+ name = cls
480
+ if props is not None:
481
+ for s in props.findall("string"):
482
+ if s.attrib.get("name") == "Name" and s.text:
483
+ name = s.text
484
+ break
485
+
486
+ if cls == "ServerScriptService" and props is not None:
487
+ for b in props.findall("bool"):
488
+ if b.attrib.get("name") == "LoadStringEnabled" and (b.text or "").lower() == "true":
489
+ f = Finding(
490
+ severity="CRITICAL",
491
+ category="StaticPlaceAudit",
492
+ title="ServerScriptService.LoadStringEnabled is TRUE in Place File",
493
+ path=f"{xml_path.name}::ServerScriptService",
494
+ flaw="Place file enables server-side loadstring() execution.",
495
+ abuse="Allows arbitrary server code execution if any script evaluates dynamic strings.",
496
+ fix="Set LoadStringEnabled to false in ServerScriptService.",
497
+ )
498
+ if session.add_finding(f):
499
+ print_finding(f, filter_level=filter_level)
500
+
501
+ if cls in ("Part", "MeshPart", "UnionOperation") and props is not None:
502
+ for b in props.findall("bool"):
503
+ if b.attrib.get("name") == "Anchored" and (b.text or "").lower() == "false":
504
+ f = Finding(
505
+ severity="WARN",
506
+ category="PhysicsAudit",
507
+ title=f"Unanchored {cls} in Place File: {name}",
508
+ path=f"{xml_path.name}::{name}",
509
+ flaw=f"{cls} '{name}' has Anchored = false.",
510
+ abuse="Clients near unanchored parts automatically acquire network ownership and can manipulate part CFrame/velocity.",
511
+ fix="Anchor static parts or lock network ownership to the server via part:SetNetworkOwner(nil).",
512
+ )
513
+ if session.add_finding(f):
514
+ print_finding(f, filter_level=filter_level)
515
+
516
+ if cls in ("Script", "LocalScript", "ModuleScript") and props is not None:
517
+ for pstr in list(props.findall("ProtectedString")) + list(props.findall("string")):
518
+ if pstr.attrib.get("name") == "Source" and pstr.text:
519
+ for finding in audit_luau_script_source(f"{xml_path.name}::{name}", pstr.text):
520
+ if session.add_finding(finding):
521
+ print_finding(finding, filter_level=filter_level)
522
+
523
+
524
+ def run_live_mcp_audit(
525
+ mcp_cfg: dict[str, Any],
526
+ session: AuditSession,
527
+ filter_level: str | None = None,
528
+ ) -> bool:
529
+ """
530
+ Attempts to connect to the configured Roblox Studio MCP server via stdio or HTTP
531
+ and perform a live static scene & script audit.
532
+ Returns True if a live Studio instance was audited.
533
+ """
534
+ command = mcp_cfg.get("command")
535
+ args = mcp_cfg.get("args", [])
536
+ env = mcp_cfg.get("env", {})
537
+ url = mcp_cfg.get("url") or mcp_cfg.get("endpoint_or_command", "")
538
+
539
+ if command and Path(command).exists():
540
+ print(f"{CYAN}→ Launching MCP stdio handshake with:{RESET} {BOLD}{command}{RESET}")
541
+ try:
542
+ with StdioMCPClient(command, args=args, env=env) as client:
543
+ studios_res = client.call_tool("list_roblox_studios", {})
544
+ studios = (
545
+ studios_res.get("studios", studios_res)
546
+ if isinstance(studios_res, dict)
547
+ else studios_res
548
+ )
549
+ if not isinstance(studios, list) or not studios:
550
+ print(
551
+ f"{YELLOW}⚠ StudioMCP binary responded, but 0 active Roblox Studio instances are currently open.{RESET}"
552
+ )
553
+ return False
554
+
555
+ studio = studios[0]
556
+ studio_id = studio.get("id") or studio.get("studio_id")
557
+ studio_name = studio.get("name", studio_id)
558
+ session.target_name = f"Roblox Studio MCP ({studio_name})"
559
+ print(f"{GREEN}✔ Connected to Studio Instance:{RESET} {BOLD}{studio_name}{RESET} ({studio_id})")
560
+
561
+ state = client.call_tool("get_studio_state", {"studio_id": studio_id})
562
+ dm_type = "Edit"
563
+ if isinstance(state, dict):
564
+ avail = state.get("available_datamodel_types") or state.get("datamodel_types") or []
565
+ if "Server" in avail:
566
+ dm_type = "Server"
567
+ elif "Edit" in avail:
568
+ dm_type = "Edit"
569
+
570
+ # 1. Execute static scene audit Luau snippet
571
+ luau_res = client.call_tool(
572
+ "execute_luau",
573
+ {"studio_id": studio_id, "datamodel_type": dm_type, "code": STATIC_AUDIT_LUAU},
574
+ )
575
+ parsed_findings = []
576
+ if isinstance(luau_res, str):
577
+ try:
578
+ parsed_findings = json.loads(luau_res)
579
+ except Exception:
580
+ pass
581
+ elif isinstance(luau_res, dict) and "result" in luau_res:
582
+ try:
583
+ parsed_findings = json.loads(str(luau_res["result"]))
584
+ except Exception:
585
+ pass
586
+ elif isinstance(luau_res, list):
587
+ parsed_findings = luau_res
588
+
589
+ for item in parsed_findings:
590
+ if isinstance(item, dict):
591
+ f = Finding(
592
+ severity=str(item.get("severity", "INFO")),
593
+ category=str(item.get("category", "MCPStaticAudit")),
594
+ title=str(item.get("title", "MCP Finding")),
595
+ path=str(item.get("path", "Studio")),
596
+ flaw=str(item.get("flaw", "")),
597
+ abuse=str(item.get("abuse", "")),
598
+ fix=str(item.get("fix", "")),
599
+ code_example=str(item.get("code_example", "")),
600
+ )
601
+ if session.add_finding(f):
602
+ print_finding(f, filter_level=filter_level)
603
+
604
+ # 2. Grep scripts for dangerous patterns via MCP script_grep
605
+ for pattern, sev, title, flaw, abuse, fix in [
606
+ (
607
+ "loadstring",
608
+ "CRITICAL",
609
+ "Script Uses loadstring()",
610
+ "Server or shared script references loadstring().",
611
+ "Enables arbitrary code execution if untrusted input reaches loadstring().",
612
+ "Remove loadstring() and use static module functions.",
613
+ ),
614
+ (
615
+ "HttpService",
616
+ "WARN",
617
+ "Script Uses HttpService",
618
+ "Script references HttpService for external network calls.",
619
+ "Unthrottled outbound HTTP calls can hit the 500 req/min limit or leak secrets.",
620
+ "Ensure HttpService calls use HttpService:GetSecret() and strict server throttling.",
621
+ ),
622
+ ]:
623
+ try:
624
+ grep_res = client.call_tool(
625
+ "script_grep", {"studio_id": studio_id, "query": pattern}
626
+ )
627
+ matches = grep_res if isinstance(grep_res, list) else (
628
+ grep_res.get("matches", []) if isinstance(grep_res, dict) else []
629
+ )
630
+ for m in matches[:10]:
631
+ spath = m.get("path", m.get("script", "Script")) if isinstance(m, dict) else str(m)
632
+ f = Finding(
633
+ severity=sev,
634
+ category="MCPScriptGrep",
635
+ title=f"{title}: {spath}",
636
+ path=spath,
637
+ flaw=flaw,
638
+ abuse=abuse,
639
+ fix=fix,
640
+ )
641
+ if session.add_finding(f):
642
+ print_finding(f, filter_level=filter_level)
643
+ except Exception:
644
+ pass
645
+
646
+ return True
647
+ except Exception as exc:
648
+ print(f"{YELLOW}⚠ MCP stdio session note: {exc}{RESET}")
649
+ return False
650
+
651
+ if isinstance(url, str) and (url.startswith("http://") or url.startswith("https://")):
652
+ print(f"{CYAN}→ Probing HTTP MCP endpoint:{RESET} {BOLD}{url}{RESET}")
653
+ try:
654
+ req = Request(
655
+ url,
656
+ data=json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}).encode("utf-8"),
657
+ headers={"Content-Type": "application/json"},
658
+ method="POST",
659
+ )
660
+ with urlopen(req, timeout=3.0) as resp:
661
+ resp.read()
662
+ print(f"{GREEN}✔ HTTP MCP endpoint reachable.{RESET}")
663
+ return True
664
+ except Exception as exc:
665
+ print(f"{YELLOW}⚠ HTTP MCP endpoint unreachable ({exc}).{RESET}")
666
+ return False
667
+
668
+ return False
669
+
670
+
671
+ def inject_simulated_mcp_findings(session: AuditSession, filter_level: str | None = None) -> None:
672
+ """
673
+ Populates realistic static MCP scene/script audit findings when --simulate is used.
674
+ """
675
+ sample_sources = {
676
+ "ServerScriptService.EconomyHandler": (
677
+ 'local ReplicatedStorage = game:GetService("ReplicatedStorage")\n'
678
+ 'local HttpService = game:GetService("HttpService")\n'
679
+ 'local WEBHOOK = "https://discord.com/api/webhooks/123456789/abcdef"\n\n'
680
+ "ReplicatedStorage.Remotes.PurchaseItem.OnServerEvent:Connect(function(player, itemName, price)\n"
681
+ " player.leaderstats.Cash.Value -= price\n"
682
+ " HttpService:PostAsync(WEBHOOK, HttpService:JSONEncode({user = player.Name, item = itemName}))\n"
683
+ "end)\n"
684
+ ),
685
+ "ServerScriptService.LegacyAdminLoader": (
686
+ 'local Remote = game:GetService("ReplicatedStorage").AdminCommand\n'
687
+ "Remote.OnServerEvent:Connect(function(player, codeString)\n"
688
+ ' if typeof(codeString) == "string" then\n'
689
+ " loadstring(codeString)()\n"
690
+ " end\n"
691
+ "end)\n"
692
+ ),
693
+ }
694
+
695
+ static_scene_findings = [
696
+ Finding(
697
+ severity="CRITICAL",
698
+ category="StaticSceneAudit",
699
+ title="ServerScriptService.LoadStringEnabled is Enabled",
700
+ path="ServerScriptService.LoadStringEnabled",
701
+ flaw="ServerScriptService.LoadStringEnabled is set to true in the place configuration.",
702
+ abuse="Combined with any remote handler or free-model backdoor calling loadstring(), attackers gain full server RCE.",
703
+ fix="Disable ServerScriptService.LoadStringEnabled in Studio Properties.",
704
+ code_example="ServerScriptService.LoadStringEnabled = false",
705
+ ),
706
+ Finding(
707
+ severity="WARN",
708
+ category="PhysicsAudit",
709
+ title="Unanchored Workspace Parts Detected (48 parts in Workspace.MapProps)",
710
+ path="Workspace.MapProps",
711
+ flaw="48 decorative BaseParts in Workspace.MapProps have Anchored = false.",
712
+ abuse="Clients walking near unanchored props automatically take network ownership and can fling or teleport them across the map.",
713
+ fix="Set Anchored = true on all static map props, or lock physics ownership to the server via part:SetNetworkOwner(nil).",
714
+ code_example=(
715
+ "for _, desc in ipairs(workspace.MapProps:GetDescendants()) do\n"
716
+ ' if desc:IsA("BasePart") then desc.Anchored = true end\n'
717
+ "end"
718
+ ),
719
+ ),
720
+ ]
721
+
722
+ for f in static_scene_findings:
723
+ if session.add_finding(f):
724
+ print_finding(f, filter_level=filter_level)
725
+
726
+ for script_path, code in sample_sources.items():
727
+ for f in audit_luau_script_source(script_path, code):
728
+ if session.add_finding(f):
729
+ print_finding(f, filter_level=filter_level)
730
+
731
+
732
+ def run_server_mode(
733
+ filter_level: str | None = None,
734
+ export_path: str | None = None,
735
+ place_path: str | None = None,
736
+ simulate: bool = False,
737
+ ) -> AuditSession:
738
+ catalog = get_catalog()
739
+ print_banner(
740
+ "SERVER / ROBLOX STUDIO MCP INSPECTOR",
741
+ subtitle=f"Static Scene & Script Auditor | {catalog.count():,} Flaw Signatures | Filter: {normalize_filter_label(filter_level)}",
742
+ )
743
+ print(f"\n{BOLD}Scanning macOS configuration files for Roblox Studio MCP...{RESET}")
744
+
745
+ mcp_info = find_studio_mcp()
746
+ if mcp_info:
747
+ print(f"{GREEN}{BOLD}✔ Found Roblox Studio MCP config in:{RESET} {CYAN}{mcp_info['source']}{RESET}")
748
+ print(f" {BOLD}Server Key:{RESET} {WHITE}{mcp_info.get('name', 'Roblox_Studio')}{RESET}")
749
+ print(f"{DIM}{json.dumps(mcp_info['config'], indent=2)}{RESET}")
750
+ else:
751
+ mcp_info = prompt_and_save_mcp_config()
752
+
753
+ session = AuditSession(
754
+ mode="server",
755
+ target_name=f"Roblox Studio MCP ({mcp_info.get('name', 'Roblox_Studio')})",
756
+ )
757
+
758
+ print(f"\n{BOLD}{CYAN}─── Running Static Scene & Script Security Audit ───{RESET}")
759
+
760
+ # 1. If a local place/script directory was passed, audit it directly
761
+ if place_path:
762
+ target = Path(place_path).expanduser().resolve()
763
+ if target.exists():
764
+ session.target_name = f"Static Audit ({target.name})"
765
+ print(f"{CYAN}→ Auditing local place/script path:{RESET} {BOLD}{target}{RESET}")
766
+ audit_local_path(target, session, filter_level=filter_level)
767
+ else:
768
+ print(f"{RED}✖ Specified --place path does not exist: {target}{RESET}")
769
+
770
+ # 2. If --simulate is requested, run the static analyzer against sample scripts & scene
771
+ if simulate:
772
+ print(f"{MAGENTA}{BOLD}[SIMULATION MODE]{RESET} Running static MCP scene & script analyzer on sample place...")
773
+ inject_simulated_mcp_findings(session, filter_level=filter_level)
774
+ elif not place_path:
775
+ # 3. Connect to live Studio MCP instance
776
+ audited_live = run_live_mcp_audit(mcp_info["config"], session, filter_level=filter_level)
777
+ if not audited_live:
778
+ print(
779
+ f"\n{YELLOW}Tip:{RESET} Open a place in Roblox Studio with the Studio MCP plugin active, "
780
+ f"or pass {BOLD}--place <dir_or_rbxlx>{RESET} / {BOLD}--simulate{RESET} to run static script & place checks offline."
781
+ )
782
+
783
+ print_session_summary(session, filter_level=filter_level)
784
+
785
+ if session.findings:
786
+ learned_new = catalog.learner.learn_from_session(session, catalog)
787
+ print(
788
+ f"{GREEN}{BOLD}✔ Adaptive Learner:{RESET} +{learned_new} new pattern(s) learned "
789
+ f"({len(catalog.learner.learned_tokens)} total) -> {CYAN}{catalog.learner.store_path}{RESET}"
790
+ )
791
+
792
+ if export_path:
793
+ saved_file = export_markdown_report(session, export_path, filter_level=filter_level)
794
+ print(f"{GREEN}{BOLD}✔ Exported Markdown audit report to:{RESET} {CYAN}{saved_file}{RESET}\n")
795
+
796
+ return session