@khanglvm/relay 0.20.3 → 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.
package/README.md CHANGED
@@ -13,7 +13,7 @@ It works with agents such as Claude Code and Codex.
13
13
 
14
14
  ## Install and try it
15
15
 
16
- Requires Node.js 18.3 or newer.
16
+ Requires Node.js 20 or newer.
17
17
 
18
18
  ```sh
19
19
  npm i -g @khanglvm/relay
package/docs/AGENT.md CHANGED
@@ -4,6 +4,7 @@ Use Relay to present files, visuals, substantial plans, diffs, and related user
4
4
  questions. Choose purpose-built blocks so users can inspect the content and
5
5
  leave precise feedback. Keep short answers and progress updates in chat.
6
6
  Respect the user’s existing authorization; boards do not add approval gates.
7
+ If your host app has its own way to ask the user or show results (native question cards, forms, pickers), use that for those. Use Relay for what the host can't show: line comments on a diff, Mermaid or Graphviz diagrams, element comments on an HTML prototype, rich multi-block review boards.
7
8
  For a concise workflow, read the bundled skill (`rly skill path`). This guide is
8
9
  a reference for fields and less common operations. Load one part with
9
10
  `rly agent <topic>` (`questions`, `blocks`, `annotate`, `lifecycle`, `sharing`,
@@ -134,62 +135,23 @@ Report the printed URL to the user and never a `localhost`, `127.0.0.1` or
134
135
  in the URL and the network behind the link are the access control. Use
135
136
  `rly share <id> --revoke --all` to cut access.
136
137
 
137
- ## Inline mode — relay as an MCP App (Claude & Codex apps)
138
-
139
- Everything above is the **CLI** surface (you run `rly` in a terminal and read
140
- JSON from stdout). relay is **also** an MCP App (SEP-1865): when a host registers
141
- `rly mcp` (see `rly mcp config` / `rly mcp install --target claude|codex`), you
142
- get two tools that render the board **inline in the conversation** instead of a
143
- browser tab. `rly mcp` speaks the MCP **stdio** transport, so it pairs with a
144
- **local desktop** host — Claude Desktop and Codex today.
145
-
146
- - **`relay_ask`** — collect decisions/feedback with real form controls.
147
- - **`relay_show`** — present a plan, diagram, diff, table, or prototype.
148
-
149
- **Web / mobile / remote hosts** can't reach a stdio subprocess, so for those run
150
- the **Streamable HTTP** transport: `rly mcp --http [--port N]` serves the same
151
- tools at `/mcp`. relay needs **only its own CLI** for this, with no extra
152
- infrastructure. Because relay is **stateless** (answers go iframe→host→model, never
153
- back to the server), **one deployed instance serves everyone**, so deploy it once
154
- on any address the app can reach and register that URL as a custom connector:
155
-
156
- - **Free MCP hosts** — the repo's `Dockerfile` runs relay with zero config on
157
- **mcpdeploy.dev**, **mcphosting.io**, **Render / Railway / Fly**, or **Glama**;
158
- the platform's `$PORT` is honored automatically. Set `RLY_MCP_TOKEN` for a
159
- bearer-protected endpoint.
160
- - **Smithery** (largest MCP marketplace) — publish the deployed URL with
161
- `smithery mcp publish <url> -n @you/relay` for discovery + an OAuth gateway, or
162
- distribute relay as a stdio bundle clients run locally.
163
-
164
- A hosted instance can't see your local files (so `codeFile`/local-image blocks
165
- won't resolve there — pass URLs or inline content); run it on your own machine if
166
- you need local-file access.
167
-
168
- Progressive rendering: if the host streams the tool call as you write it, the
169
- board renders valid blocks/questions incrementally (a "Composing…" preview) and
170
- finalizes when your call completes — so the user sees it build, not a blank wait.
171
-
172
- Both take **the exact same board spec** documented below (the tool `inputSchema`
173
- *is* this spec). Call the tool with your spec; the host shows the board, the user
174
- fills it in, and their answers come back to you (answers, per-question notes,
175
- comment) as a user-message turn, with structured context synced when the host
176
- supports it — read them just as you would the CLI's result JSON. There is **no
177
- `--detach`/`rly wait` dance, no stdout parsing, and no timeout** in this mode.
178
- `relay_ask` stays live until the user submits and the host delivers the result;
179
- `relay_show` is display-only by default and the agent continues immediately.
180
-
181
- **Near-full parity with the browser board.** Local `codeFile` / `htmlFile` /
182
- `diffFile` and local **image** files work inline too — the server inlines them
183
- (images as data URIs) while normalizing your spec, so the sandboxed board needs
184
- no file access. **Element-level annotations work inline** — the user can comment
185
- on chart points, diagram nodes, table cells, images and text selections, returned
186
- in `annotations` just like the CLI. The board also adopts the host's **theme,
187
- fonts and colors** and uses the host's **full-screen** control. The only
188
- inline-mode gaps vs. the browser board: **local video files** (use a
189
- YouTube/Vimeo/`https` URL instead — those play) and commenting on elements
190
- *inside* a custom-HTML mockup (every other annotation target works). Everything
191
- else — questions plus markdown/code/diff/table/chart/mermaid/graphviz/plantuml/
192
- image/palette/html — renders identically.
138
+ ## Inline mode: relay as an MCP App (Claude and Codex apps)
139
+
140
+ Everything outside this section is the CLI surface: you run `rly` and read JSON from stdout. Relay is also an MCP App server (SEP-1865). A host that registers `rly mcp` (see `rly mcp config` and `rly mcp install --target claude|codex`) renders the board inline in the conversation instead of a browser tab.
141
+
142
+ Tools:
143
+ - `relay_board`: takes the spec this guide describes. A spec with `questions` collects answers; one without is display-only. The result is a short summary with the `boardId`, never the spec.
144
+ - `relay_result {boardId, wait_seconds}`: the answers, notes, comment, annotations and blockEdits, or the draft while the person is still filling the board in. `wait_seconds` blocks until they submit, up to 600. A timeout is not an answer: call it again.
145
+ - `relay_help {topic}` or `relay_help {schema}`: a part of this guide, or the exact fields of one block or question type.
146
+ - `relay_ask` and `relay_show`: the old names, kept as aliases for one more minor version. Use `relay_board`.
147
+
148
+ The flow: call `relay_board`, tell the person the board is on screen, and carry on or wait. When they submit, the host posts a one-line message naming the board. Read the answers with `relay_result`. Do not ask the same questions again in chat.
149
+
150
+ `rly mcp` speaks stdio to a local desktop host. `rly mcp --http [--port N] [--token SECRET] [--allow-origin ORIGIN]` serves Streamable HTTP at `/mcp` for hosts that connect over a network; `RLY_MCP_TOKEN` sets the bearer token. Boards are stored in the relay home of the machine that runs the server, so `codeFile` and local images resolve there and nowhere else. To add the tools to a server you already run, call `registerRelay(server, {store, assetUrl, linkUrl})` from `@khanglvm/relay/mcp`.
151
+
152
+ If the host streams the tool call as you write it, the board renders valid blocks and questions as they arrive and finishes when your call completes.
153
+
154
+ Inline boards match the browser board. The server inlines `codeFile`, `htmlFile`, `diffFile` and local images (as data URIs) while it normalizes the spec, so the sandboxed board needs no file access. Element comments work on chart points, diagram nodes, table cells, images and text selections, and come back in `annotations`. The board adopts the host's theme, fonts, colors and full-screen control. Two gaps remain: local video files (use a YouTube, Vimeo or https URL) and comments on elements inside a custom HTML mockup.
193
155
 
194
156
  ## Creating boards
195
157
 
@@ -216,9 +178,8 @@ rly show --file spec.json --display-only
216
178
  ```
