@slack/radar-mcp 1.12.0 → 1.14.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/README.md CHANGED
@@ -47,6 +47,7 @@ Opens `http://localhost:8100` automatically. Set `SLACK_RADAR_WEB_PORT` to use a
47
47
  * **Traces** — performance trace spans with durations, click one for its timing and tags
48
48
  * **Logs** — device logcat, filtered to the Slack app (switch app or clear the filter)
49
49
  * **Database** — read-only browser for the on-device SQLite stores (pick a database, then a table, or run a read-only query). See the data-handling note below.
50
+ * **Preferences** — read-only browser for the on-device SharedPreferences files (pick a file, browse its keys, or search across every file at once).
50
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.
51
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.
@@ -64,6 +65,19 @@ A **▣ Screen** button opens a side panel that mirrors the live device screen,
64
65
  * ADB with a single connected device (USB or wireless debug)
65
66
  * A debug build of Slack installed on the device (must include the `slack-radar` modules)
66
67
 
68
+ ## Environment Variables
69
+
70
+ 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.
71
+
72
+ | Variable | Effect |
73
+ |---|---|
74
+ | `SLACK_RADAR_WEB_PORT` | Port the dashboard listens on. Default `8100`. |
75
+ | `SLACK_RADAR_DEVICE_PORT` | Host port forwarded to the device-side server. Default `8099`. |
76
+ | `SLACK_RADAR_NO_AUTO_CLOSE=1` | Keep the dashboard running forever instead of closing it once every tab is gone. |
77
+ | `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. |
78
+ | `SLACK_RADAR_NO_OPEN=1` | Do not open a browser window on launch. Set automatically when an MCP tool spawns the dashboard. |
79
+ | `SLACK_RADAR_NO_FFMPEG=1` | Pretend ffmpeg is absent, so screen recording degrades to screenshots. |
80
+
67
81
  ## Session Management
68
82
 
69
83
  Radar starts **disabled** each session. All tools except `ping` return an error until enabled.
@@ -102,6 +116,12 @@ Radar starts **disabled** each session. All tools except `ping` return an error
102
116
  | `list_databases` | List the app's on-device SQLite databases. Read-only. |
103
117
  | `list_tables` | List the tables in a given on-device database, with row counts. Read-only. |
104
118
  | `query_database` | Run a read-only query (SELECT, WITH, EXPLAIN, VALUES, PRAGMA) against a copy of an on-device database pulled to the host. |
119
+ | `list_prefs` | List the app's on-device SharedPreferences files. Read-only. |
120
+ | `get_prefs` | Read a preferences file's keys and values, optionally filtered to specific keys. |
121
+ | `search_prefs` | Search preference keys and values across every file by a substring. |
122
+ | `list_feature_flags` | List every feature flag with its live effective value and override status. Optionally filtered to just the overridden ones. |
123
+ | `search_feature_flags` | Case-insensitive substring search on feature flag names, against the same live list as `list_feature_flags`. |
124
+ | `get_feature_flag` | Look up one feature flag by its exact key. Returns one row per scope (authenticated/unauthenticated). |
105
125
  | `clear_buffers` | Clear all captured buffers (network, RTM, clog, trace) on the device and locally. |
106
126
  | `open_radar_dashboard` | Author or refine a custom live dashboard tab from a spec (source, filters, widgets, alerts). Suggested when a request is not covered by the pre-built tabs; not auto-invoked. Returns the dashboard URL; debug builds only, local only. |
107
127
  | `_radar_session_enable` | Enable radar for the session. Called by `/radar-enable` skill. |
@@ -133,6 +153,9 @@ All device-specific logic lives behind the `DeviceTransport` interface (`src/sha
133
153
  * **Debug builds only.** Release builds bind a no-op implementation. Server code is eliminated at compile time.
134
154
  * **Lazy activation.** Dormant until explicitly triggered.
135
155
  * **Auto-shutdown.** Device-side server shuts down after idle timeout (default 5 minutes). Zero cost when unused.
