@slack/radar-mcp 1.13.0 → 1.17.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 (46) hide show
  1. package/README.md +31 -3
  2. package/dist/mcp/db-tools.js +23 -0
  3. package/dist/mcp/dispatch.d.ts +4 -0
  4. package/dist/mcp/dispatch.js +26 -0
  5. package/dist/mcp/index.js +112 -33
  6. package/dist/mcp/platform-detect.d.ts +110 -0
  7. package/dist/mcp/platform-detect.js +246 -0
  8. package/dist/mcp/prefs-tools.d.ts +4 -3
  9. package/dist/mcp/prefs-tools.js +26 -3
  10. package/dist/mcp/session-enable.js +19 -1
  11. package/dist/mcp/snapshot.js +4 -1
  12. package/dist/mcp/sources-gate.js +6 -3
  13. package/dist/mcp/tools.d.ts +11 -0
  14. package/dist/mcp/tools.js +38 -0
  15. package/dist/shared/android.d.ts +40 -1
  16. package/dist/shared/android.js +114 -51
  17. package/dist/shared/constants.d.ts +25 -1
  18. package/dist/shared/constants.js +27 -1
  19. package/dist/shared/db.js +11 -2
  20. package/dist/shared/debug-log.js +6 -1
  21. package/dist/shared/enable-diagnosis.d.ts +28 -0
  22. package/dist/shared/enable-diagnosis.js +41 -0
  23. package/dist/shared/prefs.d.ts +0 -5
  24. package/dist/shared/prefs.js +6 -2
  25. package/dist/shared/screen.d.ts +46 -9
  26. package/dist/shared/screen.js +74 -11
  27. package/dist/shared/transport.d.ts +62 -5
  28. package/dist/shared/webapp.d.ts +50 -0
  29. package/dist/shared/webapp.js +65 -0
  30. package/dist/web/bin.js +16 -6
  31. package/dist/web/install-app.d.ts +87 -0
  32. package/dist/web/install-app.js +703 -0
  33. package/dist/web/macapp/RadarApp.swift +466 -0
  34. package/dist/web/public/icons/radar-1024.png +0 -0
  35. package/dist/web/public/icons/radar.svg +40 -0
  36. package/dist/web/public/index.html +42 -1
  37. package/dist/web/public/next/app.js +42 -1
  38. package/dist/web/public/next/db.js +153 -7
  39. package/dist/web/public/next/feed.js +18 -0
  40. package/dist/web/public/next/hooks.js +10 -1
  41. package/dist/web/public/next/screen.js +156 -46
  42. package/dist/web/public/next/store.js +164 -21
  43. package/dist/web/public/next/toast.js +134 -0
  44. package/dist/web/server.d.ts +151 -1
  45. package/dist/web/server.js +579 -22
  46. package/package.json +2 -2
package/README.md CHANGED
@@ -50,7 +50,19 @@ Opens `http://localhost:8100` automatically. Set `SLACK_RADAR_WEB_PORT` to use a
50
50
  * **Preferences** — read-only browser for the on-device SharedPreferences files (pick a file, browse its keys, or search across every file at once).
51
51
  * **Custom** — a tab Claude builds on request. Ask a Claude Code session in your terminal for a view the pre-built tabs do not cover (e.g. "graph calls per second and flag the slow ones"); it authors the view via the `open_radar_dashboard` tool and it appears here. Persists until you refresh the page.
52
52
 
