@envnyx/robloxstudio-mcp 3.5.0 → 3.6.0

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.
package/dist/index.js CHANGED
@@ -4640,8 +4640,8 @@ var SIGN_IN_START = /\[FLog::StudioKeyEvents\] login \([^)]*\) \[start\]/u;
4640
4640
  var SIGN_IN_END = /\[FLog::StudioKeyEvents\] login \[end\]\[(success|failure)\]/u;
4641
4641
  var HEAD_BYTES = 1024 * 1024;
4642
4642
  var FILETIME_UNIX_EPOCH = 116444736000000000n;
4643
- function fileTimeToUnixMs(fileTime) {
4644
- return Number((BigInt(fileTime) - FILETIME_UNIX_EPOCH) / 10000n);
4643
+ function fileTimeToUnixMs(fileTime2) {
4644
+ return Number((BigInt(fileTime2) - FILETIME_UNIX_EPOCH) / 10000n);
4645
4645
  }
4646
4646
  function studioSessionLogStartMs(name) {
4647
4647
  const match = SESSION_LOG.exec(name);
@@ -4716,6 +4716,89 @@ async function waitForStudioSignInToSettle({ logsRoot, processStartedAtMs, timeo
4716
4716
  }
4717
4717
  }
4718
4718
 
4719
+ // ../core/dist/playtest-processes.js
4720
+ var PLAYTEST_TASK = /(?:^|\s)--?task\s+"?Start(Server|Client)\b/iu;
4721
+ var PLACE_FILE_ARG = /(?:^|\s)--?local(?:Place|Project)File\s+(?:"([^"]+)"|(\S+))/iu;
4722
+ var PLACE_FILE_INTENT = /\\*"localplacefile\\*"\s*:\s*\\*"(.+?)\\*"/iu;
4723
+ var MAX_CHAIN_DEPTH = 8;
4724
+ function playtestProcessRole(commandLine) {
4725
+ const match = commandLine === void 0 ? null : PLAYTEST_TASK.exec(commandLine);
4726
+ if (!match)
4727
+ return void 0;
4728
+ return match[1].toLowerCase() === "server" ? "server" : "client";
4729
+ }
4730
+ function studioPlaceFile(commandLine) {
4731
+ if (commandLine === void 0)
4732
+ return void 0;
4733
+ const arg = PLACE_FILE_ARG.exec(commandLine);
4734
+ const raw = arg ? arg[1] ?? arg[2] : PLACE_FILE_INTENT.exec(commandLine)?.[1];
4735
+ if (raw === void 0)
4736
+ return void 0;
4737
+ const normalized = raw.replace(/[\\/]+/gu, "/").replace(/^\/+/u, "").toLowerCase();
4738
+ return normalized.length > 0 ? normalized : void 0;
4739
+ }
4740
+ function fileTime(node) {
4741
+ const value = node.StartTimeUtcFileTime;
4742
+ return value !== void 0 && /^[1-9]\d*$/u.test(value) ? BigInt(value) : void 0;
4743
+ }
4744
+ function findPlaytestProcesses(edit, processes) {
4745
+ const byId = new Map(processes.map((node) => [node.Id, node]));
4746
+ const tests = processes.filter((node) => node.Id !== edit.Id && playtestProcessRole(node.CommandLine) !== void 0 && fileTime(node) !== void 0);
4747
+ const ownerOf = (node) => {
4748
+ let current = node;
4749
+ for (let depth = 0; depth < MAX_CHAIN_DEPTH; depth += 1) {
4750
+ const parent = current.ParentId === void 0 ? void 0 : byId.get(current.ParentId);
4751
+ const parentTime = parent === void 0 ? void 0 : fileTime(parent);
4752
+ const currentTime = fileTime(current);
4753
+ if (parent === void 0 || parentTime !== void 0 && currentTime !== void 0 && parentTime > currentTime) {
4754
+ return "broken";
4755
+ }
4756
+ if (parent.Id === edit.Id)
4757
+ return "edit";
4758
+ if (playtestProcessRole(parent.CommandLine) === void 0)
4759
+ return "other";
4760
+ current = parent;
4761
+ }
4762
+ return "other";
4763
+ };
4764
+ const owned = /* @__PURE__ */ new Set();
4765
+ const orphans = [];
4766
+ for (const node of tests) {
4767
+ const owner = ownerOf(node);
4768
+ if (owner === "edit")
4769
+ owned.add(node);
4770
+ else if (owner === "broken")
4771
+ orphans.push(node);
4772
+ }
4773
+ if (orphans.length > 0) {
4774
+ const editFiles = /* @__PURE__ */ new Set();
4775
+ const ownFile = studioPlaceFile(edit.CommandLine);
4776
+ if (ownFile !== void 0)
4777
+ editFiles.add(ownFile);
4778
+ for (const node of owned) {
4779
+ const file = studioPlaceFile(node.CommandLine);
4780
+ if (file !== void 0)
4781
+ editFiles.add(file);
4782
+ }
4783
+ for (const node of processes) {
4784
+ if (node.Id === edit.Id || playtestProcessRole(node.CommandLine) !== void 0)
4785
+ continue;
4786
+ const file = studioPlaceFile(node.CommandLine);
4787
+ if (file !== void 0)
4788
+ editFiles.delete(file);
4789
+ }
4790
+ for (const node of orphans) {
4791
+ const file = studioPlaceFile(node.CommandLine);
4792
+ if (file !== void 0 && editFiles.has(file))
4793
+ owned.add(node);
4794
+ }
4795
+ }
4796
+ return tests.flatMap((node) => {
4797
+ const role = playtestProcessRole(node.CommandLine);
4798
+ return owned.has(node) && role !== void 0 && node.StartTimeUtcFileTime !== void 0 ? [{ pid: node.Id, startedAt: node.StartTimeUtcFileTime, role }] : [];
4799
+ });
4800
+ }
4801
+
4719
4802
  // ../core/dist/managed-instance-registry.js
4720
4803
  import * as fs2 from "fs/promises";
4721
4804
  import { randomUUID as randomUUID2 } from "crypto";
@@ -6316,6 +6399,31 @@ function buildWindowsStudioStopScript(processId, startedAt) {
6316
6399
  "} finally { if ($null -ne $studio) { $studio.Dispose() } }"
6317
6400
  ].join("; ");
6318
6401
  }
6402
+ function buildWindowsStudioStopManyScript(targets) {
6403
+ for (const { pid, startedAt } of targets) {
6404
+ if (!Number.isSafeInteger(pid) || pid <= 0)
6405
+ throw new Error("processId must be a positive integer.");
6406
+ if (!/^[1-9]\d*$/u.test(startedAt))
6407
+ throw new Error("startedAt must be a positive FILETIME string.");
6408
+ }
6409
+ return [
6410
+ "function Stop-ExactStudio([int]$processId, [long]$expectedStartedAt) {",
6411
+ "$studio = $null",
6412
+ "try { $studio = [System.Diagnostics.Process]::GetProcessById($processId) } catch [System.ArgumentException] { return $null }",
6413
+ "try {",
6414
+ "if ($studio.StartTime.ToUniversalTime().ToFileTimeUtc() -ne $expectedStartedAt) { $studio.Dispose(); return $null }",
6415
+ "if (-not $studio.HasExited) { try { $studio.Kill() } catch { if (-not $studio.HasExited) { $studio.Dispose(); throw } } }",
6416
+ "return $studio",
6417
+ "} catch { $studio.Dispose(); throw }",
6418
+ "}",
6419
+ "$stopped = @()",
6420
+ "$failures = @()",
6421
+ // One process that cannot be ended must not keep the others running.
6422
+ ...targets.map(({ pid, startedAt }) => `try { $stopped += @(Stop-ExactStudio ${pid} ${startedAt}) } catch { $failures += "${pid}: $($_.Exception.Message)" }`),
6423
+ "foreach ($studio in $stopped) { if ($null -ne $studio) { try { $studio.WaitForExit() } finally { $studio.Dispose() } } }",
6424
+ 'if ($failures.Count -gt 0) { throw ($failures -join "; ") }'
6425
+ ].join("\n");
6426
+ }
6319
6427
  var studioLogsRoot;