156
+ * **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.
157
+ * **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.
158
+ * **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`.
136
159
 
137
160
  ## Data Capture
138
161
 
@@ -143,6 +166,8 @@ What gets captured depends on the in-app server implementation. The MCP server i
143
166
  * **Clogs**: Analytics interceptor. Ring buffer: 1000 events. Persists across radar activation cycles.
144
167
  * **Traces**: Performance span observer. Ring buffer: 2000 spans. Persists across radar activation cycles.
145
168
  * **SQLite database** (Database tab, web dashboard only): when you open a database, a read-only **plaintext** copy of that on-device store (message text, request/response bodies, user/channel/team IDs) is pulled to a temp directory **on your own machine** (`os.tmpdir()/slack-radar-db-<port>`, files mode 0600). Auto-deleted when the dashboard process stops.
169
+ * **SharedPreferences** (`list_prefs`/`get_prefs`/`search_prefs`, and the Preferences tab): read directly off the device over `adb`, no local copy written. Files can contain feature flag overrides, cached team/org/channel IDs, and other app state.
170
+ * **Feature flags** (`list_feature_flags`/`search_feature_flags`/`get_feature_flag`): read directly off the device over `adb`, no local copy written. Shows every flag's live effective value and whether it is locally overridden.
146
171
 
147
172
  The network, RTM, clog, and trace captures are in-memory ring buffers. The Database tab is the exception: it writes a plaintext copy of the selected on-device database to a temp file on your host for the duration of the session. Review before sharing anything from it.
148
173
 
@@ -158,6 +183,7 @@ This tool captures unredacted network traffic from your debug Slack build, inclu
158
183
  * Analytics (clog) events serialized as JSON
159
184
  * Screenshots and short screen recordings on demand
160
185
  * Device logs (the app's own debug buffer, with a logcat fallback), optionally filtered by tag
186
+ * SharedPreferences files, including feature flag overrides and cached team/org/channel IDs
161
187
 
162
188
  Auth tokens and session cookies will appear in captured data. Captured data flows to your MCP client (Claude Code), which may send relevant portions to the configured AI provider per its own data handling policy.
163
189
 
@@ -102,6 +102,8 @@ export function buildApiPath(name, args) {
102
102
  params.set("limit", String(a.limit));
103
103
  return `/api/search?${params.toString()}`;
104
104
  }
105
+ // list_feature_flags/search_feature_flags/get_feature_flag are NOT here -- see
106
+ // flags-tools.ts's file header for why they fetch and filter host-side instead.
105
107
  default:
106
108
  return null;
107
109
  }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Shares one in-flight fetch of the flag list across the three tools (a model doing "list,
3
+ * then search, then get" in one turn would otherwise pay a device round-trip per call).
4
+ * Caches the PROMISE, not the resolved value, so a concurrent burst awaits the same fetch.
5
+ * An error response is not kept: the next call after it settles fetches fresh.
6
+ */
7
+ export declare function createFeatureFlagsCache<T extends {
8
+ error?: string;
9
+ }>(fetcher: () => Promise<T>, ttlMs: number, now?: () => number): {
10
+ call: () => Promise<T>;
11
+ clear: () => void;
12
+ };
13
+ export interface FeatureFlagRow {
14
+ key: string;
15
+ scope?: string;
16
+ enabled?: boolean | string;
17
+ is_overridden?: boolean;
18
+ }
19
+ interface FeatureFlagsListResponse {
20
+ feature_flags?: FeatureFlagRow[];
21
+ total_captured?: number;
22
+ error?: string;
23
+ }
24
+ /**
25
+ * Normalize the `overridden` tool arg at the handler boundary. The SDK casts args without
26
+ * enforcing the schema, so a model can send the string "false"; strict comparison downstream
27
+ * would then match nothing and return zero flags silently, the very bug class these tools
28
+ * route around. Unrecognized values mean "no filter".
29
+ */
30
+ export declare function normalizeOverriddenArg(value: unknown): boolean | undefined;
31
+ /**
32
+ * The complete flag list, optionally filtered by override status. `overridden` is applied
33
+ * host-side (see the file header for why): both true and false are filtered identically here,
34
+ * so the tool's behavior does not depend on which direction of the device's own filter
35
+ * currently works.
36
+ */
37
+ export declare function listFeatureFlags(response: FeatureFlagsListResponse, overridden?: boolean): {
38
+ data: unknown;
39
+ isError: boolean;
40
+ };
41
+ /**
42
+ * Case-insensitive substring match on flag key against an already-fetched device list.
43
+ * Returns the error verbatim if the device call itself failed, so the caller does not need
44
+ * to duplicate that check.
45
+ */
46
+ export declare function searchFeatureFlags(response: FeatureFlagsListResponse, query: string): {
47
+ data: unknown;
48
+ isError: boolean;
49
+ };
50
+ /**
51
+ * Exact-key lookup against an already-fetched device list. A miss (no row matches the key, or
52
+ * a scope is given but absent for this key) is reported as `isError: true` with a message
53
+ * naming the key or the scopes that do exist -- a model calling this tool needs to tell "your
54
+ * key or scope was wrong" apart from "found it, here are zero rows" (which never happens: a
55
+ * found key always returns at least one row), so treating a miss as an error is the correct
56
+ * and only outcome, not a fallback.
57
+ *
58
+ * A key is NOT unique on its own: every flag on a real device is listed once per scope
59
+ * (authenticated/unauthenticated), so a bare key lookup has two rows, not one (verified live,
60
+ * repeatedly, against a real Fold: every key duplicated exactly once, sometimes with
61
+ * DIFFERENT enabled/is_overridden values between the two scopes). ALWAYS returns a `rows`
62
+ * array on success, one element when the key is unambiguous, so the response shape never
63
+ * depends on how many scopes happen to exist for a given key -- a caller reads `data.rows[0]`
64
+ * (or filters/maps over `data.rows`) the same way regardless of count, rather than branching
65
+ * on whether it got a bare object or a wrapper.
66
+ */
67
+ export declare function getFeatureFlag(response: FeatureFlagsListResponse, key: string, scope?: string): {
68
+ data: unknown;
69
+ isError: boolean;
70
+ };
71
+ export {};
@@ -0,0 +1,158 @@
1
+ // Handler dispatch for list_feature_flags, search_feature_flags, and get_feature_flag. None of
2
+ // the three trust the device's own query params: verified live against a real Fold that
3
+ // ?overridden=false is silently ignored (the device build truthy-checks the query string
4
+ // "false", which is always truthy in JS/Kotlin-string terms, so it returns the COMPLETE set
5
+ // instead of filtering -- ?overridden=true works correctly, which is what let this slip past
6
+ // review). The MCP tool cannot trust one boolean direction and not the other, so all three
7
+ // fetch the unfiltered route and filter/shape entirely host-side, mirroring how the Feature
8
+ // Flags dashboard tab filters client-side after one full fetch. A device-side fix is the real
9
+ // fix (tracked separately); this stays the correct behavior either way once that ships, since
10
+ // filtering an already-correct list is a no-op.
11
+ import { friendlyFeatureFlagError } from "../shared/feature-flags.js";
12
+ /**
13
+ * Shares one in-flight fetch of the flag list across the three tools (a model doing "list,
14
+ * then search, then get" in one turn would otherwise pay a device round-trip per call).
15
+ * Caches the PROMISE, not the resolved value, so a concurrent burst awaits the same fetch.
16
+ * An error response is not kept: the next call after it settles fetches fresh.
17
+ */
18
+ export function createFeatureFlagsCache(fetcher, ttlMs, now = Date.now) {
19
+ let cached = null;
20
+ return {
21
+ call: async () => {
22
+ const t = now();
23
+ if (cached && t - cached.at < ttlMs) {
24
+ return cached.promise;
25
+ }
26
+ const promise = fetcher();
27
+ cached = { at: t, promise };
28
+ const response = await promise;
29
+ if (response.error) {
30
+ cached = null;
31
+ }
32
+ return response;
33
+ },
34
+ clear: () => {
35
+ cached = null;
36
+ },
37
+ };
38
+ }
39
+ // Both tools take the already-parsed device response (the caller runs callRadar first) so
40
+ // neither one owns forward/retry/error-shaping -- that stays centralized in callRadar, same
41
+ // division of labor as every other proxied tool in index.ts. Passing the response in (not a
42
+ // device handle) also makes these two functions pure and unit-testable without a fake transport.
43
+ /**
44
+ * Filter response.feature_flags down to well-formed rows (a real object with a string `key`).
45
+ * The response comes from an already-JSON-parsed device body with a TypeScript cast, not a
46
+ * runtime schema check, so a version-skewed or misbehaving device build (or a `feature_flags`
47
+ * that is not even an array) must degrade to "zero flags" rather than throw inside a tool
48
+ * handler. Mirrors the same defensiveness the web dashboard's handleFlags applies
49
+ * (`Array.isArray(j.feature_flags)`) before trusting the device body.
50
+ */
51
+ function wellFormedRows(response) {
52
+ const raw = response.feature_flags;
53
+ if (!Array.isArray(raw))
54
+ return [];
55
+ return raw.filter((f) => typeof f === "object" && f !== null && typeof f.key === "string");
56
+ }
57
+ // Only a real boolean `true` counts as overridden. `!!f.is_overridden` would also match a
58
+ // string like `"false"` (truthy in JS) -- the exact class of bug this filter exists to work
59
+ // around -- so this normalizes strictly instead of coercing.
60
+ function isOverridden(f) {
61
+ return f.is_overridden === true;
62
+ }
63
+ /**
64
+ * Normalize the `overridden` tool arg at the handler boundary. The SDK casts args without
65
+ * enforcing the schema, so a model can send the string "false"; strict comparison downstream
66
+ * would then match nothing and return zero flags silently, the very bug class these tools
67
+ * route around. Unrecognized values mean "no filter".
68
+ */
69
+ export function normalizeOverriddenArg(value) {
70
+ if (value === true || value === "true")
71
+ return true;
72
+ if (value === false || value === "false")
73
+ return false;
74
+ return undefined;
75
+ }
76
+ /**
77
+ * The complete flag list, optionally filtered by override status. `overridden` is applied
78
+ * host-side (see the file header for why): both true and false are filtered identically here,
79
+ * so the tool's behavior does not depend on which direction of the device's own filter
80
+ * currently works.
81
+ */
82
+ export function listFeatureFlags(response, overridden) {
83
+ if (response.error) {
84
+ return { data: { error: friendlyFeatureFlagError(response.error) }, isError: true };
85
+ }
86
+ const all = wellFormedRows(response);
87
+ const feature_flags = overridden === undefined ? all : all.filter((f) => isOverridden(f) === overridden);
88
+ // total_flags is always the full list size; returned_flags counts the filtered result, same
89
+ // split as the prefs tools' total_entries vs returned_entries.
90
+ return {
91
+ data: { feature_flags, total_flags: all.length, returned_flags: feature_flags.length },
92
+ isError: false,
93
+ };
94
+ }
95
+ /**
96
+ * Case-insensitive substring match on flag key against an already-fetched device list.
97
+ * Returns the error verbatim if the device call itself failed, so the caller does not need
98
+ * to duplicate that check.
99
+ */
100
+ export function searchFeatureFlags(response, query) {
101
+ if (response.error) {
102
+ return { data: { error: friendlyFeatureFlagError(response.error) }, isError: true };
103
+ }
104
+ const all = wellFormedRows(response);
105
+ const q = query.toLowerCase();
106
+ const matches = all.filter((f) => f.key.toLowerCase().includes(q));
107
+ return {
108
+ data: {
109
+ query,
110
+ matches,
111
+ total_flags: all.length,
112
+ matched_flags: matches.length,
113
+ },
114
+ isError: false,
115
+ };
116
+ }
117
+ /**
118
+ * Exact-key lookup against an already-fetched device list. A miss (no row matches the key, or
119
+ * a scope is given but absent for this key) is reported as `isError: true` with a message
120
+ * naming the key or the scopes that do exist -- a model calling this tool needs to tell "your
121
+ * key or scope was wrong" apart from "found it, here are zero rows" (which never happens: a
122
+ * found key always returns at least one row), so treating a miss as an error is the correct
123
+ * and only outcome, not a fallback.
124
+ *
125
+ * A key is NOT unique on its own: every flag on a real device is listed once per scope
126
+ * (authenticated/unauthenticated), so a bare key lookup has two rows, not one (verified live,
127
+ * repeatedly, against a real Fold: every key duplicated exactly once, sometimes with
128
+ * DIFFERENT enabled/is_overridden values between the two scopes). ALWAYS returns a `rows`
129
+ * array on success, one element when the key is unambiguous, so the response shape never
130
+ * depends on how many scopes happen to exist for a given key -- a caller reads `data.rows[0]`
131
+ * (or filters/maps over `data.rows`) the same way regardless of count, rather than branching
132
+ * on whether it got a bare object or a wrapper.
133
+ */
134
+ export function getFeatureFlag(response, key, scope) {
135
+ if (response.error) {
136
+ return { data: { error: friendlyFeatureFlagError(response.error) }, isError: true };
137
+ }
138
+ const all = wellFormedRows(response);
139
+ const byKey = all.filter((f) => f.key === key);
140
+ if (byKey.length === 0) {
141
+ return {
142
+ data: { error: `No flag named "${key}" (case-sensitive, exact match). Use search_feature_flags or list_feature_flags to find the right name.` },
143
+ isError: true,
144
+ };
145
+ }
146
+ if (scope !== undefined) {
147
+ const exact = byKey.find((f) => f.scope === scope);
148
+ if (!exact) {
149
+ const seenScopes = byKey.map((f) => f.scope ?? "(none)").join(", ");
150
+ return {
151
+ data: { error: `Flag "${key}" exists but not with scope "${scope}". Scopes present for this key: ${seenScopes}.` },
152
+ isError: true,
153
+ };
154
+ }
155
+ return { data: { key, rows: [exact] }, isError: false };
156
+ }
157
+ return { data: { key, rows: byKey }, isError: false };
158
+ }
package/dist/mcp/index.js CHANGED
@@ -17,9 +17,11 @@ import { clampLogLimit, shapeLogsResult } from "./logs-result.js";
17
17
  import { querySession, clampByteCap, toNum } from "./session-query.js";
18
18
  import { resolveDetailById } from "./session-detail.js";
19
19
  import { runSessionEnable } from "./session-enable.js";
20
+ import { applyEnableOutcome, clearSources, sourceGate } from "./sources-gate.js";
20
21
  import { backfillSpool, BACKFILL_SOURCES, makeSerializedRunner, } from "./session-backfill.js";
21
22
  import { handleListDatabases, handleListTables, handleQueryDatabase, } from "./db-tools.js";
22
23
  import { handleListPrefs, handleGetPrefs, handleSearchPrefs, } from "./prefs-tools.js";
24
+ import { listFeatureFlags, searchFeatureFlags, getFeatureFlag, normalizeOverriddenArg, createFeatureFlagsCache, } from "./flags-tools.js";
23
25
  import { cleanupPulledDatabases, initializeDatabasePath, resetDbState, } from "../shared/db.js";
24
26
  import { TOOL_DEFINITIONS, SERVER_INSTRUCTIONS, sessionGate } from "./tools.js";
25
27
  import { buildApiPath } from "./api-paths.js";
@@ -98,7 +100,14 @@ function postSpec(spec) {
98
100
  port: WEB_PORT,
99
101
  path: "/setspec",
100
102
  method: "POST",
101
- headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) },
103
+ // X-Radar-Dashboard marks this as an authored write, which is what lets it keep an
104
+ // MCP-driven dashboard alive with no tab open. A foreign page cannot set the header
105
+ // without a CORS preflight it fails, so it cannot forge the keep-alive.
106
+ headers: {
107
+ "Content-Type": "application/json",
108
+ "Content-Length": Buffer.byteLength(body),
109
+ "X-Radar-Dashboard": "1",
110
+ },
102
111
  timeout: 4000,
103
112
  }, (res) => {
104
113
  let b = "";
@@ -372,6 +381,23 @@ async function runMcpServer() {
372
381
  }
373
382
  }
374
383
  }
384
+ // A model exploring feature flags in one turn tends to call list, then search, then get in
385
+ // quick succession -- each would otherwise pay its own full device round-trip for the exact
386
+ // same ~500-flag x 2-scope payload. A short in-process cache collapses that burst into one
387
+ // fetch. 5s is long enough to cover a multi-tool-call turn but short enough that a flag flipped
388
+ // on-device mid-session (a manual override toggle) is visible again well within a normal pause
389
+ // between turns.
390
+ //
391
+ // Caches the in-flight PROMISE, not just the resolved value: if the MCP client dispatches two
392
+ // of the three feature-flag tools concurrently (nothing about the MCP request handler
393
+ // guarantees serialization), both must await the same underlying fetch instead of each firing
394
+ // its own -- caching only the resolved response would miss this exact burst case, which is the
395
+ // whole reason this cache exists.
396
+ const FEATURE_FLAGS_CACHE_MS = 5000;
397
+ // The cache mechanics live in flags-tools.ts (createFeatureFlagsCache) where they are
398
+ // unit-tested with a fake fetcher; this wires the real callRadar in.
399
+ const featureFlagsCache = createFeatureFlagsCache(() => callRadar("/api/feature_flags"), FEATURE_FLAGS_CACHE_MS);
400
+ const callFeatureFlags = featureFlagsCache.call;
375
401
  function textResult(data, isError = false) {
376
402
  return {
377
403
  content: [
@@ -396,6 +422,9 @@ async function runMcpServer() {
396
422
  // while the SDK reports an opaque error.
397
423
  try {
398
424
  sessionEnabled = true;
425
+ // Off (not stale) during the enable: the previous session's list may not describe this
426
+ // build (same device, upgraded app). Repopulated from the outcome below.
427
+ clearSources();
399
428
  const outcome = await runSessionEnable(timeout, deviceSerial, {
400
429
  device,
401
430
  destroyStream,
@@ -418,13 +447,18 @@ async function runMcpServer() {
418
447
  stopSpool();
419
448
  stopCapture();
420
449
  cleanupPulledDatabases();
450
+ // The old device's declared sources and cached flags do not describe the new one.
451
+ clearSources();
452
+ featureFlagsCache.clear();
421
453
  },
422
454
  });
423
455
  sessionEnabled = outcome.enabled;
456
+ applyEnableOutcome(outcome);
424
457
  return textResult(outcome.body, !outcome.enabled);
425
458
  }
426
459
  catch (e) {
427
460
  sessionEnabled = false;
461
+ clearSources();
428
462
  destroyStream();
429
463
  return textResult({
430
464
  error: `Enable failed unexpectedly: ${e.message}`,
@@ -435,8 +469,10 @@ async function runMcpServer() {
435
469
  }
436
470
  function handleSessionDisable() {
437
471
  sessionEnabled = false;
472
+ clearSources();
438
473
  destroyStream();
439
474
  clearLocalBuffers();
475
+ featureFlagsCache.clear();
440
476
  // Explicit disable stops the logcat capture immediately. Without this, the
441
477
  // capture would linger up to the capture-idle timeout (15 min) after a
442
478
  // deliberate user action saying "I am done", which is surprising and
@@ -678,7 +714,7 @@ async function runMcpServer() {
678
714
  }
679
715
  }
680
716
  // --- MCP Server ---
681
- const server = new Server({ name: "slack-radar", version: "1.12.0" }, { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS });
717
+ const server = new Server({ name: "slack-radar", version: "1.14.0" }, { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS });
682
718
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
683
719
  tools: TOOL_DEFINITIONS,
684
720
  }));
@@ -700,6 +736,12 @@ async function runMcpServer() {
700
736
  if (gate) {
701
737
  return textResult(JSON.parse(gate.content[0].text), gate.isError);
702
738
  }
739
+ // Source discovery gate: on seam builds (which list their sources on ping), block a tool
740
+ // whose capture source this build does not serve, instead of letting it 404 at the route.
741
+ const missingSource = sourceGate(name);
742
+ if (missingSource) {
743
+ return textResult(missingSource, true);
744
+ }
703
745
  if (name === "open_radar_dashboard") {
704
746
  return handleOpenDashboard(toolArgs);
705
747
  }
@@ -765,6 +807,32 @@ async function runMcpServer() {
765
807
  const { data, isError } = await handleSearchPrefs(query ?? "", user);
766
808
  return textResult(data, isError);
767
809
  }
810
+ // None of the three feature-flag tools are pure buildApiPath device-path builders: verified
811
+ // live that the device's own ?overridden=false is silently ignored, so even list_feature_flags
812
+ // fetches the unfiltered route and filters host-side (see flags-tools.ts's file header).
813
+ // callFeatureFlags shares one short-lived fetch across the three tools, since a model doing
814
+ // "list, then search, then get" in one turn would otherwise pay a full device round-trip per
815
+ // call for identical data.
816
+ if (name === "list_feature_flags") {
817
+ // The SDK does not enforce the schema, so a stringized "false" must not silently filter
818
+ // to zero flags under the strict comparison downstream.
819
+ const overridden = normalizeOverriddenArg(toolArgs["overridden"]);
820
+ const response = await callFeatureFlags();
821
+ const { data, isError } = listFeatureFlags(response, overridden);
822
+ return textResult(data, isError);
823
+ }
824
+ if (name === "search_feature_flags") {
825
+ const { query } = toolArgs;
826
+ const response = await callFeatureFlags();
827
+ const { data, isError } = searchFeatureFlags(response, query ?? "");
828
+ return textResult(data, isError);
829
+ }
830
+ if (name === "get_feature_flag") {
831
+ const { key, scope } = toolArgs;
832
+ const response = await callFeatureFlags();
833
+ const { data, isError } = getFeatureFlag(response, key ?? "", scope);
834
+ return textResult(data, isError);
835
+ }
768
836
  const apiPath = buildApiPath(name, toolArgs);
769
837
  if (apiPath === null) {
770
838
  return textResult(`Unknown tool: ${name}`, true);
@@ -0,0 +1,23 @@
1
+ export interface DeviceSource {
2
+ name: string;
3
+ kind: string;
4
+ revision: number;
5
+ }
6
+ export declare const TOOL_SOURCE: Record<string, string>;
7
+ /** Cache the `sources` array from an enable ping body. Ignores bodies without one. */
8
+ export declare function recordSources(pingBody: Record<string, unknown>): void;
9
+ /** Drop the cached list (session disable or device switch). */
10
+ export declare function clearSources(): void;
11
+ /** Apply an enable outcome: a successful enable's body carries the ping fields (and on seam
12
+ * builds the sources); a failed enable leaves the gate off. */
13
+ export declare function applyEnableOutcome(outcome: {
14
+ enabled: boolean;
15
+ body: Record<string, unknown>;
16
+ }): void;
17
+ /** The cached device sources, or null when the build reported none. */
18
+ export declare function getSources(): DeviceSource[] | null;
19
+ /**
20
+ * Blocks a tool whose source the device declared absent. Returns the error body, or null when
21
+ * the tool is allowed (unmapped tool, source present, or no discovery info to gate on).
22
+ */
23
+ export declare function sourceGate(toolName: string): Record<string, unknown> | null;
@@ -0,0 +1,63 @@
1
+ // Source discovery gate. Devices with the plugin seam (slack-android-ng #123402) report a
2
+ // `sources` array on ping: [{name, kind, revision}] for every capture source the build serves.
3
+ // This module caches that list per session and blocks tools whose source the device declared
4
+ // absent, turning a raw route 404 into one uniform, actionable error.
5
+ //
6
+ // Only sources that ship as plugins on the device are gateable. Sources still hardcoded in the
7
+ // device core (network/rtm/clog) are absent from `sources` on every build today, so their tools
8
+ // must pass through; each entry joins GATEABLE_SOURCES when its device-side migration lands.
9
+ // A build that predates the seam sends no `sources` at all, which disables gating entirely.
10
+ // Tool name -> the ping `sources` name that must be present for the tool to work. Every key
11
+ // must name a real tool in TOOL_DEFINITIONS (pinned by test).
12
+ export const TOOL_SOURCE = {
13
+ get_recent_traces: "traces",
14
+ get_trace_detail: "traces",
15
+ list_feature_flags: "feature_flags",
16
+ search_feature_flags: "feature_flags",
17
+ get_feature_flag: "feature_flags",
18
+ };
19
+ // null = no discovery info (old build or no session); gating is off.
20
+ let sessionSources = null;
21
+ /** Cache the `sources` array from an enable ping body. Ignores bodies without one. */
22
+ export function recordSources(pingBody) {
23
+ const raw = pingBody["sources"];
24
+ if (!Array.isArray(raw)) {
25
+ sessionSources = null;
26
+ return;
27
+ }
28
+ sessionSources = raw.filter((s) => !!s && typeof s === "object" && typeof s.name === "string");
29
+ }
30
+ /** Drop the cached list (session disable or device switch). */
31
+ export function clearSources() {
32
+ sessionSources = null;
33
+ }
34
+ /** Apply an enable outcome: a successful enable's body carries the ping fields (and on seam
35
+ * builds the sources); a failed enable leaves the gate off. */
36
+ export function applyEnableOutcome(outcome) {
37
+ if (outcome.enabled)
38
+ recordSources(outcome.body);
39
+ else
40
+ clearSources();
41
+ }
42
+ /** The cached device sources, or null when the build reported none. */
43
+ export function getSources() {
44
+ return sessionSources;
45
+ }
46
+ /**
47
+ * Blocks a tool whose source the device declared absent. Returns the error body, or null when
48
+ * the tool is allowed (unmapped tool, source present, or no discovery info to gate on).
49
+ */
50
+ export function sourceGate(toolName) {
51
+ if (sessionSources === null)
52
+ return null;
53
+ const required = TOOL_SOURCE[toolName];
54
+ if (!required)
55
+ return null;
56
+ if (sessionSources.some((s) => s.name === required))
57
+ return null;
58
+ return {
59
+ error: `This debug build does not serve ${required}. Update the app to a build with the ${required} Radar plugin, or re-run _radar_session_enable if the device or build changed since the session started.`,
60
+ missing_source: required,
61
+ available_sources: sessionSources.map((s) => s.name),
62
+ };
63
+ }
package/dist/mcp/tools.js CHANGED
@@ -25,7 +25,8 @@ export const SERVER_INSTRUCTIONS = [
25
25
  '- "did I get X" / "did X happen" -> search(query="X") across ALL buffers, not just one',
26
26
  '- "everything since I enabled" / "the whole session" / "what did I miss" -> query_session',
27
27
  '- "check the debug logs" -> get_recent_logs (tag is OPTIONAL: pass tag="FKDebug" to filter, or omit it for all recent lines)',
28
- '- "what feature-flag overrides are set?" / "check debug_features" -> search_prefs(query="X") or get_prefs(file="debug_features_...xml"). This shows MANUAL OVERRIDES only, not effective flag state: debug_features_*.xml holds only flags the debug menu overrode, and an override is deleted once it matches the server value. A flag missing from this file can still be ON server-side -- absence means "no override," never "disabled."',
28
+ '- "is flag X on?" / "what is the effective value of X" / "what feature flags does the app have" -> get_feature_flag(key="X") / search_feature_flags(query="X") / list_feature_flags. This is the LIVE effective state (override if set, else server value), requires a debug build with the feature-flag Radar plugin.',
29
+ '- "what feature-flag overrides are set?" / "check debug_features" -> search_prefs(query="X") or get_prefs(file="debug_features_...xml"). This shows MANUAL OVERRIDES only, not effective flag state: debug_features_*.xml holds only flags the debug menu overrode, and an override is deleted once it matches the server value. A flag missing from this file can still be ON server-side -- absence means "no override," never "disabled." Prefer get_feature_flag/list_feature_flags/search_feature_flags for the actual live value; use this route only when the manual-override history itself is what is being asked about.',
29
30
  '- "what did the app remember" / "what is cached in prefs" / "what team_prefs are set" -> list_prefs then get_prefs',
30
31
  '- "save this" / "file this as a bug" / "share this" / "bundle this" / "attach to ticket" / "give me a repro" / "snapshot this" / "preserve this" / "hold this state" / "save what you just saw" -> capture_snapshot',
31
32
  "",
@@ -567,6 +568,42 @@ export const TOOL_DEFINITIONS = [
567
568
  },
568
569
  annotations: { readOnlyHint: true },
569
570
  },
571
+ {
572
+ name: "list_feature_flags",
573
+ description: "List every feature flag the app knows about right now, with its EFFECTIVE value (local override if set, else the server value) and whether that value is a local override. This is the actual live state the app is using, unlike get_prefs/search_prefs on debug_features_*.xml, which shows only manual overrides. Requires a debug build with the feature-flag Radar plugin; older builds report a clear error instead of the list.",
574
+ inputSchema: {
575
+ type: "object",
576
+ properties: {
577
+ overridden: { type: "boolean", description: "If true, return only flags with a local override active. If false, return only flags with no override (server value in effect). Omit for the complete list." },
578
+ },
579
+ },
580
+ annotations: { readOnlyHint: true },
581
+ },
582
+ {
583
+ name: "search_feature_flags",
584
+ description: "Case-insensitive substring search on feature flag names, against the same live effective-value list as list_feature_flags. Use this instead of search_prefs when you need to know whether a flag is actually ON right now, not just whether it has a manual override.",
585
+ inputSchema: {
586
+ type: "object",
587
+ properties: {
588
+ query: { type: "string", description: "Search substring, matched against the flag key (case-insensitive)." },
589
+ },
590
+ required: ["query"],
591
+ },
592
+ annotations: { readOnlyHint: true },
593
+ },
594
+ {
595
+ name: "get_feature_flag",
596
+ description: "Look up one feature flag by its exact key (case-sensitive) and return its effective value and override status. Always returns rows: an array, since every flag exists in TWO scopes (authenticated = the value for a signed-in user, unauthenticated = the value for a visitor who has not signed in yet) with potentially different values -- rows has one entry when scope is given or when the key has only one scope, two when both scopes exist and no scope was given. Use list_feature_flags or search_feature_flags first if you are not sure of the exact key.",
597
+ inputSchema: {
598
+ type: "object",
599
+ properties: {
600
+ key: { type: "string", description: "Exact flag key, e.g. 'android_some_flag'." },
601
+ scope: { type: "string", description: "Optional. 'authenticated' (signed-in user) or 'unauthenticated' (visitor). Omit to get rows for every scope that exists." },
602
+ },
603
+ required: ["key"],
604
+ },
605
+ annotations: { readOnlyHint: true },
606
+ },
570
607
  ];
571
608
  /**
572
609
  * Check whether a tool call should be blocked by the session gate.
@@ -52,12 +52,16 @@ export declare function listDatabases(user?: string | null): {
52
52
  availableUsers: string[];
53
53
  names: string[];
54
54
  };
55
+ export declare function assertCompleteSqliteFile(name: string, bytes: Buffer | undefined): void;
55
56
  /**
56
57
  * Stream a database off the device to a local 0600 copy (scoped to the target user) and
57
58
  * return its path. `run-as ... cp` into shared storage fails silently (sandbox), so the
58
- * working path is `exec-out cat` piped to a host file. Validates the SQLite magic header
59
- * so a missing DB (whose `cat` emits an error string, not file bytes) fails with a clear
60
- * message instead of being written as a junk file that later trips an opaque parse error.
59
+ * working path is `exec-out cat` piped to a host file. Validates via
60
+ * `assertCompleteSqliteFile` (magic header, page-size legality, whole-file-size) so a
61
+ * missing or truncated pull fails with a clear message instead of being written as a junk
62
+ * file that later trips an opaque parse error. Retries the pull once on a transient
63
+ * truncation before giving up: `adb exec-out` hiccups are usually a one-shot glitch, and a
64
+ * silent retry means a dashboard user never sees the error for the common case.
61
65
  *
62
66
  * WAL: Slack's on-device DBs are WAL-mode and the live app holds write connections open,
63
67
  * so recently-committed rows live in the `-wal` sidecar, NOT yet in the main file. Pulling