@slack/radar-mcp 1.20.0 → 1.21.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 (41) hide show
  1. package/README.md +11 -6
  2. package/dist/mcp/api-paths.d.ts +11 -0
  3. package/dist/mcp/api-paths.js +67 -16
  4. package/dist/mcp/index.js +24 -7
  5. package/dist/mcp/network-detail.d.ts +5 -0
  6. package/dist/mcp/network-detail.js +86 -0
  7. package/dist/mcp/radar-response.d.ts +7 -0
  8. package/dist/mcp/radar-response.js +15 -0
  9. package/dist/mcp/session-backfill.d.ts +9 -3
  10. package/dist/mcp/session-backfill.js +77 -17
  11. package/dist/mcp/session-detail.js +54 -2
  12. package/dist/mcp/session-query.js +53 -11
  13. package/dist/mcp/sources-gate.js +4 -0
  14. package/dist/mcp/switchboard-tools.d.ts +9 -0
  15. package/dist/mcp/switchboard-tools.js +40 -0
  16. package/dist/mcp/tools.js +62 -16
  17. package/dist/shared/constants.d.ts +10 -0
  18. package/dist/shared/constants.js +10 -0
  19. package/dist/shared/event-spool.js +3 -2
  20. package/dist/shared/form-body.d.ts +18 -0
  21. package/dist/shared/form-body.js +251 -0
  22. package/dist/shared/stream.d.ts +1 -1
  23. package/dist/shared/switchboard.d.ts +9 -0
  24. package/dist/shared/switchboard.js +54 -0
  25. package/dist/shared/wire.d.ts +32 -0
  26. package/dist/web/public/index.html +172 -10
  27. package/dist/web/public/next/app.js +16 -10
  28. package/dist/web/public/next/db.js +4 -1
  29. package/dist/web/public/next/feed.js +515 -57
  30. package/dist/web/public/next/filters.js +158 -40
  31. package/dist/web/public/next/form-body.js +252 -0
  32. package/dist/web/public/next/inspector.js +103 -12
  33. package/dist/web/public/next/registry.js +21 -2
  34. package/dist/web/public/next/store.js +503 -51
  35. package/dist/web/public/next/voice-model.js +532 -0
  36. package/dist/web/public/next/voice.js +397 -0
  37. package/dist/web/server.d.ts +7 -0
  38. package/dist/web/server.js +154 -16
  39. package/dist/web/spec.d.ts +10 -6
  40. package/dist/web/spec.js +61 -6
  41. package/package.json +3 -3
package/README.md CHANGED
@@ -44,17 +44,19 @@ slack-radar
44
44
 
45
45
  Opens `http://localhost:8100` automatically. Set `SLACK_RADAR_WEB_PORT` to use a different port. (`slack-radar-web` still works as a direct alias.) Tabs:
46
46
 
47
- * **Live** — network, RTM, analytics clogs, traces, and Slack-app logcat in one timeline (**level ≥** applies to the logcat lines)
47
+ * **Live** — network, RTM, analytics clogs, traces, Slack-app logcat and Switchboard voice records in one timeline (**level ≥** applies to the logcat lines). The rate and sparkline count every source together, so a voice session raises them the way RTM traffic does
48
48
  * **Network** — calls per second vs response time, every call listed, slow ones flagged
49
49
  * **RTM** — real-time websocket events
50
50
  * **Clogs** — analytics events, click one to see its payload
51
51
  * **Traces** — performance trace spans with durations, click one for its timing and tags
52
52
  * **Logs** — device logcat, filtered to the Slack app. **app** switches app or shows all apps; **level ≥** sets the lowest level to show (VERBOSE shows everything; the choice follows you between Logs and Live and waits while you visit another tab)
53
+ * **Switchboard** — the Slackbot voice transport's own records: session begin and end, connection, mic and speaking state changes, every websocket frame (← in, → out) with type and size, phase timings, and player diagnostics (re-arms, jitter trims, read stalls, pre-ready drops). Click a row for the rest of its fields; no level, so hide noise with the filter box or **exclude**, and the kinds chips on the toolbar turn one kind of record off at a time. Records arrive once a Slackbot voice session starts. A debug build that declares its sources and lacks the plugin hides the tab; one too old to declare them shows it empty. Above the feed, a session panel draws the newest session: connection, mic and speaking pills, the handshake waterfall, model/you tracks with markers for re-arms, tts.stop and focus loss, and four stat cards, at a 60 s, 5 min or whole session zoom; the audio levels are not drawn.
53
54
  * **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.
54
55
  * **Preferences** — read-only browser for the on-device SharedPreferences files (pick a file, browse its keys, or search across every file at once).
