@slack/radar-mcp 1.20.0 → 1.22.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.
Files changed (91) hide show
  1. package/README.md +75 -17
  2. package/dist/mcp/api-paths.d.ts +11 -0
  3. package/dist/mcp/api-paths.js +56 -20
  4. package/dist/mcp/dashboard-identity.d.ts +6 -0
  5. package/dist/mcp/dashboard-identity.js +11 -0
  6. package/dist/mcp/index.js +138 -36
  7. package/dist/mcp/logs-result.d.ts +1 -0
  8. package/dist/mcp/logs-result.js +1 -0
  9. package/dist/mcp/network-detail.d.ts +5 -0
  10. package/dist/mcp/network-detail.js +86 -0
  11. package/dist/mcp/radar-export-get.d.ts +30 -0
  12. package/dist/mcp/radar-export-get.js +49 -0
  13. package/dist/mcp/radar-response.d.ts +11 -1
  14. package/dist/mcp/radar-response.js +23 -3
  15. package/dist/mcp/session-backfill.d.ts +9 -3
  16. package/dist/mcp/session-backfill.js +76 -17
  17. package/dist/mcp/session-detail.js +54 -2
  18. package/dist/mcp/session-enable.d.ts +1 -0
  19. package/dist/mcp/session-enable.js +146 -15
  20. package/dist/mcp/session-query.js +53 -11
  21. package/dist/mcp/snapshot.js +42 -26
  22. package/dist/mcp/sources-gate.js +5 -0
  23. package/dist/mcp/stale-dashboard.d.ts +23 -0
  24. package/dist/mcp/stale-dashboard.js +122 -0
  25. package/dist/mcp/switchboard-spool.d.ts +12 -0
  26. package/dist/mcp/switchboard-spool.js +107 -0
  27. package/dist/mcp/switchboard-tools.d.ts +18 -0
  28. package/dist/mcp/switchboard-tools.js +178 -0
  29. package/dist/mcp/tools.d.ts +4 -1
  30. package/dist/mcp/tools.js +114 -23
  31. package/dist/mcp/web-child-env.d.ts +4 -1
  32. package/dist/mcp/web-child-env.js +4 -1
  33. package/dist/shared/android.d.ts +43 -0
  34. package/dist/shared/android.js +227 -19
  35. package/dist/shared/constants.d.ts +19 -4
  36. package/dist/shared/constants.js +19 -4
  37. package/dist/shared/event-spool.js +3 -2
  38. package/dist/shared/feature-flags.d.ts +1 -0
  39. package/dist/shared/feature-flags.js +1 -0
  40. package/dist/shared/form-body.d.ts +18 -0
  41. package/dist/shared/form-body.js +251 -0
  42. package/dist/shared/ios-logs.d.ts +10 -0
  43. package/dist/shared/ios-logs.js +91 -0
  44. package/dist/shared/ios.d.ts +25 -2
  45. package/dist/shared/ios.js +157 -3
  46. package/dist/{web → shared}/log-session.d.ts +45 -31
  47. package/dist/shared/log-session.js +300 -0
  48. package/dist/shared/radar-request-raw.d.ts +7 -0
  49. package/dist/shared/radar-request-raw.js +89 -0
  50. package/dist/shared/radar-token.d.ts +25 -0
  51. package/dist/shared/radar-token.js +164 -0
  52. package/dist/shared/stream.d.ts +4 -1
  53. package/dist/shared/stream.js +107 -15
  54. package/dist/shared/switchboard-host-store.d.ts +21 -0
  55. package/dist/shared/switchboard-host-store.js +166 -0
  56. package/dist/shared/switchboard-note.d.ts +15 -0
  57. package/dist/shared/switchboard-note.js +92 -0
  58. package/dist/shared/switchboard-report-file.d.ts +5 -0
  59. package/dist/shared/switchboard-report-file.js +26 -0
  60. package/dist/shared/switchboard-report.d.ts +20 -0
  61. package/dist/shared/switchboard-report.js +406 -0
  62. package/dist/shared/switchboard.d.ts +118 -0
  63. package/dist/shared/switchboard.js +487 -0
  64. package/dist/shared/transport.d.ts +43 -3
  65. package/dist/shared/version.d.ts +2 -0
  66. package/dist/shared/version.js +18 -0
  67. package/dist/shared/wire.d.ts +46 -1
  68. package/dist/web/install-app.d.ts +57 -8
  69. package/dist/web/install-app.js +270 -60
  70. package/dist/web/macapp/RadarApp.swift +340 -22
  71. package/dist/web/public/index.html +216 -12
  72. package/dist/web/public/next/app.js +43 -22
  73. package/dist/web/public/next/db.js +4 -1
  74. package/dist/web/public/next/feed.js +604 -59
  75. package/dist/web/public/next/filters.js +158 -40
  76. package/dist/web/public/next/flags.js +3 -0
  77. package/dist/web/public/next/form-body.js +252 -0
  78. package/dist/web/public/next/inspector.js +171 -14
  79. package/dist/web/public/next/prefs.js +5 -2
  80. package/dist/web/public/next/registry.js +35 -3
  81. package/dist/web/public/next/store.js +947 -69
  82. package/dist/web/public/next/switchboard-note.js +93 -0
  83. package/dist/web/public/next/toast.js +9 -5
  84. package/dist/web/public/next/voice-model.js +712 -0
  85. package/dist/web/public/next/voice.js +552 -0
  86. package/dist/web/server.d.ts +20 -9
  87. package/dist/web/server.js +834 -174
  88. package/dist/web/spec.d.ts +11 -6
  89. package/dist/web/spec.js +62 -6
  90. package/package.json +4 -4
  91. package/dist/web/log-session.js +0 -166