217
179
 
218
180
  `--display-only` automatically detaches the browser board. In MCP App mode,
219
- `relay_show` is display-only by default; set `responseRequired:true` only when
220
- the user really needs to acknowledge or leave feedback. `relay_ask` remains the
221
- response-bearing tool.
181
+ `relay_board` with no `questions` is display-only; set `responseRequired:true` only
182
+ when the user really needs to acknowledge or leave feedback.
222
183
 
223
184
  Read a markdown file (no questions; library-free renderer; submit reads "Done"):
224
185
 
@@ -783,8 +744,8 @@ file write alone starts a new model turn.
783
744
 
784
745
  | Client/surface | Recommended Relay return path |
785
746
  |---|---|
786
- | MCP App (`relay_ask`) | No CLI wait. The inline board stays live and sends `ui/message` on submit, which starts the user-return turn. |
787
- | MCP App (`relay_show`) | Display-only by default. Present it and continue immediately; no acknowledgement is requested. |
747
+ | MCP App (`relay_board` with questions) | No CLI wait. The board stays live; on submit the host posts a one-line message and `relay_result` returns the answers. |
748
+ | MCP App (`relay_board`, display-only) | Present it and continue immediately; no acknowledgement is requested. |
788
749
  | Claude Code | Run `rly wait <id> --timeout 0` as a [background Bash task](https://docs.anthropic.com/en/docs/claude-code/interactive-mode#background-bash-commands); retain its task id/output rather than opening a second board. |
789
750
  | Gemini CLI | Run the waiter in the background and set [`tools.shell.backgroundCompletionBehavior` to `"inject"`](https://geminicli.com/docs/reference/configuration/) so completion is returned to the agent; `"notify"` only informs the chat UI. |
790
751
  | Codex | Keep one foreground waiter. Codex background terminals use explicit `write_stdin` polling (the [poll window defaults to five minutes](https://developers.openai.com/codex/config-reference)); the process can outlive each poll, but no portable browser-submit API wakes a stopped turn. |
package/docs/SETUP.md CHANGED
@@ -37,10 +37,11 @@ rly mcp install --target codex
37
37
 
38
38
  The first command configures Claude Code; the others write Claude Desktop
39
39
  and Codex config respectively. Use `rly mcp config` to print config snippets.
40
- The server exposes `relay_ask` for feedback and `relay_show` for display.
40
+ The server exposes `relay_board` to show a board, `relay_result` to read the answers and `relay_help` for exact field shapes. `relay_ask` and `relay_show` remain as aliases of `relay_board` for one more minor version.
41
41
 
42
42
  For remote clients, `rly mcp --http` serves Streamable HTTP. Run `rly help`
43
- for host, port, token, and origin flags. The repo includes a `Dockerfile`.
43
+ for host, port, token, and origin flags. Boards live in the relay home of the
44
+ machine that runs the server. The repo includes a `Dockerfile`.
44
45
  See the [agent guide](AGENT.md) for board schemas, transport details,
45
46
  and host requirements.
46
47
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@khanglvm/relay",
3
- "version": "0.20.3",
3
+ "version": "0.21.0",
4
4
  "description": "Question boards with rich blocks (markdown, charts, mermaid, tables, code, diffs, video, sandboxed HTML), clickable local file-links, and element-level annotations for AI coding agents (Claude Code, Codex, \u2026): ask users structured questions, present interactive visuals, collect inline comments, read answers as JSON \u2014 in a local browser board OR rendered INLINE inside the Claude & Codex apps as an MCP App (SEP-1865).",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -45,7 +45,7 @@
45
45
  "LICENSE"
46
46
  ],
47
47
  "engines": {
48
- "node": ">=18.3"
48
+ "node": ">=20"
49
49
  },
50
50
  "scripts": {
51
51
  "check": "tsc -p tsconfig.json",
@@ -58,6 +58,7 @@
58
58
  },
59
59
  "devDependencies": {
60
60
  "@biomejs/biome": "^2.6.8",
61
+ "@modelcontextprotocol/client": "^2.4.0",
61
62
  "@types/node": "^20.19.43",
62
63
  "typescript": "^7.0.2"
63
64
  },
@@ -75,12 +76,18 @@
75
76
  "default": "./src/a2ui/compile.js"
76
77
  },
77
78
  "./mcp": {
78
- "types": "./types/mcp.d.ts",
79
- "default": "./src/mcp.js"
79
+ "types": "./types/mcp/index.d.ts",
80
+ "default": "./src/mcp/index.js"
80
81
  },
81
82
  "./schema.json": "./schema/spec.v1.json",
82
83
  "./package.json": "./package.json"
83
84
  },
84
85
  "main": "./src/index.js",
85
- "types": "./types/index.d.ts"
86
+ "types": "./types/index.d.ts",
87
+ "dependencies": {
88
+ "@modelcontextprotocol/ext-apps": "^2.0.4",
89
+ "@modelcontextprotocol/node": "^2.1.2",
90
+ "@modelcontextprotocol/server": "^2.4.0",
91
+ "zod": "^4.6.7"
92
+ }
86
93
  }
