@khanglvm/relay 0.20.2 → 0.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 (54) hide show
  1. package/README.md +2 -2
  2. package/docs/AGENT.md +56 -83
  3. package/docs/SETUP.md +3 -2
  4. package/package.json +12 -5
  5. package/skills/relay/SKILL.md +45 -145
  6. package/src/cli/agent-topics.js +84 -0
  7. package/src/cli/config.js +26 -2
  8. package/src/cli/index.js +3 -5
  9. package/src/cli/mcp.js +4 -2
  10. package/src/cli/skill.js +21 -22
  11. package/src/mcp/boards.js +173 -0
  12. package/src/mcp/config.js +20 -0
  13. package/src/mcp/constants.js +31 -0
  14. package/src/mcp/index.js +5 -0
  15. package/src/mcp/page.js +59 -0
  16. package/src/mcp/schemas.js +42 -0
  17. package/src/mcp/serve.js +116 -0
  18. package/src/mcp/server.js +23 -0
  19. package/src/mcp/store.js +35 -0
  20. package/src/mcp/token.js +31 -0
  21. package/src/mcp/tools.js +171 -0
  22. package/src/mcp-ui/board/block-ctx.js +22 -0
  23. package/src/mcp-ui/board/bridge.js +12 -2
  24. package/src/mcp-ui/board/core.js +2 -0
  25. package/src/mcp-ui/board/lifecycle.js +47 -9
  26. package/src/mcp-ui/board/render.js +36 -44
  27. package/src/mcp-ui/board/vendors.js +56 -11
  28. package/src/spec/blocks/chart.js +8 -4
  29. package/src/spec/constants.js +19 -0
  30. package/src/spec/index.js +1 -0
  31. package/src/spec/lookup.js +78 -0
  32. package/src/spec/normalize.js +9 -4
  33. package/src/spec/ready.js +15 -1
  34. package/src/ui/manifest.js +1 -1
  35. package/types/cli/agent-topics.d.ts +46 -0
  36. package/types/mcp/boards.d.ts +168 -0
  37. package/types/{mcp.d.ts → mcp/config.d.ts} +1 -8
  38. package/types/mcp/constants.d.ts +21 -0
  39. package/types/mcp/index.d.ts +4 -0
  40. package/types/mcp/page.d.ts +27 -0
  41. package/types/mcp/schemas.d.ts +46 -0
  42. package/types/mcp/serve.d.ts +16 -0
  43. package/types/mcp/server.d.ts +4 -0
  44. package/types/mcp/store.d.ts +52 -0
  45. package/types/mcp/token.d.ts +5 -0
  46. package/types/mcp/tools.d.ts +17 -0
  47. package/types/server/result.d.ts +10 -0
  48. package/types/server/sanitize.d.ts +6 -0
  49. package/types/spec/blocks/chart.d.ts +1 -1
  50. package/types/spec/constants.d.ts +14 -0
  51. package/types/spec/index.d.ts +1 -0
  52. package/types/spec/lookup.d.ts +57 -0
  53. package/types/spec/ready.d.ts +2 -0
  54. package/src/mcp.js +0 -483
package/src/cli/index.js CHANGED
@@ -1,5 +1,4 @@
1
1
  // The rly command router.
2
- import { SPEC_SCHEMA } from '../spec/index.js';
3
2
  import { CliError } from '../util.js';
4
3
  import { cmdSkill, firstRunHint, skillFreshnessWarning } from './skill.js';
5
4
  import { printHelp } from './help.js';