53
- Each tab has a rate, sparkline, graph, a filter / sort / pause feed, and a payload inspector. The filter box takes space-separated terms that must all match, `-term` to exclude, `/pattern/` for regex, and `"quoted phrases"` for spaces or a literal `-` or `/`. Committed terms turn into removable pills; a leading `-` is now the exclude operator (the old box matched it as plain text), and quoting restores the literal. Regex flags are optional and short (i/m/s/g, 1-2 letters only, so an ambiguous tail like `/api/im` reads as flags, noted in the tooltip); typos like `/error/x` become part of the pattern and match literally, and quoting any `/…/` term matches it literally. Invalid regexes and incomplete typing (e.g. `/foo(`) are ignored (the term turns amber) instead of blanking the feed. On the Live tab a kind name (`log`, `clog`, `trace`, `rtm`, `network`) also matches rows of that type, and its `-kind` form excludes by row type only, so `-log` hides logcat lines without touching a `logout` clog (quote it, `-"log"`, to exclude by text instead). Switching tabs replays what you have already seen this session (the browser caches it, bounded by count and age) so the view does not reset to empty. ADB forwarding and device activation are handled for you; a reconnect control re-arms after a device sleep. The dashboard follows your system light/dark setting by default; the theme toggle in the header overrides it and is remembered.
53
+ Each tab has a rate, sparkline, graph, a filter / sort / pause / clear feed, and a payload inspector. **Clear** empties the dashboard's own view only, so the device keeps its buffers and a reconnect or a source switch backfills recent records again (ask a Claude Code session for `clear_buffers` to wipe the device too). The filter box takes space-separated terms that must all match, `-term` to exclude, `/pattern/` for regex, and `"quoted phrases"` for spaces or a literal `-` or `/`. Committed terms turn into removable pills; a leading `-` is now the exclude operator (the old box matched it as plain text), and quoting restores the literal. Regex flags are optional and short (i/m/s/g, 1-2 letters only, so an ambiguous tail like `/api/im` reads as flags, noted in the tooltip); typos like `/error/x` become part of the pattern and match literally, and quoting any `/…/` term matches it literally. Invalid regexes and incomplete typing (e.g. `/foo(`) are ignored (the term turns amber) instead of blanking the feed. On the Live tab a kind name (`log`, `clog`, `trace`, `rtm`, `network`) also matches rows of that type, and its `-kind` form excludes by row type only, so `-log` hides logcat lines without touching a `logout` clog (quote it, `-"log"`, to exclude by text instead). Switching tabs replays what you have already seen this session (the browser caches it, bounded by count and age) so the view does not reset to empty. ADB forwarding and device activation are handled for you; a reconnect control re-arms after a device sleep. The dashboard follows your system light/dark setting by default; the theme toggle in the header overrides it and is remembered.
54
+
55
+ ### Install it to your dock (macOS)
56
+
57
+ To open Radar from the dock instead of a terminal:
58
+
59
+ ```bash
60
+ npx @slack/radar-mcp install-app
61
+ ```
62
+
63
+ That writes `~/Applications/Slack Radar.app`. Open it once, then right-click its dock icon and choose **Options > Keep in Dock**.
64
+
65
+ Clicking it starts the dashboard if it is not already running (the server auto-closes 5 minutes after the last tab closes, so this is the usual case), waits for the port, then shows it. If Xcode's command line tools are installed (`xcode-select --install`), `install-app` compiles a small native window for this — its own dock icon, its own process, no browser tab, no tab bar. Without a Swift toolchain it falls back to opening your default browser instead.
54
66
 
55
67
  ### Screen overlay
56
68
 
@@ -65,6 +77,19 @@ A **▣ Screen** button opens a side panel that mirrors the live device screen,
65
77
  * ADB with a single connected device (USB or wireless debug)
66
78
  * A debug build of Slack installed on the device (must include the `slack-radar` modules)
67
79
 
80
+ ## Environment Variables
81
+
82
+ All optional. Set them on the process that runs the MCP server or the dashboard. One further variable, `SLACK_RADAR_INITIAL_SPEC`, is set automatically when a tool spawns the dashboard and is not meant to be set by hand.
83
+
84
+ | Variable | Effect |
85
+ |---|---|
86
+ | `SLACK_RADAR_WEB_PORT` | Port the dashboard listens on. Default `8100`. |
87
+ | `SLACK_RADAR_DEVICE_PORT` | Host port forwarded to the device-side server. Default `8099`. |
88
+ | `SLACK_RADAR_NO_AUTO_CLOSE=1` | Keep the dashboard running forever instead of closing it once every tab is gone. |
89
+ | `SLACK_RADAR_ALLOWED_HOSTS` | Extra `Host` values the dashboard will answer, comma-separated (`radar.local,myhost:8100`). Only needed when you reach it by a name other than localhost. See Security. |
90
+ | `SLACK_RADAR_NO_OPEN=1` | Do not open a browser window on launch. Set automatically when an MCP tool spawns the dashboard. |
91
+ | `SLACK_RADAR_NO_FFMPEG=1` | Pretend ffmpeg is absent, so screen recording degrades to screenshots. |
92
+
68
93
  ## Session Management
69
94
 
70
95
  Radar starts **disabled** each session. All tools except `ping` return an error until enabled.
@@ -130,9 +155,9 @@ Mobile debug build (device)
130
155
  +-- public/ Static HTML/CSS/JS served to the browser
131
156
  ```
132
157
 
133
- All device-specific logic lives behind the `DeviceTransport` interface (`src/shared/transport.ts`). The MCP server, web dashboard, tools, SSE streaming, and session management are fully platform-agnostic.
158
+ All device-specific logic lives behind the `DeviceTransport` interface (`src/shared/transport.ts`). Buffers, SSE streaming, session management, and the HTTP wire protocol are platform-agnostic: the wire format is plain `GET /api/<resource>` with JSON, and adb appears only in the transport.
134
159
 
135
- **Adding a new platform**: implement `DeviceTransport` in `src/shared/<platform>.ts`, add a case to `createTransport()` in `src/mcp/index.ts`. No other files change.
160
+ **Adding a new platform**: implement `DeviceTransport` in `src/shared/<platform>.ts` and add a case to `createTransport()` in `src/mcp/index.ts`. The device-shaped operations (screenshot, screen recording, app state, device logs) are optional members, so implement what the platform supports and leave the rest absent; callers report each absent capability as "not supported on platform X". Two things stay Android-only for now and are guarded rather than abstracted: the dashboard (its flow assumes a device to arm) and adb port forwarding.
136
161
 
137
162
  ## Security
138
163
 
@@ -140,6 +165,9 @@ All device-specific logic lives behind the `DeviceTransport` interface (`src/sha
140
165
  * **Debug builds only.** Release builds bind a no-op implementation. Server code is eliminated at compile time.