@@ -7,13 +7,15 @@ description: "Show the user files, visuals, diffs, plans, charts or a set of rel
7
7
 
8
8
  Put content in front of the person and read what they decide. Keep short answers and progress updates in chat. A board adds no approval step of its own; follow the authorization the user already gave.
9
9
 
10
+ If your host app has its own way to ask the user or show results (native question cards, forms, pickers), use that for those. Use Relay for what the host can't show: line comments on a diff, Mermaid or Graphviz diagrams, element comments on an HTML prototype, rich multi-block review boards.
11
+
10
12
  ## Workflow
11
13
  1. Write a spec to a JSON file. Never pass big JSON in a shell argument.
12
14
  2. `rly ask --file spec.json --detach` prints `{boardId,url}` at once. When no reply is needed: `rly show --file spec.json --display-only`.
13
15
  3. Give the person the url. To get the result: `rly wait <boardId> --timeout 1800 --while-active --idle-grace 300` (blocks until submit) or `rly result <boardId>` (now). A timeout is not an answer: run `rly result` before you decide.
14
16
  4. Read `answers`, `notes`, `comment`, `annotations` and `blockEdits` together; any of them can qualify an answer. When stdout is cut short, read the `resultFile` it names.
15
17
 
16
- If Relay MCP tools are connected, `relay_ask` (answers wanted) and `relay_show` (display only) take the same spec and the board renders inline. Embed file content with `mdFile`, `codeFile` or an image block, because inline boards cannot open local file links.
18
+ If Relay MCP tools are connected, call `relay_board` with the same spec (questions make it collect answers, none make it display-only) and the board renders inline. Read the answers with `relay_result {boardId, wait_seconds}`; `relay_help` gives exact fields. Embed file content with `mdFile`, `codeFile` or an image block, because inline boards cannot open local file links.
17
19
 
18
20
  ## Spec in one screen
19
21
  ```json
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 },
@@ -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
+ });