@slack/radar-mcp 1.19.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 (44) hide show
  1. package/README.md +48 -8
  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 +69 -18
  17. package/dist/shared/constants.d.ts +14 -3
  18. package/dist/shared/constants.js +14 -3
  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/install-app.d.ts +64 -1
  27. package/dist/web/install-app.js +174 -24
  28. package/dist/web/macapp/RadarApp.swift +1287 -71
  29. package/dist/web/public/index.html +216 -11
  30. package/dist/web/public/next/app.js +22 -12
  31. package/dist/web/public/next/db.js +180 -18
  32. package/dist/web/public/next/feed.js +571 -53
  33. package/dist/web/public/next/filters.js +160 -34
  34. package/dist/web/public/next/form-body.js +252 -0
  35. package/dist/web/public/next/inspector.js +103 -12
  36. package/dist/web/public/next/registry.js +33 -3
  37. package/dist/web/public/next/store.js +577 -53
  38. package/dist/web/public/next/voice-model.js +532 -0
  39. package/dist/web/public/next/voice.js +397 -0
  40. package/dist/web/server.d.ts +110 -6
  41. package/dist/web/server.js +436 -40
  42. package/dist/web/spec.d.ts +13 -6
  43. package/dist/web/spec.js +89 -6
  44. package/package.json +3 -3
@@ -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
@@ -10,6 +10,7 @@
10
10
  // once, cache it, and return it. A pull failure degrades to the summary. It never throws.
11
11
  import { MAX_RADAR_RESPONSE_BYTES } from "../shared/constants.js";
12
12
  import { buildApiPath } from "./api-paths.js";
13
+ import { DECODED_COPY_KEYS, stripOwned, withDecodedRequestBody } from "./network-detail.js";
13
14
  import { detailTypeFor, selectById } from "./session-query.js";
14
15
  // Sources whose spool frame is a SUMMARY, so an id read must pull the body from the device once and
15
16
  // write it back. The value is the device-detail tool name buildApiPath already knows, so the pull