55
- * **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.
56
+ * **Feature Flags** — live view of every feature flag and experiment the Slack app knows about, with its current effective value (ON/OFF for toggles, group name for experiments), its scope, and whether it is locally overridden; updates as they change on the device. Filter by name.
57
+ * **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. A Custom view can carry `exclude` terms to hide noisy rows; add more with the **exclude…** control on the feed toolbar or the Filters panel (comma-separated there), or have the agent set them in the spec (one phrase per term, no commas or line breaks). A log view narrowed to one tag is the same kind of ask: "show me only the `<Tag>` logs, DEBUG and up, without the noisy lines" becomes a spec with `source: log`, `match: {package, tag}`, `minLevel` and `exclude`, opened as a Custom tab. Persists until you refresh the page; exclude terms are remembered in the browser only on the pre-built tabs.
56
58
 
57
- 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 `/` (curly quotes count too, and pasting text with spaces quotes it for you, unless you are mid-word or the text starts in filter syntax). The `?` at the right edge of the box opens a short legend under it. A phrase that itself contains a quote character goes in `/regex/` form instead, where quotes are plain text. 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 device-side session shuts down after its idle timeout, and an open dashboard tab now recovers that on its own: the header says there is no radar session on the device and re-enables it, once right away (or on the minute, if the session just came back and died again) and then at most once a minute, giving up after three failed attempts (a session that dies again within a minute of coming back counts as a failed attempt), or at once if the attached device changed, so the next press is yours. Only a tab you are looking at does this (a background tab never arms a device you let idle out), never a dashboard an agent opened, and **✋ stop auto re-enable** in the header turns it off for dashboards at this address if you would rather do it by hand (`SLACK_RADAR_NO_ARM=1` on the process turns it off for that process, along with the arm at launch). The dashboard follows your system light/dark setting by default; the theme toggle in the header overrides it and is remembered.
59
+ Each tab has a filter / sort / pause / clear feed and a payload inspector, most a live rate, Network and Traces a graph. **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 `/` (curly quotes count too, and pasting text with spaces quotes it for you, unless you are mid-word or the text starts in filter syntax). `-term` is page-wide and gone on reload; to keep an exclusion, use the **exclude…** control on the feed toolbar (one term, then Enter), the **exclude** row in the Filters panel (comma separated) or an agent's `exclude` on the spec: the terms show above the feed as removable chips, are saved with the tab, and on a pre-built tab are remembered in the browser when you come back; a spec an agent pushes lands as written and does not touch that memory. An exclude term written `field:value` (say `kind:frame`, the Switchboard record's own kind field; no space after the colon) hides rows whose field equals the value, case-insensitive, and a field no row carries hides nothing; plain terms match by substring, and the Switchboard tab's kind chips toggle those `kind:` terms for you. The `?` at the right edge of the box opens a short legend under it. A phrase that itself contains a quote character goes in `/regex/` form instead, where quotes are plain text. 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 row type name (`log`, `clog`, `trace`, `rtm`, `network`, `switchboard`) also matches rows of that type, and the `-log` form excludes by row type only, so it 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 device-side session shuts down after its idle timeout, and an open dashboard tab now recovers that on its own: the header says there is no radar session on the device and re-enables it, once right away (or on the minute, if the session just came back and died again) and then at most once a minute, giving up after three failed attempts (a session that dies again within a minute of coming back counts as a failed attempt), or at once if the attached device changed, so the next press is yours. Only a tab you are looking at does this (a background tab never arms a device you let idle out), never a dashboard an agent opened, and **✋ stop auto re-enable** in the header turns it off for dashboards at this address if you would rather do it by hand (`SLACK_RADAR_NO_ARM=1` on the process turns it off for that process, along with the arm at launch). The dashboard follows your system light/dark setting by default; the theme toggle in the header overrides it and is remembered. A form-encoded request body is shown decoded, field by field, JSON fields expanded; Copy cURL still carries the raw bytes. A field whose JSON nests too deep stays as text with a note saying so, and a request body the device cap cut shows a truncation banner.
58
60
 
59
61
  ### Install it to your dock (macOS)
60
62
 
@@ -123,20 +125,23 @@ Radar starts **disabled** each session. All tools except `ping` return an error
123
125
  |---|---|
124
126
  | `ping` | Health check. Returns uptime, buffer sizes, remaining session time, stream status, the Radar MCP version (`mcp_version`), and which app/profile is bound (`android_user_id`, `profile` personal/secondary, `package`). Use `timeout_minutes` to extend sessions. |
125
127
  | `get_recent_network_calls` | HTTP call summaries: method, URL, status code, duration. Filterable by URL substring and status code. |
