@khanglvm/relay 0.20.3 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +1 -1
  2. package/docs/AGENT.md +35 -62
  3. package/docs/SETUP.md +3 -2
  4. package/package.json +17 -5
  5. package/schema/spec.v1.json +55 -3
  6. package/skills/relay/SKILL.md +5 -2
  7. package/src/a2ui/board-catalog.json +1004 -0
  8. package/src/a2ui/board-constants.js +35 -0
  9. package/src/a2ui/board.js +5 -0
  10. package/src/a2ui/from-a2ui.js +71 -0
  11. package/src/a2ui/negotiate.js +38 -0
  12. package/src/a2ui/to-a2ui.js +147 -0
  13. package/src/cli/args.js +1 -1
  14. package/src/cli/help.js +2 -1
  15. package/src/cli/mcp.js +23 -3
  16. package/src/mcp/boards.js +195 -0
  17. package/src/mcp/config.js +20 -0
  18. package/src/mcp/constants.js +33 -0
  19. package/src/mcp/index.js +5 -0
  20. package/src/mcp/page.js +59 -0
  21. package/src/mcp/schemas.js +45 -0
  22. package/src/mcp/serve.js +116 -0
  23. package/src/mcp/server.js +24 -0
  24. package/src/mcp/store.js +35 -0
  25. package/src/mcp/token.js +56 -0
  26. package/src/mcp/tools.js +179 -0
  27. package/src/mcp-ui/board/block-ctx.js +22 -0
  28. package/src/mcp-ui/board/bridge.js +12 -2
  29. package/src/mcp-ui/board/core.js +2 -0
  30. package/src/mcp-ui/board/lifecycle.js +47 -9
  31. package/src/mcp-ui/board/normalize.js +12 -0
  32. package/src/mcp-ui/board/render.js +38 -45
  33. package/src/mcp-ui/board/state.js +3 -0
  34. package/src/mcp-ui/board/vendors.js +56 -11
  35. package/src/server/board.js +12 -9
  36. package/src/server/http.js +19 -0
  37. package/src/server/page.js +4 -0
  38. package/src/spec/constants.js +13 -1
  39. package/src/spec/index.js +1 -0
  40. package/src/spec/lookup.js +1 -0
  41. package/src/spec/normalize.js +3 -0
  42. package/src/spec/pick.js +104 -0
  43. package/src/spec/schema.js +26 -3
  44. package/src/ui/app/drafts.js +3 -0
  45. package/src/ui/app/render.js +1 -0
  46. package/src/ui/app/submit.js +1 -1
  47. package/src/ui/manifest.js +3 -2
  48. package/src/ui/pick.css +32 -0
  49. package/src/ui/pick.js +246 -0
  50. package/types/a2ui/board-constants.d.ts +24 -0
  51. package/types/a2ui/from-a2ui.d.ts +16 -0
  52. package/types/a2ui/negotiate.d.ts +17 -0
  53. package/types/a2ui/to-a2ui.d.ts +12 -0
  54. package/types/cli/agent-topics.d.ts +46 -0
  55. package/types/mcp/boards.d.ts +178 -0
  56. package/types/{mcp.d.ts → mcp/config.d.ts} +1 -8
  57. package/types/mcp/constants.d.ts +21 -0
  58. package/types/mcp/index.d.ts +4 -0
  59. package/types/mcp/page.d.ts +27 -0
  60. package/types/mcp/schemas.d.ts +49 -0
  61. package/types/mcp/serve.d.ts +16 -0
  62. package/types/mcp/server.d.ts +4 -0
  63. package/types/mcp/store.d.ts +52 -0
  64. package/types/mcp/token.d.ts +9 -0
  65. package/types/mcp/tools.d.ts +17 -0
  66. package/types/server/result.d.ts +10 -0
  67. package/types/server/sanitize.d.ts +6 -0
  68. package/types/spec/constants.d.ts +9 -0
  69. package/types/spec/index.d.ts +1 -0
  70. package/types/spec/lookup.d.ts +2 -1
  71. package/types/spec/pick.d.ts +25 -0
  72. package/types/spec/schema.d.ts +48 -0
  73. package/src/mcp.js +0 -483