@@ -96,8 +97,27 @@ export async function resolveDetailById(frames, id, source, deps, cap = MAX_RADA
96
97
  // on every id-path branch that returns a frame so an oversized clog or device-pushed detail served
97
98
  // from file cannot flood the model context. An optional summary note rides along when the frame
98
99
  // still fits; if the frame itself is too big, the exceeds-cap note replaces it.
100
+ //
101
+ // A network detail also gets the decoded form-body view here, on the way out and after any spool
102
+ // write, so a query_session id read carries the same reading aid get_network_call_detail does,
103
+ // without the decoded copy ever being persisted. The cap is measured on what goes out, and the
104
+ // decoration never costs a record: when the decorated frame is over budget the decoded copy goes
105
+ // first (the omitted note in its place, the truncation flag kept); if that is still over, the
106
+ // note goes and the flag alone stays; if even that is over, the record goes out as stored with
107
+ // only the decoder's own keys removed, which is what went out before any of this existed; only a
108
+ // record that is over budget in that form is dropped.
99
109
  function cappedFrameResult(frame, cap, note) {
100
- if (Buffer.byteLength(JSON.stringify(frame)) > cap) {
110
+ const fits = (f) => Buffer.byteLength(JSON.stringify(f)) <= cap;
111
+ const decorated = decorateFrame(frame);
112
+ const bare = bareFrame(frame);
113
+ let served = decorated;
114
+ if (!fits(served))
115
+ served = withoutDecodedCopy(served);
116
+ if (!fits(served))
117
+ served = flagOnly(bare, decorated);
118
+ if (!fits(served))
119
+ served = bare;
120
+ if (!fits(served)) {
101
121
  return {
102
122
  frames: [],
103
123
  count: 0,
@@ -105,5 +125,37 @@ function cappedFrameResult(frame, cap, note) {
105
125
  note: "the frame with that id alone exceeds the byte cap",
106
126
  };
107
127
  }
108
- return { frames: [frame], count: 1, truncated: false, ...(note !== undefined ? { note } : {}) };
128
+ return { frames: [served], count: 1, truncated: false, ...(note !== undefined ? { note } : {}) };
129
+ }
130
+ const DECODED_OVER_CAP_NOTE = "decoded form would put the record over the response byte cap; request_body holds the raw bytes";
131
+ // Drop the decoded copy (and its unparsed-field notes) from a decorated frame, leaving every other
132
+ // decoration in place, and say why. A frame that carried no decoded copy is returned as it is.
133
+ function withoutDecodedCopy(frame) {
134
+ if (!DECODED_COPY_KEYS.some((k) => k in frame.event))
135
+ return frame;
136
+ const event = { ...frame.event };
137
+ for (const k of DECODED_COPY_KEYS)
138
+ delete event[k];
139
+ event.request_body_decoded_omitted = DECODED_OVER_CAP_NOTE;
140
+ return { ...frame, event };
141
+ }
142
+ // The bare frame plus only the truncation flag, when the decorated frame carried it.
143
+ function flagOnly(bare, decorated) {
144
+ if (decorated.event.request_body_truncated !== true)
145
+ return bare;
146
+ return { ...bare, event: { ...bare.event, request_body_truncated: true } };
147
+ }
148
+ // The stored network detail with the decoder's own keys removed (a spool written by another
149
+ // version could carry stale ones); any other frame as it is.
150
+ function bareFrame(frame) {
151
+ if (frame.type !== "network_detail")
152
+ return frame;
153
+ const event = stripOwned(frame.event);
154
+ return event === frame.event ? frame : { ...frame, event };
155
+ }
156
+ function decorateFrame(frame) {
157
+ if (frame.type !== "network_detail")
158
+ return frame;
159
+ const event = withDecodedRequestBody(frame.event);
160
+ return event === frame.event ? frame : { ...frame, event };
109
161
  }
@@ -68,22 +68,63 @@ export function baseSourceOf(type) {
68
68
  function baseSourceOfFrame(frame) {
69
69
  return baseSourceOf(frame.type) ?? frame.type;
70
70
  }
71
+ // The list-read collapse key: (base source, id, timestamp). A summary and its pulled detail share
72
+ // all three (the device writes the record's timestamp on both routes), so they still fold to one.
73
+ // Two records that share an id but not a timestamp are two records: the device id counters
74
+ // restart with the app process, and switchboard in particular reuses id 1 on every restart, so an
75
+ // id-only key would hide the earlier process's records.
76
+ //
77
+ // A frame with no numeric timestamp cannot be keyed on its own. `stamps` holds, per (base, id),
78
+ // the distinct numeric timestamps seen in the list: when there is exactly one, the unstamped frame
79
+ // is that record (a detail route that omits the field) and folds onto it; otherwise it keys on the
80
+ // id alone, since there is no telling which record it belongs to. A detail the device restamped
81
+ // carries a different number and stays its own record.
82
+ function groupKey(frame, id) {
83
+ return `${baseSourceOfFrame(frame)}\u0000${id}`;
84
+ }
85
+ function frameTimestamp(frame) {
86
+ const ts = frame.event?.timestamp;
87
+ return typeof ts === "number" ? ts : undefined;
88
+ }
89
+ function collapseKey(frame, id, stamps) {
90
+ const group = groupKey(frame, id);
91
+ let ts = frameTimestamp(frame);
92
+ if (ts === undefined) {
93
+ const seen = stamps.get(group);
94
+ if (seen !== undefined && seen.size === 1)
95
+ ts = [...seen][0];
96
+ }
97
+ return `${group}\u0000${ts ?? ""}`;
98
+ }
71
99
  // After a lazy pull the spool holds BOTH a summary and its `<source>_detail` for the same id, so an
72
- // unfiltered list read would show that id twice. Collapse each (base source, id) pair to one frame,
73
- // preferring the detail (the fuller record). A frame with no numeric id, or whose (base, id) pair
74
- // appears once, passes through untouched. Order is preserved so the newest-first walk is unaffected.
75
- // Pure: it only reshapes the frame list. The dedup is by base source via baseSourceOfFrame, never a
76
- // hard-coded source-name switch, so a future plugin source dedups for free.
100
+ // unfiltered list read would show that id twice. Collapse each collapseKey to one frame, preferring
101
+ // the detail (the fuller record). A frame with no numeric id, or whose key appears once, passes
102
+ // through untouched. Order is preserved so the newest-first walk is unaffected. Pure: it only
103
+ // reshapes the frame list. The dedup is by base source via baseSourceOfFrame, never a hard-coded
104
+ // source-name switch, so a future plugin source dedups for free.
77
105
  function dedupSummaryDetail(frames) {
78
- // First pass: for each (base source, id) key, remember the LAST frame that carried it. Append
79
- // order means the last write wins, so a reused id resolves to its freshest record, not a stale
80
- // detail. Mirrors selectById's recency rule.
106
+ // Index the timestamps each (base, id) group carries, so an unstamped frame can fold onto its
107
+ // group's one record (see collapseKey).
108
+ const stamps = new Map();
109
+ for (const frame of frames) {
110
+ const id = frameId(frame);
111
+ const ts = id === undefined ? undefined : frameTimestamp(frame);
112
+ if (id === undefined || ts === undefined)
113
+ continue;
114
+ const group = groupKey(frame, id);
115
+ const seen = stamps.get(group) ?? new Set();
116
+ seen.add(ts);
117
+ stamps.set(group, seen);
118
+ }
119
+ // First pass: for each key, remember the LAST frame that carried it. Append order means the last
120
+ // write wins, so a re-pulled detail resolves to its freshest record, not a stale one. Mirrors
121
+ // selectById's recency rule.
81
122
  const winner = new Map();
82
123
  for (const frame of frames) {
83
124
  const id = frameId(frame);
84
125
  if (id === undefined)
85
126
  continue;
86
- winner.set(`${baseSourceOfFrame(frame)}\u0000${id}`, frame);
127
+ winner.set(collapseKey(frame, id, stamps), frame);
87
128
  }
88
129
  // Second pass: keep no-id frames as-is; for id-bearing frames emit only the winner, at the
89
130
  // position of the key's FIRST appearance so the newest-first walk order stays stable.
@@ -95,7 +136,7 @@ function dedupSummaryDetail(frames) {
95
136
  out.push(frame);
96
137
  continue;
97
138
  }
98
- const key = `${baseSourceOfFrame(frame)}\u0000${id}`;
139
+ const key = collapseKey(frame, id, stamps);
99
140
  if (emitted.has(key))
100
141
  continue;
101
142
  emitted.add(key);
@@ -224,7 +265,8 @@ export function querySession(frames, rawFilter, epoch) {
224
265
  // id-bypass, PURE mirror of the id path. In production handleQuerySession resolves an id read via
225
266
  // resolveDetailById (which does the lazy device pull) before this function is reached, so this
226
267
  // branch does not run for the MCP tool. It stays as the pure, no-pull reference the unit tests
227
- // exercise: same selectById + byte-cap semantics, minus the device fetch. Keep the two in step.
268
+ // exercise: same selectById, the hard cap on the stored frame, minus the device fetch and minus
269
+ // the form-body decoration the live path adds on the way out.
228
270
  // Prefer a stored detail frame over a summary; honor the hard cap so no single id floods context.
229
271
  if (filter.id !== undefined) {
230
272
  const idCap = clampByteCap(filter.byte_cap);
@@ -18,6 +18,10 @@ export const TOOL_SOURCE = {
18
18
  list_feature_flags: "feature_flags",
19
19
  search_feature_flags: "feature_flags",
20
20
  get_feature_flag: "feature_flags",
21
+ // The switchboard plugin declares itself as `switchboard`; a build without it answers 404 on the
22
+ // routes, so the gate turns that into the uniform "build does not serve" error.
23
+ get_switchboard_sessions: "switchboard",
24
+ get_switchboard_session: "switchboard",
21
25
  };
22
26
  // null = no discovery info (old build or no session); gating is off.
23
27
  let sessionSources = null;
@@ -0,0 +1,9 @@
1
+ import { type RadarResponse } from "./radar-response.js";
2
+ export interface HandlerResult {
3
+ data: unknown;
4
+ isError: boolean;
5
+ }
6
+ export type RadarFetch = (apiPath: string) => Promise<RadarResponse>;
7
+ export declare const SWITCHBOARD_BUDGET_HINT = "Pass kind or lower limit; for the whole session use query_session with source switchboard, which pages with a cursor.";
8
+ export declare function handleGetSwitchboardSessions(fetch: RadarFetch): Promise<HandlerResult>;
9
+ export declare function handleGetSwitchboardSession(args: Record<string, unknown>, fetch: RadarFetch): Promise<HandlerResult>;
@@ -0,0 +1,40 @@
1
+ // The two switchboard tools' handlers, pure so a test can drive them with a fake callRadar.
2
+ // get_switchboard_sessions proxies the device's session list; get_switchboard_session validates
3
+ // its args host-side (a bad id never reaches the device) and proxies one session's page. Both
4
+ // keep the device's own error body (a 404 for an unknown id) as the tool error. An answer over the
5
+ // response budget, whether radarRequest cut it on the wire or the parsed body would blow it once
6
+ // serialized, comes back as the shared over-budget note with a hint of their own, since
7
+ // capture_snapshot does not bundle switchboard.
8
+ import { MAX_RADAR_RESPONSE_BYTES } from "../shared/constants.js";
9
+ import { buildApiPath, switchboardSessionQuery } from "./api-paths.js";
10
+ import { responseBudgetError } from "./radar-response.js";
11
+ export const SWITCHBOARD_BUDGET_HINT = "Pass kind or lower limit; for the whole session use query_session with source switchboard, which pages with a cursor.";
12
+ // The device answer as the tool result: its error stays the error, except the wire-cap trip, which
13
+ // gets the switchboard hint in place of the stock one. The budget is measured on the exact text
14
+ // the model receives, built once here and handed on as the result: compact JSON, the same form
15
+ // query_session emits, so a page spends no more context than the same records read there (the
16
+ // pretty print would be about half again as large on a page of frames). The wire cap already
17
+ // measures the device's compact bytes, so this second measure only matters for a body that fits
18
+ // on the wire and would not once serialized with the tool's own additions.
19
+ function passThrough(res) {
20
+ if (res._truncated === true)
21
+ return { data: responseBudgetError(SWITCHBOARD_BUDGET_HINT), isError: true };
22
+ if (res.error)
23
+ return { data: res, isError: true };
24
+ const text = JSON.stringify(res);
25
+ if (Buffer.byteLength(text, "utf8") > MAX_RADAR_RESPONSE_BYTES) {
26
+ return { data: responseBudgetError(SWITCHBOARD_BUDGET_HINT), isError: true };
27
+ }
28
+ return { data: text, isError: false };
29
+ }
30
+ export async function handleGetSwitchboardSessions(fetch) {
31
+ // buildApiPath is the pinned route table; the list takes no args.
32
+ const apiPath = buildApiPath("get_switchboard_sessions", {});
33
+ return passThrough(await fetch(apiPath));
34
+ }
35
+ export async function handleGetSwitchboardSession(args, fetch) {
36
+ const q = switchboardSessionQuery(args);
37
+ if ("error" in q)
38
+ return { data: { error: q.error }, isError: true };
39
+ return passThrough(await fetch(q.path));
40
+ }
package/dist/mcp/tools.js CHANGED
@@ -1,4 +1,5 @@
1
- import { SOURCES, VIZ, SERIES_METRICS } from "../web/spec.js";
1
+ import { FORM_DECODE_LIMIT_LABEL } from "../shared/constants.js";
2
+ import { SOURCES, VIZ, SERIES_METRICS, LOG_LEVELS } from "../web/spec.js";
2
3
  export const SERVER_INSTRUCTIONS = [
3
4
  "Slack Radar provides on-device debugging tools for the Slack Android app via ADB.",
4
5
  "",
@@ -9,7 +10,7 @@ export const SERVER_INSTRUCTIONS = [
9
10
  "AUTO-ENABLE: When the user asks an obvious device question, invoke the Skill tool with",
10
11
  'skill="radar-enable" FIRST, then proceed with the radar tool call. No need to ask.',
11
12
  "Obvious device questions include: clogs, network calls, RTM events, screenshots,",
12
- "app state, device logs, or any reference to what is happening on the connected device.",
13
+ "app state, device logs, Slackbot voice sessions, or any reference to what is happening on the connected device.",
13
14
  "",
14
15
  "TIMEOUT: The device-side radar auto-shuts down after idle. On tool call failure,",
15
16
  "the session flips to disabled. Tell the user and offer to re-enable.",
@@ -24,7 +25,8 @@ export const SERVER_INSTRUCTIONS = [
24
25
  '- "what API call was that" -> get_recent_network_calls then get_network_call_detail',
25
26
  '- "did I get X" / "did X happen" -> search(query="X") across ALL buffers, not just one',
26
27
  '- "everything since I enabled" / "the whole session" / "what did I miss" -> query_session',
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 happened in the voice session" / "why did playback stutter" / "did the mic open" -> get_switchboard_sessions then get_switchboard_session(id, kind=...): player for stutter, state for mic and connection, phase for slow start',
29
+ '- "check the debug logs" -> get_recent_logs (tag is OPTIONAL: pass tag="SlackRadar" to filter, or omit it for all recent lines)',
28
30
  '- "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
31
  '- "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.',
30
32
  '- "what did the app remember" / "what is cached in prefs" / "what team_prefs are set" -> list_prefs then get_prefs',
@@ -55,8 +57,10 @@ export const SERVER_INSTRUCTIONS = [
55
57
  "",
56
58
  "WEB DASHBOARD (/radar-ui):",
57
59
  "A browser-based dashboard (http://localhost:8100) shows the same live device data as",
58
- "tabs: Live (everything), Network, RTM, Clogs, Traces, and Logs, each with counters, a graph, a",
59
- "filterable feed, and a payload inspector. Launched via the /radar-ui skill, which runs",
60
+ "tabs: Live (everything), Network, RTM, Clogs, Traces, Logs, and Switchboard, each with a",
61
+ "filterable feed and a payload inspector, a live rate on most, a graph on Network and Traces,",
62
+ "plus the Database/Preferences/Feature Flags browsers.",
63
+ "Launched via the /radar-ui skill, which runs",
60
64
  "`npx @slack/radar-mcp web` (a global install also exposes it as `slack-radar`).",
61
65
  "",
62
66
  "PROACTIVELY offer the dashboard when it would help — do not wait to be asked. The moment a",
@@ -85,7 +89,8 @@ export const SERVER_INSTRUCTIONS = [
85
89
  "screen.installHint, so you can check before suggesting.",
86
90
  "",
87
91
  "CUSTOM DASHBOARD (open_radar_dashboard):",
88
- "The pre-built tabs (Live/Network/RTM/Clogs/Traces/Logs) cover the common cases. When the user",
92
+ "The pre-built tabs (Live/Network/RTM/Clogs/Traces/Logs/Switchboard, plus the Database/Preferences/Feature Flags",
93
+ "browsers) cover the common cases. When the user",
89
94
  "describes a live view the tabs do not show, SUGGEST building it; invoke open_radar_dashboard",
90
95
  "only after they agree or explicitly ask for a custom view/dashboard (same discipline as",
91
96
  "/radar-ui). To build, translate their words into a spec and call the tool; it renders your",
@@ -95,15 +100,22 @@ export const SERVER_INSTRUCTIONS = [
95
100
  '- "count every DM I receive and beep when one arrives"',
96
101
  '- "show only RTM events on channel C... and let me click each for its payload"',
97
102
  '- "watch network calls whose body contains <substring>"',
103
+ '- "show me only the <Tag> logs, DEBUG and up, without the noisy lines": a constrained log view,',
104
+ " e.g. {source: \"log\", match: {package: \"com.Slack.internal.debug\", tag: \"<Tag>\"}, minLevel: \"DEBUG\",",
105
+ " exclude: [\"noisy term\"]}. It lands as a Custom tab, gone on a page refresh unless pushed again;",
106
+ " exclude terms are remembered in the browser only on the pre-built tabs, not on Custom. One",
107
+ " phrase per exclude term, no commas or line breaks.",
98
108
  "Authoring rules:",
99
- "- source is one of network/rtm/clog/trace/log/all ('all' = one unified timeline).",
109
+ "- source is one of network/rtm/clog/trace/log/switchboard/all ('all' = one unified timeline).",
100
110
  "- match filters on SUMMARY fields only, by source: network=url/method/status_code,",
101
111
  " rtm=event_type/direction/channel, clog=event_name, trace=trace_name/span_name,",
102
- " log=tag/level/message/pid/package.",
112
+ " log=tag/level/message/pid/package,",
113
+ " switchboard=kind/session_id/direction/frame_type/state_kind/phase/event.",
103
114
  " NEVER invent a field; a match on a field the stream does not carry silently matches",
104
115
  " nothing. To filter on body text use bodyContains (network/all only), which fetches detail.",
105
- "- viz composes counter/rate/sparkline/feed/inspector/graph. graph needs a series array",
116
+ "- viz composes counter/rate/sparkline/feed/inspector/graph/voice. graph needs a series array",
106
117
  " (1-2 entries; metric ratePerSec/count/avg/errorRate; avg needs a field like duration_ms).",
118
+ " voice is the Switchboard tab's session panel and draws only for source switchboard.",
107
119
  "- highlight {field, op, value} flags rows breaching a numeric threshold; alert {sound,flash,",
108
120
  " say, at} fires on each live match (or once at the Nth). Author an honest one-line `summary`.",
109
121
  "Calling it again replaces/refines the live custom dashboard. The dashboard reads a connected",
@@ -194,7 +206,7 @@ export const TOOL_DEFINITIONS = [
194
206
  },
195
207
  {
196
208
  name: "get_network_call_detail",
197
- description: "Get full details of a specific network call by ID, including request/response headers and bodies.",
209
+ description: `Get full details of a specific network call by ID, including request/response headers and bodies. A form-encoded request body also comes back decoded in request_body_decoded, one key per field name (a repeated name becomes an array), JSON-valued fields parsed; request_body is always the raw bytes. When the raw body or its decoded copy is over ${FORM_DECODE_LIMIT_LABEL} the decoded copy is skipped and request_body_decoded_omitted says so; a field whose JSON was left unparsed is named in request_body_decoded_unparsed, with the reason. request_body_truncated: true means the device cap cut the body and request_body shows where it ends (a build that reports the cut itself is believed; otherwise it is read from the body's shape). For a form body, request_body_decoded, when present, holds every field before the cut; the last one may be partial.`,
198
210
  inputSchema: {
199
211
  type: "object",
200
212
  properties: {
@@ -286,7 +298,7 @@ export const TOOL_DEFINITIONS = [
286
298
  properties: {
287
299
  event_type: { type: "string", description: "RTM event type to wait for" },
288
300
  channel: { type: "string", description: "Filter by channel ID" },
289
- source: { type: "string", description: "Limit to one stream: network, rtm, clog, log, or trace (default: all)" },
301
+ source: { type: "string", description: "Limit to one stream: network, rtm, clog, log, trace, or switchboard (default: all). During a Slackbot voice session switchboard emits several records a second, so an unscoped wait fills with them; scope to the source you want or shorten timeout_ms." },
290
302
  timeout_ms: { type: "number", description: "Max time to wait in ms (default: 30000)" },
291
303
  idle_timeout_ms: { type: "number", description: "Resolve after this many ms of silence (default: 3000)" },
292
304
  },
@@ -306,6 +318,35 @@ export const TOOL_DEFINITIONS = [
306
318
  },
307
319
  annotations: { readOnlyHint: true },
308
320
  },
321
+ {
322
+ name: "get_switchboard_sessions",
323
+ description: "List the Slackbot voice (switchboard) sessions the device still holds, at most 8, newest first. A session is one voice conversation attempt, from the controller starting (before any socket opens) to it ending. Each entry carries session_id, team_id, began_at, ended_at (null while live), total_captured (records held), frames {incoming, outgoing} counts, last_state (the newest connection/mic/speaking state, absent before the first state record) and levels (the newest audio level tick, or null). session_id restarts at 1 with the app process, so a small id can be the newest session; go by began_at. A session already running when radar was enabled lists from its first seen record, with team_id null. Follow with get_switchboard_session(id) for the records.",
324
+ inputSchema: { type: "object", properties: {} },
325
+ annotations: { readOnlyHint: true },
326
+ },
327
+ {
328
+ name: "get_switchboard_session",
329
+ description: "Get one voice session's summary plus the newest `limit` of its records (events), oldest first; events is only the page. Record kinds: state = connection, mic and speaking transitions (state_kind, from, to, cause); frame = control frames in and out (direction, frame_type, bytes), audio frames carry frame_type audio and a byte count, never the audio; player = playback events rearm, jitter_trim, read_stall and pre_ready_drop with gap_ms and bytes_queued; phase = startup phase durations (phase, duration_ms); session = begin and end. Pass kind to narrow (player for stutter); the device filters by kind before taking the limit, so the page is the newest limit of that kind, while total_captured still counts every kind. No older page, raise limit instead. An unknown id is a device 404. The same records are in query_session under source switchboard.",
330
+ inputSchema: {
331
+ type: "object",
332
+ properties: {
333
+ id: { type: "number", description: "The session_id from get_switchboard_sessions" },
334
+ kind: {
335
+ type: "string",
336
+ enum: ["session", "state", "frame", "phase", "player"],
337
+ description: "Only records of this kind (default: every kind)",
338
+ },
339
+ limit: {
340
+ type: "number",
341
+ description: "How many of the newest records to return (default: 50, max: 2000, the device's per-session ring)",
342
+ minimum: 1,
343
+ maximum: 2000,
344
+ },
345
+ },
346
+ required: ["id"],
347
+ },
348
+ annotations: { readOnlyHint: true },
349
+ },
309
350
  {
310
351
  name: "get_app_state",
311
352
  description: "Get the current app state from the device.",
@@ -352,7 +393,7 @@ export const TOOL_DEFINITIONS = [
352
393
  },
353
394
  {
354
395
  name: "capture_snapshot",
355
- description: "Bundle the current Radar state into a single on-disk artifact for sharing. Writes four files to ~/.slack-radar/snapshots/snapshot-<ts>/: bundle.json (network + RTM + clog + trace buffers, up to 1000 items each — a bulk export, much larger than point queries like get_network_call_detail), logcat.tail.log (last N lines of the active capture), screenshot.png (current screen), and README.txt (receiver-facing explainer). Use when the user says 'save this', 'file this as a bug', 'share this', 'bundle this up', 'attach to a ticket', 'make me a repro', or otherwise wants a shareable reproducible handoff. PRIVACY: bundle.json contains raw API request/response bodies including auth headers, RTM message content, user/team/channel IDs, clog payloads, and performance trace spans — review before sharing externally.",
396
+ description: "Bundle the current Radar state into a single on-disk artifact for sharing. Writes four files to ~/.slack-radar/snapshots/snapshot-<ts>/: bundle.json (network + RTM + clog + trace buffers, up to 1000 items each — a bulk export, much larger than point queries like get_network_call_detail), logcat.tail.log (last N lines of the active capture), screenshot.png (current screen), and README.txt (receiver-facing explainer). Switchboard voice sessions are not bundled; keep them with get_switchboard_session or query_session(source=switchboard). Use when the user says 'save this', 'file this as a bug', 'share this', 'bundle this up', 'attach to a ticket', 'make me a repro', or otherwise wants a shareable reproducible handoff. PRIVACY: bundle.json contains raw API request/response bodies including auth headers, RTM message content, user/team/channel IDs, clog payloads, and performance trace spans — review before sharing externally.",
356
397
  inputSchema: {
357
398
  type: "object",
358
399
  properties: {
@@ -426,7 +467,7 @@ export const TOOL_DEFINITIONS = [
426
467
  {
427
468
  name: "open_radar_dashboard",
428
469
  description: "Build or refine a custom live dashboard tab in the Slack Radar web UI from a spec YOU author. " +
429
- "Suggest this when the user describes a live view the pre-built tabs (Live/Network/RTM/Clogs/Traces/Logs) do not cover " +
470
+ "Suggest this when the user describes a live view the pre-built tabs (Live/Network/RTM/Clogs/Traces/Logs/Switchboard, plus the Database, Preferences and Feature Flags browsers) do not cover " +
430
471
  "(e.g. 'graph calls per second vs response time and flag slow ones', 'beep when I get a DM'); invoke it once they agree. " +
431
472
  "Translate the request into the spec fields below and call this tool; it ensures the web dashboard is " +
432
473
  "running (default http://localhost:8100) and renders your spec as a 'Custom' tab, then returns the URL to share. " +
@@ -443,18 +484,28 @@ export const TOOL_DEFINITIONS = [
443
484
  source: {
444
485
  type: "string",
445
486
  enum: [...SOURCES],
446
- description: "Which device stream to read. 'all' is a unified timeline mixing network, RTM, clog, trace, and log.",
487
+ description: "Which device stream to read. 'all' is a unified timeline mixing network, RTM, clog, trace, log, and switchboard. 'switchboard' is the Slackbot voice transport's own records (kind: session|state|frame|phase|player).",
447
488
  },
448
489
  match: {
449
490
  type: "object",
450
491
  description: "Case-insensitive substring filter on SUMMARY fields, keyed by source. network: url/method/status_code; " +
451
- "rtm: event_type/direction/channel; clog: event_name; trace: trace_name/span_name; log: tag/level/package. NEVER invent a field " +
452
- "(a match on an absent field silently matches nothing). For body text use bodyContains instead.",
492
+ "rtm: event_type/direction/channel; clog: event_name; trace: trace_name/span_name; log: tag/level/package; switchboard: kind/session_id/direction/frame_type/state_kind/phase/event. NEVER invent a field " +
493
+ "(a match on an absent field silently matches nothing). For body text use bodyContains instead; for a log level floor use minLevel, not match.level.",
453
494
  },
454
495
  bodyContains: {
455
496
  type: "string",
456
497
  description: "network/all only: keep calls whose request/response BODY contains this substring (fetches each call's detail).",
457
498
  },
499
+ minLevel: {
500
+ type: "string",
501
+ enum: [...LOG_LEVELS],
502
+ description: "log/all only: show log lines at this level or above (WARN keeps WARN, ERROR and FATAL). Rows of other kinds are unaffected. Omit to show every line; VERBOSE means the same and is stored as omitted.",
503
+ },
504
+ exclude: {
505
+ type: "array",
506
+ items: { type: "string" },
507
+ description: "Stream sources only. Hide rows whose summary text (the same text the filter box searches, never bodies) contains any term, case-insensitive; a field:value term (kind:frame, no space after the colon) instead hides rows whose field equals the value, case-insensitive, and a field no row carries hides nothing. Up to 20 terms of 200 characters; trimmed and deduplicated. One phrase per term, no commas or line breaks. Hidden rows also leave the rate and graph counts.",
508
+ },
458
509
  viz: {
459
510
  type: "array",
460
511
  items: { type: "string", enum: [...VIZ] },
@@ -537,11 +588,11 @@ export const TOOL_DEFINITIONS = [
537
588
  },
538
589
  {
539
590
  name: "query_session",
540
- description: "Read the whole current Radar session from the host event spool (every network/RTM/clog/trace frame captured since radar was enabled), filtered and byte-capped so it cannot flood the model context. Covers network/rtm/clog/trace; device logs are not the spool's primary source, use get_recent_logs for those. Use it for 'everything since I enabled', 'the whole session', or 'what did I miss': the get_recent_* tools read the device rings, which drop the oldest events on a long session, while the spool keeps the full session record. A list read (no id) returns SUMMARY fields for network/RTM/trace and full clog records inline. An id read returns the FULL record: for network/RTM/trace the body (request/response, headers, full payload) is pulled from the device on first open and cached in the spool, so a later id read of the same record is served from the file with no device round-trip; clog is already the full record inline. If the body cannot be pulled (device offline, aged out of the ring, or a single body over the byte budget) the id read falls back to the summary with a note. Frames come back newest-first; when truncated:true the result carries an opaque cursor STRING token, which you pass back verbatim as cursor to page strictly older across all sources. Do not build or change the token; it is not an id and not a count. A token from before a spool rotation or a re-enable is rejected with a note (bounded; a normal session never rotates), and you start paging from the newest page again. Pass id (optionally with source) to fetch one whole record by id regardless of age. Ids are per-source, so an unsourced id can match more than one ring; pass source to disambiguate, and the returned frame type tells you which ring answered. A list read scoped to a plain source (source network) returns summaries; to list cached full bodies for a source, scope to its detail tag (source network_detail). An unscoped list read and an id read already prefer the cached full body. When id is set, all filters except source are ignored. Returns an empty result with a note when no spool exists (radar not enabled).",
591
+ description: "Read the whole current Radar session from the host event spool (every network/RTM/clog/trace/switchboard frame captured since radar was enabled), filtered and byte-capped so it cannot flood the model context. Device logs are not spooled; use get_recent_logs for those. Use it for 'everything since I enabled', 'the whole session', or 'what did I miss': the get_recent_* tools read the device rings, which drop the oldest events on a long session, while the spool keeps the full session record. A list read (no id) returns SUMMARY fields for network/RTM/trace and full clog and switchboard records inline; it collapses one summary and its pulled detail for an id, while records from two app processes that share an id are kept apart by timestamp; an id read returns the newest record carrying that id, so only the newer of such a pair is reachable by id. An id read returns the FULL record: for network/RTM/trace the body (request/response, headers, full payload) is pulled from the device on first open and cached in the spool, so a later id read of the same record is served from the file with no device round-trip; clog and switchboard are already the full record inline. If the body cannot be pulled (device offline, aged out of the ring, or a single body over the byte budget) the id read falls back to the summary with a note. Frames come back newest-first; when truncated:true the result carries an opaque cursor STRING token, which you pass back verbatim as cursor to page strictly older across all sources. Do not build or change the token. A token from before a spool rotation or a re-enable is rejected with a note, and you start paging from the newest page again. Ids are per-source, so an unsourced id can match more than one ring; pass source to disambiguate, and the returned frame type tells you which ring answered. A list read scoped to a plain source (source network) returns summaries; to list cached full bodies for a source, scope to its detail tag (source network_detail). When id is set, all filters except source are ignored. Returns an empty result with a note when no spool exists (radar not enabled). Switchboard (Slackbot voice transport) frames are spooled raw as source switchboard; filter them with source and text. An id read of a network record adds the same decoded-form fields get_network_call_detail adds; a large record may come back without them, with request_body_decoded_omitted saying so. The spool itself keeps only the raw bytes.",
541
592
  inputSchema: {
542
593
  type: "object",
543
594
  properties: {
544
- source: { type: "string", description: "Opaque frame type tag to match, e.g. network, rtm, clog, trace (or a future source). Matched exactly, not enumerated." },
595
+ source: { type: "string", description: "Opaque frame type tag to match, e.g. network, rtm, clog, trace, switchboard. Matched exactly, not enumerated." },
545
596
  id: { type: "number", description: "Return the single whole frame with this id, bypassing the newest-first byte budget. Optionally scope with source. id addresses one record and is unrelated to cursor; there is no older-than-id filter, page with cursor instead." },
546
597
  cursor: { type: "string", description: "An OPAQUE paging token returned by a prior truncated result; pass it back verbatim to get the next older page across all sources. It is NOT an event id and NOT a count; do not construct or modify it. A token from before a spool rotation or a re-enable is rejected with a note, and you start paging from the newest page again." },
547
598
  url_filter: { type: "string", description: "Keep frames whose url contains this substring." },
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * Package version, read once from package.json at load — NOT a hardcoded copy, so it cannot
3
- * drift from the published version. Surfaced as the `X-Radar-Version` header on /spec so a
4
- * second launcher can tell whether the dashboard already holding the port is a different
5
- * Radar version than itself (the adopt path notices a mismatch; it still adopts, never kills).
3
+ * drift from the published version. Surfaced as the `X-Radar-Version` header on every dashboard
4
+ * response past the Host gate (docs/wire-contract.md §7) so a second launcher can tell whether the dashboard
5
+ * already holding the port is a different Radar version than itself (the adopt path notices a
6
+ * mismatch; it still adopts, never kills), and a machine consumer can detect version skew.
6
7
  * Falls back to "unknown" if package.json cannot be read (should not happen in a real install).
7
8
  */
8
9
  export declare const RADAR_VERSION: string;
@@ -86,3 +87,13 @@ export declare const MAX_RADAR_RESPONSE_BYTES: number;
86
87
  * any future second caller of this cap shares it rather than risking drift.
87
88
  */
88
89
  export declare const MAX_PREFS_RESPONSE_BYTES: number;
90
+ /**
91
+ * Past this many UTF-8 bytes get_network_call_detail (and a query_session id read) skip the decoded
92
+ * copy of a form-encoded request body and say so in request_body_decoded_omitted; the raw bytes
93
+ * still ride in request_body. The decoded pretty print runs about three times the raw, so the copy
94
+ * would otherwise pile onto an already large payload in the model context. Both the raw body and
95
+ * the decoded pretty print are measured against this one number. The label is the prose form
96
+ * every note and tool description in the server uses, so the number is spelled once there.
97
+ */
98
+ export declare const MAX_FORM_DECODE_BYTES: number;
99
+ export declare const FORM_DECODE_LIMIT_LABEL = "64 KB";