126
- | `get_network_call_detail` | Full request/response headers and bodies for a specific call (gzip/brotli decompressed). |
128
+ | `get_network_call_detail` | Full request/response headers and bodies for a specific call (gzip/brotli decompressed). A form-encoded request body (by the record's `request_content_type`, or by shape on a build without it) also comes back decoded in `request_body_decoded`, JSON-valued fields parsed. A body, or its decoded copy, over 64 KB skips the decoded copy and `request_body_decoded_omitted` says so; a field left unparsed is named in `request_body_decoded_unparsed`. `request_body` stays the raw bytes; `request_body_truncated: true` means the device cap cut it (a build that reports the cut itself is believed, otherwise it is read from the body's shape). |
129
+ | `query_session` | The whole session from the host event spool (network, RTM, clogs, traces, switchboard), newest first, byte-capped, with a cursor to page older. An id read returns the full record, pulling the body from the device once and caching it; a network record gets the same decoded-form fields as `get_network_call_detail`; a body that cannot be pulled falls back to the summary with a note. |
127
130
  | `get_recent_rtm_events` | RTM event summaries: type, direction, channel, timestamp. Filterable by type, direction, channel. Uses subtypes (e.g. `message_changed`, not `message`). |
128
131
  | `get_rtm_event_detail` | Full RTM event JSON payload for a specific event. |
129
132
  | `get_recent_clogs` | Analytics event summaries: name and timestamp. Filterable by event name substring. Persists from app start. |
130
133
  | `get_clog_detail` | Full clog JSON payload for a specific event. |
131
134
  | `get_recent_traces` | Performance trace/span summaries: trace name, span name, duration. Filterable by name substring. |
132
135
  | `get_trace_detail` | Full trace/span detail for a specific trace, including tags. |
136
+ | `get_switchboard_sessions` | Slackbot voice (switchboard) sessions the device still holds, newest first: `session_id`, `team_id`, `began_at`, `ended_at`, record and frame counts, the newest state and audio levels. Ids restart with the app process. |
137
+ | `get_switchboard_session` | One voice session's summary plus its records, oldest first: `state` transitions, control frames (`frame`) in and out, `player` stutter events, `phase` startup timings, `session` begin and end. Narrow with `kind`; `limit` is how many of the newest records come back (default 50, max 2000), filtered by kind first, so a kind page is the newest `limit` records of that kind. |
133
138
  | `wait_for_events` | Block until matching events arrive via SSE stream. Idle-timeout based, not polling. |
134
139
  | `search` | Full-text search across network, RTM, clog, and trace buffers. |
135
140
  | `get_app_state` | Current Activity/Fragment state via `dumpsys`. Shows visible screen, parameters, tab state. |
136
- | `get_recent_logs` | Recent device logs, optionally filtered by tag (omit `tag` for all lines). Reads the app's own debug log buffer first, falling back to logcat; the result's `source` field (`app_buffer` / `logcat_capture` / `logcat_ring`) names which one served it. For Timber debug logs (`FKDebug`, `SlackRadar`, etc.). |
141
+ | `get_recent_logs` | Recent device logs, optionally filtered by tag (omit `tag` for all lines). Reads the app's own debug log buffer first, falling back to logcat; the result's `source` field (`app_buffer` / `logcat_capture` / `logcat_ring`) names which one served it. For Timber debug logs (`SlackRadar`, `OkHttp`, etc.). |
137
142
  | `list_profiles` | List the Android users and profiles on the device (personal, work, and so on). |
138
143
  | `activate_for_user` | Activate radar for a specific Android user or profile. |
139
- | `capture_snapshot` | Bundle the current network, RTM, clog, and trace buffers, plus an optional screenshot, into one saved snapshot for a bug report or repro. |
144
+ | `capture_snapshot` | Bundle the current network, RTM, clog, and trace buffers, plus an optional screenshot, into one saved snapshot for a bug report or repro. Switchboard voice records are not included. |
140
145
  | `screenshot` | Capture device screen as PNG. 720px default, `full_res=true` for full resolution. |
141
146
  | `record_screen` | Record short screen video (MP4). Default 5s, max 30s. |
142
147
  | `list_databases` | List the app's on-device SQLite databases. Read-only. |
@@ -1 +1,12 @@
1
+ import { SWITCHBOARD_KINDS, type SwitchboardKind } from "../shared/switchboard.js";
2
+ export { SWITCHBOARD_KINDS, type SwitchboardKind };
3
+ export declare const SWITCHBOARD_DEFAULT_LIMIT = 50;
4
+ export declare const SWITCHBOARD_MAX_LIMIT = 2000;
5
+ export declare function nonNegativeIntArg(v: unknown): number | null;
6
+ export declare function switchboardSessionQuery(args: Record<string, unknown>): {
7
+ path: string;
8
+ } | {
9
+ error: string;
10
+ };
11
+ export declare function clampSwitchboardLimit(limit: unknown): number;
1
12
  export declare function buildApiPath(name: string, args: Record<string, unknown>): string | null;
@@ -6,28 +6,75 @@
6
6
  //
7
7
  // The arg shapes here are the query-param subset each tool sends; they intentionally duplicate
8
8
  // the (wider) handler arg interfaces in index.ts rather than couple this pure module to them.