@@ -10,7 +9,7 @@ import { cmdHistory, cmdList, cmdOpen, cmdReopen, cmdRescue, cmdReuse, cmdRm, cm
10
9
  import { cmdDiff, cmdGit } from './git.js';
11
10
  import { cmdResult, cmdWait } from './wait.js';
12
11
  import { cmdShare } from './share.js';
13
- import { cmdA2ui, cmdAgent, cmdConfig, cmdServeInternal } from './config.js';
12
+ import { cmdA2ui, cmdAgent, cmdConfig, cmdSchema, cmdServeInternal } from './config.js';
14
13
  import { cmdInstall } from './install.js';
15
14
  import { cmdUpgrade } from './upgrade.js';
16
15
  import { cmdMcp } from './mcp.js';
@@ -79,12 +78,11 @@ export async function main(argv) {
79
78
  case 'self-update':
80
79
  return await cmdUpgrade(parseArgs(rest));
81
80
  case 'agent':
82
- return cmdAgent();
81
+ return cmdAgent(rest[0]);
83
82
  case 'a2ui':
84
83
  return cmdA2ui();
85
84
  case 'schema':
86
- console.log(JSON.stringify(SPEC_SCHEMA, null, 2));
87
- return 0;
85
+ return cmdSchema(rest[0]);
88
86
  case 'mcp':
89
87
  return await cmdMcp(rest);
90
88
  case '__serve':
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,6 +22,7 @@ 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'),
@@ -31,6 +32,7 @@ export async function cmdMcp(rest) {
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
 
@@ -52,7 +54,7 @@ function cmdMcpConfig(args, sub) {
52
54
  const claudePath = claudeDesktopConfigPath();
53
55
  const codexPath = path.join(os.homedir(), '.codex', 'config.toml');
54
56
  printJson({
55
- note: 'Register relay as an MCP App server, then call relay_ask / relay_show from inside the host.',
57
+ note: 'Register relay as an MCP App server, then call relay_board from inside the host.',
56
58
  claudeCode: 'claude mcp add relay -- rly mcp',
57
59
  claudeDesktop: { file: claudePath, add: cfg.json },
58
60
  codex: { file: codexPath, add: cfg.toml },
package/src/cli/skill.js CHANGED
@@ -119,31 +119,30 @@ export function stampSkillVersion() {
119
119
  // AGENTS.md, …). A skill is only a tier-1 hint that agents can ignore; these
120
120
  // rules, appended to the instructions the agent always reads, enforce usage.
121
121
  // Printed to stdout so `rly skill rules >> CLAUDE.md` is the whole install.
122
- export const SKILL_RULES = `## relay — visual boards and structured feedback
122
+ export const SKILL_RULES = `## relay: visual boards and structured feedback
123
123
 
124
- - Use Relay for files, visuals, plans, diffs, and multiple related questions.
125
- Keep brief answers and progress updates in chat; follow existing user authorization.
124
+ - Use Relay for files, visuals, plans, diffs and several related questions. Keep brief
125
+ answers and progress updates in chat, and follow the authorization the user already gave.
126
126
  - Show without feedback: \`rly show --file spec.json --display-only\` (no waiter).
127
127
  Collect input: \`rly ask --file spec.json --detach\`, then keep
128
- \`rly wait <boardId> --timeout 1800 --while-active --idle-grace 300\` in the
129
- foreground. If it times out, read \`rly result <boardId>\` before continuing.
130
- - Use the most specific block: table/chart/kpi for data, image/compare for visuals,
131
- code/diff for source, mermaid for flows, markdown for prose, html for custom UI.
132
- \`rly view\`, \`rly diff\`, and \`rly git\` are shortcuts; visual options use \`options[].blocks\`.
133
- - Browser file links such as \`[source](/absolute/app.js:98)\` open supported files
134
- in a modal and highlight source lines. Unsupported files offer Open in app.
135
- For inline MCP or shared reviewers, embed file content as blocks instead.
136
- - Reconnect existing boards by ID with \`rly rescue\` / \`rly reopen\`; update
137
- content with \`rly update\`. Preserve the original port and saved input.
138
- - On a setup with \`devlink\`, add \`--devlink\` (or run \`rly config link devlink\` once)
139
- so the board opens on a private URL that phones and other Macs can reach.
140
- Share that printed URL, never a localhost one.
141
- - Small live widgets (status lists, numbers, buttons) are \`a2ui\` blocks; the
142
- grammar is in \`rly a2ui\`. Questions you depend on stay normal questions.
143
- - Read answers, notes, comment, annotations, and blockEdits together. Use the
144
- returned resultFile when stdout is truncated; a timeout is not an answer.
145
- - Full skill: \`rly skill path\`; fields: \`rly schema\`; advanced recipes and
146
- sharing permissions: \`rly agent\`. Load details only when needed.`;
128
+ \`rly wait <boardId> --timeout 1800 --while-active --idle-grace 300\` in the foreground.
129
+ A timeout is not an answer: read \`rly result <boardId>\` before continuing.
130
+ - Pick the most specific block: table, chart or kpi for data; image or compare for visuals;
131
+ code or diff for source; mermaid for flows; markdown for prose. Buttons and live status
132
+ are \`a2ui\`. Per-area sign-off is one \`checklist\` question. A visual choice puts
133
+ its picture in \`options[].blocks\`.
134
+ - Exact fields on demand: \`rly schema chart\` (any block or question type), \`rly agent <topic>\`
135
+ (questions, blocks, annotate, lifecycle, sharing, mcp, a2ui). \`rly view\`, \`rly diff\` and
136
+ \`rly git\` are shortcuts.
137
+ - A reader on another device needs an https url: \`--public-url 'https://host:{port}'\` or
138
+ \`--link-command CMD\` (a command that takes the port and prints the url); \`rly config link\`
139
+ saves it. Give the person the printed url, never a localhost one.
140
+ - Browser file links such as \`[source](/absolute/app.js:98)\` open in a modal. For inline MCP
141
+ boards and shared reviewers, embed file content as blocks instead.
142
+ - Reconnect a board by id with \`rly rescue\` or \`rly reopen\`, and change it with \`rly update\`.
143
+ - Read answers, notes, comment, annotations and blockEdits together. Use the returned
144
+ resultFile when stdout is cut short.
145
+ - The full skill is at \`rly skill path\`.`;
147
146
 
148
147
  export function cmdSkill(rest) {
149
148
  const sub = rest[0];
@@ -0,0 +1,173 @@
1
+ // What each relay tool does to a board, apart from MCP framing: build, view, draft, submit, read.
2
+ import { assertSpecReady, normalizeSpec } from '../spec/index.js';
3
+ import { CliError } from '../util.js';
4
+ import { saveBoardArtifact } from '../store.js';
5
+ import { assertSafeJson } from '../a2ui/compile.js';
6
+ import { findBlock, sanitizeAnnotations, sanitizeBlockEdits } from '../server/sanitize.js';
7
+ import { ARTIFACT_MAX_BYTES, ARTIFACT_MIMES, artifactBytesMatch } from '../server/result.js';
8
+ import { RESULT_BUDGET_BYTES } from './constants.js';
9
+
10
+ const MAX_TEXT = 20000;
11
+ const MAX_EVENTS = 200;
12
+ const MAX_CROPS = 500;
13
+ const MAX_CROP_BASE64 = Math.ceil(ARTIFACT_MAX_BYTES / 3) * 4;
14
+ const MAX_EVENT_CONTEXT = 4096;
15
+ const EVENT_NAME = /^[a-z][a-z0-9_-]{0,39}$/;
16
+
17
+ const limit = (v, max) => (typeof v === 'string' ? v.slice(0, max) : '');
18
+ const asObject = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : {});
19
+
20
+ /** One board call's mode: a board that wants a reply is `ask`, anything else `show`. Questions always want a reply. */
21
+ export const modeOf = (spec) => (spec.responseRequired === false ? 'show' : 'ask');
22
+
23
+ /**
24
+ * Normalizes the tool arguments into a stored board. Spec errors come back as
25
+ * CliError so the tool can answer with an isError result the model can fix.
26
+ * @param {import('./store.js').RelayStore} store
27
+ * @param {Record<string, any>} args
28
+ * @param {{ displayOnly?: boolean }} [options]
29
+ */
30
+ export async function createMcpBoard(store, args, options = {}) {
31
+ const raw = { ...args };
32
+ const hasQuestions = Array.isArray(raw.questions) && raw.questions.length > 0;
33
+ if (options.displayOnly || (!hasQuestions && raw.responseRequired === undefined)) raw.responseRequired = false;
34
+ const spec = normalizeSpec(raw);
35
+ await assertSpecReady(spec);
36
+ const record = await store.create(spec);
37
+ return { record, spec, mode: modeOf(spec) };
38
+ }
39
+
40
+ /** The compact list of questions a model sees in the relay_board result: id, type, label. */
41
+ export function questionList(spec, labelMax = 80) {
42
+ return spec.questions.map((q) => ({ id: q.id, type: q.type, label: limit(q.label, labelMax), ...(q.required ? { required: true } : {}) }));
43
+ }
44
+
45
+ /**
46
+ * The relay_board result: a summary and structuredContent, never the spec.
47
+ * The question list shrinks until the whole result fits RESULT_BUDGET_BYTES.
48
+ * @returns {ToolResult}
49
+ */
50
+ export function boardResult(record, spec, mode) {
51
+ const title = limit(spec.title, 120);
52
+ const text = mode === 'ask'
53
+ ? `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.`
54
+ : `Board "${title}" (${record.id}) is on screen, display-only. Continue without waiting.`;
55
+ for (const labelMax of [80, 40, 20, 0]) {
56
+ const structuredContent = { boardId: record.id, mode, title, questions: questionList(spec, labelMax) };
57
+ const size = Buffer.byteLength(text) + Buffer.byteLength(JSON.stringify(structuredContent));
58
+ if (size <= RESULT_BUDGET_BYTES) return { content: [{ type: 'text', text }], structuredContent };
59
+ }
60
+ const structuredContent = { boardId: record.id, mode, title: limit(spec.title, 80), questionCount: spec.questions.length };
61
+ return { content: [{ type: 'text', text }], structuredContent };
62
+ }
63
+
64
+ /** @typedef {import('@modelcontextprotocol/server').CallToolResult} ToolResult */
65
+
66
+ /** @returns {ToolResult} */
67
+ export const errorResult = (message) => ({ content: [{ type: 'text', text: message }], isError: true });
68
+
69
+ /** An invalid spec as a tool error; anything else is a server bug and rethrows. */
70
+ export function specError(err) {
71
+ if (err instanceof CliError) return errorResult(`relay: invalid board spec. ${err.message}`);
72
+ throw err;
73
+ }
74
+
75
+ /** Saves the person's answers so far, so relay_result can show them before the final submit. */
76
+ export async function saveDraft(store, id, draft) {
77
+ const d = asObject(draft);
78
+ return store.update(id, {
79
+ draft: {
80
+ answers: asObject(d.answers),
81
+ comment: limit(d.comment, MAX_TEXT),
82
+ notes: asObject(d.notes),
83
+ annotations: sanitizeAnnotations(d.annotations, id),
84
+ updatedAt: new Date().toISOString(),
85
+ },
86
+ });
87
+ }
88
+
89
+ /** One base64 region crop written to the board's artifacts, under the same checks as the browser board's upload. */
90
+ function persistCrop(id, crop) {
91
+ const mime = crop.mime ?? 'image/png';
92
+ if (crop.data.length > MAX_CROP_BASE64 || !Object.hasOwn(ARTIFACT_MIMES, mime)) return undefined;
93
+ const bytes = Buffer.from(crop.data, 'base64');
94
+ if (!bytes.length || bytes.length > ARTIFACT_MAX_BYTES || !artifactBytesMatch(mime, bytes)) return undefined;
95
+ return { path: saveBoardArtifact(id, bytes, ARTIFACT_MIMES[mime]), mime, width: crop.width, height: crop.height };
96
+ }
97
+
98
+ // An iframe sends a region crop as base64; the record keeps a file path, like the browser board.
99
+ // Only a crop the sanitizer will keep is written, so a submit cannot fill the disk with dropped files.
100
+ function persistCrops(id, annotations) {
101
+ if (!Array.isArray(annotations)) return annotations;
102
+ let written = 0;
103
+ return annotations.map((a) => {
104
+ const crop = a && a.target && a.target.crop;
105
+ if (!crop || typeof crop.data !== 'string') return a;
106
+ const keep = written < MAX_CROPS && a.target.kind === 'image-region' && typeof a.text === 'string' && a.text.length <= 5000;
107
+ const saved = keep ? persistCrop(id, crop) : undefined;
108
+ if (saved) written++;
109
+ return { ...a, target: { ...a.target, crop: saved } };
110
+ });
111
+ }
112
+
113
+ /**
114
+ * Stores the final answers. A second submit is refused so a stray click cannot
115
+ * overwrite what the agent may already have read.
116
+ * @returns {Promise<{ ok: boolean, status?: string, error?: string }>}
117
+ */
118
+ export async function submitBoard(store, record, body) {
119
+ if (record.spec.responseRequired === false) return { ok: false, error: 'this board is display-only' };
120
+ if (record.result) return { ok: false, error: 'this board was already submitted' };
121
+ const b = asObject(body);
122
+ const answers = asObject(b.answers);
123
+ const status = record.spec.questions.length ? 'submitted' : 'acknowledged';
124
+ const result = {
125
+ status,
126
+ answers,
127
+ skipped: record.spec.questions.filter((q) => !(q.id in answers)).map((q) => q.id),
128
+ comment: limit(b.comment, MAX_TEXT),
129
+ notes: asObject(b.notes),
130
+ annotations: sanitizeAnnotations(persistCrops(record.id, b.annotations), record.id),
131
+ blockEdits: sanitizeBlockEdits(b.blockEdits),
132
+ submittedAt: new Date().toISOString(),
133
+ };
134
+ await store.update(record.id, { result });
135
+ return { ok: true, status };
136
+ }
137
+
138
+ /**
139
+ * Appends one a2ui button click for relay_result to report. The click must name
140
+ * an a2ui block on this board and pass the checks the browser board applies to a2ui state.
141
+ * @returns {Promise<{ ok: boolean, entry?: object, error?: string }>}
142
+ */
143
+ export async function recordEvent(store, record, event) {
144
+ const e = asObject(event);
145
+ if (typeof e.blockId !== 'string' || !findBlock(record.spec, e.blockId, 'a2ui')) return { ok: false, error: 'no a2ui block with that id' };
146
+ if (typeof e.name !== 'string' || !EVENT_NAME.test(e.name)) return { ok: false, error: 'invalid a2ui event name' };
147
+ const context = asObject(e.context);
148
+ try {
149
+ assertSafeJson(context, 'a2ui event');
150
+ } catch (err) {
151
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
152
+ }
153
+ if (JSON.stringify(context).length > MAX_EVENT_CONTEXT) return { ok: false, error: 'a2ui event context is too large' };
154
+ const entry = { blockId: e.blockId, name: e.name, context, at: new Date().toISOString() };
155
+ const events = [...(record.events || []), entry].slice(-MAX_EVENTS);
156
+ await store.update(record.id, { events });
157
+ return { ok: true, entry };
158
+ }
159
+
160
+ /** What relay_result reports for a board right now. */
161
+ export function resultOf(record) {
162
+ const r = record.result;
163
+ if (r) return { boardId: record.id, ...r, ...(record.events?.length ? { events: record.events } : {}) };
164
+ const status = record.spec.responseRequired === false ? 'display-only' : 'open';
165
+ return {
166
+ boardId: record.id,
167
+ status,
168
+ ...(record.draft ? { draft: record.draft } : {}),
169
+ ...(record.events?.length ? { events: record.events } : {}),
170
+ };
171
+ }
172
+
173
+ 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,31 @@
1
+ // Names and limits shared by the MCP server modules and the board page.
2
+ export const UI_EXT = 'io.modelcontextprotocol/ui';
3
+ export const UI_MIME = 'text/html;profile=mcp-app';
4
+ export const BOARD_URI = 'ui://relay/board';
5
+ export const VENDOR_URI_PREFIX = 'ui://relay/vendor/';
6
+ export const HTTP_PATH = '/mcp';
7
+ export const DEFAULT_HTTP_PORT = 4319;
8
+
9
+ // A relay_asset chunk is at most this many raw bytes, so one tool result stays
10
+ // well under the size a host will pass to an iframe.
11
+ export const VENDOR_CHUNK_BYTES = 768 * 1024;
12
+
13
+ // The longest relay_result may block. A host's own tool timeout is usually
14
+ // shorter, so the person polls again instead of the call hanging.
15
+ export const MAX_WAIT_SECONDS = 600;
16
+
17
+ // relay_board results stay under this size so a model reading it pays for a summary, not the spec.
18
+ export const RESULT_BUDGET_BYTES = 2048;
19
+
20
+ export const TOOL = {
21
+ board: 'relay_board',
22
+ help: 'relay_help',
23
+ result: 'relay_result',
24
+ view: 'relay_view',
25
+ draft: 'relay_draft',
26
+ submit: 'relay_submit',
27
+ asset: 'relay_asset',
28
+ a2uiAction: 'a2ui_action',
29
+ ask: 'relay_ask',
30
+ show: 'relay_show',
31
+ };
@@ -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';
@@ -0,0 +1,59 @@
1
+ // The board page served as the ui:// resource, and the vendor libraries it loads on demand.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { fillPage, SRC_DIR } from '../ui/manifest.js';
6
+ import { VENDOR_CHUNK_BYTES } from './constants.js';
7
+
8
+ const PKG_ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
9
+ const VENDOR_DIR = path.join(PKG_ROOT, 'vendor');
10
+
11
+ /** The vendored libraries a board may load, by file name. Nothing else under vendor/ is served. */
12
+ export const VENDOR_FILES = ['chart.umd.js', 'mermaid.min.js', 'viz-standalone.js'];
13
+
14
+ export const PKG = JSON.parse(fs.readFileSync(path.join(PKG_ROOT, 'package.json'), 'utf8'));
15
+ export const DOCS_DIR = path.join(PKG_ROOT, 'docs');
16
+
17
+ const cache = new Map();
18
+ const readSrc = (file) => {
19
+ if (!cache.has(file)) cache.set(file, fs.readFileSync(path.join(SRC_DIR, file), 'utf8'));
20
+ return cache.get(file);
21
+ };
22
+
23
+ /** The single self-contained page: styles, block renderer and the MCP client, inlined. Built once per process. */
24
+ export function boardPage() {
25
+ if (!cache.has('page')) {
26
+ const boot = JSON.stringify({ version: PKG.version }).replace(/</g, '\\u003c');
27
+ cache.set('page', fillPage(readSrc('mcp-ui/index.html'), { title: 'Relay', bootJson: boot, entry: 'board' }, readSrc));
28
+ }
29
+ return cache.get('page');
30
+ }
31
+
32
+ /** The text of one vendor file, or null when the name is not on the allowlist. */
33
+ export function vendorText(name) {
34
+ if (!VENDOR_FILES.includes(name)) return null;
35
+ return fs.readFileSync(path.join(VENDOR_DIR, name), 'utf8');
36
+ }
37
+
38
+ /**
39
+ * One base64 chunk of a vendor file, for hosts that refuse resources/read.
40
+ * @returns {{ name: string, index: number, count: number, data: string } | null}
41
+ */
42
+ export function vendorChunk(name, index) {
43
+ if (!VENDOR_FILES.includes(name)) return null;
44
+ const bytes = fs.readFileSync(path.join(VENDOR_DIR, name));
45
+ const count = Math.ceil(bytes.length / VENDOR_CHUNK_BYTES);
46
+ if (!Number.isInteger(index) || index < 0 || index >= count) return null;
47
+ const slice = bytes.subarray(index * VENDOR_CHUNK_BYTES, (index + 1) * VENDOR_CHUNK_BYTES);
48
+ return { name, index, count, data: slice.toString('base64') };
49
+ }
50
+
51
+ /** The resource metadata hosts read to build the iframe's CSP. */
52
+ export const BOARD_RESOURCE_META = {
53
+ prefersBorder: false,
54
+ csp: {
55
+ connectDomains: [],
56
+ resourceDomains: ['https://*', 'data:', 'blob:'],
57
+ frameDomains: ['https://www.youtube-nocookie.com', 'https://player.vimeo.com', 'blob:', 'data:'],
58
+ },
59
+ };
@@ -0,0 +1,42 @@
1
+ // Tool input schemas. They stay small on purpose: the exact block and question shapes come from relay_help.
2
+ import * as z from 'zod';
3
+ import { AGENT_TOPICS } from '../cli/agent-topics.js';
4
+
5
+ const loose = z.record(z.string(), z.unknown());
6
+
7
+ /** The relay_board input: the spec's top-level fields, with blocks and questions left open. */
8
+ export const boardInput = z.looseObject({
9
+ title: z.string().optional().describe('Board heading'),
10
+ intro: z.string().optional().describe('One line of context under the heading'),
11
+ blocks: z.array(loose).optional().describe('Content blocks, shown above the questions'),
12
+ questions: z.array(loose).optional().describe('Questions to answer; leave out for a display-only board'),
13
+ responseRequired: z.boolean().optional(),
14
+ });
15
+
16
+ const boardId = z.string();
17
+ const token = z.string();
18
+
19
+ /** The deprecated relay_ask and relay_show take the same fields, but their schema stays empty so the tool list stays small. */
20
+ export const aliasInput = z.looseObject({});
21
+
22
+ export const viewInput = z.object({ boardId, token });
23
+ export const draftInput = z.object({ boardId, token, draft: loose });
24
+ export const submitInput = z.object({ boardId, token, payload: loose });
25
+ export const actionInput = z.object({
26
+ boardId,
27
+ token,
28
+ blockId: z.string(),
29
+ name: z.string(),
30
+ context: loose.optional(),
31
+ });
32
+ export const assetInput = z.object({ name: z.string(), index: z.number().int().min(0).default(0) });
33
+
34
+ export const helpInput = z.object({
35
+ topic: z.enum(Object.keys(AGENT_TOPICS)).optional().describe('Guide topic; omit for the list'),
36
+ schema: z.string().optional().describe('A block or question type, for its exact fields: chart, checklist, ...'),
37
+ });
38
+
39
+ export const resultInput = z.object({
40
+ boardId,
41
+ wait_seconds: z.number().min(0).optional().describe('Block up to this long for the submission; default 0 returns now'),
42
+ });
@@ -0,0 +1,116 @@
1
+ // Runs the relay MCP server over stdio or Streamable HTTP. The SDK is imported here, on demand, so the plain CLI stays light.
2
+ import crypto from 'node:crypto';
3
+ import http from 'node:http';
4
+ import { DEFAULT_HTTP_PORT, HTTP_PATH } from './constants.js';
5
+ import { loadServerKey } from './token.js';
6
+
7
+ const escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
8
+
9
+ /** Serves MCP over this process's stdin and stdout until the host closes stdin. */
10
+ export async function runMcp() {
11
+ const { serveStdio } = await import('@modelcontextprotocol/server/stdio');
12
+ const { createRelayServer } = await import('./server.js');
13
+ const tokenKey = loadServerKey();
14
+ const handle = serveStdio(() => createRelayServer({ tokenKey }), { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
15
+ // Resolves only once the host disconnects, so the CLI's exit timer never fires.
16
+ return new Promise((resolve) => {
17
+ const finish = () => handle.close().finally(() => resolve(0));
18
+ process.stdin.on('end', finish);
19
+ process.stdin.on('close', finish);
20
+ process.on('SIGINT', finish);
21
+ process.on('SIGTERM', finish);
22
+ });
23
+ }
24
+
25
+ const corsHeaders = (origin) => ({
26
+ 'access-control-allow-origin': origin || '*',
27
+ 'access-control-allow-methods': 'GET, POST, DELETE, OPTIONS',
28
+ 'access-control-allow-headers': 'content-type, authorization, mcp-session-id, mcp-protocol-version, last-event-id',
29
+ 'access-control-expose-headers': 'Mcp-Session-Id',
30
+ 'access-control-max-age': '86400',
31
+ vary: 'Origin',
32
+ });
33
+
34
+ /** A browser Origin is trusted when it is local or the one the operator allowed. A client with no Origin is not a browser. */
35
+ export function originAllowed(origin, allowOrigin) {
36
+ if (!origin) return true;
37
+ if (allowOrigin === '*' || (allowOrigin && origin === allowOrigin)) return true;
38
+ try {
39
+ return ['localhost', '127.0.0.1', '[::1]', '::1'].includes(new URL(origin).hostname);
40
+ } catch {
41
+ return false;
42
+ }
43
+ }
44
+
45
+ /** Constant-time string comparison for the bearer token. */
46
+ export function safeEqual(a, b) {
47
+ const x = Buffer.from(String(a));
48
+ const y = Buffer.from(String(b));
49
+ return x.length === y.length && crypto.timingSafeEqual(x, y);
50
+ }
51
+
52
+ const healthPage = (endpoint) =>
53
+ '<!doctype html><meta charset="utf-8"><title>relay MCP</title>' +
54
+ '<style>body{font:15px/1.6 -apple-system,system-ui,sans-serif;max-width:640px;margin:14vh auto;padding:0 20px;color:#1c1b19;background:#fcfbf9}code{background:#f1efe8;padding:2px 6px;border-radius:5px;font-size:13px}</style>' +
55
+ '<h1>relay MCP server</h1><p>Point an MCP client at <code>' + escapeHtml(endpoint) + '</code> and call <code>relay_board</code>.</p>';
56
+
57
+ /** The node request listener: CORS, origin and bearer checks, then the MCP handler. */
58
+ function requestListener({ serve, token, allowOrigin, endpoint }) {
59
+ return (req, res) => {
60
+ const origin = req.headers.origin || '';
61
+ const url = (req.url || '/').split('?')[0];
62
+ const cors = corsHeaders(origin);
63
+ if (req.method === 'OPTIONS') {
64
+ if (!originAllowed(origin, allowOrigin)) { res.writeHead(403); return res.end(); }
65
+ res.writeHead(204, cors);
66
+ return res.end();
67
+ }
68
+ if (req.method === 'GET' && url === '/') {
69
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
70
+ return res.end(healthPage(endpoint));
71
+ }
72
+ if (url !== HTTP_PATH) { res.writeHead(404, cors); return res.end('not found'); }
73
+ if (!originAllowed(origin, allowOrigin)) { res.writeHead(403, cors); return res.end('origin not allowed'); }
74
+ if (token && !bearerOk(req.headers.authorization, token)) {
75
+ res.writeHead(401, { ...cors, 'www-authenticate': 'Bearer' });
76
+ return res.end('unauthorized');
77
+ }
78
+ for (const [k, v] of Object.entries(cors)) res.setHeader(k, v);
79
+ serve(req, res).catch((e) => {
80
+ process.stderr.write(`relay mcp: ${e.message}\n`);
81
+ if (!res.headersSent) res.writeHead(500);
82
+ res.end();
83
+ });
84
+ };
85
+ }
86
+
87
+ const bearerOk = (header = '', token) => /^bearer /i.test(header) && safeEqual(header.slice(7), token);
88
+
89
+ /**
90
+ * Serves MCP over Streamable HTTP. Localhost by default; a bearer token and an
91
+ * allowed Origin are the controls for anything wider.
92
+ */
93
+ export async function runMcpHttp({ port = DEFAULT_HTTP_PORT, host = '127.0.0.1', token = '', allowOrigin = '' } = {}) {
94
+ const { createMcpHandler } = await import('@modelcontextprotocol/server');
95
+ const { toNodeHandler } = await import('@modelcontextprotocol/node');
96
+ const { createRelayServer } = await import('./server.js');
97
+ const tokenKey = loadServerKey();
98
+ const handler = createMcpHandler(() => createRelayServer({ tokenKey }), { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
99
+ const serve = toNodeHandler(handler, { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
100
+
101
+ const server = http.createServer(requestListener({ serve, token, allowOrigin, endpoint: `http://${host === '0.0.0.0' ? 'localhost' : host}:${port}${HTTP_PATH}` }));
102
+
103
+ return new Promise((resolve) => {
104
+ server.on('error', (e) => { process.stderr.write(`relay mcp http error: ${e.message}\n`); resolve(1); });
105
+ server.listen(port, host, () => {
106
+ const shown = host === '0.0.0.0' ? 'localhost' : host;
107
+ process.stderr.write(`relay MCP (Streamable HTTP) listening on http://${shown}:${port}${HTTP_PATH}\n`);
108
+ if (!token && host !== '127.0.0.1' && host !== 'localhost') {
109
+ process.stderr.write(' warning: bound to a non-local interface with no --token. Anyone who can reach this port can drive relay.\n');
110
+ }
111
+ });
112
+ const stop = () => { server.close(); handler.close().finally(() => resolve(0)); };
113
+ process.on('SIGINT', stop);
114
+ process.on('SIGTERM', stop);
115
+ });
116
+ }
@@ -0,0 +1,23 @@
1
+ // Builds an McpServer with the relay tools registered.
2
+ import { McpServer } from '@modelcontextprotocol/server';
3
+ import { UI_EXT, UI_MIME } from './constants.js';
4
+ import { PKG } from './page.js';
5
+ import { registerRelay } from './tools.js';
6
+
7
+ const INSTRUCTIONS = 'Relay shows boards inline. Call relay_board with a spec; the person answers in the board, then read it with relay_result. relay_help gives exact field shapes.';
8
+
9
+ const clientRendersBoards = (capabilities) => Boolean(capabilities?.extensions?.[UI_EXT]);
10
+
11
+ /** @param {Parameters<typeof registerRelay>[1]} [options] */
12
+ export function createRelayServer(options = {}) {
13
+ const server = new McpServer(
14
+ { name: 'relay', version: PKG.version },
15
+ { instructions: INSTRUCTIONS, capabilities: { extensions: { [UI_EXT]: { mimeTypes: [UI_MIME] } } } },
16
+ );
17
+ const appTools = registerRelay(server, options);
18
+ // The iframe tools only matter to a host that renders the board; others never see them.
19
+ server.server.oninitialized = () => {
20
+ if (!clientRendersBoards(server.server.getClientCapabilities())) for (const tool of appTools) tool.disable();
21
+ };
22
+ return server;
23
+ }
@@ -0,0 +1,35 @@
1
+ // The board store behind the MCP tools. registerRelay takes any object with this shape.
2
+ import { createBoard, loadBoard, saveBoard, saveResultFile } from '../store.js';
3
+
4
+ /**
5
+ * @typedef {object} BoardRecord
6
+ * @property {string} id
7
+ * @property {any} spec the normalized board spec
8
+ * @property {any} [draft] the person's answers so far
9
+ * @property {any} [result] set once the person submits
10
+ * @property {any[]} [events] a2ui button clicks, newest last
11
+ */
12
+
13
+ /**
14
+ * @typedef {object} RelayStore
15
+ * @property {(spec: any) => BoardRecord | Promise<BoardRecord>} create
16
+ * @property {(id: string) => BoardRecord | null | Promise<BoardRecord | null>} get
17
+ * @property {(id: string, patch: Partial<BoardRecord>) => BoardRecord | null | Promise<BoardRecord | null>} update
18
+ */
19
+
20
+ /** The default store: one JSON file per board under the relay home, shared with the CLI. */
21
+ export function fileStore() {
22
+ const get = (id) => (/^b-[a-z0-9]+$/i.test(String(id)) ? loadBoard(id) : null);
23
+ return {
24
+ create: (spec) => createBoard(spec),
25
+ get,
26
+ update(id, patch) {
27
+ const record = get(id);
28
+ if (!record) return null;
29
+ Object.assign(record, patch);
30
+ saveBoard(record);
31
+ if (patch.result) saveResultFile(id, patch.result);
32
+ return record;
33
+ },
34
+ };
35
+ }