141
166
  * **Lazy activation.** Dormant until explicitly triggered.
142
167
  * **Auto-shutdown.** Device-side server shuts down after idle timeout (default 5 minutes). Zero cost when unused.
168
+ * **Dashboard auto-close.** Once a dashboard has been opened in a browser, the process shuts itself down roughly 6 minutes after the last tab closes, so a dashboard you walked away from does not linger. Opening a dashboard again (`open_radar_dashboard`, which writes a spec) pushes that deadline out by another grace window, but nothing else does: the other MCP tools read the device directly and never touch the dashboard, so a long agent session with no tab open will still close on schedule. Reopen it, or use the opt-out below, if you want it to stay. Two more exceptions: a dashboard that no tab has **ever** opened (one an agent spawned and nobody visited) stays up until you visit it once or stop it, because there is no "last tab closed" moment to measure from; and when you first upgrade to a version that has auto-close, **reload any tab that was already open** — page code from before this feature does not report itself as present, so it will not keep the process alive even while you are looking at it. Reloading once is enough; later upgrades do not need it. Click **⏻ Stop dashboard** in the header to stop it immediately instead (click twice to confirm — it kills the process with no undo). Set `SLACK_RADAR_NO_AUTO_CLOSE=1` to turn auto-close off entirely.
169
+ * **Keep-alive is not forgeable from a web page.** Only the dashboard's own client and the MCP can postpone auto-close. A write to `/setspec` or `/enable` has to carry `X-Radar-Dashboard: 1`, or a content-type whose type is exactly `application/json`; the `/health` presence ping requires the header specifically, since a content-type says nothing about a request with no body. A cross-origin request cannot set either one without a CORS preflight it will fail. A request without either still works and still writes, it just does not extend the process lifetime, so `curl -X POST .../setspec -H 'Content-Type: text/plain'` sets the spec but will not stop the dashboard closing on schedule; use `-H 'Content-Type: application/json'` if you want it to count. This is a CSRF guard, not authentication: any local process can send either header, and the port is loopback-only by design.
170
+ * **Loopback `Host` only.** The dashboard answers a request only when its `Host` header names this machine (`localhost`, `127.0.0.1`, `[::1]`, `0.0.0.0`, with or without a port). Anything else gets a 403 whose body names the host it refused and how to allow it. Binding to 127.0.0.1 alone is not enough: a page that resolves its own domain to 127.0.0.1 connects locally, counts as same-origin in the browser, and could otherwise set the header above and stop your dashboard. If you reach the dashboard by some other name — a `/etc/hosts` alias, a container or Codespaces forwarded URL, your machine's LAN hostname — list it in `SLACK_RADAR_ALLOWED_HOSTS` (comma-separated, host or `host:port`). A plain SSH or VS Code port forward needs nothing, because the `Host` stays `localhost`.
143
171
 
144
172
  ## Data Capture
145
173
 
@@ -83,6 +83,17 @@ function resolveUser(transport) {
83
83
  }
84
84
  }