@@ -0,0 +1,35 @@
1
+ // Names the A2UI board surface and its negotiation share, in one place. The MIME
2
+ // strings and the action tool name come from a2ui.org's "A2UI over MCP" guide, which
3
+ // the package source does not confirm and one secondary source spells differently,
4
+ // so both MIME spellings are accepted and nothing else in Relay repeats them.
5
+
6
+ /** Relay's own id for the board catalog; a renderer lists it in `supportedCatalogIds`. */
7
+ export const BOARD_CATALOG_ID = 'https://github.com/khanglvm/relay/a2ui/catalog/board/v1';
8
+ export const A2UI_PROTOCOL_VERSION = '1.0';
9
+
10
+ /** The MIME a surface is sent as, then the other spelling a host may declare it under. */
11
+ export const A2UI_MIME = 'application/a2ui+json';
12
+ export const A2UI_MIMES = [A2UI_MIME, 'application/json+a2ui'];
13
+
14
+ /** The tool a host calls with a renderer event. */
15
+ export const A2UI_ACTION_TOOL = 'a2ui_action';
16
+ export const ACTION_SUBMIT = 'relay.submit';
17
+ export const ACTION_DRAFT = 'relay.draft';
18
+
19
+ /** Where the person's input lives in the surface's data model. */
20
+ export const DATA_ROOT = {
21
+ answers: 'answers',
22
+ notes: 'notes',
23
+ comment: 'comment',
24
+ annotations: 'annotations',
25
+ blockEdits: 'blockEdits',
26
+ };
27
+
28
+ /** Ids that would reach Object.prototype if used as a data-model key. */
29
+ export const UNSAFE_KEYS = ['__proto__', 'constructor', 'prototype'];
30
+
31
+ /** Escapes one data-model path segment (RFC 6901). */
32
+ export const pointerSegment = (key) => String(key).replace(/~/g, '~0').replace(/\//g, '~1');
33
+
34
+ /** The data-model pointer for one entry under a root: `/answers/q1`. */
35
+ export const dataPath = (root, key) => `/${DATA_ROOT[root]}/${pointerSegment(key)}`;
@@ -0,0 +1,5 @@
1
+ // The public board-catalog entry (@khanglvm/relay/a2ui-board): a Relay board as A2UI messages and back.
2
+ export { A2UI_MIME, A2UI_MIMES, BOARD_CATALOG_ID } from './board-constants.js';
3
+ export { declaresBoardCatalog, wantsA2ui } from './negotiate.js';
4
+ export { fromA2ui } from './from-a2ui.js';
5
+ export { toA2ui } from './to-a2ui.js';
@@ -0,0 +1,71 @@
1
+ // fromA2ui: the data model a renderer sends back, as the payload a board submit takes.
2
+ // It applies the same "was this answered" rules the web board does, so both surfaces
3
+ // produce one result for one set of answers. It is pure: the caller stores the result.
4
+ import { cleanPick } from '../spec/pick.js';
5
+ import { DATA_ROOT } from './board-constants.js';
6
+
7
+ const NOTE_MAX = 20000;
8
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
9
+ const own = (obj, key) => (isObject(obj) && Object.hasOwn(obj, key) ? obj[key] : undefined);
10
+ const text = (v) => (typeof v === 'string' ? v.trim() : '');
11
+
12
+ /** The value to submit for one answer, or undefined while the question counts as unanswered. */
13
+ export function answeredValue(q, raw) {
14
+ switch (q.type) {
15
+ case 'single': return typeof raw === 'string' && raw ? raw : undefined;
16
+ case 'multi': {
17
+ const picked = Array.isArray(raw) ? raw.filter((v) => typeof v === 'string' && v) : [];
18
+ return picked.length ? picked : undefined;
19
+ }
20
+ case 'yesno': return raw === 'yes' || raw === 'no' ? raw : undefined;
21
+ case 'scale': return typeof raw === 'number' && Number.isFinite(raw) ? raw : undefined;
22
+ case 'rank': return Array.isArray(raw) && raw.length ? [...raw] : undefined;
23
+ case 'checklist': return isObject(raw) && Object.keys(raw).length ? { ...raw } : undefined;
24
+ case 'allocate': {
25
+ const sum = isObject(raw) ? Object.values(raw).reduce((a, n) => a + (Number(n) || 0), 0) : 0;
26
+ return sum > 0 ? { ...raw } : undefined;
27
+ }
28
+ case 'pick': return cleanPick(q, raw);
29
+ default: return text(raw) || undefined;
30
+ }
31
+ }
32
+
33
+ /** Block comments (`/annotations/<blockId>`: text) as the annotation records a result carries. */
34
+ function blockAnnotations(spec, raw, now) {
35
+ const owner = new Map();
36
+ for (const q of spec.questions) for (const b of q.blocks || []) owner.set(b.id, q.id);
37
+ const known = new Set([...owner.keys(), ...(spec.blocks || []).map((b) => b.id)]);
38
+ return Object.keys(isObject(raw) ? raw : {})
39
+ .filter((blockId) => known.has(blockId) && text(raw[blockId]))
40
+ .map((blockId) => ({
41
+ id: `a2ui-${blockId}`, questionId: owner.get(blockId) ?? null, blockId,
42
+ target: { kind: 'block' }, text: text(raw[blockId]).slice(0, 5000), createdAt: now,
43
+ }));
44
+ }
45
+
46
+ /**
47
+ * @param {Record<string, any>} dataModel the surface's data model: /answers, /notes, /comment, /annotations, /blockEdits
48
+ * @param {Record<string, any>} spec the normalized spec the surface was made from
49
+ * @returns {{ answers: Record<string, unknown>, comment: string, notes: Record<string, string>, annotations: object[], blockEdits: Record<string, unknown> }}
50
+ */
51
+ export function fromA2ui(dataModel, spec, { now = new Date().toISOString() } = {}) {
52
+ const model = isObject(dataModel) ? dataModel : {};
53
+ const rawAnswers = model[DATA_ROOT.answers];
54
+ const rawNotes = model[DATA_ROOT.notes];
55
+ const answers = {};
56
+ const notes = {};
57
+ for (const q of spec.questions) {
58
+ const value = answeredValue(q, own(rawAnswers, q.id));
59
+ if (value !== undefined) answers[q.id] = value;
60
+ const note = text(own(rawNotes, q.id));
61
+ if (note) notes[q.id] = note.slice(0, NOTE_MAX);
62
+ }
63
+ const edits = model[DATA_ROOT.blockEdits];
64
+ return {
65
+ answers,
66
+ comment: text(model[DATA_ROOT.comment]).slice(0, NOTE_MAX),
67
+ notes,
68
+ annotations: blockAnnotations(spec, model[DATA_ROOT.annotations], now),
69
+ blockEdits: isObject(edits) ? edits : {},
70
+ };
71
+ }
@@ -0,0 +1,38 @@
1
+ // Decides whether a caller can draw the board catalog, from what it declared.
2
+ import { A2UI_MIMES, A2UI_PROTOCOL_VERSION, BOARD_CATALOG_ID } from './board-constants.js';
3
+
4
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
5
+
6
+ /** The a2ui declaration inside client capabilities: top-level, or under `extensions` or `experimental`. */
7
+ function declared(capabilities) {
8
+ if (!isObject(capabilities)) return undefined;
9
+ const nested = (key) => (isObject(capabilities[key]) ? capabilities[key].a2ui : undefined);
10
+ return capabilities.a2ui ?? nested('extensions') ?? nested('experimental');
11
+ }
12
+
13
+ /** True when the client declared the board catalog when it connected. */
14
+ export const capabilitiesDeclareBoardCatalog = (capabilities) => declaresBoardCatalog(declared(capabilities));
15
+
16
+ /**
17
+ * True when a declaration lists the board catalog for protocol 1.0:
18
+ * `{"1.0": {supportedCatalogIds: [...]}}`. A declaration that names the MIME
19
+ * types it accepts must include one Relay sends.
20
+ */
21
+ export function declaresBoardCatalog(declaration) {
22
+ if (!isObject(declaration)) return false;
23
+ const version = declaration[A2UI_PROTOCOL_VERSION];
24
+ if (!isObject(version) || !Array.isArray(version.supportedCatalogIds)) return false;
25
+ if (!version.supportedCatalogIds.includes(BOARD_CATALOG_ID)) return false;
26
+ const mimes = declaration.mimeTypes ?? version.mimeTypes;
27
+ return !Array.isArray(mimes) || mimes.some((m) => A2UI_MIMES.includes(m));
28
+ }
29
+
30
+ /**
31
+ * Whether a call should get A2UI messages: the call's own `_meta.a2ui` decides first,
32
+ * then the capabilities the client declared when it connected.
33
+ * @param {{ capabilities?: any, meta?: any }} caller
34
+ */
35
+ export function wantsA2ui({ capabilities, meta }) {
36
+ if (isObject(meta) && 'a2ui' in meta) return declaresBoardCatalog(meta.a2ui);
37
+ return capabilitiesDeclareBoardCatalog(capabilities);
38
+ }
@@ -0,0 +1,147 @@
1
+ // toA2ui: a normalized board spec as the A2UI v1.0 messages that draw it on the board catalog
2
+ // (board-catalog.json). It is pure: the host renders, and answers come back through fromA2ui.
3
+ import { CliError } from '../util.js';
4
+ import {
5
+ A2UI_PROTOCOL_VERSION, ACTION_SUBMIT, BOARD_CATALOG_ID, DATA_ROOT, dataPath, UNSAFE_KEYS,
6
+ } from './board-constants.js';
7
+
8
+ const COMPONENT_OF = {
9
+ markdown: 'Markdown', chart: 'Chart', table: 'Table', code: 'Code', diff: 'Diff', mermaid: 'Mermaid',
10
+ graphviz: 'Graphviz', plantuml: 'Plantuml', image: 'Image', compare: 'Compare', html: 'Html',
11
+ palette: 'Palette', kpi: 'Kpi', typography: 'Typography', video: 'Video', pdf: 'Pdf',
12
+ 'git-conflict': 'GitConflict', a2ui: 'Widget',
13
+ };
14
+
15
+ const FALLBACK_CHARS = 2000;
16
+ const clip = (s, max = FALLBACK_CHARS) => (typeof s === 'string' && s.length > max ? `${s.slice(0, max)}…` : String(s ?? ''));
17
+
18
+ /** The plain text a renderer shows for a block it cannot draw. */
19
+ export function fallbackText(block) {
20
+ switch (block.type) {
21
+ case 'markdown': return clip(block.md);
22
+ case 'chart': return clip(`Chart${block.title ? `: ${block.title}` : ''}${block.kind ? ` (${block.kind})` : ''}${Array.isArray(block.labels) ? `. ${block.labels.join(', ')}` : ''}`);
23
+ case 'table': return clip(`Table with ${Array.isArray(block.rows) ? block.rows.length : 0} rows. Columns: ${(block.columns || []).map((c) => (typeof c === 'string' ? c : c.label ?? c.key)).join(', ')}`);
24
+ case 'code': case 'mermaid': case 'plantuml': return clip(block.code);
25
+ case 'graphviz': return clip(block.dot);
26
+ case 'diff': return clip(block.diff);
27
+ case 'image': return clip(block.alt || block.src);
28
+ case 'compare': return clip(`${block.beforeLabel || 'Before'} and ${block.afterLabel || 'After'}`);
29
+ case 'html': return 'Custom page. Open the full board to see it.';
30
+ case 'video': return clip(block.title || `${block.provider} video ${block.videoId}`);
31
+ case 'pdf': return clip(block.title || block.src);
32
+ case 'kpi': return clip((block.items || []).map((i) => `${i.label}: ${i.value}`).join('; '));
33
+ case 'git-conflict': return clip(block.filename || 'A file with merge conflicts');
34
+ case 'a2ui': return clip(block.title || 'Widget');
35
+ default: return clip(block.title || block.type);
36
+ }
37
+ }
38
+
39
+ /** Maps block and question ids to unique component ids that fit the A2UI id rules. */
40
+ function idMaker() {
41
+ const used = new Set(['root', 'comment', 'submit']);
42
+ return (prefix, raw) => {
43
+ // A2UI component ids are UAX #31 identifiers: letters, digits and underscores.
44
+ const base = `${prefix}_${String(raw).replace(/[^A-Za-z0-9_]/g, '_')}`.slice(0, 60);
45
+ let id = base;
46
+ for (let n = 2; used.has(id); n++) id = `${base}_${n}`;
47
+ used.add(id);
48
+ return id;
49
+ };
50
+ }
51
+
52
+ function blockComponent(block, id, extra = {}) {
53
+ const { id: _id, type, a2uiSurface, components, dataModel, express, ...fields } = block;
54
+ const out = { id, component: COMPONENT_OF[type], ...fields, text: fallbackText(block), ...extra };
55
+ if (type === 'a2ui') {
56
+ out.widgetComponents = components ?? [];
57
+ if (dataModel) out.widgetData = dataModel;
58
+ }
59
+ if (!out.title && type !== 'markdown') out.title = block.title ?? block.filename ?? block.type;
60
+ return out;
61
+ }
62
+
63
+ function questionComponent(q, id, childIds) {
64
+ const { id: questionId, type, label, blocks, html, htmlFile, htmlHeight, note, ...rest } = q;
65
+ return {
66
+ id, component: 'Question', questionId, questionType: type, label, ...rest,
67
+ hasNote: note === true,
68
+ text: clip(label),
69
+ value: { '@path': dataPath('answers', questionId) },
70
+ note: { '@path': dataPath('notes', questionId) },
71
+ ...(childIds.length ? { children: childIds } : {}),
72
+ };
73
+ }
74
+
75
+ /** Questions are keyed in the data model by their ids, so the ones that could reach the prototype are refused. */
76
+ function assertSafeIds(spec) {
77
+ const bad = spec.questions.find((q) => UNSAFE_KEYS.includes(q.id));
78
+ if (bad) throw new CliError(`question id "${bad.id}" cannot be sent as A2UI; use another id.`);
79
+ }
80
+
81
+ /** The data model a surface starts with: defaults, then the saved draft. */
82
+ function initialData(spec, draft) {
83
+ const answers = new Map();
84
+ for (const q of spec.questions) if (q.default !== undefined) answers.set(q.id, q.default);
85
+ const saved = draft && typeof draft === 'object' ? draft : {};
86
+ if (saved.answers && typeof saved.answers === 'object') for (const [k, v] of Object.entries(saved.answers)) answers.set(k, v);
87
+ const pick = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? Object.fromEntries(Object.entries(v)) : {});
88
+ return {
89
+ [DATA_ROOT.answers]: Object.fromEntries(answers),
90
+ [DATA_ROOT.notes]: pick(saved.notes),
91
+ [DATA_ROOT.comment]: typeof saved.comment === 'string' ? saved.comment : '',
92
+ [DATA_ROOT.annotations]: {},
93
+ [DATA_ROOT.blockEdits]: pick(saved.blockEdits),
94
+ };
95
+ }
96
+
97
+ /**
98
+ * The three messages that make up a board's surface: createSurface, updateComponents, updateDataModel.
99
+ * @param {Record<string, any>} spec a normalized spec
100
+ * @param {{ surfaceId?: string, draft?: Record<string, any> | null }} [options]
101
+ * @returns {Array<Record<string, any>>}
102
+ */
103
+ export function toA2ui(spec, { surfaceId = 'relay-board', draft = null } = {}) {
104
+ assertSafeIds(spec);
105
+ const nextId = idMaker();
106
+ const components = [];
107
+ const children = [];
108
+ const addBlock = (block, extra) => {
109
+ const id = nextId('b', block.id);
110
+ components.push(blockComponent(block, id, extra));
111
+ return id;
112
+ };
113
+ for (const block of spec.blocks || []) children.push(addBlock(block));
114
+ for (const q of spec.questions) {
115
+ const own = [];
116
+ for (const block of q.blocks || []) own.push(addBlock(block));
117
+ for (const option of q.options || []) {
118
+ for (const block of option.blocks || []) own.push(addBlock(block, { optionValue: option.value }));
119
+ }
120
+ const id = nextId('q', q.id);
121
+ components.push(questionComponent({ ...q, options: (q.options || []).map(({ blocks, ...o }) => o) }, id, own));
122
+ children.push(id);
123
+ }
124
+ const display = spec.responseRequired === false;
125
+ if (!display) {
126
+ if (spec.note) {
127
+ components.push({ id: 'comment', component: 'Comment', label: 'Anything else?', value: { '@path': `/${DATA_ROOT.comment}` } });
128
+ children.push('comment');
129
+ }
130
+ components.push({
131
+ id: 'submit', component: 'Submit', label: spec.submitLabel || 'Submit',
132
+ action: { event: { name: ACTION_SUBMIT, context: {} } },
133
+ });
134
+ children.push('submit');
135
+ }
136
+ components.unshift({
137
+ id: 'root', component: 'Board', title: spec.title, text: clip(spec.intro || spec.title),
138
+ ...(spec.intro ? { intro: spec.intro } : {}), children,
139
+ responseRequired: !display, allowPartial: spec.allowPartial !== false,
140
+ });
141
+ const v = A2UI_PROTOCOL_VERSION;
142
+ return [
143
+ { version: v, createSurface: { surfaceId, catalogId: BOARD_CATALOG_ID, sendDataModel: !display } },
144
+ { version: v, updateComponents: { surfaceId, components } },
145
+ { version: v, updateDataModel: { surfaceId, value: initialData(spec, draft) } },
146
+ ];
147
+ }
package/src/cli/args.js CHANGED
@@ -5,7 +5,7 @@ const VALUED_FLAGS = new Set([
5
5
  'file', 'html', 'html-file', 'title', 'intro', 'timeout', 'port',
6
6
  'submit-label', 'height', 'limit', 'target', 'id', 'replies',
7
7
  'on-result', 'notify-cmd', 'idle-grace', 'scope', 'range',
8
- 'host', 'token', 'allow-origin', 'role', 'public-url', 'link', 'link-command',
8
+ 'host', 'token', 'token-file', 'allow-origin', 'role', 'public-url', 'link', 'link-command',
9
9
  ]);