6320
6428
  async function settleWindowsStudioSignIn(startedAt) {
6321
6429
  studioLogsRoot ??= (async () => {
@@ -6724,6 +6832,43 @@ function parseWindowsStudioProcesses(output) {
6724
6832
  }
6725
6833
  return processes.map(({ Path, ...processInfo }) => Path === null ? processInfo : { ...processInfo, Path });
6726
6834
  }
6835
+ var WINDOWS_STUDIO_PROCESS_TREE_QUERY = [
6836
+ "$ErrorActionPreference = 'Stop'",
6837
+ '$studio = @(); try { $studio = @(Get-Process RobloxStudioBeta -ErrorAction Stop) } catch { if ($_.FullyQualifiedErrorId -notlike "NoProcessFoundForGivenName,*") { throw } }',
6838
+ "$details = @{}",
6839
+ `if ($studio.Count -gt 0) { Get-CimInstance Win32_Process -Filter "Name='RobloxStudioBeta.exe'" | ForEach-Object { $details[[int]$_.ProcessId] = $_ } }`,
6840
+ "$processes = @($studio | ForEach-Object { $detail = $details[[int]$_.Id]; [PSCustomObject]@{ Id = $_.Id; ParentId = $(if ($null -ne $detail) { [int]$detail.ParentProcessId } else { $null }); CommandLine = $(if ($null -ne $detail) { $detail.CommandLine } else { $null }); MainWindowTitle = $_.MainWindowTitle; StartTimeUtcFileTime = $_.StartTime.ToUniversalTime().ToFileTimeUtc().ToString() } })",
6841
+ "ConvertTo-Json -InputObject $processes -Compress"
6842
+ ].join("; ");
6843
+ function parseWindowsStudioProcessTree(output) {
6844
+ const parsed = JSON.parse(output);
6845
+ const entries = Array.isArray(parsed) ? parsed : [parsed];
6846
+ return entries.map((value) => {
6847
+ if (value === null || typeof value !== "object" || !("Id" in value) || typeof value.Id !== "number" || !Number.isSafeInteger(value.Id) || value.Id <= 0 || !("StartTimeUtcFileTime" in value) || typeof value.StartTimeUtcFileTime !== "string" || !/^[1-9]\d*$/u.test(value.StartTimeUtcFileTime)) {
6848
+ throw new Error("Malformed Roblox Studio process tree result.");
6849
+ }
6850
+ const node = { Id: value.Id, StartTimeUtcFileTime: value.StartTimeUtcFileTime };
6851
+ if ("ParentId" in value && typeof value.ParentId === "number" && Number.isSafeInteger(value.ParentId))
6852
+ node.ParentId = value.ParentId;
6853
+ if ("CommandLine" in value && typeof value.CommandLine === "string")
6854
+ node.CommandLine = value.CommandLine;
6855
+ if ("MainWindowTitle" in value && typeof value.MainWindowTitle === "string")
6856
+ node.MainWindowTitle = value.MainWindowTitle;
6857
+ return node;
6858
+ });
6859
+ }
6860
+ async function observeStudioProcessTree(timeoutMs = 15e3) {
6861
+ if (process.platform !== "win32" && !isWsl()) {
6862
+ return { status: "unavailable", reason: "Test windows are tracked by process only on Windows and WSL." };
6863
+ }
6864
+ const observedAt = Date.now();
6865
+ try {
6866
+ const out = await powershellAsync(WINDOWS_STUDIO_PROCESS_TREE_QUERY, timeoutMs);
6867
+ return { status: "ok", observedAt, processes: out.trim() === "" ? [] : parseWindowsStudioProcessTree(out) };
6868
+ } catch (error) {
6869
+ return { status: "error", observedAt, error: error instanceof Error ? error.message : String(error) };
6870
+ }
6871
+ }
6727
6872
  async function observeStudioProcesses(timeoutMs = 15e3) {
6728
6873
  const observedAt = Date.now();
6729
6874
  try {
@@ -7294,6 +7439,9 @@ var StudioInstanceManager = class {
7294
7439
  };
7295
7440
  }
7296
7441
  }
7442
+ const listStarted = Date.now();
7443
+ const testWindows = await this.playtestProcessesOfEdit(processId, record.nativeProcessStartedAt);
7444
+ deadline += Date.now() - listStarted;
7297
7445
  if (!abort)
7298
7446
  deadline = await this.beforeStudioStop(record.nativeProcessStartedAt, deadline);
7299
7447
  try {
@@ -7325,6 +7473,7 @@ var StudioInstanceManager = class {
7325
7473
  instanceId: record.instanceId
7326
7474
  };
7327
7475
  }
7476
+ await this.closeOrphanedPlaytestProcesses(testWindows);
7328
7477
  const closedAt = Date.now();
7329
7478
  record.closedAt = closedAt;
7330
7479
  record.exitedAt = record.exitedAt ?? closedAt;
@@ -7353,8 +7502,138 @@ var StudioInstanceManager = class {
7353
7502
  if (!process2) {
7354
7503
  throw new Error(`Could not find a Studio process for connected instance "${instance.instanceId}".`);
7355
7504
  }
7505
+ const listStarted = Date.now();
7506
+ const testWindows = await this.playtestProcessesOfEdit(process2.Id, process2.StartTimeUtcFileTime);
7507
+ deadline += Date.now() - listStarted;
7356
7508
  deadline = await this.beforeStudioStop(process2.StartTimeUtcFileTime, deadline);
7357
7509
  await this.closeProcess(process2.Id, process2.StartTimeUtcFileTime, void 0, deadline);
7510
+ await this.closeOrphanedPlaytestProcesses(testWindows);
7511
+ }
7512
+ /**
7513
+ * The test windows (multiplayer Server and clients) of the edit Studio behind
7514
+ * a connected instance, found by process rather than by connected plugins: a
7515
+ * window whose plugin is still loading, or never connects, is listed too.
7516
+ */
7517
+ async listPlaytestProcesses(instance) {
7518
+ const snapshot = await this.readProcessTreeSnapshot();
7519
+ if (snapshot.status === "unavailable")
7520
+ return snapshot;
7521
+ if (snapshot.status === "error") {
7522
+ return { status: "error", error: `Could not list Studio processes: ${snapshot.error}` };
7523
+ }
7524
+ const edit = await this.findEditProcessNode(instance, snapshot.processes);
7525
+ if ("reason" in edit)
7526
+ return { status: "unavailable", reason: edit.reason };
7527
+ return { status: "ok", editProcessId: edit.Id, processes: findPlaytestProcesses(edit, snapshot.processes) };
7528
+ }
7529
+ /** Ends each listed test window by exact identity and verifies that it exited. */
7530
+ async closePlaytestProcesses(processes, timeoutMs = this.closeTimeoutMs) {
7531
+ if (processes.length === 0)
7532
+ return { closed: [], remaining: [] };
7533
+ let deadline = Date.now() + timeoutMs;
7534
+ const settleSignIn = this.settleSignIn;
7535
+ if (settleSignIn) {
7536
+ const waitStarted = Date.now();
7537
+ await Promise.all(processes.map((entry) => settleSignIn(entry.startedAt).catch((error) => {
7538
+ console.error(`[studio] Could not check Studio sign-in before closing: ${error instanceof Error ? error.message : String(error)}`);
7539
+ })));
7540
+ deadline += Date.now() - waitStarted;
7541
+ }
7542
+ this.cachedSnapshot = void 0;
7543
+ const stopErrors = [];
7544
+ if (this.processAdapter.stopProcess) {
7545
+ for (const entry of processes) {
7546
+ try {
7547
+ await this.processAdapter.stopProcess(entry.pid, entry.startedAt);
7548
+ } catch (error) {
7549
+ stopErrors.push(`${entry.pid}: ${error instanceof Error ? error.message : String(error)}`);
7550
+ }
7551
+ }
7552
+ } else if (process.platform === "win32" || isWsl()) {
7553
+ try {
7554
+ await powershellAsync(buildWindowsStudioStopManyScript(processes), Math.max(1, deadline - Date.now()));
7555
+ } catch (error) {
7556
+ stopErrors.push(error instanceof Error ? error.message : String(error));
7557
+ }
7558
+ } else {
7559
+ return { closed: [], remaining: processes, error: "Test windows can be closed by process only on Windows and WSL." };
7560
+ }
7561
+ for (; ; ) {
7562
+ const snapshot = await this.readProcessTreeSnapshot(Math.max(5e3, deadline - Date.now()));
7563
+ if (snapshot.status !== "ok") {
7564
+ return {
7565
+ closed: [],
7566
+ remaining: processes,
7567
+ error: `Could not verify that test windows exited: ${snapshot.status === "error" ? snapshot.error : snapshot.reason}`
7568
+ };
7569
+ }
7570
+ const remaining = processes.filter((entry) => snapshot.processes.some((node) => node.Id === entry.pid && node.StartTimeUtcFileTime === entry.startedAt));
7571
+ if (remaining.length === 0 || Date.now() >= deadline) {
7572
+ return {
7573
+ closed: processes.filter((entry) => !remaining.includes(entry)),
7574
+ remaining,
7575
+ ...remaining.length > 0 ? {
7576
+ error: stopErrors.length > 0 ? `Could not close test windows: ${stopErrors.join("; ")}` : `Timed out closing test windows ${remaining.map((entry) => entry.pid).join(", ")}.`
7577
+ } : {}
7578
+ };
7579
+ }
7580
+ await delay4(Math.min(250, Math.max(1, deadline - Date.now())));
7581
+ }
7582
+ }
7583
+ // The test windows of one exact edit Studio process; empty when they cannot be listed.
7584
+ async playtestProcessesOfEdit(processId, startedAt) {
7585
+ if (startedAt === void 0)
7586
+ return [];
7587
+ const snapshot = await this.readProcessTreeSnapshot();
7588
+ if (snapshot.status !== "ok")
7589
+ return [];
7590
+ const edit = snapshot.processes.find((node) => node.Id === processId && node.StartTimeUtcFileTime === startedAt);
7591
+ return edit ? findPlaytestProcesses(edit, snapshot.processes) : [];
7592
+ }
7593
+ // Closing an edit Studio does not end the test windows it started.
7594
+ async closeOrphanedPlaytestProcesses(processes) {
7595
+ if (processes.length === 0)
7596
+ return;
7597
+ const result = await this.closePlaytestProcesses(processes);
7598
+ if (result.error)
7599
+ console.error(`[studio] ${result.error}`);
7600
+ }
7601
+ async findEditProcessNode(instance, processes) {
7602
+ const record = this.managedByInstanceId.get(instance.instanceId) ?? await (async () => {
7603
+ const registryRecord = await this.registry.findAnyByInstanceId(instance.instanceId);
7604
+ return registryRecord ? this.fromRegistryRecord(registryRecord) : void 0;
7605
+ })();
7606
+ if (record && record.closedAt === void 0 && record.nativeProcessId !== void 0) {
7607
+ if (record.nativeProcessStartedAt === void 0) {
7608
+ return { reason: "The managed edit Studio has no recorded process creation time." };
7609
+ }
7610
+ const edit2 = processes.find((node) => node.Id === record.nativeProcessId && node.StartTimeUtcFileTime === record.nativeProcessStartedAt);
7611
+ return edit2 ?? { reason: "The managed edit Studio process is not running." };
7612
+ }
7613
+ const edits = processes.filter((node) => playtestProcessRole(node.CommandLine) === void 0);
7614
+ let match;
7615
+ try {
7616
+ match = this.findProcessForConnectedInstance(instance, edits, { requireTitleMatch: true });
7617
+ } catch (error) {
7618
+ return { reason: error instanceof Error ? error.message : String(error) };
7619
+ }
7620
+ const edit = match === void 0 ? void 0 : edits.find((node) => node.Id === match.Id);
7621
+ return edit ?? { reason: `Could not find the edit Studio process for connected instance "${instance.instanceId}".` };
7622
+ }
7623
+ async readProcessTreeSnapshot(timeoutMs = 15e3) {
7624
+ try {
7625
+ if (this.processAdapter.observeStudioProcessTree)
7626
+ return await this.processAdapter.observeStudioProcessTree();
7627
+ if (this.processAdapter.observeStudioProcesses || this.processAdapter.listStudioProcesses) {
7628
+ return { status: "unavailable", reason: "The configured Studio process adapter does not report parent processes." };
7629
+ }
7630
+ if (/^(0|off|false)$/iu.test(process.env.ROBLOX_STUDIO_TEST_WINDOW_CLEANUP ?? "")) {
7631
+ return { status: "unavailable", reason: "Test window tracking is turned off (ROBLOX_STUDIO_TEST_WINDOW_CLEANUP)." };
7632
+ }
7633
+ return await observeStudioProcessTree(Math.max(1, timeoutMs));
7634
+ } catch (error) {
7635
+ return { status: "error", observedAt: Date.now(), error: error instanceof Error ? error.message : String(error) };
7636
+ }
7358
7637
  }
7359
7638
  async beforeStudioStop(startedAt, deadline) {
7360
7639
  if (!this.settleSignIn || startedAt === void 0 || !/^[1-9]\d*$/u.test(startedAt))
@@ -7429,10 +7708,10 @@ var StudioInstanceManager = class {
7429
7708
  }
7430
7709
  return { status: "running", observedAt: snapshot.observedAt };
7431
7710
  }
7432
- findProcessForConnectedInstance(instance, processes) {
7711
+ findProcessForConnectedInstance(instance, processes, { requireTitleMatch = false } = {}) {
7433
7712
  if (processes.length === 0)
7434
7713
  return void 0;
7435
- if (processes.length === 1)
7714
+ if (processes.length === 1 && !requireTitleMatch)
7436
7715
  return processes[0];
7437
7716
  const names = [instance.dataModelName, instance.placeName].map((name) => name.trim()).filter((name, index, all) => name.length > 0 && all.indexOf(name) === index);
7438
7717
  const candidates = processes.filter((proc) => {
@@ -21080,7 +21359,8 @@ import { createMcpHandler, fromJsonSchema, McpServer } from "@modelcontextprotoc
21080
21359
  // ../core/dist/code-mode.js
21081
21360
  import { types } from "util";
21082
21361
  import vm from "vm";
21083
- var CODE_MODE_INSTRUCTIONS = "Code mode: Studio tools are not listed individually. Call search with keywords to get TypeScript signatures, then call execute with JavaScript that awaits studio.<tool_name>(input) and returns or console.logs only what you need. Tool names below are those studio methods.";
21362
+ var CODE_MODE_MAX_PARALLEL_CALLS = 16;
21363
+ var CODE_MODE_INSTRUCTIONS = "Code mode: Studio tools are not listed individually. Call search to get TypeScript signatures (several exact tool names separated by spaces return all of them in one call), then call execute with JavaScript that awaits studio.<tool_name>(input) and returns or console.logs only what you need. Batch: do a whole step in one execute. Chain dependent calls with await and run independent ones together with Promise.all (up to 16 run in parallel; Promise.allSettled keeps the other results when one fails). Tool names below are those studio methods.";
21084
21364
  function codeModeEnabled(env = process.env) {
21085
21365
  return /^(1|true|yes)$/i.test(env.ROBLOX_MCP_CODE_MODE ?? "");
21086
21366
  }
@@ -21140,11 +21420,19 @@ function searchTools(tools, query, limit = 8) {
21140
21420
  if (terms.length === 0) {
21141
21421
  return tools.map((tool) => `${tool.name}: ${tool.description}`).join("\n");
21142
21422
  }
21423
+ const words = query.split(/[\s,|]+/).filter(Boolean);
21424
+ const byName = new Map(tools.map((tool) => [tool.name, tool]));
21425
+ if (words.length > 0 && words.every((word) => byName.has(word))) {
21426
+ const exact = [...new Set(words)].map((word) => byName.get(word));
21427
+ return `declare const studio: {
21428
+ ${exact.map(toolDeclaration).join("\n\n")}
21429
+ };`;
21430
+ }
21143
21431
  const ranked = tools.map((tool) => {
21144
21432
  const name = tool.name.toLowerCase();
21145
21433
  const description = tool.description.toLowerCase();
21146
21434
  const score = terms.reduce((sum, term) => sum + (name.includes(term) ? 3 : 0) + (description.includes(term) ? 1 : 0), 0);
21147
- return { tool, score };
21435
+ return { tool, score: score + (words.includes(tool.name) ? 100 : 0) };
21148
21436
  }).filter((entry) => entry.score > 0).sort((a, b) => b.score - a.score).slice(0, Math.max(1, limit));
21149
21437
  if (ranked.length === 0)
21150
21438
  return `No tools match "${query}". Call search with an empty query to list every tool.`;
@@ -21483,8 +21771,8 @@ function normalizeToolResult(raw, era) {
21483
21771
  ...isError ? { isError: true } : {}
21484
21772
  };
21485
21773
  }
21486
- function withErrorText(result) {
21487
- if (!result.isError || !result.structuredContent || result.content.some((block) => block.type === "text")) {
21774
+ function withStructuredText(result) {
21775
+ if (!result.structuredContent || result.content.some((block) => block.type === "text")) {
21488
21776
  return result;
21489
21777
  }
21490
21778
  return {
@@ -21655,9 +21943,9 @@ function createToolServer(options) {
21655
21943
  }, async (args, context) => {
21656
21944
  try {
21657
21945
  const raw = await options.invoke(options.getTools(), definition.name, args, { signal: context.mcpReq.signal });
21658
- return withErrorText(normalizeToolResult(raw, options.era));
21946
+ return withStructuredText(normalizeToolResult(raw, options.era));
21659
21947
  } catch (error) {
21660
- return withErrorText(normalizeToolResult({
21948
+ return withStructuredText(normalizeToolResult({
21661
21949
  content: [{ type: "text", text: JSON.stringify(publicToolErrorBody(definition.name, error)) }],
21662
21950
  isError: true
21663
21951
  }, options.era));
@@ -21672,11 +21960,11 @@ function registerCodeModeTools(server, definitions, options) {
21672
21960
  const names = new Set(catalog.map((tool) => tool.name));
21673
21961
  const inputSchemas = new Map(definitions.map((definition) => [definition.name, fromJsonSchema(definition.inputSchema)]));
21674
21962
  server.registerTool("search", {
21675
- description: "Find Studio tools by keywords. Returns TypeScript signatures to call inside execute. An empty query lists every tool.",
21963
+ description: "Find Studio tools. Keywords return the best matching TypeScript signatures; exact tool names separated by spaces return exactly those signatures in one call. An empty query lists every tool.",
21676
21964
  inputSchema: fromJsonSchema({
21677
21965
  type: "object",
21678
21966
  properties: {
21679
- query: { type: "string", description: 'Keywords, e.g. "edit script" or "playtest logs".' },
21967
+ query: { type: "string", description: 'Keywords ("edit script") or exact tool names ("get_script_source edit_script_lines").' },
21680
21968
  limit: { type: "integer", minimum: 1, maximum: 50, description: "Max signatures; default 8." }
21681
21969
  },
21682
21970
  required: ["query"]
@@ -21684,7 +21972,7 @@ function registerCodeModeTools(server, definitions, options) {
21684
21972
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }
21685
21973
  }, async (args) => ({ content: [{ type: "text", text: searchTools(catalog, args.query, args.limit ?? 8) }] }));
21686
21974
  server.registerTool("execute", {
21687
- description: "Run JavaScript (an async function body, or an async arrow function) with studio.<tool>(input) in scope. Return a value or console.log what you need; failed tool calls throw.",
21975
+ description: "Run JavaScript (an async function body, or an async arrow function) with studio.<tool>(input) in scope. Batch a whole step into one call: await dependent calls in sequence and run independent ones with Promise.all (up to 16 at once; Promise.allSettled tolerates failures). Return a value or console.log what you need; failed tool calls throw.",
21688
21976
  inputSchema: fromJsonSchema({
21689
21977
  type: "object",
21690
21978
  properties: { code: { type: "string", description: "e.g. const r = await studio.get_place_info({}); return r.placeId;" } },
@@ -21693,16 +21981,31 @@ function registerCodeModeTools(server, definitions, options) {
21693
21981
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
21694
21982
  }, async (args, context) => {
21695
21983
  const media = [];
21984
+ let active = 0;
21985
+ const waiting = [];
21986
+ const acquire = () => active < CODE_MODE_MAX_PARALLEL_CALLS ? (active++, Promise.resolve()) : new Promise((resolve7) => {
21987
+ waiting.push(resolve7);
21988
+ });
21989
+ const release = () => {
21990
+ const next = waiting.shift();
21991
+ if (next)
21992
+ next();
21993
+ else
21994
+ active--;
21995
+ };
21696
21996
  const call = async (name, input) => {
21697
21997
  const checked = await inputSchemas.get(name)["~standard"].validate(input);
21698
21998
  if (checked.issues) {
21699
21999
  throw new Error(`${name}: invalid input: ${checked.issues.map((issue) => issue.message).join("; ")}`);
21700
22000
  }
22001
+ await acquire();
21701
22002
  let result;
21702
22003
  try {
21703
22004
  const raw = await options.invoke(options.getTools(), name, checked.value, { signal: context.mcpReq.signal });
21704
22005
  result = normalizeToolResult(raw, "modern");
22006
+ release();
21705
22007
  } catch (error) {
22008
+ release();
21706
22009
  throw new Error(`${name}: ${JSON.stringify(publicToolErrorBody(name, error))}`);
21707
22010
  }
21708
22011
  media.push(...result.content.filter((block) => block.type !== "text"));
@@ -22068,6 +22371,19 @@ function runtimeEvalFailure(readiness, running, stopAction) {
22068
22371
  };
22069
22372
  }
22070
22373
  var DEFAULT_PLAYTEST_READY_TIMEOUT_S = 90;
22374
+ var TEST_WINDOW_EXIT_GRACE_MS = 5e3;
22375
+ function testWindowFields(cleanup) {
22376
+ if (!cleanup.tracked)
22377
+ return {};
22378
+ return {
22379
+ ...cleanup.closed > 0 ? { closedTestWindows: cleanup.closed } : {},
22380
+ ...cleanup.remaining > 0 ? { remainingTestWindows: cleanup.remaining } : {},
22381
+ ...cleanup.error !== void 0 ? { testWindowError: cleanup.error } : {}
22382
+ };
22383
+ }
22384
+ function isActiveMultiplayerPhase(phase) {
22385
+ return phase === "starting" || phase === "running";
22386
+ }
22071
22387
  function asRecord(value) {
22072
22388
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
22073
22389
  }
@@ -22807,7 +23123,11 @@ var RobloxStudioTools = class {
22807
23123
  // Runs `run` but answers within the response budget. A call still running then
22808
23124
  // returns a pending request id; an identical call (same key) while it runs
22809
23125
  // joins it instead of starting the work again.
22810
- async _withinResponseBudget(tool, action, args, run2) {
23126
+ // `run` gets a signal that follows the caller's only while the caller waits.
23127
+ // Once the call answers pending, the work belongs to the server: an HTTP
23128
+ // transport closes after sending that answer and aborts the request's signal
23129
+ // ("Connection closed"), which must not stop the work it reported as running.
23130
+ async _withinResponseBudget(tool, action, args, run2, signal) {
22811
23131
  const now = Date.now();
22812
23132
  for (const [id, job2] of this.toolJobs) {
22813
23133
  if (job2.settledAt !== void 0 && now - job2.settledAt > TOOL_JOB_RETENTION_MS)
@@ -22816,9 +23136,23 @@ var RobloxStudioTools = class {
22816
23136
  const key = JSON.stringify([tool, action, ...args]);
22817
23137
  let job = [...this.toolJobs.values()].find((candidate) => candidate.key === key && candidate.outcome === void 0);
22818
23138
  const joined = job !== void 0;
23139
+ let detachCaller = () => {
23140
+ };
22819
23141
  if (!job) {
23142
+ let jobSignal;
23143
+ if (signal) {
23144
+ const jobAbort = new AbortController();
23145
+ const forward = () => jobAbort.abort(signal.reason);
23146
+ if (signal.aborted)
23147
+ forward();
23148
+ else {
23149
+ signal.addEventListener("abort", forward, { once: true });
23150
+ detachCaller = () => signal.removeEventListener("abort", forward);
23151
+ }
23152
+ jobSignal = jobAbort.signal;
23153
+ }
22820
23154
  const created = { id: `${tool}-${randomUUID6()}`, key, tool, action, startedAt: now, done: Promise.resolve() };
22821
- created.done = run2().then((result) => {
23155
+ created.done = run2(jobSignal).then((result) => {
22822
23156
  created.outcome = { result };
22823
23157
  }, (error) => {
22824
23158
  created.outcome = { error };
@@ -22829,6 +23163,7 @@ var RobloxStudioTools = class {
22829
23163
  job = created;
22830
23164
  }
22831
23165
  const outcome = await this._awaitToolJob(job, responseBudgetMs());
23166
+ detachCaller();
22832
23167
  if (!outcome)
22833
23168
  return this._textResult({ ...this._toolJobPending(job), ...joined ? { joinedRunningCall: true } : {} });
22834
23169
  if (!joined)
@@ -23853,7 +24188,7 @@ var RobloxStudioTools = class {
23853
24188
  throw new Error(`${tool} poll_ms must be an integer from 50 to 10000`);
23854
24189
  }
23855
24190
  const requestedTarget = typeof target === "string" ? target : target.requested;
23856
- return this._withinResponseBudget(tool, "wait_until", [instance_id, requestedTarget, code, condition, timeoutS, pollMs, operation_id], async () => {
24191
+ return this._withinResponseBudget(tool, "wait_until", [instance_id, requestedTarget, code, condition, timeoutS, pollMs, operation_id], async (signal2) => {
23857
24192
  const intervalMs = Math.max(pollMs, Math.ceil(timeoutS * 1e3 / MAX_WAIT_PROBES));
23858
24193
  const startedAt = Date.now();
23859
24194
  const deadline = startedAt + timeoutS * 1e3;
@@ -23877,10 +24212,10 @@ var RobloxStudioTools = class {
23877
24212
  let lastValue;
23878
24213
  let lastError;
23879
24214
  for (; ; ) {
23880
- signal?.throwIfAborted();
24215
+ signal2?.throwIfAborted();
23881
24216
  polls += 1;
23882
24217
  try {
23883
- const response = await send({ code: probe }, Math.max(1e3, Math.min(1e4, deadline - Date.now())), signal);
24218
+ const response = await send({ code: probe }, Math.max(1e3, Math.min(1e4, deadline - Date.now())), signal2);
23884
24219
  const reply = response.ok === true && typeof response.result === "string" ? response.result : void 0;
23885
24220
  if (reply !== void 0 && (reply.startsWith("T") || reply.startsWith("F"))) {
23886
24221
  lastValue = reply.slice(1);
@@ -23905,7 +24240,7 @@ var RobloxStudioTools = class {
23905
24240
  }
23906
24241
  }
23907
24242
  } catch (error) {
23908
- if (signal?.aborted)
24243
+ if (signal2?.aborted)
23909
24244
  throw error;
23910
24245
  if (error instanceof RoutingFailure) {
23911
24246
  if (routedRole === void 0)
@@ -23916,9 +24251,9 @@ var RobloxStudioTools = class {
23916
24251
  }
23917
24252
  if (polls >= MAX_WAIT_PROBES || Date.now() + intervalMs >= deadline)
23918
24253
  break;
23919
- await sleepUnlessAborted(intervalMs, signal);
24254
+ await sleepUnlessAborted(intervalMs, signal2);
23920
24255
  }
23921
- signal?.throwIfAborted();
24256
+ signal2?.throwIfAborted();
23922
24257
  return finish({
23923
24258
  ...codeResult,
23924
24259
  satisfied: false,
@@ -23927,7 +24262,7 @@ var RobloxStudioTools = class {
23927
24262
  lastError,
23928
24263
  error: `wait_until timed out after ${timeoutS}s: the condition never became truthy.`
23929
24264
  });
23930
- });
24265
+ }, signal);
23931
24266
  }
23932
24267
  async setNetworkProfile(profile, target, overrides, instance_id) {
23933
24268
  const values = normalizeNetworkProfile(profile, overrides);
@@ -25177,8 +25512,8 @@ var RobloxStudioTools = class {
25177
25512
  throw new Error("solo_playtest mode must be play or run (default play)");
25178
25513
  }
25179
25514
  const readyTimeoutS = ready_timeout_s ?? timeout;
25180
- return this._withinResponseBudget("solo_playtest", action, [instance_id, startMode, readyTimeoutS], async () => {
25181
- const body = this._parseTextResult(await this.startPlaytest(startMode, void 0, instance_id, readyTimeoutS, signal));
25515
+ return this._withinResponseBudget("solo_playtest", action, [instance_id, startMode, readyTimeoutS], async (jobSignal) => {
25516
+ const body = this._parseTextResult(await this.startPlaytest(startMode, void 0, instance_id, readyTimeoutS, jobSignal));
25182
25517
  if (body.success === true && body.runtimeReady !== false) {
25183
25518
  return this._textResult({
25184
25519
  success: true,
@@ -25200,7 +25535,7 @@ var RobloxStudioTools = class {
25200
25535
  message: body.success !== true ? body.message ?? "Playtest did not start." : Array.isArray(body.disconnected) ? `Playtest started, but ${body.disconnected.join(", ")} disconnected before answering an eval.` : "Playtest did not become ready before ready_timeout_s.",
25201
25536
  roles: Array.isArray(body.roles) ? body.roles : void 0
25202
25537
  });
25203
- });
25538
+ }, signal);
25204
25539
  }
25205
25540
  return this._withinResponseBudget("solo_playtest", action, [instance_id, timeout], async () => {
25206
25541
  const body = this._parseTextResult(await this.stopPlaytest(instance_id, timeout));
@@ -25485,6 +25820,100 @@ var RobloxStudioTools = class {
25485
25820
  }
25486
25821
  return false;
25487
25822
  }
25823
+ // The edit Studio behind a scope, as the instance manager identifies its process.
25824
+ _editInstanceForScope(instanceId) {
25825
+ return this.bridge.getPeersInScope(instanceId).find((peer) => peer.role === "edit");
25826
+ }
25827
+ async _listTestWindows(instanceId) {
25828
+ const edit = this._editInstanceForScope(instanceId);
25829
+ if (!edit)
25830
+ return { status: "unavailable", reason: "The edit Studio is not connected." };
25831
+ return this.instanceManager.listPlaytestProcesses(edit);
25832
+ }
25833
+ /**
25834
+ * Closes every test window (Server and clients) of the edit Studio behind
25835
+ * `instanceId`, whether or not its plugin ever connected. Windows still get
25836
+ * `graceMs` to exit on their own first, as they do after EndTest.
25837
+ */
25838
+ async _closeTestWindows(instanceId, graceMs) {
25839
+ let listing = await this._listTestWindows(instanceId);
25840
+ if (listing.status === "unavailable")
25841
+ return { tracked: false, reason: listing.reason };
25842
+ if (listing.status === "error")
25843
+ return { tracked: true, found: 0, closed: 0, remaining: 0, listingFailed: true, error: listing.error };
25844
+ const found = listing.processes.length;
25845
+ const graceDeadline = Date.now() + graceMs;
25846
+ while (listing.status === "ok" && listing.processes.length > 0 && Date.now() < graceDeadline) {
25847
+ await sleep2(Math.min(500, Math.max(1, graceDeadline - Date.now())));
25848
+ listing = await this._listTestWindows(instanceId);
25849
+ }
25850
+ if (listing.status === "unavailable")
25851
+ return { tracked: false, reason: listing.reason };
25852
+ if (listing.status === "error")
25853
+ return { tracked: true, found, closed: 0, remaining: 0, listingFailed: true, error: listing.error };
25854
+ if (listing.processes.length === 0)
25855
+ return { tracked: true, found, closed: 0, remaining: 0 };
25856
+ const result = await this.instanceManager.closePlaytestProcesses(listing.processes);
25857
+ return {
25858
+ tracked: true,
25859
+ found,
25860
+ closed: result.closed.length,
25861
+ remaining: result.remaining.length,
25862
+ ...result.error ? { error: result.error } : {}
25863
+ };
25864
+ }
25865
+ // The edit plugin's multiplayer session; empty when it cannot answer.
25866
+ async _multiplayerEditSession(instanceId) {
25867
+ if (!this._rolesForScope(instanceId).includes("edit"))
25868
+ return {};
25869
+ try {
25870
+ const editState = await this._request("/api/multiplayer-test-state", {}, instanceId, "edit", 2e3);
25871
+ const session = editState?.session;
25872
+ return {
25873
+ phase: typeof session?.phase === "string" ? session.phase : void 0,
25874
+ testId: typeof session?.testId === "string" ? session.testId : void 0
25875
+ };
25876
+ } catch {
25877
+ return {};
25878
+ }
25879
+ }
25880
+ /**
25881
+ * Closes the test windows of a playtest whose plugins are gone, and confirms
25882
+ * the teardown only when none remain and Studio no longer reports that test
25883
+ * starting or running. Studio can open the windows seconds after its start
25884
+ * call, so while it still reports the test running this keeps closing new
25885
+ * ones until `timeoutSec`. Studio runs one test at a time: once it reports a
25886
+ * different test (`testId`, by default the one running at the first check),
25887
+ * that test's windows are someone else's and are left alone.
25888
+ * Without process tracking, only the phase counts.
25889
+ */
25890
+ async _endTestWindows(instanceId, timeoutSec, graceMs, ownTestId) {
25891
+ const deadline = Date.now() + timeoutSec * 1e3;
25892
+ let found = 0;
25893
+ let closed = 0;
25894
+ let grace = graceMs;
25895
+ let session = await this._multiplayerEditSession(instanceId);
25896
+ const testId = ownTestId ?? session.testId;
25897
+ const anotherTest = () => isActiveMultiplayerPhase(session.phase) && testId !== void 0 && session.testId !== testId;
25898
+ if (anotherTest())
25899
+ return { cleanup: { tracked: true, found, closed, remaining: 0 }, confirmed: true, editPhase: session.phase };
25900
+ for (; ; ) {
25901
+ const cleanup = await this._closeTestWindows(instanceId, grace);
25902
+ grace = 0;
25903
+ session = await this._multiplayerEditSession(instanceId);
25904
+ const over = !isActiveMultiplayerPhase(session.phase) || anotherTest();
25905
+ if (!cleanup.tracked)
25906
+ return { cleanup, confirmed: over, editPhase: session.phase };
25907
+ found += cleanup.found;
25908
+ closed += cleanup.closed;
25909
+ const total = { ...cleanup, found, closed };
25910
+ if (cleanup.listingFailed || cleanup.remaining > 0)
25911
+ return { cleanup: total, confirmed: false, editPhase: session.phase };
25912
+ if (over || Date.now() >= deadline)
25913
+ return { cleanup: total, confirmed: over, editPhase: session.phase };
25914
+ await sleep2(Math.min(1e3, Math.max(1, deadline - Date.now())));
25915
+ }
25916
+ }
25488
25917
  async _isMultiplayerTestRunning(instanceId) {
25489
25918
  const refresh = this.bridge.refreshTopologyForRouting();
25490
25919
  if (refresh)
@@ -25532,9 +25961,13 @@ var RobloxStudioTools = class {
25532
25961
  const refresh = this.bridge.refreshTopologyForRouting();
25533
25962
  if (refresh)
25534
25963
  await refresh;
25535
- const state = await this._buildMultiplayerState(this._resolveInstanceIdOnly(instanceId));
25964
+ const scopeInstanceId = this._resolveInstanceIdOnly(instanceId);
25965
+ const state = await this._buildMultiplayerState(scopeInstanceId);
25536
25966
  const roles = Array.isArray(state.peers) ? state.peers.flatMap((peer) => peer !== null && typeof peer === "object" && "role" in peer && typeof peer.role === "string" ? [peer.role] : []) : [];
25537
25967
  const unresponsiveClients = (this._brokeredClients(state.server) ?? []).flatMap((client) => client.playerPresent && client.role !== void 0 && roles.includes(client.role) && (client.heartbeatAgeMs ?? 0) > CLIENT_BRIDGE_STALE_MS ? [client.role] : []);
25968
+ const testWindows = await this._listTestWindows(scopeInstanceId);
25969
+ const windowCount = testWindows.status === "ok" ? testWindows.processes.length : 0;
25970
+ const unanswered = windowCount - roles.filter((role) => role === "server" || /^client-\d+$/.test(role)).length;
25538
25971
  return {
25539
25972
  phase: state.phase,
25540
25973
  multiplayerGroupId: typeof state.multiplayerGroupId === "string" ? state.multiplayerGroupId : void 0,
@@ -25544,6 +25977,11 @@ var RobloxStudioTools = class {
25544
25977
  ...unresponsiveClients.length > 0 ? {
25545
25978
  unresponsiveClients,
25546
25979
  hint: "These clients' MCP bridges sent no heartbeat for over 10 s: their Studio process may have exited or be frozen. leave_client removes them."
25980
+ } : {},
25981
+ ...windowCount > 0 ? { testWindows: windowCount } : {},
25982
+ ...unanswered > 0 ? {
25983
+ unansweredTestWindows: unanswered,
25984
+ testWindowHint: "Test windows are running without a connected MCP plugin (still loading, or never connected). end closes them."
25547
25985
  } : {}
25548
25986
  };
25549
25987
  };
@@ -25554,7 +25992,7 @@ var RobloxStudioTools = class {
25554
25992
  ...await briefState(instance_id)
25555
25993
  });
25556
25994
  }
25557
- return this._withinResponseBudget("multiplayer_playtest", action, [instance_id, numPlayers, target, testArgs, value, timeout, ready_timeout_s], () => this._multiplayerPlaytestAction(action, numPlayers, target, testArgs, value, timeout, instance_id, ready_timeout_s, signal));
25995
+ return this._withinResponseBudget("multiplayer_playtest", action, [instance_id, numPlayers, target, testArgs, value, timeout, ready_timeout_s], (jobSignal) => this._multiplayerPlaytestAction(action, numPlayers, target, testArgs, value, timeout, instance_id, ready_timeout_s, jobSignal), signal);
25558
25996
  }
25559
25997
  // start, add_players, leave_client and end, run under the response budget.
25560
25998
  async _multiplayerPlaytestAction(action, numPlayers, target, testArgs, value, timeout, instance_id, ready_timeout_s, signal) {
@@ -25586,7 +26024,14 @@ var RobloxStudioTools = class {
25586
26024
  running: typeof body2.running === "boolean" ? body2.running : void 0,
25587
26025
  elapsedMs: body2.elapsedMs,
25588
26026
  studioError: typeof body2.studioError === "string" ? body2.studioError : void 0,
25589
- recoveryHint: typeof body2.recoveryHint === "string" ? body2.recoveryHint : void 0
26027
+ recoveryHint: typeof body2.recoveryHint === "string" ? body2.recoveryHint : void 0,
26028
+ teardownConfirmed: typeof body2.teardownConfirmed === "boolean" ? body2.teardownConfirmed : void 0,
26029
+ closedTestWindows: typeof body2.closedTestWindows === "number" ? body2.closedTestWindows : void 0,
26030
+ remainingTestWindows: typeof body2.remainingTestWindows === "number" ? body2.remainingTestWindows : void 0,
26031
+ testWindowError: typeof body2.testWindowError === "string" ? body2.testWindowError : void 0,
26032
+ teardownError: typeof body2.teardownError === "string" ? body2.teardownError : void 0,
26033
+ testWindows: typeof body2.testWindows === "number" ? body2.testWindows : void 0,
26034
+ editPhase: typeof body2.editPhase === "string" ? body2.editPhase : void 0
25590
26035
  });
25591
26036
  }
25592
26037
  if (action === "add_players") {
@@ -25625,12 +26070,20 @@ var RobloxStudioTools = class {
25625
26070
  }
25626
26071
  const body = this._parseTextResult(await this.multiplayerTestEnd(value, timeout, instance_id));
25627
26072
  const multiplayerGroupId = typeof body.multiplayerGroupId === "string" ? body.multiplayerGroupId : void 0;
26073
+ const closedTestWindows = typeof body.closedTestWindows === "number" ? body.closedTestWindows : void 0;
26074
+ const remainingTestWindows = typeof body.remainingTestWindows === "number" ? body.remainingTestWindows : void 0;
26075
+ const editPhase = typeof body.editPhase === "string" ? body.editPhase : void 0;
25628
26076
  return this._textResult(body.success === true && body.ended === true ? {
25629
26077
  success: true,
25630
26078
  action,
25631
26079
  multiplayerGroupId,
25632
- message: body.alreadyEnded === true ? "Multiplayer playtest already ended." : body.teardownConfirmed === false ? 'Multiplayer playtest end requested; teardown still in progress. Use multiplayer_playtest action="status" to confirm.' : "Multiplayer playtest ended.",
25633
- teardownConfirmed: body.teardownConfirmed === true
26080
+ message: body.alreadyEnded === true ? "Multiplayer playtest already ended." : remainingTestWindows !== void 0 ? `Multiplayer playtest end requested, but ${remainingTestWindows} test window(s) are still running.` : body.teardownConfirmed === false ? editPhase === "starting" || editPhase === "running" ? "Studio still reports a multiplayer test in progress, but no server or client plugin answered; its windows may still be opening. Call end again, or close its Server and client windows in Studio." : 'Multiplayer playtest end requested; teardown still in progress. Use multiplayer_playtest action="status" to confirm.' : closedTestWindows !== void 0 ? `Multiplayer playtest ended; closed ${closedTestWindows} test window(s) that were still running.` : "Multiplayer playtest ended.",
26081
+ teardownConfirmed: body.teardownConfirmed === true,
26082
+ closedTestWindows,
26083
+ remainingTestWindows,
26084
+ testWindowError: typeof body.testWindowError === "string" ? body.testWindowError : void 0,
26085
+ editPhase: body.teardownConfirmed === false ? editPhase : void 0,
26086
+ testWindowTracking: typeof body.testWindowTracking === "string" ? body.testWindowTracking : void 0
25634
26087
  } : {
25635
26088
  success: false,
25636
26089
  action,
@@ -25662,6 +26115,18 @@ var RobloxStudioTools = class {
25662
26115
  runtimeRoles: existingRuntime.map((target) => target.role)
25663
26116
  });
25664
26117
  }
26118
+ const staleListing = await this._listTestWindows(editTarget.instanceId);
26119
+ if (staleListing.status === "ok" && staleListing.processes.length > 0) {
26120
+ const { phase } = await this._multiplayerEditSession(editTarget.instanceId);
26121
+ return this._textResult({
26122
+ success: false,
26123
+ error: "stale_test_windows",
26124
+ message: isActiveMultiplayerPhase(phase) ? `Studio is still starting a multiplayer test: ${staleListing.processes.length} test window(s) are open and no plugin has connected yet. Wait for it, or end it with multiplayer_playtest action="end".` : `${staleListing.processes.length} test window(s) of this Studio are running without a connected MCP plugin. Close them with multiplayer_playtest action="end", then start again.`,
26125
+ testWindows: staleListing.processes.length,
26126
+ editPhase: phase,
26127
+ roles: this._rolesForScope(editTarget.instanceId)
26128
+ });
26129
+ }
25665
26130
  const startedAt = Date.now();
25666
26131
  const response = await this._requestPeer("/api/multiplayer-test-start", { numPlayers, testArgs: testArgs ?? {} }, editTarget.targetPeerId);
25667
26132
  const groupId = typeof response?.testId === "string" ? response.testId : void 0;
@@ -25675,9 +26140,17 @@ var RobloxStudioTools = class {
25675
26140
  }
25676
26141
  await this.bridge.createMultiplayerGroupEverywhere(groupId, editTarget.instanceId);
25677
26142
  const readyTimeoutS = timeout ?? DEFAULT_PLAYTEST_READY_TIMEOUT_S;
25678
- const wait = await this._waitForMultiplayerStart(editTarget.instanceId, numPlayers, readyTimeoutS, startedAt, signal);
26143
+ let wait;
26144
+ let readiness;
26145
+ try {
26146
+ wait = await this._waitForMultiplayerStart(editTarget.instanceId, numPlayers, readyTimeoutS, startedAt, signal);
26147
+ readiness = wait.ok ? await this._waitForRuntimeEval(editTarget.instanceId, startedAt + readyTimeoutS * 1e3, signal) : void 0;
26148
+ } catch (error) {
26149
+ await this._teardownFailedStart(editTarget.instanceId, groupId);
26150
+ throw error;
26151
+ }
25679
26152
  const launched = wait.ok;
25680
- const readiness = wait.ok ? await this._waitForRuntimeEval(editTarget.instanceId, startedAt + readyTimeoutS * 1e3, signal) : void 0;
26153
+ const startTeardown = wait.ok || wait.phase === "failed" ? void 0 : await this._teardownFailedStart(editTarget.instanceId, groupId);
25681
26154
  const state = await this._buildMultiplayerState(editTarget.instanceId);
25682
26155
  const success = wait.ok && readiness?.ready === true;
25683
26156
  const runtimeStillConnected = this._runtimeTargetsForScope(editTarget.instanceId).length > 0;
@@ -25706,15 +26179,41 @@ var RobloxStudioTools = class {
25706
26179
  disconnected: evalFailure?.disconnected,
25707
26180
  state,
25708
26181
  error: success ? void 0 : startFailure?.error ?? (readiness?.ready === false ? "runtime_eval_not_ready" : wait.error ?? "multiplayer_start_not_detected"),
25709
- message: success ? "Multiplayer Studio test started and every runtime peer answered an eval." : startFailure?.message ?? (evalFailure?.disconnected ? `Multiplayer Studio test started, but ${evalFailure.disconnected.join(", ")} disconnected before answering an eval.` : evalFailure ? "Multiplayer Studio test started, but some runtime peers did not answer an eval before ready_timeout_s." : "Multiplayer Studio test start was requested, but MCP did not detect the required server/client peers before timeout."),
26182
+ message: success ? "Multiplayer Studio test started and every runtime peer answered an eval." : startFailure?.message ?? (evalFailure?.disconnected ? `Multiplayer Studio test started, but ${evalFailure.disconnected.join(", ")} disconnected before answering an eval.` : evalFailure ? "Multiplayer Studio test started, but some runtime peers did not answer an eval before ready_timeout_s." : "Multiplayer Studio test start was requested, but MCP did not detect the required server/client peers before timeout.") + (startTeardown === void 0 || startFailure !== void 0 ? "" : startTeardown.teardownConfirmed === true ? typeof startTeardown.closedTestWindows === "number" ? ` MCP ended the attempt and closed its ${startTeardown.closedTestWindows} test window(s).` : " MCP ended the attempt." : ` MCP could not confirm that the attempt's test windows closed; call multiplayer_playtest action="end".`),
25710
26183
  studioError: startFailure?.studioError,
25711
26184
  recoveryHint: startFailure?.recoveryHint ?? evalFailure?.recoveryHint,
26185
+ ...startTeardown,
25712
26186
  elapsedMs: Date.now() - startedAt,
25713
26187
  startedAt
25714
26188
  })
25715
26189
  }]
25716
26190
  };
25717
26191
  }
26192
+ // Ends a start that failed or was cancelled: through the server plugin when
26193
+ // one connected, and by closing the test's windows either way.
26194
+ async _teardownFailedStart(instanceId, testId) {
26195
+ let ended;
26196
+ try {
26197
+ ended = this._parseTextResult(await this.multiplayerTestEnd("start_failed", 30, instanceId));
26198
+ } catch (error) {
26199
+ ended = { error: error instanceof Error ? error.message : String(error) };
26200
+ }
26201
+ const closedByEnd = typeof ended.closedTestWindows === "number" ? ended.closedTestWindows : 0;
26202
+ if (ended.teardownConfirmed === true) {
26203
+ return { teardownConfirmed: true, ...closedByEnd > 0 ? { closedTestWindows: closedByEnd } : {} };
26204
+ }
26205
+ const teardown = await this._endTestWindows(instanceId, 30, 0, testId);
26206
+ const { cleanup } = teardown;
26207
+ const closed = closedByEnd + (cleanup.tracked ? cleanup.closed : 0);
26208
+ const runtimeLeft = this._runtimeTargetsForScope(instanceId).length > 0;
26209
+ return {
26210
+ teardownConfirmed: cleanup.tracked && teardown.confirmed && !runtimeLeft,
26211
+ ...closed > 0 ? { closedTestWindows: closed } : {},
26212
+ ...cleanup.tracked && cleanup.remaining > 0 ? { remainingTestWindows: cleanup.remaining } : {},
26213
+ ...cleanup.tracked && cleanup.error !== void 0 ? { testWindowError: cleanup.error } : {},
26214
+ teardownError: typeof ended.error === "string" ? ended.error : cleanup.tracked ? void 0 : `Test windows cannot be closed here: ${cleanup.reason}`
26215
+ };
26216
+ }
25718
26217
  async multiplayerTestState(instance_id) {
25719
26218
  const refresh = this.bridge.refreshTopologyForRouting();
25720
26219
  if (refresh)
@@ -25816,15 +26315,23 @@ var RobloxStudioTools = class {
25816
26315
  const group2 = this.bridge.getMultiplayerGroups().find((candidate) => candidate.instanceIds.includes(instanceId));
25817
26316
  const hasRuntime = this._rolesForScope(instanceId).some((role) => role === "server" || /^client-\d+$/.test(role));
25818
26317
  if (!hasRuntime) {
25819
- if (group2)
26318
+ const teardown2 = await this._endTestWindows(instanceId, timeout ?? 30, 0, group2?.id);
26319
+ const { cleanup } = teardown2;
26320
+ const found = cleanup.tracked ? cleanup.found : 0;
26321
+ if (group2 && teardown2.confirmed)
25820
26322
  await this.bridge.removeMultiplayerGroupEverywhere(group2.id);
25821
26323
  return this._textResult({
25822
26324
  success: true,
25823
26325
  multiplayerGroupId: group2?.id,
25824
26326
  ended: true,
25825
- alreadyEnded: true,
25826
- teardownConfirmed: true,
25827
- message: "No active multiplayer test to end (already ended)."
26327
+ alreadyEnded: found === 0 && teardown2.confirmed,
26328
+ teardownConfirmed: teardown2.confirmed,
26329
+ ...testWindowFields(cleanup),
26330
+ ...teardown2.confirmed ? {} : {
26331
+ editPhase: teardown2.editPhase,
26332
+ ...cleanup.tracked ? {} : { testWindowTracking: cleanup.reason }
26333
+ },
26334
+ message: found === 0 && teardown2.confirmed ? "No active multiplayer test to end (already ended)." : void 0
25828
26335
  });
25829
26336
  }
25830
26337
  throw error;
@@ -25839,19 +26346,30 @@ var RobloxStudioTools = class {
25839
26346
  });
25840
26347
  }
25841
26348
  const editDone = await this._waitForMultiplayerEditDone(scopeInstanceId, timeout ?? 30);
25842
- const wait = await this._waitForRuntimeRoles(scopeInstanceId, { noRuntime: true }, timeout ?? 30);
26349
+ let wait = await this._waitForRuntimeRoles(scopeInstanceId, { noRuntime: true }, timeout ?? 30);
26350
+ let teardown = await this._endTestWindows(scopeInstanceId, wait.ok ? 10 : 0, wait.ok ? TEST_WINDOW_EXIT_GRACE_MS : 0, group?.id);
26351
+ if (!wait.ok && teardown.cleanup.tracked && teardown.cleanup.closed > 0) {
26352
+ wait = await this._waitForRuntimeRoles(scopeInstanceId, { noRuntime: true }, 10);
26353
+ if (wait.ok) {
26354
+ const settled = await this._endTestWindows(scopeInstanceId, 10, 0, group?.id);
26355
+ const before = teardown.cleanup;
26356
+ teardown = settled.cleanup.tracked ? { ...settled, cleanup: { ...settled.cleanup, found: before.found + settled.cleanup.found, closed: before.closed + settled.cleanup.closed } } : settled;
26357
+ }
26358
+ }
26359
+ const teardownConfirmed = wait.ok && teardown.confirmed;
25843
26360
  const state = await this._buildMultiplayerState(scopeInstanceId);
25844
26361
  const result = this._textResult({
25845
26362
  ...response,
25846
26363
  multiplayerGroupId: group?.id,
25847
26364
  ended: response.success === true,
25848
- teardownConfirmed: wait.ok,
26365
+ teardownConfirmed,
25849
26366
  editDone,
25850
26367
  timedOut: wait.timedOut,
25851
26368
  roles: wait.roles,
26369
+ ...testWindowFields(teardown.cleanup),
25852
26370
  state
25853
26371
  });
25854
- if (wait.ok && group)
26372
+ if (teardownConfirmed && group)
25855
26373
  await this.bridge.removeMultiplayerGroupEverywhere(group.id);
25856
26374
  return result;
25857
26375
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@envnyx/robloxstudio-mcp",
3
- "version": "3.5.0",
3
+ "version": "3.6.0",
4
4
  "description": "MCP server for testing, debugging, and controlling Roblox Studio from AI coding tools",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -1794,6 +1794,69 @@ local function invokeClientCapture(entry, target, data, context)
1794
1794
  return result
1795
1795
  end
1796
1796
  local LEAVE_CLIENT_ENDPOINT = "/api/multiplayer-test-leave-client"
1797
+ -- After a client confirms its leave, a heartbeat gap this long since the later of
1798
+ -- its last heartbeat and the confirmation means its Studio process has exited.
1799
+ -- Heartbeats arrive every second; the process exits within about a second.
1800
+ local LEAVE_EXIT_SILENCE_SECONDS = 3
1801
+ -- How long the server watches a confirmed leave before handing the wait back to MCP.
1802
+ local LEAVE_EXIT_MAX_WAIT_SECONDS = 15
1803
+ local LEAVE_EXIT_POLL_SECONDS = 0.1
1804
+ -- The client answers the leave request before StudioTestService.LeaveTest runs,
1805
+ -- and the engine keeps the Player of a client that left this way until its
1806
+ -- connection timeout, about 55 s later. The client's bridge heartbeat stops with
1807
+ -- its process, so once it does, the server removes the Player itself. A client
1808
+ -- that keeps sending heartbeats is still running and is left alone: kicking it
1809
+ -- would leave its window open on a disconnect dialog.
1810
+ local function completeConfirmedLeave(call, result)
1811
+ local _result = result
1812
+ if not (type(_result) == "table") then
1813
+ return result
1814
+ end
1815
+ local reply = result
1816
+ if reply.success ~= true then
1817
+ return result
1818
+ end
1819
+ local _binding = call
1820
+ local entry = _binding.entry
1821
+ local target = _binding.target
1822
+ local playerName = entry.player.Name
1823
+ local confirmedAt = Workspace:GetServerTimeNow()
1824
+ local waitUntil = math.min(call.deadlineAt, os.clock() + LEAVE_EXIT_MAX_WAIT_SECONDS)
1825
+ while true do
1826
+ if entry.player.Parent == nil then
1827
+ unregisterProxy(entry.player, entry)
1828
+ return result
1829
+ end
1830
+ if call.context.isCancelled() or not RunService:IsRunning() or entry.heartbeat == nil then
1831
+ return result
1832
+ end
1833
+ local silenceSeconds = Workspace:GetServerTimeNow() - math.max(entry.heartbeat.receivedAt, confirmedAt)
1834
+ if silenceSeconds > LEAVE_EXIT_SILENCE_SECONDS then
1835
+ break
1836
+ end
1837
+ local remaining = waitUntil - os.clock()
1838
+ if remaining <= 0 then
1839
+ return result
1840
+ end
1841
+ task.wait(math.min(LEAVE_EXIT_POLL_SECONDS, remaining))
1842
+ end
1843
+ local kicked, kickError = pcall(function()
1844
+ return entry.player:Kick("The MCP server removed this client after it left the test.")
1845
+ end)
1846
+ if not kicked then
1847
+ local _object = table.clone(reply)
1848
+ setmetatable(_object, nil)
1849
+ _object.message = `{target} confirmed the leave and its MCP bridge stopped, but removing its Player {playerName} from the server failed: {tostring(kickError)}`
1850
+ return _object
1851
+ end
1852
+ unregisterProxy(entry.player, entry)
1853
+ local _object = table.clone(reply)
1854
+ setmetatable(_object, nil)
1855
+ _object.removedByServer = true
1856
+ _object.localPlayer = playerName
1857
+ _object.message = `{target} left and its Studio process exited. The server removed its Player {playerName} instead of waiting out the engine's connection timeout.`
1858
+ return _object
1859
+ end
1797
1860
  -- A client whose Studio process exited keeps its Player on the server until the
1798
1861
  -- engine's connection timeout, a minute or more later, but its bridge heartbeat
1799
1862
  -- stops at once. So the leave request stops waiting when the heartbeat goes
@@ -1806,7 +1869,7 @@ local function leaveClient(entry, target, data, context)
1806
1869
  if failure == nil then
1807
1870
  local outcome = invokeClient(call, LEAVE_CLIENT_ENDPOINT, data)
1808
1871
  if outcome.ok then
1809
- return outcome.result
1872
+ return completeConfirmedLeave(call, outcome.result)
1810
1873
  end
1811
1874
  failure = outcome.failure
1812
1875
  end
@@ -2778,9 +2841,9 @@ local function computeBridgeStamp()
2778
2841
  for i = 1, #combined do
2779
2842
  h = (h * 33 + (string.byte(combined, i))) % 2147483647
2780
2843
  end
2781
- -- "3.5.0" is replaced with the package version at package time
2844
+ -- "3.6.0" is replaced with the package version at package time
2782
2845
  -- (scripts/build-plugin.mjs injectVersion), so a release bump also restamps.
2783
- return `{tostring(h)}-3.5.0`
2846
+ return `{tostring(h)}-3.6.0`
2784
2847
  end
2785
2848
  local BRIDGE_STAMP = computeBridgeStamp()
2786
2849
  local function setSource(scriptInst, source)
@@ -13783,7 +13846,7 @@ return {
13783
13846
  <Properties>
13784
13847
  <string name="Name">State</string>
13785
13848
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
13786
- local CURRENT_VERSION = "3.5.0"
13849
+ local CURRENT_VERSION = "3.6.0"
13787
13850
  local PLUGIN_VARIANT = "main"
13788
13851
  local BASE_PORT = 58741
13789
13852
  local SENSITIVE_DIAGNOSTIC_TERMS = { "token", "authorization", "bearer", "password", "cookie", "secret" }