package/dist/mcp/index.js CHANGED
@@ -16,11 +16,15 @@ import { RADAR_HOST, RADAR_PORT, RADAR_VERSION, WEB_PORT_DEFAULT, WEBAPP_DEFAULT
16
16
  import { dashboardPlatformError, decidePlatform, pingLooksLikeWebappRadar, quickAndroidDeviceState, unsupportedCapabilityError, } from "./platform-detect.js";
17
17
  import { stopCapture } from "../shared/logcat-capture.js";
18
18
  import { getSpoolFilePath, epochFromSpoolPath, initializeSpoolDir, readSpool, startSpool, stopSpool, writeFrame, registerCleanup as registerSpoolCleanup, } from "../shared/event-spool.js";
19
- import { connectStream, destroyStream, waitForEvents, clearLocalBuffers, isStreamConnected, localNetworkBuffer, localRtmBuffer, setTransport, setOnReconnect, } from "../shared/stream.js";
19
+ import { connectStream, destroyStream, waitForEvents, clearLocalBuffers, isStreamConnected, wasStreamRejected, clearStreamRejected, localNetworkBuffer, localRtmBuffer, setTransport, setOnReconnect, } from "../shared/stream.js";
20
+ import { makeCallRadarForExport } from "./radar-export-get.js";
21
+ import { radarRequestRaw } from "../shared/radar-request-raw.js";
22
+ import { TokenFileError, clearRadarTokenCache, openModeWarning, radarTokenHeaderFor, tokenFileMessage, unauthorizedMessageFor } from "../shared/radar-token.js";
20
23
  import { buildBufferPath, createSnapshot } from "./snapshot.js";
21
24
  import { clampLogLimit, shapeLogsResult } from "./logs-result.js";
22
25
  import { querySession, clampByteCap, toNum } from "./session-query.js";
23
26
  import { resolveDetailById } from "./session-detail.js";
27
+ import { decorateToolResult } from "./network-detail.js";
24
28
  import { runSessionEnable } from "./session-enable.js";
25
29
  import { applyEnableOutcome, clearSources, sourceGate } from "./sources-gate.js";
26
30
  import { computeDispatch } from "./dispatch.js";
@@ -30,8 +34,13 @@ import { handleListPrefs, handleGetPrefs, handleSearchPrefs, } from "./prefs-too
30
34
  import { listFeatureFlags, searchFeatureFlags, getFeatureFlag, normalizeOverriddenArg, createFeatureFlagsCache, } from "./flags-tools.js";
31
35
  import { cleanupPulledDatabases, initializeDatabasePath, resetDbState, } from "../shared/db.js";
32
36
  import { TOOL_DEFINITIONS, serverInstructions, sessionGate } from "./tools.js";
37
+ import { dashboardMatchesDevice } from "./dashboard-identity.js";
33
38
  import { buildApiPath } from "./api-paths.js";
34
- import { interpretRadarResponse } from "./radar-response.js";
39
+ import { dispatchExportSwitchboardSession, handleGetSwitchboardSession, handleGetSwitchboardSessions, shouldExportSwitchboardOffline, } from "./switchboard-tools.js";
40
+ import { getSpoolSwitchboardRecords, markSwitchboardSpoolCleared, newestSpoolSwitchboardSessionId } from "./switchboard-spool.js";
41
+ import { nonNegativeIntArg, SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES, SWITCHBOARD_EXPORT_IDLE_MS, SWITCHBOARD_EXPORT_OVERALL_MS } from "../shared/switchboard.js";
42
+ import { interpretRadarResponse, responseBudgetError, unauthorizedResponse } from "./radar-response.js";
43
+ import { buildOpenDashboardResult, readDashboardFingerprint } from "./stale-dashboard.js";
35
44
  // --- Subcommand + bin-name dispatch ---
36
45
  // See computeDispatch's own comment (dispatch.ts) for the full front-door table and rationale;
37
46
  // pulled out to a pure function so the bin-name/subcommand rules are unit-testable.
@@ -69,7 +78,7 @@ function webAlive() {
69
78
  req.end();
70
79
  });
71
80
  }
72
- function startWeb(initialSpec) {
81
+ function startWeb(device, initialSpec) {
73
82
  // Detached + unref so the dashboard outlives this MCP process; inherit env so the
74
83
  // child honors the same SLACK_RADAR_WEB_PORT. Reuse the current node binary rather
75
84
  // than assuming `node` is on PATH (MCP hosts often launch with a bare PATH).
@@ -89,7 +98,7 @@ function startWeb(initialSpec) {
89
98
  const child = spawn(process.execPath, [WEB_BIN], {
90
99
  detached: true,
91
100
  stdio: "ignore",
92
- env: webChildEnv(initialSpec),
101
+ env: webChildEnv(initialSpec, { platform: device.platform, serial: device.getSelectedDevice?.()?.serial }),
93
102
  });
94
103
  child.unref();
95
104
  }
@@ -154,12 +163,12 @@ function getSpecTitle() {
154
163
  req.end();
155
164
  });
156
165
  }