10
10
 
11
11
  function camel(key) {
package/src/cli/help.js CHANGED
@@ -70,7 +70,8 @@ USAGE
70
70
  rly mcp run relay as an MCP App server (stdio) — boards render INLINE in
71
71
  a local desktop host (Claude Desktop, Codex) instead of a browser tab
72
72
  rly mcp --http [--port N] serve over Streamable HTTP for web/mobile/remote hosts
73
- [--host H --token SECRET --allow-origin ORIGIN]
73
+ [--host H --token-file PATH --allow-origin ORIGIN]
74
+ (token: --token-file, $RLY_MCP_TOKEN, or --token, which shows in the process list)
74
75
  rly mcp config | install --target print host setup, or write it (claude | codex)
75
76
 
76
77
  COMMON FLAGS
package/src/cli/mcp.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
- import { mcpConfig, runMcp, runMcpHttp } from '../mcp.js';
5
+ import { mcpConfig } from '../mcp/config.js';
6
6
  import { CliError } from '../util.js';
7
7
  import { parseArgs } from './args.js';
8
8
  import { printJson } from './io.js';
@@ -22,18 +22,38 @@ export async function cmdMcp(rest) {
22
22
  // Port precedence: --port flag, then PaaS-injected $PORT / $RLY_MCP_PORT,
23
23
  // then the default. PaaS hosts (Render, Railway, Fly, mcpdeploy, …) set $PORT.
24
24
  const envPort = process.env.PORT || process.env.RLY_MCP_PORT;
25
+ const { runMcpHttp } = await import('../mcp/serve.js');
25
26
  return runMcpHttp({
26
27
  port: args.port ? Number(args.port) : (envPort ? Number(envPort) : undefined),
27
28
  host: typeof args.host === 'string' ? args.host : (process.env.RLY_MCP_HOST || '127.0.0.1'),
28
- token: typeof args.token === 'string' ? args.token : (process.env.RLY_MCP_TOKEN || ''),
29
+ token: resolveToken(args),
29
30
  allowOrigin: typeof args.allowOrigin === 'string' ? args.allowOrigin : (process.env.RLY_MCP_ALLOW_ORIGIN || ''),
30
31
  });
31
32
  }
32
33
  // Default: be the stdio server. main() never resolves this, so the CLI's
33
34
  // post-run exit timer never arms — the server lives until stdin closes.
35
+ const { runMcp } = await import('../mcp/serve.js');
34
36
  return runMcp();
35
37
  }