9
- // Build the device path for a detail-by-id tool. The MCP SDK casts args without enforcing the
10
- // JSON Schema (no zod), so `id` can arrive as a string carrying "/" or ".." even though the
11
- // schema says number. All four detail tools (network/rtm/clog/trace) read the device's OWN
12
- // forwarded server with no shell/fs, so the blast radius is small, but an un-encoded id is still
13
- // a path-traversal smell. Accept only a non-negative integer id; anything else returns null
14
- // (the caller reports "unknown tool"/no path rather than firing a malformed device request).
15
- function detailPath(resource, id) {
9
+ import { switchboardListPath, switchboardSessionPath, SWITCHBOARD_KINDS } from "../shared/switchboard.js";
10
+ // The record kinds the device's switchboard page filters on. Lower-case here; the device matches
11
+ // case-insensitively, so the query is sent normalized.
12
+ export { SWITCHBOARD_KINDS };
13
+ // The device pages at 50 without a limit and holds at most 2000 records per session.
14
+ export const SWITCHBOARD_DEFAULT_LIMIT = 50;
15
+ export const SWITCHBOARD_MAX_LIMIT = 2000;
16
+ // One id rule for every detail-by-id tool, switchboard included: a non-negative safe integer, as
17
+ // a number or as a clean digit string (the SDK casts args without enforcing the schema, so "7"
18
+ // arrives as a string). Whitespace around the digits is trimmed like clampSwitchboardLimit does.
19
+ // Anything else (negative, fractional, 1e21, "7/../x", objects, arrays, booleans) is refused.
20
+ export function nonNegativeIntArg(v) {
16
21
  let n;
17
- if (typeof id === "number") {
18
- n = id;
22
+ if (typeof v === "number") {
23
+ n = v;
19
24
  }
20
- else if (typeof id === "string" && /^\d+$/.test(id.trim())) {
21
- // a clean digit string only -- Number("") and Number(" ") are 0 and Number("1/../x") is NaN,
22
- // but "1e3"/"0x10"/" 5 " would also coerce; the \d+ test rejects all of those outright.
23
- n = Number(id.trim());
25
+ else if (typeof v === "string" && /^\d+$/.test(v.trim())) {
26
+ n = Number(v.trim());
24
27
  }
25
28
  else {
26
29
  return null;
27
30
  }
28
- if (!Number.isInteger(n) || n < 0)
29
- return null;
30
- return `/api/${resource}/${n}`;
31
+ return Number.isSafeInteger(n) && n >= 0 ? n : null;
32
+ }
33
+ // What a refused argument looks like in an error: JSON, cut at 80 characters so a huge argument
34
+ // does not become a huge error.
35
+ const ECHO_MAX = 80;
36
+ function echoArg(v) {
37
+ const s = String(JSON.stringify(v));
38
+ return s.length > ECHO_MAX ? s.slice(0, ECHO_MAX) + "..." : s;
39
+ }
40
+ // The get_switchboard_session args as a device path, or the reason they cannot be one. The path
41
+ // builders live in shared/switchboard.ts so the MCP tool and the dashboard's replay hit the same
42
+ // strings. limit is clamped to what the ring can answer rather than rejected; a bad kind is an
43
+ // error, since a misspelling would silently page every kind, while an empty kind means every kind.
44
+ export function switchboardSessionQuery(args) {
45
+ const id = nonNegativeIntArg(args?.id);
46
+ if (id === null) {
47
+ return {
48
+ error: `id must be a non-negative integer session_id from get_switchboard_sessions; got ${echoArg(args?.id)}.`,
49
+ };
50
+ }
51
+ let kind;
52
+ if (args?.kind !== undefined && args.kind !== null) {
53
+ const k = String(args.kind).trim().toLowerCase();
54
+ if (k !== "") {
55
+ if (!SWITCHBOARD_KINDS.includes(k)) {
56
+ return { error: `kind must be one of ${SWITCHBOARD_KINDS.join("|")}; got ${echoArg(args.kind)}.` };
57
+ }
58
+ kind = k;
59
+ }
60
+ }
61
+ return { path: switchboardSessionPath(id, clampSwitchboardLimit(args?.limit), kind) };
62
+ }
63
+ // 1..2000, default 50. A digit string counts, the same rule as id; anything else that is not a
64
+ // finite number falls back to the default.
65
+ export function clampSwitchboardLimit(limit) {
66
+ const n = typeof limit === "number" ? limit : typeof limit === "string" && /^\d+$/.test(limit.trim()) ? Number(limit) : NaN;
67
+ if (!Number.isFinite(n))
68
+ return SWITCHBOARD_DEFAULT_LIMIT;
69
+ return Math.min(SWITCHBOARD_MAX_LIMIT, Math.max(1, Math.floor(n)));
70
+ }
71
+ // Build the device path for a detail-by-id tool. All four detail tools (network/rtm/clog/trace)
72
+ // read the device's OWN forwarded server with no shell/fs, so the blast radius is small, but an
73
+ // un-encoded id is still a path-traversal smell. nonNegativeIntArg is the rule; anything it refuses
74
+ // returns null (the caller reports "unknown tool"/no path rather than firing a malformed request).
75
+ function detailPath(resource, id) {
76
+ const n = nonNegativeIntArg(id);
77
+ return n === null ? null : `/api/${resource}/${n}`;
31
78
  }
32
79
  export function buildApiPath(name, args) {
33
80
  switch (name) {
@@ -102,6 +149,10 @@ export function buildApiPath(name, args) {
102
149
  params.set("limit", String(a.limit));
103
150
  return `/api/search?${params.toString()}`;
104
151
  }
152
+ case "get_switchboard_sessions":
153
+ return switchboardListPath();
154
+ // get_switchboard_session is not here: index.ts dispatches it to its own handler, which
155
+ // validates the args and answers a bad id with the reason (switchboardSessionQuery).
105
156
  // list_feature_flags/search_feature_flags/get_feature_flag are NOT here -- see
106
157
  // flags-tools.ts's file header for why they fetch and filter host-side instead.
107
158
  default:
package/dist/mcp/index.js CHANGED
@@ -21,6 +21,7 @@ import { buildBufferPath, createSnapshot } from "./snapshot.js";
21
21
  import { clampLogLimit, shapeLogsResult } from "./logs-result.js";
22
22
  import { querySession, clampByteCap, toNum } from "./session-query.js";
23
23
  import { resolveDetailById } from "./session-detail.js";
24
+ import { decorateToolResult } from "./network-detail.js";
24
25
  import { runSessionEnable } from "./session-enable.js";
25
26
  import { applyEnableOutcome, clearSources, sourceGate } from "./sources-gate.js";
26
27
  import { computeDispatch } from "./dispatch.js";
@@ -31,7 +32,8 @@ import { listFeatureFlags, searchFeatureFlags, getFeatureFlag, normalizeOverridd
31
32
  import { cleanupPulledDatabases, initializeDatabasePath, resetDbState, } from "../shared/db.js";
32
33
  import { TOOL_DEFINITIONS, serverInstructions, sessionGate } from "./tools.js";
33
34
  import { buildApiPath } from "./api-paths.js";
34
- import { interpretRadarResponse } from "./radar-response.js";
35
+ import { handleGetSwitchboardSession, handleGetSwitchboardSessions } from "./switchboard-tools.js";
36
+ import { interpretRadarResponse, responseBudgetError } from "./radar-response.js";
35
37
  // --- Subcommand + bin-name dispatch ---
36
38
  // See computeDispatch's own comment (dispatch.ts) for the full front-door table and rationale;
37
39
  // pulled out to a pure function so the bin-name/subcommand rules are unit-testable.
@@ -333,6 +335,14 @@ async function runMcpServer() {
333
335
  const arr = key ? res[key] : undefined;
334
336
  return Array.isArray(arr) ? arr : [];
335
337
  },
338
+ // The switchboard leg's raw GET: an error reply (a build without the plugin answers 404) is
339
+ // null, so the leg contributes nothing rather than failing the round.
340
+ fetchJson: async (apiPath) => {
341
+ const res = await callRadar(apiPath);
342
+ if (res.error)
343
+ return null;
344
+ return res;
345
+ },
336
346
  readSpool,
337
347
  write: writeFrame,
338
348
  };
@@ -386,10 +396,7 @@ async function runMcpServer() {
386
396
  if (bytes > MAX_RADAR_RESPONSE_BYTES) {
387
397
  // Resolve the truncation NOW (not on "end" — req.destroy() aborts the response so
388
398
  // "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
- });
399
+ done(responseBudgetError());
393
400
  req.destroy();
394
401
  return;
395
402
  }
@@ -810,7 +817,7 @@ async function runMcpServer() {
810
817
  }
811
818
  }
812
819
  // --- MCP Server ---
813
- const server = new Server({ name: "slack-radar", version: "1.20.0" }, { capabilities: { tools: {} }, instructions: serverInstructions(device.platform) });
820
+ const server = new Server({ name: "slack-radar", version: "1.21.0" }, { capabilities: { tools: {} }, instructions: serverInstructions(device.platform) });
814
821
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
815
822
  tools: TOOL_DEFINITIONS,
816
823
  }));