85
85
  export function handleListDatabases(transport) {
86
+ // shared/db.ts shells straight to adb, bypassing the transport interface entirely, so a
87
+ // transport that cannot reach on-device files must be turned away here rather than falling
88
+ // through to a db.ts call that assumes adb exists. Keyed on the CAPABILITY, not on the platform
89
+ // name: a platform check rejects every future transport by construction, whether or not it
90
+ // could actually serve this.
91
+ if (!transport.supportsLocalFileAccess) {
92
+ return {
93
+ data: { error: `Database access not supported on platform ${transport.platform}`, databases: [] },
94
+ isError: true,
95
+ };
96
+ }
86
97
  try {
87
98
  const { user, availableUsers, names } = listDatabases(resolveUser(transport));
88
99
  return { data: { user, available_users: availableUsers, databases: names }, isError: false };
@@ -94,6 +105,12 @@ export function handleListDatabases(transport) {
94
105
  export async function handleListTables(transport, db, refresh = false) {
95
106
  if (!db)
96
107
  return { data: { error: "db is required" }, isError: true };
108
+ if (!transport.supportsLocalFileAccess) {
109
+ return {
110
+ data: { error: `Database access not supported on platform ${transport.platform}`, tables: [] },
111
+ isError: true,
112
+ };
113
+ }
97
114
  const user = resolveUser(transport);
98
115
  try {
99
116
  // force=refresh re-pulls the live device copy; default reuses the cached pull so a
@@ -122,6 +139,12 @@ export async function handleQueryDatabase(transport, db, sql, refresh = false) {
122
139
  return { data: { error: "db is required" }, isError: true };
123
140
  if (!sql)
124
141
  return { data: { error: "sql is required" }, isError: true };
142
+ if (!transport.supportsLocalFileAccess) {
143
+ return {
144
+ data: { error: `Database access not supported on platform ${transport.platform}`, rows: [] },
145
+ isError: true,
146
+ };
147
+ }
125
148
  // Gate the SQL BEFORE the device pull: a rejected write/exfil query must not trigger a
126
149
  // multi-MB `exec-out cat` first. queryDatabase re-checks, so this is an early-out, not the
127
150
  // sole boundary. Running device-free, it also makes the read-only gate unit-testable here.
@@ -0,0 +1,4 @@
1
+ export declare function computeDispatch(argv1: string | undefined, sub: string | undefined): {
2
+ wantsInstallApp: boolean;
3
+ wantsWeb: boolean;
4
+ };
@@ -0,0 +1,26 @@
1
+ // Which of the three front doors a CLI invocation wants, extracted from index.ts (a top-level
2
+ // const computed from process.argv, unreachable by a unit test) into its own pure function.
3
+ //
4
+ // slack-radar -> web dashboard (the human launcher: bare = open the UI)
5
+ // slack-radar web -> web dashboard
6
+ // slack-radar install-app -> build the macOS dock launcher, then exit
7
+ // slack-radar mcp -> stdio MCP server (explicit, if a human ever needs it)
8
+ // radar-mcp -> stdio MCP server (the name MCP hosts configure; no arg)
9
+ // slack-radar-mcp -> stdio MCP server
10
+ // npx @slack/radar-mcp web -> web dashboard (npx picks the radar-mcp bin; "web" arg)
11
+ // slack-radar-web -> web dashboard (package.json points this bin straight at
12
+ // web/bin.js, bypassing this function entirely --
13
+ // listed for completeness, not resolved here)
14
+ //
15
+ // Rationale: a person typing `slack-radar` wants the UI, not a process that blocks on stdin
16
+ // looking hung. But `radar-mcp`/`slack-radar-mcp` are what editor/agent MCP configs launch with
17
+ // no args, so those MUST stay stdio. Disambiguate on the invoked bin name (argv[1]) and let an
18
+ // explicit subcommand override either way. `install-app` builds the dock launcher and exits; it
19
+ // is neither the web server nor the MCP stdio server, so it is excluded from wantsWeb -- any
20
+ // non-"mcp" subcommand on the slack-radar bin otherwise means web.
21
+ export function computeDispatch(argv1, sub) {
22
+ const binName = (argv1 ?? "").split("/").pop() ?? "";
23
+ const wantsInstallApp = sub === "install-app";
24
+ const wantsWeb = !wantsInstallApp && (sub === "web" || (binName === "slack-radar" && sub !== "mcp"));
25
+ return { wantsInstallApp, wantsWeb };
26
+ }
package/dist/mcp/index.js CHANGED
@@ -8,7 +8,9 @@ import http from "http";
8
8
  import path from "path";
9
9
  import { fileURLToPath } from "url";
10
10
  import { AndroidTransport } from "../shared/android.js";
11
- import { RADAR_HOST, RADAR_PORT, RADAR_VERSION, WEB_PORT_DEFAULT, MAX_RADAR_RESPONSE_BYTES } from "../shared/constants.js";
11
+ import { WebappTransport } from "../shared/webapp.js";
12
+ import { RADAR_HOST, RADAR_PORT, RADAR_VERSION, WEB_PORT_DEFAULT, WEBAPP_DEFAULT_PORT, MAX_RADAR_RESPONSE_BYTES, setRadarPort, } from "../shared/constants.js";
13
+ import { dashboardPlatformError, decidePlatform, pingLooksLikeWebappRadar, quickAndroidDeviceState, unsupportedCapabilityError, } from "./platform-detect.js";
12
14
  import { stopCapture } from "../shared/logcat-capture.js";
13
15
  import { getSpoolFilePath, epochFromSpoolPath, initializeSpoolDir, readSpool, startSpool, stopSpool, writeFrame, registerCleanup as registerSpoolCleanup, } from "../shared/event-spool.js";
14
16
  import { connectStream, destroyStream, waitForEvents, clearLocalBuffers, isStreamConnected, localNetworkBuffer, localRtmBuffer, setTransport, setOnReconnect, } from "../shared/stream.js";
@@ -18,33 +20,28 @@ import { querySession, clampByteCap, toNum } from "./session-query.js";
18
20
  import { resolveDetailById } from "./session-detail.js";
19
21
  import { runSessionEnable } from "./session-enable.js";
20
22
  import { applyEnableOutcome, clearSources, sourceGate } from "./sources-gate.js";
23
+ import { computeDispatch } from "./dispatch.js";
21
24
  import { backfillSpool, BACKFILL_SOURCES, makeSerializedRunner, } from "./session-backfill.js";
22
25
  import { handleListDatabases, handleListTables, handleQueryDatabase, } from "./db-tools.js";
23
26
  import { handleListPrefs, handleGetPrefs, handleSearchPrefs, } from "./prefs-tools.js";
24
27
  import { listFeatureFlags, searchFeatureFlags, getFeatureFlag, normalizeOverriddenArg, createFeatureFlagsCache, } from "./flags-tools.js";
25
28
  import { cleanupPulledDatabases, initializeDatabasePath, resetDbState, } from "../shared/db.js";
26
- import { TOOL_DEFINITIONS, SERVER_INSTRUCTIONS, sessionGate } from "./tools.js";
29
+ import { TOOL_DEFINITIONS, serverInstructions, sessionGate } from "./tools.js";
27
30
  import { buildApiPath } from "./api-paths.js";
28
31
  import { interpretRadarResponse } from "./radar-response.js";
29
32
  // --- Subcommand + bin-name dispatch ---
30
- //
31
- // One entrypoint, two front doors, chosen so each invocation does the obvious thing:
32
- //
33
- // slack-radar -> web dashboard (the human launcher: bare = open the UI)
34
- // slack-radar web -> web dashboard
35
- // slack-radar mcp -> stdio MCP server (explicit, if a human ever needs it)
36
- // radar-mcp -> stdio MCP server (the name MCP hosts configure; no arg)
37
- // slack-radar-mcp -> stdio MCP server
38
- // npx @slack/radar-mcp web -> web dashboard (npx picks the radar-mcp bin; "web" arg)
39
- // slack-radar-web -> web dashboard (dedicated bin, still works)
40
- //
41
- // Rationale: a person typing `slack-radar` wants the UI, not a process that blocks
42
- // on stdin looking hung. But `radar-mcp`/`slack-radar-mcp` are what editor/agent MCP
43
- // configs launch with no args, so those MUST stay stdio. We disambiguate on the
44
- // invoked bin name (argv[1]) and allow an explicit subcommand to override either way.
33
+ // See computeDispatch's own comment (dispatch.ts) for the full front-door table and rationale;
34
+ // pulled out to a pure function so the bin-name/subcommand rules are unit-testable.
45
35
  const sub = process.argv[2];
46
- const binName = (process.argv[1] ?? "").split("/").pop() ?? "";
47
- const wantsWeb = sub === "web" || (binName === "slack-radar" && sub !== "mcp");
36
+ const { wantsInstallApp, wantsWeb } = computeDispatch(process.argv[1], sub);
37
+ // The background check RadarApp.swift spawns on every dock launch (see install-app.ts's
38
+ // runSelfHealCheck). A sibling of install-app, not a third dispatch branch: same subcommand,
39
+ // different entry point once inside.
40
+ const wantsSelfHealCheck = wantsInstallApp && process.argv.includes("--self-heal-check");
41
+ // What RadarApp.swift ACTUALLY spawns now (see install-app.ts's runSelfHealPrecheck): a safe
42
+ // registry-version precheck that only falls through to --self-heal-check once a real upgrade is
43
+ // confirmed. Checked before wantsSelfHealCheck below so the two flags stay mutually exclusive.
44
+ const wantsSelfHealPrecheck = wantsInstallApp && process.argv.includes("--self-heal-precheck");
48
45
  // --- Web dashboard bridge (open_radar_dashboard) ---
49
46
  //
50
47
  // The MCP server and the web dashboard are separate processes. open_radar_dashboard
@@ -81,12 +78,18 @@ function startWeb(initialSpec) {
81
78
  // SLACK_RADAR_NO_OPEN: this is a bridge-spawned dashboard, so the server must NOT
82
79
  // auto-open a browser (the Claude Code session returns the URL; popping a window unbidden would
83
80
  // violate the no-auto-open-browser rule the SERVER_INSTRUCTIONS state for /radar-ui).
81
+ // Pass the resolved device port explicitly. RADAR_PORT is a mutable module binding, so a
82
+ // setRadarPort() call in this process is invisible to a child that re-evaluates the same
83
+ // expression from env: it would silently fall back to the 8099 default and talk to the wrong
84
+ // server. Inheriting env alone did not carry the override, which left the platform guard on
85
+ // open_radar_dashboard as the only thing preventing that, load-bearing by accident.
84
86
  const child = spawn(process.execPath, [WEB_BIN], {
85
87
  detached: true,
86
88
  stdio: "ignore",
87
89
  env: {
88
90
  ...process.env,
89
91
  SLACK_RADAR_NO_OPEN: "1",
92
+ SLACK_RADAR_DEVICE_PORT: String(RADAR_PORT),
90
93
  ...(initialSpec ? { SLACK_RADAR_INITIAL_SPEC: JSON.stringify(initialSpec) } : {}),
91
94
  },
92
95
  });
@@ -100,7 +103,14 @@ function postSpec(spec) {
100
103
  port: WEB_PORT,
101
104
  path: "/setspec",
102
105
  method: "POST",
103
- headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) },
106
+ // X-Radar-Dashboard marks this as an authored write, which is what lets it keep an
107
+ // MCP-driven dashboard alive with no tab open. A foreign page cannot set the header
108
+ // without a CORS preflight it fails, so it cannot forge the keep-alive.
109
+ headers: {
110
+ "Content-Type": "application/json",
111
+ "Content-Length": Buffer.byteLength(body),
112
+ "X-Radar-Dashboard": "1",
113
+ },
104
114
  timeout: 4000,
105
115
  }, (res) => {
106
116
  let b = "";
@@ -176,7 +186,21 @@ async function openDashboardSpec(spec) {
176
186
  }
177
187
  return r.json;
178
188
  }
179
- if (wantsWeb) {
189
+ if (wantsInstallApp) {
190
+ if (wantsSelfHealPrecheck) {
191
+ const { runSelfHealPrecheck } = await import("../web/install-app.js");
192
+ runSelfHealPrecheck();
193
+ }
194
+ else if (wantsSelfHealCheck) {
195
+ const { runSelfHealCheck } = await import("../web/install-app.js");
196
+ runSelfHealCheck();
197
+ }
198
+ else {
199
+ const { runInstallApp } = await import("../web/install-app.js");
200
+ runInstallApp();
201
+ }
202
+ }
203
+ else if (wantsWeb) {
180
204
  const { startWebServer } = await import("../web/bin.js");
181
205
  startWebServer();
182
206
  }
@@ -185,17 +209,50 @@ else {
185
209
  }
186
210
  async function runMcpServer() {
187
211
  // --- Platform selection ---
212
+ //
213
+ // No-flag auto-detect probes, in order: an attached adb device wins (android, exactly like today);
214
+ // a device the probe could not confirm, or confirmed as attached-but-not-usable, ALSO wins for
215
+ // android, with a note explaining which -- only a confirmed empty cable may try webapp, because
216
+ // picking android wrongly is a loud correctable failure while picking webapp wrongly silently
217
+ // serves another system's telemetry. Else a webapp Radar dev server answering on
218
+ // WEBAPP_DEFAULT_PORT wins; else fall through to android (preserves today's exact behavior/error
219
+ // for neither being present). The decision itself lives in platform-detect.ts (pure, injected
220
+ // probes) so it is unit-testable without a device or a real webapp server; this just wires the real
221
+ // probes and acts on the decision. --platform= stays an explicit manual override that skips
222
+ // auto-detection entirely.
188
223
  function createTransport() {
189
224
  const platformArg = process.argv.find((a) => a.startsWith("--platform="));
190
- const platform = platformArg?.split("=")[1] ?? "android";
191
- switch (platform) {
192
- case "android":
193
- return new AndroidTransport();
194
- default:
195
- throw new Error(`Unsupported platform: ${platform}. Supported: android`);
196
- }
225
+ const explicitPlatform = platformArg?.split("=")[1];
226
+ return decidePlatform({
227
+ explicitPlatform,
228
+ envPortOverride: !!process.env.SLACK_RADAR_DEVICE_PORT,
229
+ // A short-timeout probe (platform-detect.ts), NOT AndroidTransport.listDevices() -- this
230
+ // runs on every no-flag startup before server.connect(), so it cannot pay listDevices()'s
231
+ // 5000ms ceiling.
232
+ androidDeviceState: () => quickAndroidDeviceState(),
233
+ webappReachable: () => pingLooksLikeWebappRadar(RADAR_HOST, WEBAPP_DEFAULT_PORT),
234
+ }).then((decision) => {
235
+ switch (decision.platform) {
236
+ case "android":
237
+ // Set on every android outcome the user cannot infer from behaviour alone, which is any
238
+ // decision that did NOT come from a confirmed usable device. A confirmed device stays
239
+ // silent; a device that is attached but not ready, and a probe that could not answer, each
240
+ // say which one happened.
241
+ if (decision.note)
242
+ console.error(`[radar] ${decision.note}`);
243
+ return new AndroidTransport();
244
+ case "webapp":
245
+ // Never called on the android path: android's RADAR_PORT resolution stays
246
+ // byte-for-byte identical to today (see constants.ts).
247
+ if (decision.setPort)
248
+ setRadarPort(WEBAPP_DEFAULT_PORT);
249
+ return new WebappTransport();
250
+ case "unsupported":
251
+ throw new Error(`Unsupported platform: ${decision.requested}. Supported: android, webapp`);
252
+ }
253
+ });
197
254
  }
198
- const device = createTransport();
255
+ const device = await createTransport();
199
256
  setTransport(device);
200
257
  // Scope pulled-DB copies to THIS process by pid, then clean them on exit (mirrors the web
201
258
  // server's lifecycle). The DB tools write plaintext message-store copies to a 0600 tmp dir;
@@ -504,6 +561,10 @@ async function runMcpServer() {
504
561
  });
505
562
  }
506
563
  function handleGetAppState() {
564
+ // Absent, not throwing: the capability check IS the presence of the method (transport.ts).
565
+ if (!device.getAppState) {
566
+ return textResult({ error: unsupportedCapabilityError(device.platform, "App state query") }, true);
567
+ }
507
568
  try {
508
569
  const output = device.getAppState();
509
570
  return textResult(output);
@@ -582,6 +643,9 @@ async function runMcpServer() {
582
643
  }
583
644
  }
584
645
  function handleGetRecentLogs(args) {
646
+ if (!device.getRecentLogs) {
647
+ return textResult({ error: unsupportedCapabilityError(device.platform, "Log retrieval"), lines: [] }, true);
648
+ }
585
649
  try {
586
650
  const tag = args.tag ?? "";
587
651
  const limit = clampLogLimit(args.limit);
@@ -630,6 +694,9 @@ async function runMcpServer() {
630
694
  return textResult(JSON.stringify(querySession(frames, filter, spoolEpoch())));
631
695
  }
632
696
  function handleScreenshot(args) {
697
+ if (!device.screenshot) {
698
+ return textResult({ error: unsupportedCapabilityError(device.platform, "Screenshot") }, true);
699
+ }
633
700
  try {
634
701
  const fullRes = args?.full_res === true;
635
702
  const tmpFile = device.screenshot(fullRes);
@@ -646,6 +713,9 @@ async function runMcpServer() {
646
713
  }
647
714
  }
648
715
  function handleRecordScreen(args) {
716
+ if (!device.recordScreen) {
717
+ return textResult({ error: unsupportedCapabilityError(device.platform, "Screen recording") }, true);
718
+ }
649
719
  try {
650
720
  const duration = Math.min(Math.max(args?.duration_s || 5, 1), 30);
651
721
  const tmpFile = device.recordScreen(duration);
@@ -684,6 +754,15 @@ async function runMcpServer() {
684
754
  return textResult(result, !!result.error);
685
755
  }
686
756
  async function handleOpenDashboard(args) {
757
+ // The success copy below assumes a device dashboard ("must be enabled on it", "Reconnect
758
+ // button if the device is not yet armed"); WebappTransport.activate() is a documented no-op
759
+ // with no device/arming concept, so such a session must be turned away here rather than
760
+ // getting device-shaped language. Keyed on the capability, not the platform name, the same way
761
+ // db-tools.ts/prefs-tools.ts gate on supportsLocalFileAccess.
762
+ const platformError = dashboardPlatformError(device);
763
+ if (platformError !== null) {
764
+ return textResult({ error: platformError }, true);
765
+ }
687
766
  try {
688
767
  // The web server runs its own coerce+validate on /setspec, so a thin pass of
689
768
  // the authored args is enough; a bad spec comes back as an HTTP 400 with its
@@ -707,7 +786,7 @@ async function runMcpServer() {
707
786
  }
708
787
  }
709
788
  // --- MCP Server ---
710
- const server = new Server({ name: "slack-radar", version: "1.13.0" }, { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS });
789
+ const server = new Server({ name: "slack-radar", version: "1.17.0" }, { capabilities: { tools: {} }, instructions: serverInstructions(device.platform) });
711
790
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
712
791
  tools: TOOL_DEFINITIONS,
713
792
  }));
@@ -787,17 +866,17 @@ async function runMcpServer() {
787
866
  }
788
867
  if (name === "list_prefs") {
789
868
  const { user } = toolArgs;
790
- const { data, isError } = await handleListPrefs(user);
869
+ const { data, isError } = await handleListPrefs(device, user);
791
870
  return textResult(data, isError);
792
871
  }
793
872
  if (name === "get_prefs") {
794
873
  const { file, user, keys } = toolArgs;
795
- const { data, isError } = await handleGetPrefs(file ?? "", user, keys);
874
+ const { data, isError } = await handleGetPrefs(device, file ?? "", user, keys);
796
875
  return textResult(data, isError);
797
876
  }
798
877
  if (name === "search_prefs") {
799
878
  const { query, user } = toolArgs;
800
- const { data, isError } = await handleSearchPrefs(query ?? "", user);
879
+ const { data, isError } = await handleSearchPrefs(device, query ?? "", user);
801
880
  return textResult(data, isError);
802
881
  }
803
882
  // None of the three feature-flag tools are pure buildApiPath device-path builders: verified
@@ -0,0 +1,110 @@
1
+ /**
2
+ * What the android device probe managed to establish. Every value adb can report about what is on
3
+ * the cable maps onto exactly one of these, and each is decided explicitly in decidePlatform.
4
+ *
5
+ * A tri-state settles the "did the call work" axis; it does not by itself settle "was the answer
6
+ * ambiguous". `unusable` is that second axis: adb answered clearly, and what it said was "there is
7
+ * a device here that you cannot drive yet". Folding that into `none` reported a confirmed absence
8
+ * of something plainly present, which is how a phone with an unaccepted debugging prompt selected
9
+ * the webapp transport in silence.
10
+ */
11
+ export type DeviceAttachState =
12
+ /** At least one device in adb's "device" state: attached and usable now. */
13
+ "attached"
14
+ /** adb listed at least one device, none of them usable (unauthorized, offline, and friends). */
15
+ | "unusable"
16
+ /** adb answered, and there is genuinely nothing attached. The only state that may try webapp. */
17
+ | "none"
18
+ /** The probe never got an answer: no adb on PATH, a timeout, or a failed call. */
19
+ | "unknown";
20
+ export interface PlatformDetectInput {
21
+ /** The explicit --platform=<x> argv value, or undefined when no flag was passed. */
22
+ explicitPlatform: string | undefined;
23
+ /** True when SLACK_RADAR_DEVICE_PORT is already set: an explicit port override. */
24
+ envPortOverride: boolean;
25
+ /** Injected: what the device listing established. See DeviceAttachState. */
26
+ androidDeviceState: () => DeviceAttachState;
27
+ /** Injected: true if something answering the webapp default port's /api/ping looks like Radar. */
28
+ webappReachable: () => boolean | Promise<boolean>;
29
+ }
30
+ export type PlatformDecision = {
31
+ platform: "android";
32
+ note?: string;
33
+ } | {
34
+ platform: "webapp";
35
+ setPort: boolean;
36
+ } | {
37
+ platform: "unsupported";
38
+ requested: string;
39
+ };
40
+ /**
41
+ * The guard for open_radar_dashboard: its success copy assumes a device dashboard ("Slack Radar
42
+ * must be enabled on it", "the dashboard has its own Reconnect button if the device is not yet
43
+ * armed"), but WebappTransport.activate() is a documented no-op with no device/arming concept, so a
44
+ * transport without one must be turned away with a clean error instead. Split out here (mirroring
45
+ * decidePlatform above) so index.ts's handler logic is unit-testable without importing index.ts
46
+ * itself, which connects stdio at module load.
47
+ *
48
+ * Keyed on the CAPABILITY, not on the platform name, for the reason stated on DeviceTransport: a
49
+ * `platform !== "android"` check rejects every future transport by construction rather than by an
50
+ * actual gap. The platform name is still taken, for the message only.
51
+ *
52
+ * Returns null when it is fine to proceed, or the error string to surface when it is not.
53
+ */
54
+ export declare function dashboardPlatformError(transport: {
55
+ readonly platform: string;
56
+ readonly supportsDeviceDashboard?: boolean;
57
+ }): string | null;
58
+ /**
59
+ * The one wording for "this transport does not do that", used by every handler guarding an
60
+ * optional DeviceTransport capability. The rejection was previously spelled three different ways
61
+ * across eleven sites, and on the four device-operation tools it arrived wrapped in a
62
+ * failure-sounding prefix ("Screenshot failed: Screenshot not supported on...") because the
63
+ * transport threw and the handler's catch treated it as a runtime error. It is not a failure; the
64
+ * capability was never there.
65
+ *
66
+ * @param platform The transport's platform name, for the message only.
67
+ * @param what Sentence-leading description of the capability, e.g. "Screenshot".
68
+ */
69
+ export declare function unsupportedCapabilityError(platform: string, what: string): string;
70
+ /**
71
+ * Decide which platform createTransport() should instantiate, and whether it should call
72
+ * setRadarPort() first. Pure decision logic: the caller (index.ts) wires the real
73
+ * androidDeviceAttached/webappReachable probes and the real setRadarPort()/transport
74
+ * construction based on the returned decision.
75
+ */
76
+ export declare function decidePlatform(input: PlatformDetectInput): Promise<PlatformDecision>;
77
+ /**
78
+ * The real (non-injected) android-device-attached probe for createTransport()'s no-flag
79
+ * auto-detect path. Deliberately separate from AndroidTransport.listDevices() (shared/android.ts):
80
+ * that method keeps its existing 5000ms timeout because its other callers (selectDevice(), run
81
+ * from an explicit user action) legitimately want to wait that long, and this probe runs on
82
+ * EVERY no-flag startup before the server can even connect, so it needs a short ceiling instead.
83
+ * Matches pingLooksLikeWebappRadar's 800ms default so the two auto-detect probes cost about the
84
+ * same. Reuses parseAdbDevicesOutput (shared/android.ts) for the actual line parsing -- same
85
+ * source of truth listDevices() uses, so a future adb output-format change only needs fixing in
86
+ * one place.
87
+ *
88
+ * Reports "unknown", not "none", when it could not tell. The 800ms ceiling is SHORTER than a cold
89
+ * adb daemon's real startup (measured ~3.1s cold, and it is daemon startup rather than enumeration,
90
+ * so an empty device list costs the same), so a timeout here is an ordinary event on the first
91
+ * call after a reboot, not an exotic one. Reporting that as an absence made a slow success
92
+ * indistinguishable from a confirmed absence, and decidePlatform went on to pick webapp with a
93
+ * phone plugged in.
94
+ *
95
+ * "unusable" is the same mistake one level in: a listing that holds only unauthorized or offline
96
+ * entries is a confirmed answer, but the answer is "there is a phone here", not "there is no
97
+ * phone". An unaccepted debugging prompt is the ordinary case on a fresh machine, a new cable, or
98
+ * after an adb key reset, and it used to select webapp silently.
99
+ */
100
+ export declare function quickAndroidDeviceState(timeoutMs?: number): DeviceAttachState;
101
+ /**
102
+ * The real (non-injected) webapp reachability probe: a short-timeout GET against
103
+ * `http://<host>:<port>/api/ping`. Any response at all proves something is listening, but this
104
+ * only commits to "looks like Radar" when the parsed body has the `ok`/`target` shape Radar's
105
+ * own /api/ping returns -- a stray dev server answering something else on the same port must
106
+ * not be mistaken for Radar. host/port are parameters (not read from shared/constants.ts)
107
+ * so tests can point this at a real ephemeral local server instead of the hardcoded
108
+ * WEBAPP_DEFAULT_PORT.
109
+ */
110
+ export declare function pingLooksLikeWebappRadar(host: string, port: number, timeoutMs?: number): Promise<boolean>;