36
38
 
39
+ /**
40
+ * The bearer token for --http. `--token` shows up in `ps`, so prefer `--token-file PATH`
41
+ * or $RLY_MCP_TOKEN; the flag keeps working. A file that cannot be read is an error,
42
+ * never an open endpoint.
43
+ */
44
+ function resolveToken(args) {
45
+ if (typeof args.tokenFile === 'string') {
46
+ try {
47
+ const token = fs.readFileSync(args.tokenFile, 'utf8').trim();
48
+ if (token) return token;
49
+ } catch (e) {
50
+ throw new CliError(`cannot read --token-file ${args.tokenFile}: ${e.message}`);
51
+ }
52
+ throw new CliError(`--token-file ${args.tokenFile} is empty`);
53
+ }
54
+ return typeof args.token === 'string' ? args.token : (process.env.RLY_MCP_TOKEN || '');
55
+ }
56
+
37
57
  // Resolve Claude Desktop's config path for this platform.
38
58
  function claudeDesktopConfigPath() {
39
59
  const home = os.homedir();
@@ -52,7 +72,7 @@ function cmdMcpConfig(args, sub) {
52
72
  const claudePath = claudeDesktopConfigPath();
53
73
  const codexPath = path.join(os.homedir(), '.codex', 'config.toml');
54
74
  printJson({
55
- note: 'Register relay as an MCP App server, then call relay_ask / relay_show from inside the host.',
75
+ note: 'Register relay as an MCP App server, then call relay_board from inside the host.',
56
76
  claudeCode: 'claude mcp add relay -- rly mcp',
57
77
  claudeDesktop: { file: claudePath, add: cfg.json },
58
78
  codex: { file: codexPath, add: cfg.toml },
@@ -0,0 +1,195 @@
1
+ // What each relay tool does to a board, apart from MCP framing: build, view, draft, submit, read.
2
+ import { assertSpecReady, cleanAnswers, normalizeSpec } from '../spec/index.js';
3
+ import { CliError } from '../util.js';
4
+ import { saveBoardArtifact } from '../store.js';
5
+ import { ACTION_DRAFT, ACTION_SUBMIT } from '../a2ui/board-constants.js';
6
+ import { assertSafeJson } from '../a2ui/compile.js';
7
+ import { fromA2ui } from '../a2ui/from-a2ui.js';
8
+ import { findBlock, sanitizeAnnotations, sanitizeBlockEdits } from '../server/sanitize.js';
9
+ import { ARTIFACT_MAX_BYTES, ARTIFACT_MIMES, artifactBytesMatch } from '../server/result.js';
10
+ import { RESULT_BUDGET_BYTES } from './constants.js';
11
+
12
+ const MAX_TEXT = 20000;
13
+ const MAX_EVENTS = 200;
14
+ const MAX_CROPS = 500;
15
+ const MAX_CROP_BASE64 = Math.ceil(ARTIFACT_MAX_BYTES / 3) * 4;
16
+ const MAX_EVENT_CONTEXT = 4096;
17
+ const EVENT_NAME = /^[a-z][a-z0-9_-]{0,39}$/;
18
+
19
+ const limit = (v, max) => (typeof v === 'string' ? v.slice(0, max) : '');
20
+ const asObject = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : {});
21
+
22
+ /** One board call's mode: a board that wants a reply is `ask`, anything else `show`. Questions always want a reply. */
23
+ export const modeOf = (spec) => (spec.responseRequired === false ? 'show' : 'ask');
24
+
25
+ /**
26
+ * Normalizes the tool arguments into a stored board. Spec errors come back as
27
+ * CliError so the tool can answer with an isError result the model can fix.
28
+ * @param {import('./store.js').RelayStore} store
29
+ * @param {Record<string, any>} args
30
+ * @param {{ displayOnly?: boolean }} [options]
31
+ */
32
+ export async function createMcpBoard(store, args, options = {}) {
33
+ const raw = { ...args };
34
+ const hasQuestions = Array.isArray(raw.questions) && raw.questions.length > 0;
35
+ if (options.displayOnly || (!hasQuestions && raw.responseRequired === undefined)) raw.responseRequired = false;
36
+ const spec = normalizeSpec(raw);
37
+ await assertSpecReady(spec);
38
+ const record = await store.create(spec);
39
+ return { record, spec, mode: modeOf(spec) };
40
+ }
41
+
42
+ /** The compact list of questions a model sees in the relay_board result: id, type, label. */
43
+ export function questionList(spec, labelMax = 80) {
44
+ return spec.questions.map((q) => ({ id: q.id, type: q.type, label: limit(q.label, labelMax), ...(q.required ? { required: true } : {}) }));
45
+ }
46
+
47
+ /**
48
+ * The relay_board result: a summary and structuredContent, never the spec.
49
+ * The question list shrinks until the whole result fits RESULT_BUDGET_BYTES.
50
+ * @returns {ToolResult}
51
+ */
52
+ export function boardResult(record, spec, mode) {
53
+ const title = limit(spec.title, 120);
54
+ const text = mode === 'ask'
55
+ ? `Board "${title}" (${record.id}) is on screen${spec.questions.length ? ` with ${spec.questions.length} question${spec.questions.length === 1 ? '' : 's'}` : ' for the person to acknowledge'}. They answer there. Read the answers with relay_result {boardId, wait_seconds}. Do not re-ask them in chat.`
56
+ : `Board "${title}" (${record.id}) is on screen, display-only. Continue without waiting.`;
57
+ for (const labelMax of [80, 40, 20, 0]) {
58
+ const structuredContent = { boardId: record.id, mode, title, questions: questionList(spec, labelMax) };
59
+ const size = Buffer.byteLength(text) + Buffer.byteLength(JSON.stringify(structuredContent));
60
+ if (size <= RESULT_BUDGET_BYTES) return { content: [{ type: 'text', text }], structuredContent };
61
+ }
62
+ const structuredContent = { boardId: record.id, mode, title: limit(spec.title, 80), questionCount: spec.questions.length };
63
+ return { content: [{ type: 'text', text }], structuredContent };
64
+ }
65
+
66
+ /** @typedef {import('@modelcontextprotocol/server').CallToolResult} ToolResult */
67
+
68
+ /** @returns {ToolResult} */
69
+ export const errorResult = (message) => ({ content: [{ type: 'text', text: message }], isError: true });
70
+
71
+ /** An invalid spec as a tool error; anything else is a server bug and rethrows. */
72
+ export function specError(err) {
73
+ if (err instanceof CliError) return errorResult(`relay: invalid board spec. ${err.message}`);
74
+ throw err;
75
+ }
76
+
77
+ /** Saves the person's answers so far, so relay_result can show them before the final submit. */
78
+ export async function saveDraft(store, id, draft, spec) {
79
+ const d = asObject(draft);
80
+ return store.update(id, {
81
+ draft: {
82
+ answers: spec ? cleanAnswers(spec, asObject(d.answers)) : asObject(d.answers),
83
+ comment: limit(d.comment, MAX_TEXT),
84
+ notes: asObject(d.notes),
85
+ annotations: sanitizeAnnotations(d.annotations, id),
86
+ updatedAt: new Date().toISOString(),
87
+ },
88
+ });
89
+ }
90
+
91
+ /** One base64 region crop written to the board's artifacts, under the same checks as the browser board's upload. */
92
+ function persistCrop(id, crop) {
93
+ const mime = crop.mime ?? 'image/png';
94
+ if (crop.data.length > MAX_CROP_BASE64 || !Object.hasOwn(ARTIFACT_MIMES, mime)) return undefined;
95
+ const bytes = Buffer.from(crop.data, 'base64');
96
+ if (!bytes.length || bytes.length > ARTIFACT_MAX_BYTES || !artifactBytesMatch(mime, bytes)) return undefined;
97
+ return { path: saveBoardArtifact(id, bytes, ARTIFACT_MIMES[mime]), mime, width: crop.width, height: crop.height };
98
+ }
99
+
100
+ // An iframe sends a region crop as base64; the record keeps a file path, like the browser board.
101
+ // Only a crop the sanitizer will keep is written, so a submit cannot fill the disk with dropped files.
102
+ function persistCrops(id, annotations) {
103
+ if (!Array.isArray(annotations)) return annotations;
104
+ let written = 0;
105
+ return annotations.map((a) => {
106
+ const crop = a && a.target && a.target.crop;
107
+ if (!crop || typeof crop.data !== 'string') return a;
108
+ const keep = written < MAX_CROPS && a.target.kind === 'image-region' && typeof a.text === 'string' && a.text.length <= 5000;
109
+ const saved = keep ? persistCrop(id, crop) : undefined;
110
+ if (saved) written++;
111
+ return { ...a, target: { ...a.target, crop: saved } };
112
+ });
113
+ }
114
+
115
+ /**
116
+ * Stores the final answers. A second submit is refused so a stray click cannot
117
+ * overwrite what the agent may already have read.
118
+ * @returns {Promise<{ ok: boolean, status?: string, error?: string }>}
119
+ */
120
+ export async function submitBoard(store, record, body) {
121
+ if (record.spec.responseRequired === false) return { ok: false, error: 'this board is display-only' };
122
+ if (record.result) return { ok: false, error: 'this board was already submitted' };
123
+ const b = asObject(body);
124
+ const answers = cleanAnswers(record.spec, asObject(b.answers));
125
+ const status = record.spec.questions.length ? 'submitted' : 'acknowledged';
126
+ const result = {
127
+ status,
128
+ answers,
129
+ skipped: record.spec.questions.filter((q) => !(q.id in answers)).map((q) => q.id),
130
+ comment: limit(b.comment, MAX_TEXT),
131
+ notes: asObject(b.notes),
132
+ annotations: sanitizeAnnotations(persistCrops(record.id, b.annotations), record.id),
133
+ blockEdits: sanitizeBlockEdits(b.blockEdits),
134
+ submittedAt: new Date().toISOString(),
135
+ };
136
+ await store.update(record.id, { result });
137
+ return { ok: true, status };
138
+ }
139
+
140
+ /**
141
+ * Appends one a2ui button click for relay_result to report. The click must name
142
+ * an a2ui block on this board and pass the checks the browser board applies to a2ui state.
143
+ * @returns {Promise<{ ok: boolean, entry?: object, error?: string }>}
144
+ */
145
+ export async function recordEvent(store, record, event) {
146
+ const e = asObject(event);
147
+ if (typeof e.blockId !== 'string' || !findBlock(record.spec, e.blockId, 'a2ui')) return { ok: false, error: 'no a2ui block with that id' };
148
+ if (typeof e.name !== 'string' || !EVENT_NAME.test(e.name)) return { ok: false, error: 'invalid a2ui event name' };
149
+ const context = asObject(e.context);
150
+ try {
151
+ assertSafeJson(context, 'a2ui event');
152
+ } catch (err) {
153
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
154
+ }
155
+ if (JSON.stringify(context).length > MAX_EVENT_CONTEXT) return { ok: false, error: 'a2ui event context is too large' };
156
+ const entry = { blockId: e.blockId, name: e.name, context, at: new Date().toISOString() };
157
+ const events = [...(record.events || []), entry].slice(-MAX_EVENTS);
158
+ await store.update(record.id, { events });
159
+ return { ok: true, entry };
160
+ }
161
+
162
+ /**
163
+ * A renderer event from an A2UI surface. `relay.submit` and `relay.draft` carry the surface's
164
+ * data model and store it as a submit or a draft; any other name is a widget button click.
165
+ * @returns {Promise<{ ok: boolean, status?: string, error?: string }>}
166
+ */
167
+ export async function handleSurfaceAction(store, record, args) {
168
+ const action = asObject(args.action);
169
+ const name = typeof action.name === 'string' ? action.name : args.name;
170
+ if (name !== ACTION_SUBMIT && name !== ACTION_DRAFT) {
171
+ const blockId = args.blockId;
172
+ return recordEvent(store, record, { blockId, name, context: args.context ?? action.context });
173
+ }
174
+ const dataModel = args.dataModel ?? asObject(action.context).dataModel ?? action.dataModel;
175
+ if (!dataModel || typeof dataModel !== 'object') return { ok: false, error: 'the event carries no data model' };
176
+ const payload = fromA2ui(dataModel, record.spec);
177
+ if (name === ACTION_SUBMIT) return submitBoard(store, record, payload);
178
+ await saveDraft(store, record.id, payload, record.spec);
179
+ return { ok: true };
180
+ }
181
+
182
+ /** What relay_result reports for a board right now. */
183
+ export function resultOf(record) {
184
+ const r = record.result;
185
+ if (r) return { boardId: record.id, ...r, ...(record.events?.length ? { events: record.events } : {}) };
186
+ const status = record.spec.responseRequired === false ? 'display-only' : 'open';
187
+ return {
188
+ boardId: record.id,
189
+ status,
190
+ ...(record.draft ? { draft: record.draft } : {}),
191
+ ...(record.events?.length ? { events: record.events } : {}),
192
+ };
193
+ }
194
+
195
+ export const isFinal = (record) => Boolean(record.result) || record.spec.responseRequired === false;
@@ -0,0 +1,20 @@
1
+ // The setup snippets `rly mcp config` prints.
2
+ import { DEFAULT_HTTP_PORT, HTTP_PATH } from './constants.js';
3
+
4
+ /** Setup for each host: a JSON entry, a Codex TOML block, and how to run the HTTP transport. */
5
+ export function mcpConfig({ command = 'rly', httpPort = DEFAULT_HTTP_PORT } = {}) {
6
+ const url = `http://127.0.0.1:${httpPort}${HTTP_PATH}`;
7
+ return {
8
+ command,
9
+ args: ['mcp'],
10
+ httpPort,
11
+ httpUrl: url,
12
+ json: { mcpServers: { relay: { command, args: ['mcp'] } } },
13
+ toml: `[mcp_servers.relay]\ncommand = "${command}"\nargs = ["mcp"]\n`,
14
+ http: {
15
+ run: `${command} mcp --http --port ${httpPort}`,
16
+ url,
17
+ note: 'Set RLY_MCP_TOKEN for a bearer-protected endpoint, and RLY_MCP_ALLOW_ORIGIN for a browser host on another origin. Boards live in the relay home of the machine that runs the server.',
18
+ },
19
+ };
20
+ }
@@ -0,0 +1,33 @@
1
+ // Names and limits shared by the MCP server modules and the board page.
2
+ import { A2UI_ACTION_TOOL } from '../a2ui/board-constants.js';
3
+
4
+ export const UI_EXT = 'io.modelcontextprotocol/ui';
5
+ export const UI_MIME = 'text/html;profile=mcp-app';
6
+ export const BOARD_URI = 'ui://relay/board';
7
+ export const VENDOR_URI_PREFIX = 'ui://relay/vendor/';
8
+ export const HTTP_PATH = '/mcp';
9
+ export const DEFAULT_HTTP_PORT = 4319;
10
+
11
+ // A relay_asset chunk is at most this many raw bytes, so one tool result stays
12
+ // well under the size a host will pass to an iframe.
13
+ export const VENDOR_CHUNK_BYTES = 768 * 1024;
14
+
15
+ // The longest relay_result may block. A host's own tool timeout is usually
16
+ // shorter, so the person polls again instead of the call hanging.
17
+ export const MAX_WAIT_SECONDS = 600;
18
+
19
+ // relay_board results stay under this size so a model reading it pays for a summary, not the spec.
20
+ export const RESULT_BUDGET_BYTES = 2048;
21
+
22
+ export const TOOL = {
23
+ board: 'relay_board',
24
+ help: 'relay_help',
25
+ result: 'relay_result',
26
+ view: 'relay_view',
27
+ draft: 'relay_draft',
28
+ submit: 'relay_submit',
29
+ asset: 'relay_asset',
30
+ a2uiAction: A2UI_ACTION_TOOL,
31
+ ask: 'relay_ask',
32
+ show: 'relay_show',
33
+ };
@@ -0,0 +1,5 @@
1
+ // The public MCP entry (@khanglvm/relay/mcp). runMcp and runMcpHttp load the SDK when a server starts.
2
+ export { mcpConfig } from './config.js';
3
+ export { runMcp, runMcpHttp } from './serve.js';
4
+ export { fileStore } from './store.js';
5
+ export { registerRelay } from './tools.js';