@@ -929,12 +936,22 @@ async function runMcpServer() {
929
936
  const { data, isError } = getFeatureFlag(response, key ?? "", scope, orgId);
930
937
  return textResult(data, isError);
931
938
  }
939
+ // The switchboard tools validate host-side and answer a bad id with a reason, where the generic
940
+ // buildApiPath fallthrough below would only say "unknown tool" for a null path.
941
+ if (name === "get_switchboard_sessions") {
942
+ const { data, isError } = await handleGetSwitchboardSessions(callRadar);
943
+ return textResult(data, isError);
944
+ }
945
+ if (name === "get_switchboard_session") {
946
+ const { data, isError } = await handleGetSwitchboardSession(toolArgs, callRadar);
947
+ return textResult(data, isError);
948
+ }
932
949
  const apiPath = buildApiPath(name, toolArgs);
933
950
  if (apiPath === null) {
934
951
  return textResult(`Unknown tool: ${name}`, true);
935
952
  }
936
953
  const result = await callRadar(apiPath);
937
- return textResult(result, !!result.error);
954
+ return textResult(decorateToolResult(name, result), !!result.error);
938
955
  });
939
956
  const transport = new StdioServerTransport();
940
957
  await server.connect(transport);
@@ -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
+ }
@@ -19,3 +19,10 @@ export interface RadarResponse {
19
19
  * body keeps the existing {raw} behavior, a real if unusual success payload.
20
20
  */
21
21
  export declare function interpretRadarResponse(status: number, body: string): RadarResponse;
22
+ /**
23
+ * The error a proxied answer gets when it would not fit the response budget. radarRequest trips it
24
+ * on the wire as the bytes arrive; a handler that receives a parsed answer through an injected
25
+ * fetch trips it after the fact. One text for both so the model sees one note either way.
26
+ */
27
+ export declare const RESPONSE_BUDGET_DEFAULT_HINT = "Narrow the query (lower limit, add a name/filter), or use capture_snapshot for a bulk export.";
28
+ export declare function responseBudgetError(hint?: string): RadarResponse;
@@ -1,6 +1,7 @@
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";
4
5
  /**
5
6
  * Turn a device HTTP (status, body) into the RadarResponse the tool layer returns. Parse JSON
6
7
  * when the body is JSON: this preserves the device's own error bodies (e.g. an in-app 404 sends
@@ -36,3 +37,17 @@ export function interpretRadarResponse(status, body) {
36
37
  }
37
38
  return parsed;
38
39
  }
40
+ /**
41
+ * The error a proxied answer gets when it would not fit the response budget. radarRequest trips it
42
+ * on the wire as the bytes arrive; a handler that receives a parsed answer through an injected
43
+ * fetch trips it after the fact. One text for both so the model sees one note either way.
44
+ */
45
+ // The hint is what to do instead; the default suits the ring tools, a tool capture_snapshot does
46
+ // not bundle passes its own.
47
+ export const RESPONSE_BUDGET_DEFAULT_HINT = "Narrow the query (lower limit, add a name/filter), or use capture_snapshot for a bulk export.";
48
+ export function responseBudgetError(hint = RESPONSE_BUDGET_DEFAULT_HINT) {
49
+ return {
50
+ error: `Device response exceeded the ${Math.round(MAX_RADAR_RESPONSE_BYTES / 1024)}KB response budget and was dropped to protect the model context. ${hint}`,
51
+ _truncated: true,
52
+ };
53
+ }
@@ -1,7 +1,11 @@
1
1
  import type { ParsedSSE, RadarEvent } from "../shared/stream.js";
2
2
  export declare const BACKFILL_SOURCES: Map<string, string>;
3
+ export declare const SWITCHBOARD_BACKFILL_LIMIT = 2000;
3
4
  export interface BackfillDeps {
4
5
  fetchList: (source: string) => Promise<RadarEvent[]>;
6
+ fetchJson: (apiPath: string) => Promise<Record<string, unknown> | null>;
7
+ switchboardLimit?: number;
8
+ switchboardDeadlineMs?: number;
5
9
  readSpool: () => ParsedSSE[];
6
10
  write: (frame: ParsedSSE) => void;
7
11
  }
@@ -12,9 +16,11 @@ export interface BackfillSummary {
12
16
  * Backfill the device rings into the spool.
13
17
  *
14
18
  * For each backfillable source it fetches the device ring list, reads what the spool already holds,
15
- * and writes only the rows whose (base source, id) is NOT already present (as a summary OR as a
16
- * cached detail). Frames are written in the SAME shape the SSE push produces ({type: source,
17
- * event: row}) and oldest-first (ascending id) so the spool stays append-ordered like the live push.
19
+ * and writes only the rows whose dedupKey is NOT already present (as a summary OR as a cached
20
+ * detail). Switchboard is fetched per session (see fetchSwitchboardRows) and keyed with its
21
+ * timestamp. Frames are written in the SAME shape the SSE push produces ({type: source,
22
+ * event: row}) and oldest-first (ascending id, or timestamp for switchboard) so the spool stays
23
+ * append-ordered like the live push.
18
24
  *
19
25
  * Never throws: a failed list fetch for one source is swallowed (that source is simply not
20
26
  * backfilled this round) so a device blip cannot break enable or the stream. A row with no numeric
@@ -1,3 +1,4 @@
1
+ import { SWITCHBOARD_BACKFILL_DEADLINE_MS, SWITCHBOARD_KIND, newestSwitchboardSessionIds, switchboardListPath, switchboardPageEvents, switchboardSessionPath, } from "../shared/switchboard.js";
1
2
  import { baseSourceOf } from "./session-query.js";
2
3
  // The sources with a device ring and a list endpoint, each paired with the buildApiPath list-tool
3
4
  // name so the fetch reuses the pinned device-route table instead of hand-building a path. This is
@@ -10,6 +11,12 @@ export const BACKFILL_SOURCES = new Map([
10
11
  ["clog", "get_recent_clogs"],
11
12
  ["trace", "get_recent_traces"],
12
13
  ]);
14
+ // Switchboard has no flat ring list: the device keeps it per session, two routes deep, so it is
15
+ // its own leg below rather than a BACKFILL_SOURCES row. Records per session asked for: the device
16
+ // holds 2000 per session (SwitchboardRadarPlugin eventCapacity), so this asks for the whole ring;
17
+ // without it the device pages at 50, a few seconds of a live voice session. A full page of 2000
18
+ // records at about 250 bytes each stays under the device's 1 MB response cap.
19
+ export const SWITCHBOARD_BACKFILL_LIMIT = 2000;
13
20
  // A read frame's numeric id, or undefined when it carries none. Only rows with a numeric id can be
14
21
  // deduped; a row with no id is written every round (it cannot be matched against the spool).
15
22
  function frameId(frame) {
@@ -26,8 +33,6 @@ function frameId(frame) {
26
33
  function baseSourceOfFrame(frame) {
27
34
  return baseSourceOf(frame.type) ?? frame.type;
28
35
  }
29
- // The dedup key for a (source, id) pair. NUL-separated so an id that contains a source substring
30
- // cannot collide with a different (source, id) pair.
31
36
  // Read a row's numeric id, or undefined. The device rows are plain objects of unknown shape.
32
37
  function numId(row) {
33
38
  if (typeof row !== "object" || row === null)
@@ -35,16 +40,26 @@ function numId(row) {
35
40
  const raw = row.id;
36
41
  return typeof raw === "number" ? raw : undefined;
37
42
  }
38
- function dedupKey(source, id) {
39
- return `${source}\u0000${id}`;
43
+ // The dedup key for a row. (source, id) for the ring sources, whose ids are unique for the life
44
+ // of the spool. Switchboard adds the record's timestamp: the plugin's id counter restarts with the
45
+ // app process, so two voice sessions either side of a restart both hold an id 1 and only the
46
+ // timestamp tells them apart. NUL-separated so an id that contains a source substring cannot
47
+ // collide with a different (source, id) pair.
48
+ function dedupKey(source, id, row) {
49
+ if (source !== SWITCHBOARD_KIND)
50
+ return `${source}\u0000${id}`;
51
+ const ts = row?.timestamp;
52
+ return `${source}\u0000${id}\u0000${typeof ts === "number" ? ts : ""}`;
40
53
  }
41
54
  /**
42
55
  * Backfill the device rings into the spool.
43
56
  *
44
57
  * For each backfillable source it fetches the device ring list, reads what the spool already holds,
45
- * and writes only the rows whose (base source, id) is NOT already present (as a summary OR as a
46
- * cached detail). Frames are written in the SAME shape the SSE push produces ({type: source,
47
- * event: row}) and oldest-first (ascending id) so the spool stays append-ordered like the live push.
58
+ * and writes only the rows whose dedupKey is NOT already present (as a summary OR as a cached
59
+ * detail). Switchboard is fetched per session (see fetchSwitchboardRows) and keyed with its
60
+ * timestamp. Frames are written in the SAME shape the SSE push produces ({type: source,
61
+ * event: row}) and oldest-first (ascending id, or timestamp for switchboard) so the spool stays
62
+ * append-ordered like the live push.
48
63
  *
49
64
  * Never throws: a failed list fetch for one source is swallowed (that source is simply not
50
65
  * backfilled this round) so a device blip cannot break enable or the stream. A row with no numeric
@@ -61,13 +76,18 @@ export async function backfillSpool(deps) {
61
76
  const id = frameId(frame);
62
77
  if (id === undefined)
63
78
  continue;
64
- have.add(dedupKey(baseSourceOfFrame(frame), id));
79
+ have.add(dedupKey(baseSourceOfFrame(frame), id, frame.event));
65
80
  }
66
81
  // Fetch all sources in parallel: each is an independent device pull, so running them concurrently
67
- // caps the wall time at one fetch, not the sum of four (each callRadar has its own timeout). A
68
- // per-source rejection is contained by allSettled so one blip never fails the others or enable.
82
+ // caps the wall time at the longer of one fetch (each callRadar has its own timeout) and the
83
+ // switchboard leg's deadline, not the sum of them all. A per-source rejection is contained by
84
+ // allSettled so one blip never fails the others or enable.
69
85
  const sources = [...BACKFILL_SOURCES.keys()];
70
- const results = await Promise.allSettled(sources.map((source) => deps.fetchList(source)));
86
+ const results = await Promise.allSettled([
87
+ ...sources.map((source) => deps.fetchList(source)),
88
+ fetchSwitchboardRows(deps),
89
+ ]);
90
+ sources.push(SWITCHBOARD_KIND);
71
91
  // Write sequentially over the resolved lists so the shared `have` dedup set is updated race-free.
72
92
  for (let i = 0; i < sources.length; i++) {
73
93
  const source = sources[i];
@@ -78,11 +98,15 @@ export async function backfillSpool(deps) {
78
98
  const rows = settled.value;
79
99
  if (!Array.isArray(rows))
80
100
  continue;
81
- // Append oldest-first so the spool stays append=ascending-id, which the newest-first read walk
82
- // and the before_id pager depend on. The device already returns oldest-first, but sort by id
83
- // ascending here rather than trust the order, matching the web server's defensive sort; a row
84
- // with no numeric id keeps its relative position. This also makes the fetch order irrelevant.
85
- const ordered = [...rows]
101
+ // Append oldest-first so each source's rows land in time order. The device already returns
102
+ // oldest-first, but sort by id ascending here rather than trust the order, matching the web
103
+ // server's defensive sort; a row with no numeric id keeps its relative position. This also
104
+ // makes the fetch order irrelevant. Switchboard is already sorted by timestamp in its leg: its
105
+ // ids restart with the app process, so across a restart the id order is not the time order.
106
+ // Append order is not global time order: a backfill of a reconnect gap appends after frames
107
+ // the live stream already wrote, and the pager keys on append seq, so a reader that wants time
108
+ // order sorts by each frame's timestamp.
109
+ const ordered = source === SWITCHBOARD_KIND ? rows : [...rows]
86
110
  .map((row, idx) => ({ row, idx }))
87
111
  .sort((a, b) => {
88
112
  const ai = numId(a.row);
@@ -97,7 +121,7 @@ export async function backfillSpool(deps) {
97
121
  continue;
98
122
  const id = numId(row);
99
123
  if (id !== undefined) {
100
- const key = dedupKey(source, id);
124
+ const key = dedupKey(source, id, row);
101
125
  if (have.has(key))
102
126
  continue;
103
127
  // Mark it held so a duplicate id within THIS same list is not written twice either.
@@ -109,6 +133,42 @@ export async function backfillSpool(deps) {
109
133
  }
110
134
  return { written };
111
135
  }
136
+ // The switchboard leg: list the sessions, take the newest few, fetch each one's page with the
137
+ // limit forwarded, and hand back every record oldest first by its own timestamp (the pages land in
138
+ // any order, and the sort is stable so records sharing a timestamp keep the device's order). A
139
+ // device that predates the source (no route, error JSON, non-JSON) answers null at every step and
140
+ // contributes nothing; one session failing leaves the others intact. Never throws: the caller's
141
+ // allSettled would contain it, but the leg owns its own failures the way fetchJson does.
142
+ //
143
+ // The leg is two waves (list, then pages), so on its own it could hold enable for two callRadar
144
+ // timeouts while a device sits on /api/switchboard. It races SWITCHBOARD_BACKFILL_DEADLINE_MS and
145
+ // past it resolves with the pages that had landed; a fetch still open then is left to callRadar's
146
+ // own timeout and its page is dropped.
147
+ function fetchSwitchboardRows(deps) {
148
+ const limit = deps.switchboardLimit ?? SWITCHBOARD_BACKFILL_LIMIT;
149
+ const deadlineMs = deps.switchboardDeadlineMs ?? SWITCHBOARD_BACKFILL_DEADLINE_MS;
150
+ const landed = [];
151
+ const when = (e) => (typeof e.timestamp === "number" ? e.timestamp : 0);
152
+ return new Promise((resolve) => {
153
+ let settled = false;
154
+ const finish = () => {
155
+ if (settled)
156
+ return;
157
+ settled = true;
158
+ clearTimeout(timer);
159
+ resolve(landed.flat().sort((a, b) => when(a) - when(b)));
160
+ };
161
+ const timer = setTimeout(finish, deadlineMs);
162
+ const walk = async () => {
163
+ const list = await deps.fetchJson(switchboardListPath()).catch(() => null);
164
+ await Promise.all(newestSwitchboardSessionIds(list).map(async (id) => {
165
+ const page = await deps.fetchJson(switchboardSessionPath(id, limit)).then(switchboardPageEvents, () => []);
166
+ landed.push(page);
167
+ }));
168
+ };
169
+ walk().then(finish, finish);
170
+ });
171
+ }
112
172
  // Serialize an async run so two triggers never overlap. The wiring layer (index.ts) calls the real
113
173
  // backfill from two places: the enable path and the reconnect hook. If a reconnect fires while a run
114
174
  // is still awaiting its device fetches, a second run would snapshot the same point-in-time `have` set