157
- async function openDashboardSpec(spec) {
166
+ async function openDashboardSpec(device, spec) {
158
167
  const cold = !(await webAlive());
159
168
  if (cold) {
160
169
  // Seed the spec into the spawned server so it is the startup writer and the browser's
161
170
  // bootDefault() never overwrites it with the Live preset (see startWeb / server.ts).
162
- startWeb(spec);
171
+ startWeb(device, spec);
163
172
  // Poll for the freshly-spawned server to start listening (~5s budget).
164
173
  for (let i = 0; i < 20; i++) {
165
174
  await new Promise((r) => setTimeout(r, 250));
@@ -167,6 +176,16 @@ async function openDashboardSpec(spec) {
167
176
  break;
168
177
  }
169
178
  }
179
+ const health = await (await fetch(`${WEB_BASE}/health`, {
180
+ // /health waits up to the device ping ceiling.
181
+ signal: AbortSignal.timeout(6000),
182
+ })).json();
183
+ const selected = device.getSelectedDevice?.()?.serial;
184
+ if (!dashboardMatchesDevice(device.platform, selected, health)) {
185
+ throw new Error("The dashboard port belongs to a different platform or device. Use a separate SLACK_RADAR_WEB_PORT.");
186
+ }
187
+ // A dashboard keeps the version it started with, so read its version on both the cold and warm paths.
188
+ const fingerprint = await readDashboardFingerprint(WEB_BASE);
170
189
  const r = await postSpec(spec);
171
190
  if (r.status !== 200) {
172
191
  throw new Error(r.json.error ?? `dashboard rejected the spec (HTTP ${r.status})`);
@@ -182,7 +201,7 @@ async function openDashboardSpec(spec) {
182
201
  break;
183
202
  await postSpec(spec);
184
203
  }
185
- return r.json;
204
+ return { ...r.json, fingerprint };
186
205
  }
187
206
  if (wantsInstallApp) {
188
207
  if (wantsSelfHealPrecheck) {
@@ -333,6 +352,14 @@ async function runMcpServer() {
333
352
  const arr = key ? res[key] : undefined;
334
353
  return Array.isArray(arr) ? arr : [];
335
354
  },
355
+ // The switchboard leg's raw GET: an error reply (a build without the plugin answers 404) is
356
+ // null, so the leg contributes nothing rather than failing the round.
357
+ fetchJson: async (apiPath) => {
358
+ const res = await callRadar(apiPath);
359
+ if (res.error)
360
+ return null;
361
+ return res;
362
+ },
336
363
  readSpool,
337
364
  write: writeFrame,
338
365
  };
@@ -374,6 +401,7 @@ async function runMcpServer() {
374
401
  const req = http.get({
375
402
  host: RADAR_HOST,
376
403
  port: RADAR_PORT,
404
+ headers: radarTokenHeaderFor(device),
377
405
  path: requestPath,
378
406
  timeout: timeoutMs,
379
407
  }, (res) => {
@@ -386,10 +414,7 @@ async function runMcpServer() {
386
414
  if (bytes > MAX_RADAR_RESPONSE_BYTES) {
387
415
  // Resolve the truncation NOW (not on "end" — req.destroy() aborts the response so
388
416
  // "end" never fires; it surfaces as an "error" the settled-guard then swallows).
389
- done({
390
- error: `Device response exceeded the ${Math.round(MAX_RADAR_RESPONSE_BYTES / 1024)}KB response budget and was dropped to protect the model context. Narrow the query (lower limit, add a name/filter), or use capture_snapshot for a bulk export.`,
391
- _truncated: true,
392
- });
417
+ done(responseBudgetError());
393
418
  req.destroy();
394
419
  return;
395
420
  }
@@ -415,9 +440,6 @@ async function runMcpServer() {
415
440
  return device.reassertForward?.() ?? device.ensureForward();
416
441
  }
417
442
  async function callRadar(requestPath) {
418
- // The host port is global and may currently be occupied by an Android adb forward. A transport
419
- // that has no Radar HTTP server (currently iOS Simulator) must stop before reassertForward():
420
- // its simulator-presence check cannot prove that the listener belongs to the selected platform.
421
443
  if (!device.supportsRadarHttpTools) {
422
444
  return {
423
445
  error: unsupportedCapabilityError(device.platform, "Radar HTTP tools"),
@@ -428,10 +450,25 @@ async function runMcpServer() {
428
450
  error: "Port forwarding failed. Ensure a device is connected and the debug build is running.",
429
451
  };
430
452
  }
453
+ const requestFromVerifiedPeer = async () => {
454
+ if (device.acceptsRadarPeer) {
455
+ const peer = await radarRequest("/api/ping", 2000);
456
+ if (!device.acceptsRadarPeer(peer)) {
457
+ return {
458
+ error: `The Radar listener on the shared host port does not belong to the selected ${device.platform} app.`,
459
+ };
460
+ }
461
+ if (requestPath === "/api/ping")
462
+ return peer;
463
+ }
464
+ if (!wasStreamRejected())
465
+ connectStream();
466
+ return radarRequest(requestPath);
467
+ };
468
+ const mismatch = (response) => unauthorizedResponse(response, device);
431
469
  device.activate(device.getTimeoutMinutes());
432
- connectStream();
433
470
  try {
434
- return await radarRequest(requestPath);
471
+ return mismatch(await requestFromVerifiedPeer());
435
472
  }
436
473
  catch {
437
474
  device.resetState();
@@ -443,9 +480,10 @@ async function runMcpServer() {
443
480
  };
444
481
  }
445
482
  device.activate(device.getTimeoutMinutes());
446
- connectStream();
483
+ // The re-arm is a fresh claim on the device, so a refusal from before it is stale.
484
+ clearStreamRejected();
447
485
  try {
448
- return await radarRequest(requestPath);
486
+ return mismatch(await requestFromVerifiedPeer());
449
487
  }
450
488
  catch (e2) {
451
489
  sessionEnabled = false;
@@ -455,6 +493,23 @@ async function runMcpServer() {
455
493
  }
456
494
  }
457
495
  }
496
+ const callRadarForExport = makeCallRadarForExport({
497
+ request: (requestPath, idleMs, overallMs, capBytes, deadline) => radarRequestRaw(RADAR_HOST, RADAR_PORT, requestPath, idleMs, overallMs, capBytes, deadline, device),
498
+ // supportsRadarHttpTools is optional on DeviceTransport; absent reads as unsupported.
499
+ supportsRadarHttpTools: () => device.supportsRadarHttpTools === true,
500
+ forwardForRead,
501
+ ensureForward: () => device.ensureForward(),
502
+ resetState: () => device.resetState(),
503
+ activate: (m) => device.activate(m),
504
+ getTimeoutMinutes: () => device.getTimeoutMinutes(),
505
+ connectStream,
506
+ wasStreamRejected,
507
+ clearStreamRejected,
508
+ destroyStream,
509
+ onSessionDisabled: () => {
510
+ sessionEnabled = false;
511
+ },
512
+ }, SWITCHBOARD_EXPORT_IDLE_MS, SWITCHBOARD_EXPORT_OVERALL_MS, SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES);
458
513
  // A model exploring feature flags in one turn tends to call list, then search, then get in
459
514
  // quick succession -- each would otherwise pay its own full device round-trip for the exact
460
515
  // same ~500-flag x 2-scope payload. A short in-process cache collapses that burst into one
@@ -496,6 +551,7 @@ async function runMcpServer() {
496
551
  // while the SDK reports an opaque error.
497
552
  try {
498
553
  sessionEnabled = true;
554
+ clearStreamRejected();
499
555
  // Off (not stale) during the enable: the previous session's list may not describe this
500
556
  // build (same device, upgraded app). Repopulated from the outcome below.
501
557
  clearSources();
@@ -504,6 +560,7 @@ async function runMcpServer() {
504
560
  destroyStream,
505
561
  connectStream,
506
562
  isStreamConnected,
563
+ wasStreamRejected,
507
564
  resetDbState,
508
565
  startSpool,
509
566
  runBackfill: runBackfillSerialized,
@@ -518,6 +575,8 @@ async function runMcpServer() {
518
575
  // spool, capture, and pulled DBs are stale for the new hardware.
519
576
  onDeviceSwitch: () => {
520
577
  clearLocalBuffers();
578
+ // Closing the spool is also what keeps the old device's switchboard records out of
579
+ // export_switchboard_session's device-free fallback.
521
580
  stopSpool();
522
581
  stopCapture();
523
582
  cleanupPulledDatabases();
@@ -542,9 +601,13 @@ async function runMcpServer() {
542
601
  }
543
602
  }
544
603
  function handleSessionDisable() {
604
+ device.stopLogCapture?.();
545
605
  sessionEnabled = false;
546
606
  clearSources();
547
607
  destroyStream();
608
+ clearStreamRejected();
609
+ // A transient device error must not clear this, but an explicit disable, a device switch, and
610
+ // process exit all do.
548
611
  clearLocalBuffers();
549
612
  featureFlagsCache.clear();
550
613
  // Explicit disable stops the logcat capture immediately. Without this, the
@@ -563,10 +626,24 @@ async function runMcpServer() {
563
626
  });
564
627
  }
565
628
  async function handleWaitForEvents(args) {
629
+ const refused = () => textResult({ error: unauthorizedMessageFor(device) }, true);
630
+ // A refused stream stays final until an enable or a re-arm; retrying here would re-broadcast the token.
631
+ if (wasStreamRejected())
632
+ return refused();
566
633
  if (!isStreamConnected()) {
567
634
  if (!forwardForRead()) {
568
635
  return textResult({ error: "Not connected. Ensure device is connected and radar is enabled." }, true);
569
636
  }
637
+ if (device.acceptsRadarPeer) {
638
+ // connectStream() checks the peer too, but only by declining to connect; without this
639
+ // the tool would wait out its timeout and report "no events" from a foreign listener.
640
+ const peer = await radarRequest("/api/ping", 2000).catch(() => null);
641
+ if (peer && !device.acceptsRadarPeer(peer)) {
642
+ return textResult({
643
+ error: `The Radar listener on the shared host port does not belong to the selected ${device.platform} app.`,
644
+ }, true);
645
+ }
646
+ }
570
647
  device.activate(device.getTimeoutMinutes());
571
648
  connectStream();
572
649
  await new Promise((r) => setTimeout(r, 1000));
@@ -578,6 +655,9 @@ async function runMcpServer() {
578
655
  timeout_ms: args?.timeout_ms,
579
656
  idle_timeout_ms: args?.idle_timeout_ms,
580
657
  });
658
+ // A 401 during the settle or the wait hands back an empty list at once.
659
+ if (events.length === 0 && wasStreamRejected())
660
+ return refused();
581
661
  return textResult({
582
662
  event_count: events.length,
583
663
  events,
@@ -621,10 +701,12 @@ async function runMcpServer() {
621
701
  }
622
702
  try {
623
703
  const timeout = args?.timeout_minutes || device.getTimeoutMinutes() || 5;
704
+ clearRadarTokenCache();
624
705
  maybe.activateForUser(args.user_id, timeout);
625
706
  // Restart the SSE stream so network/RTM/clog events from the newly
626
707
  // activated profile start flowing again.
627
708
  destroyStream();
709
+ clearStreamRejected();
628
710
  connectStream();
629
711
  // Give the newly spawned adb logcat child a moment to emit its first
630
712
  // lines to the capture file. Matches the warmup delay used by
@@ -639,7 +721,7 @@ async function runMcpServer() {
639
721
  });
640
722
  }
641
723
  catch (e) {
642
- return textResult({ error: `Profile activation failed: ${e.message}` }, true);
724
+ return textResult({ error: e instanceof TokenFileError ? tokenFileMessage(e, "profile") : `Profile activation failed: ${e.message}. Is the device connected? Check adb devices.` }, true);
643
725
  }
644
726
  }
645
727
  async function handleCaptureSnapshot(args) {
@@ -755,13 +837,19 @@ async function runMcpServer() {
755
837
  }
756
838
  }
757
839
  async function handleClearBuffers() {
840
+ // The spool stays open for query_session, so the switchboard copy is cut by a mark instead:
841
+ // without it, an export after the device ring is emptied would fall back to the pre-clear call.
758
842
  clearLocalBuffers();
843
+ markSwitchboardSpoolCleared();
759
844
  const result = await callRadar("/api/clear");
760
845
  return textResult(result, !!result.error);
761
846
  }
762
847
  async function handlePing(args) {
763
848
  if (args?.timeout_minutes) {
764
849
  device.activate(args.timeout_minutes);
850
+ const tokenFileError = device.getLastActivateTokenFileError?.();
851
+ if (tokenFileError)
852
+ return textResult({ error: tokenFileError.message, mcp_version: RADAR_VERSION }, true);
765
853
  }
766
854
  const result = await callRadar("/api/ping");
767
855
  // Version is a property of this process, not the device, so it is reported
@@ -774,6 +862,9 @@ async function runMcpServer() {
774
862
  result.local_rtm_buffer = localRtmBuffer.length;
775
863
  result.timeout_minutes = device.getTimeoutMinutes();
776
864
  result.platform = device.platform;
865
+ const warning = openModeWarning(result.token_required);
866
+ if (warning)
867
+ result.warning = warning;
777
868
  }
778
869
  return textResult(result, !!result.error);
779
870
  }
@@ -791,16 +882,8 @@ async function runMcpServer() {
791
882
  // The web server runs its own coerce+validate on /setspec, so a thin pass of
792
883
  // the authored args is enough; a bad spec comes back as an HTTP 400 with its
793
884
  // reason, which we surface verbatim rather than rendering silent zeros.
794
- const out = await openDashboardSpec(args);
795
- const url = out.url ?? WEB_BASE;
796
- return textResult({
797
- ok: true,
798
- url,
799
- title: out.title ?? args.title ?? "",
800
- note: `Custom dashboard "${out.title ?? args.title ?? ""}" is live at ${url} (the 'Custom' tab). ` +
801
- "It reads the connected device, so Slack Radar must be enabled on it — the dashboard has " +
802
- "its own Reconnect button if the device is not yet armed. Call open_radar_dashboard again to refine it.",
803
- });
885
+ const out = await openDashboardSpec(device, args);
886
+ return textResult(buildOpenDashboardResult({ ...out, title: out.title ?? args.title }, out.fingerprint, RADAR_VERSION, WEB_BASE));
804
887
  }
805
888
  catch (e) {
806
889
  return textResult({
@@ -810,7 +893,7 @@ async function runMcpServer() {
810
893
  }
811
894
  }
812
895
  // --- MCP Server ---
813
- const server = new Server({ name: "slack-radar", version: "1.20.0" }, { capabilities: { tools: {} }, instructions: serverInstructions(device.platform) });
896
+ const server = new Server({ name: "slack-radar", version: "1.22.0" }, { capabilities: { tools: {} }, instructions: serverInstructions(device.platform) });
814
897
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
815
898
  tools: TOOL_DEFINITIONS,
816
899
  }));
@@ -823,12 +906,15 @@ async function runMcpServer() {
823
906
  if (name === "_radar_session_disable") {
824
907
  return handleSessionDisable();
825
908
  }
909
+ // A host-only switchboard report needs no device call, so it may run while disabled when this
910
+ // process already spooled the records.
911
+ const allowSwitchboardExportOffline = name === "export_switchboard_session" &&
912
+ !sessionEnabled &&
913
+ shouldExportSwitchboardOffline(nonNegativeIntArg(toolArgs.id), getSpoolSwitchboardRecords, newestSpoolSwitchboardSessionId);
826
914
  // Single source of truth for the session gate (also unit-tested in tools.test.mjs).
827
- // Returns an error result when a tool requires an enabled session and there is none;
828
- // null when the tool is allowed (ping, the session enable/disable verbs, and
829
- // open_radar_dashboard — the dashboard is an independent local process with its own
830
- // device-enable Reconnect button, so opening it does not need an enabled MCP session).
831
- const gate = sessionGate(name, sessionEnabled);
915
+ // open_radar_dashboard passes while disabled because the dashboard is an independent local
916
+ // process with its own device-enable Reconnect button.
917
+ const gate = sessionGate(name, sessionEnabled, allowSwitchboardExportOffline);
832
918
  if (gate) {
833
919
  return textResult(JSON.parse(gate.content[0].text), gate.isError);
834
920
  }
@@ -929,12 +1015,28 @@ async function runMcpServer() {
929
1015
  const { data, isError } = getFeatureFlag(response, key ?? "", scope, orgId);
930
1016
  return textResult(data, isError);
931
1017
  }
1018
+ // The switchboard tools validate host-side and answer a bad id with a reason, where the generic
1019
+ // buildApiPath fallthrough below would only say "unknown tool" for a null path.
1020
+ if (name === "get_switchboard_sessions") {
1021
+ const { data, isError } = await handleGetSwitchboardSessions(callRadar);
1022
+ return textResult(data, isError);
1023
+ }
1024
+ if (name === "get_switchboard_session") {
1025
+ const { data, isError } = await handleGetSwitchboardSession(toolArgs, callRadar);
1026
+ return textResult(data, isError);
1027
+ }
1028
+ if (name === "export_switchboard_session") {
1029
+ // A disabled session only reaches here via allowSwitchboardExportOffline, and then the
1030
+ // dispatch takes the offline path, which makes no device calls.
1031
+ const { data, isError } = await dispatchExportSwitchboardSession(toolArgs, () => sessionEnabled, callRadarForExport, device);
1032
+ return textResult(data, isError);
1033
+ }
932
1034
  const apiPath = buildApiPath(name, toolArgs);
933
1035
  if (apiPath === null) {
934
1036
  return textResult(`Unknown tool: ${name}`, true);
935
1037
  }
936
1038
  const result = await callRadar(apiPath);
937
- return textResult(result, !!result.error);
1039
+ return textResult(decorateToolResult(name, result), !!result.error);
938
1040
  });
939
1041
  const transport = new StdioServerTransport();
940
1042
  await server.connect(transport);
@@ -4,6 +4,7 @@ export interface LogsToolResult {
4
4
  lines: string[];
5
5
  count: number;
6
6
  source?: string;
7
+ capture_error?: string;
7
8
  }
8
9
  export declare function clampLogLimit(limit: number | undefined): number;
9
10
  export declare function shapeLogsResult(tag: string, result: LogResult): LogsToolResult;
@@ -11,5 +11,6 @@ export function shapeLogsResult(tag, result) {
11
11
  lines: result.lines,
12
12
  count: result.lines.length,
13
13
  source: result.source,
14
+ ...(result.capture_error ? { capture_error: result.capture_error } : {}),
14
15
  };
15
16
  }
@@ -0,0 +1,5 @@
1
+ import type { RadarResponse } from "./radar-response.js";
2
+ export declare const DECODED_COPY_KEYS: readonly ["request_body_decoded", "request_body_decoded_unparsed"];
3
+ export declare function withDecodedRequestBody(input: RadarResponse): RadarResponse;
4
+ export declare function stripOwned(result: RadarResponse): RadarResponse;
5
+ export declare function decorateToolResult(name: string, result: RadarResponse): RadarResponse;
@@ -0,0 +1,86 @@
1
+ // Decorate a network-call detail with a decoded view of a form-encoded request body. Split out
2
+ // of index.ts so it is unit-testable (index connects stdio at load). The raw request_body is
3
+ // left untouched: it is the bytes a caller replays; the decoded object is a reading aid. Applied
4
+ // on the way out only, both by get_network_call_detail and by a query_session id read, so the
5
+ // spool keeps the raw record and a spool written before this existed reads the same.
6
+ import { FORM_DECODE_LIMIT_LABEL, MAX_FORM_DECODE_BYTES } from "../shared/constants.js";
7
+ import { decodeFormBody, formBodyLooksTruncated, formBodyToObject, formTextLooksTruncated, isFormBody, jsonTextLooksCut, } from "../shared/form-body.js";
8
+ const OMITTED_NOTE = `form body over ${FORM_DECODE_LIMIT_LABEL}; request_body holds the raw bytes`;
9
+ const DECODED_OMITTED_NOTE = `decoded form over ${FORM_DECODE_LIMIT_LABEL}; request_body holds the raw bytes`;
10
+ // The decoded-copy fields, the ones a byte-capped reader may drop while keeping the rest.
11
+ export const DECODED_COPY_KEYS = ["request_body_decoded", "request_body_decoded_unparsed"];
12
+ // Every field this decorator owns. The MCP is the only writer of these three (the device emits
13
+ // none of them), so a record that arrives already carrying one (a spool written by another
14
+ // version) has it recomputed here, never merged with a stale copy. request_body_truncated is not
15
+ // owned: the device knows whether its cap cut the body and a build that serializes that knowledge
16
+ // is authoritative; the shape read below only fills the flag in when the record carries none.
17
+ const OWNED_KEYS = [...DECODED_COPY_KEYS, "request_body_decoded_omitted"];
18
+ export function withDecodedRequestBody(input) {
19
+ const result = stripOwned(input);
20
+ const raw = result.request_body;
21
+ if (typeof raw !== "string")
22
+ return result;
23
+ // A record with request_content_type settles the form question; a record without it is read
24
+ // by shape. Same for the cut: a boolean request_body_truncated from the device stands, and the
25
+ // shape rules (bracket balance, a cut field name) decide only when it is absent. Shape cannot
26
+ // see a body clipped inside a plain value, which is the most ordinary cut there is.
27
+ const contentType = result.request_content_type;
28
+ const deviceFlag = typeof result.request_body_truncated === "boolean" ? result.request_body_truncated : undefined;
29
+ const cut = (byShape) => deviceFlag ?? byShape();
30
+ if (!isFormBody(raw, contentType)) {
31
+ // A JSON body the device cap cut deserves the same flag a cut form body gets, or its absence
32
+ // means nothing: a model reading a clipped body would take it for the whole request.
33
+ return cut(() => jsonTextLooksCut(raw, contentType)) ? { ...result, request_body_truncated: true } : result;
34
+ }
35
+ // Over the limit the decoded copy would be skipped anyway, so the saving is skipping
36
+ // formBodyToObject and the stringify below: the body still gets the truncation read of its
37
+ // last pair (for a single-pair body that pair is the whole body). Bytes, not string length:
38
+ // the payload leaves as UTF-8.
39
+ if (Buffer.byteLength(raw, "utf8") > MAX_FORM_DECODE_BYTES) {
40
+ const out = { ...result, request_body_decoded_omitted: OMITTED_NOTE };
41
+ if (cut(() => formTextLooksTruncated(raw)))
42
+ out.request_body_truncated = true;
43
+ return out;
44
+ }
45
+ const form = decodeFormBody(raw, contentType);
46
+ if (!form)
47
+ return result;
48
+ const out = { ...result };
49
+ const decoded = formBodyToObject(form);
50
+ // Measured as the pretty print textResult emits, in UTF-8 bytes, so the gate sees the same
51
+ // size the model does.
52
+ if (Buffer.byteLength(JSON.stringify(decoded, null, 2), "utf8") > MAX_FORM_DECODE_BYTES) {
53
+ out.request_body_decoded_omitted = DECODED_OMITTED_NOTE;
54
+ }
55
+ else {
56
+ out.request_body_decoded = decoded;
57
+ // A field whose JSON was deliberately left unparsed says so, by field name, the way the size
58
+ // gate explains itself above; otherwise the flat string reads as a value the app sent flat.
59
+ // Built without a prototype, like formBodyToObject, so a field named __proto__ survives.
60
+ const unparsed = Object.create(null);
61
+ for (const f of form.fields)
62
+ if (f.unparsedReason)
63
+ unparsed[f.key] = f.unparsedReason;
64
+ if (Object.keys(unparsed).length)
65
+ out.request_body_decoded_unparsed = Object.fromEntries(Object.entries(unparsed));
66
+ }
67
+ if (cut(() => formBodyLooksTruncated(form)))
68
+ out.request_body_truncated = true;
69
+ return out;
70
+ }
71
+ export function stripOwned(result) {
72
+ // A request_body_truncated that is not a boolean is nobody's verdict and goes too.
73
+ const junkFlag = "request_body_truncated" in result && typeof result.request_body_truncated !== "boolean";
74
+ if (!junkFlag && !OWNED_KEYS.some((k) => k in result))
75
+ return result;
76
+ const out = { ...result };
77
+ for (const k of OWNED_KEYS)
78
+ delete out[k];
79
+ if (junkFlag)
80
+ delete out.request_body_truncated;
81
+ return out;
82
+ }
83
+ // Only the detail tool carries a request body worth decoding; every other tool passes through.
84
+ export function decorateToolResult(name, result) {
85
+ return name === "get_network_call_detail" ? withDecodedRequestBody(result) : result;
86
+ }
@@ -0,0 +1,30 @@
1
+ import type { SwitchboardExportGet } from "../shared/switchboard.js";
2
+ export type RadarRequestRaw = (requestPath: string, idleMs: number, overallMs: number, capBytes: number, deadline?: number) => Promise<{
3
+ status: number;
4
+ body: Record<string, unknown> | null;
5
+ bytes?: number;
6
+ capped?: boolean;
7
+ }>;
8
+ export interface CallRadarForExportDeps {
9
+ request: RadarRequestRaw;
10
+ supportsRadarHttpTools: () => boolean;
11
+ forwardForRead: () => boolean;
12
+ ensureForward: () => boolean;
13
+ resetState: () => void;
14
+ activate: (timeoutMinutes: number) => void;
15
+ getTimeoutMinutes: () => number;
16
+ connectStream: () => void;
17
+ wasStreamRejected: () => boolean;
18
+ clearStreamRejected: () => void;
19
+ destroyStream: () => void;
20
+ onSessionDisabled: () => void;
21
+ }
22
+ /**
23
+ * Build the export path's raw device GET, retrying once after a forward rebuild like callRadar,
24
+ * but without radarRequest's model-context byte budget.
25
+ *
26
+ * A capped result is returned without retrying: the same cap would trip again, and the device
27
+ * did nothing wrong, so none of the reset/reconnect/disable side effects apply. Past the
28
+ * deadline, no further attempt is made.
29
+ */
30
+ export declare function makeCallRadarForExport(deps: CallRadarForExportDeps, idleMs: number, overallMs: number, defaultCapBytes: number): SwitchboardExportGet;
@@ -0,0 +1,49 @@
1
+ // callRadarForExport's forward-then-retry-once logic as an injectable factory, so a test can
2
+ // drive it with fakes (index.ts connects stdio at module load and cannot be imported).
3
+ /**
4
+ * Build the export path's raw device GET, retrying once after a forward rebuild like callRadar,
5
+ * but without radarRequest's model-context byte budget.
6
+ *
7
+ * A capped result is returned without retrying: the same cap would trip again, and the device
8
+ * did nothing wrong, so none of the reset/reconnect/disable side effects apply. Past the
9
+ * deadline, no further attempt is made.
10
+ */
11
+ export function makeCallRadarForExport(deps, idleMs, overallMs, defaultCapBytes) {
12
+ const msLeft = (deadline) => (deadline === undefined ? undefined : deadline - Date.now());
13
+ return async function callRadarForExport(requestPath, capBytes = defaultCapBytes, deadline) {
14
+ if (!deps.supportsRadarHttpTools())
15
+ return { status: 0, body: null };
16
+ if (!deps.forwardForRead())
17
+ return { status: 0, body: null };
18
+ const firstLeft = msLeft(deadline);
19
+ if (firstLeft !== undefined && firstLeft <= 0)
20
+ return { status: 0, body: null };
21
+ deps.activate(deps.getTimeoutMinutes());
22
+ if (!deps.wasStreamRejected())
23
+ deps.connectStream();
24
+ const first = await deps.request(requestPath, idleMs, overallMs, capBytes, deadline);
25
+ if (first.status !== 0 || first.capped)
26
+ return first;
27
+ // Out of time is not the device's fault, so skip the retry without its disable side effects.
28
+ const retryLeft = msLeft(deadline);
29
+ if (retryLeft !== undefined && retryLeft <= 0)
30
+ return first;
31
+ deps.resetState();
32
+ deps.destroyStream();
33
+ if (!deps.ensureForward()) {
34
+ deps.onSessionDisabled();
35
+ return { status: 0, body: null };
36
+ }
37
+ const secondLeft = msLeft(deadline);
38
+ if (secondLeft !== undefined && secondLeft <= 0)
39
+ return first;
40
+ deps.activate(deps.getTimeoutMinutes());
41
+ // The re-arm is a fresh claim on the device, so a refusal from before it is stale.
42
+ deps.clearStreamRejected();
43
+ deps.connectStream();
44
+ const second = await deps.request(requestPath, idleMs, overallMs, capBytes, deadline);
45
+ if (second.status === 0 && !second.capped)
46
+ deps.onSessionDisabled();
47
+ return second;
48
+ };
49
+ }
@@ -1,6 +1,8 @@
1
+ import { type RadarTokenSender } from "../shared/radar-token.js";
1
2
  export interface RadarResponse {
2
3
  error?: string;
3
- status?: number;
4
+ status?: unknown;
5
+ http_status?: number;
4
6
  stream_connected?: boolean;
5
7
  local_network_buffer?: number;
6
8
  local_rtm_buffer?: number;
@@ -19,3 +21,11 @@ export interface RadarResponse {
19
21
  * body keeps the existing {raw} behavior, a real if unusual success payload.
20
22
  */
21
23
  export declare function interpretRadarResponse(status: number, body: string): RadarResponse;
24
+ export declare function unauthorizedResponse(response: RadarResponse, sender: RadarTokenSender): RadarResponse;
25
+ /**
26
+ * The error a proxied answer gets when it would not fit the response budget. radarRequest trips it
27
+ * on the wire as the bytes arrive; a handler that receives a parsed answer through an injected
28
+ * fetch trips it after the fact. One text for both so the model sees one note either way.
29
+ */
30
+ export declare const RESPONSE_BUDGET_DEFAULT_HINT = "Narrow the query (lower limit, add a name/filter), or use capture_snapshot for a bulk export.";
31
+ export declare function responseBudgetError(hint?: string): RadarResponse;
@@ -1,6 +1,8 @@
1
1
  // The shape a proxied device call resolves to, and how a raw (status, body) becomes one. Split
2
2
  // out of index.ts so it is unit-testable: index.ts connects stdio at module load, so importing it
3
3
  // from a test would hang.
4
+ import { MAX_RADAR_RESPONSE_BYTES } from "../shared/constants.js";
5
+ import { unauthorizedMessageFor } from "../shared/radar-token.js";
4
6
  /**
5
7
  * Turn a device HTTP (status, body) into the RadarResponse the tool layer returns. Parse JSON
6
8
  * when the body is JSON: this preserves the device's own error bodies (e.g. an in-app 404 sends
@@ -23,6 +25,7 @@ export function interpretRadarResponse(status, body) {
23
25
  return {
24
26
  error: `Device returned HTTP ${status} with a non-JSON body. The route may not exist on this build (an older debug build can predate a newer tool), or an upstream error occurred.${bodyDetail}`,
25
27
  status,
28
+ http_status: status,
26
29
  };
27
30
  }
28
31
  return { raw: body };
@@ -31,8 +34,25 @@ export function interpretRadarResponse(status, body) {
31
34
  // RadarResponse, and a downstream `result.error` read on a non-object (esp. null) would throw.
32
35
  // Keep it as a raw payload instead of casting a lie. (The old code cast straight to
33
36
  // RadarResponse and carried this hole; guarding here closes it.)
34
- if (typeof parsed !== "object" || parsed === null) {
35
- return { raw: body };
37
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
38
+ return status >= 400 ? { raw: body, http_status: status } : { raw: body };
36
39
  }
37
- return parsed;
40
+ return status >= 400 ? { ...parsed, http_status: status } : parsed;
41
+ }
42
+ export function unauthorizedResponse(response, sender) {
43
+ return response.http_status === 401 ? { error: unauthorizedMessageFor(sender), http_status: 401 } : response;
44
+ }
45
+ /**
46
+ * The error a proxied answer gets when it would not fit the response budget. radarRequest trips it
47
+ * on the wire as the bytes arrive; a handler that receives a parsed answer through an injected
48
+ * fetch trips it after the fact. One text for both so the model sees one note either way.
49
+ */
50
+ // The hint is what to do instead; the default suits the ring tools, a tool capture_snapshot does
51
+ // not bundle passes its own.
52
+ export const RESPONSE_BUDGET_DEFAULT_HINT = "Narrow the query (lower limit, add a name/filter), or use capture_snapshot for a bulk export.";
53
+ export function responseBudgetError(hint = RESPONSE_BUDGET_DEFAULT_HINT) {
54
+ return {
55
+ error: `Device response exceeded the ${Math.round(MAX_RADAR_RESPONSE_BYTES / 1024)}KB response budget and was dropped to protect the model context. ${hint}`,
56
+ _truncated: true,
57
+ };
38
58
  }