@khanglvm/relay 0.21.0 → 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.
- package/docs/AGENT.md +14 -2
- package/package.json +6 -1
- package/schema/spec.v1.json +55 -3
- package/skills/relay/SKILL.md +2 -1
- package/src/a2ui/board-catalog.json +1004 -0
- package/src/a2ui/board-constants.js +35 -0
- package/src/a2ui/board.js +5 -0
- package/src/a2ui/from-a2ui.js +71 -0
- package/src/a2ui/negotiate.js +38 -0
- package/src/a2ui/to-a2ui.js +147 -0
- package/src/cli/args.js +1 -1
- package/src/cli/help.js +2 -1
- package/src/cli/mcp.js +19 -1
- package/src/mcp/boards.js +26 -4
- package/src/mcp/constants.js +3 -1
- package/src/mcp/schemas.js +5 -2
- package/src/mcp/server.js +2 -1
- package/src/mcp/token.js +33 -8
- package/src/mcp/tools.js +14 -6
- package/src/mcp-ui/board/normalize.js +12 -0
- package/src/mcp-ui/board/render.js +2 -1
- package/src/mcp-ui/board/state.js +3 -0
- package/src/server/board.js +12 -9
- package/src/server/http.js +19 -0
- package/src/server/page.js +4 -0
- package/src/spec/constants.js +13 -1
- package/src/spec/index.js +1 -0
- package/src/spec/lookup.js +1 -0
- package/src/spec/normalize.js +3 -0
- package/src/spec/pick.js +104 -0
- package/src/spec/schema.js +26 -3
- package/src/ui/app/drafts.js +3 -0
- package/src/ui/app/render.js +1 -0
- package/src/ui/app/submit.js +1 -1
- package/src/ui/manifest.js +2 -1
- package/src/ui/pick.css +32 -0
- package/src/ui/pick.js +246 -0
- package/types/a2ui/board-constants.d.ts +24 -0
- package/types/a2ui/from-a2ui.d.ts +16 -0
- package/types/a2ui/negotiate.d.ts +17 -0
- package/types/a2ui/to-a2ui.d.ts +12 -0
- package/types/mcp/boards.d.ts +11 -1
- package/types/mcp/schemas.d.ts +5 -2
- package/types/mcp/token.d.ts +5 -1
- package/types/spec/constants.d.ts +9 -0
- package/types/spec/index.d.ts +1 -0
- package/types/spec/lookup.d.ts +2 -1
- package/types/spec/pick.d.ts +25 -0
- package/types/spec/schema.d.ts +48 -0
|
@@ -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
|
|
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
|
@@ -26,7 +26,7 @@ export async function cmdMcp(rest) {
|
|
|
26
26
|
return runMcpHttp({
|
|
27
27
|
port: args.port ? Number(args.port) : (envPort ? Number(envPort) : undefined),
|
|
28
28
|
host: typeof args.host === 'string' ? args.host : (process.env.RLY_MCP_HOST || '127.0.0.1'),
|
|
29
|
-
token:
|
|
29
|
+
token: resolveToken(args),
|
|
30
30
|
allowOrigin: typeof args.allowOrigin === 'string' ? args.allowOrigin : (process.env.RLY_MCP_ALLOW_ORIGIN || ''),
|
|
31
31
|
});
|
|
32
32
|
}
|
|
@@ -36,6 +36,24 @@ export async function cmdMcp(rest) {
|
|
|
36
36
|
return runMcp();
|
|
37
37
|
}
|
|
38
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
|
+
|
|
39
57
|
// Resolve Claude Desktop's config path for this platform.
|
|
40
58
|
function claudeDesktopConfigPath() {
|
|
41
59
|
const home = os.homedir();
|
package/src/mcp/boards.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
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';
|
|
2
|
+
import { assertSpecReady, cleanAnswers, normalizeSpec } from '../spec/index.js';
|
|
3
3
|
import { CliError } from '../util.js';
|
|
4
4
|
import { saveBoardArtifact } from '../store.js';
|
|
5
|
+
import { ACTION_DRAFT, ACTION_SUBMIT } from '../a2ui/board-constants.js';
|
|
5
6
|
import { assertSafeJson } from '../a2ui/compile.js';
|
|
7
|
+
import { fromA2ui } from '../a2ui/from-a2ui.js';
|
|
6
8
|
import { findBlock, sanitizeAnnotations, sanitizeBlockEdits } from '../server/sanitize.js';
|
|
7
9
|
import { ARTIFACT_MAX_BYTES, ARTIFACT_MIMES, artifactBytesMatch } from '../server/result.js';
|
|
8
10
|
import { RESULT_BUDGET_BYTES } from './constants.js';
|
|
@@ -73,11 +75,11 @@ export function specError(err) {
|
|
|
73
75
|
}
|
|
74
76
|
|
|
75
77
|
/** 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) {
|
|
78
|
+
export async function saveDraft(store, id, draft, spec) {
|
|
77
79
|
const d = asObject(draft);
|
|
78
80
|
return store.update(id, {
|
|
79
81
|
draft: {
|
|
80
|
-
answers: asObject(d.answers),
|
|
82
|
+
answers: spec ? cleanAnswers(spec, asObject(d.answers)) : asObject(d.answers),
|
|
81
83
|
comment: limit(d.comment, MAX_TEXT),
|
|
82
84
|
notes: asObject(d.notes),
|
|
83
85
|
annotations: sanitizeAnnotations(d.annotations, id),
|
|
@@ -119,7 +121,7 @@ export async function submitBoard(store, record, body) {
|
|
|
119
121
|
if (record.spec.responseRequired === false) return { ok: false, error: 'this board is display-only' };
|
|
120
122
|
if (record.result) return { ok: false, error: 'this board was already submitted' };
|
|
121
123
|
const b = asObject(body);
|
|
122
|
-
const answers = asObject(b.answers);
|
|
124
|
+
const answers = cleanAnswers(record.spec, asObject(b.answers));
|
|
123
125
|
const status = record.spec.questions.length ? 'submitted' : 'acknowledged';
|
|
124
126
|
const result = {
|
|
125
127
|
status,
|
|
@@ -157,6 +159,26 @@ export async function recordEvent(store, record, event) {
|
|
|
157
159
|
return { ok: true, entry };
|
|
158
160
|
}
|
|
159
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
|
+
|
|
160
182
|
/** What relay_result reports for a board right now. */
|
|
161
183
|
export function resultOf(record) {
|
|
162
184
|
const r = record.result;
|
package/src/mcp/constants.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
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
|
+
|
|
2
4
|
export const UI_EXT = 'io.modelcontextprotocol/ui';
|
|
3
5
|
export const UI_MIME = 'text/html;profile=mcp-app';
|
|
4
6
|
export const BOARD_URI = 'ui://relay/board';
|
|
@@ -25,7 +27,7 @@ export const TOOL = {
|
|
|
25
27
|
draft: 'relay_draft',
|
|
26
28
|
submit: 'relay_submit',
|
|
27
29
|
asset: 'relay_asset',
|
|
28
|
-
a2uiAction:
|
|
30
|
+
a2uiAction: A2UI_ACTION_TOOL,
|
|
29
31
|
ask: 'relay_ask',
|
|
30
32
|
show: 'relay_show',
|
|
31
33
|
};
|
package/src/mcp/schemas.js
CHANGED
|
@@ -22,12 +22,15 @@ export const aliasInput = z.looseObject({});
|
|
|
22
22
|
export const viewInput = z.object({ boardId, token });
|
|
23
23
|
export const draftInput = z.object({ boardId, token, draft: loose });
|
|
24
24
|
export const submitInput = z.object({ boardId, token, payload: loose });
|
|
25
|
+
/** A widget button click (`blockId`, `name`, `context`), or a renderer event (`action`, plus the surface's `dataModel`). */
|
|
25
26
|
export const actionInput = z.object({
|
|
26
27
|
boardId,
|
|
27
28
|
token,
|
|
28
|
-
blockId: z.string(),
|
|
29
|
-
name: z.string(),
|
|
29
|
+
blockId: z.string().optional(),
|
|
30
|
+
name: z.string().optional(),
|
|
30
31
|
context: loose.optional(),
|
|
32
|
+
action: loose.optional(),
|
|
33
|
+
dataModel: loose.optional(),
|
|
31
34
|
});
|
|
32
35
|
export const assetInput = z.object({ name: z.string(), index: z.number().int().min(0).default(0) });
|
|
33
36
|
|
package/src/mcp/server.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
// Builds an McpServer with the relay tools registered.
|
|
2
2
|
import { McpServer } from '@modelcontextprotocol/server';
|
|
3
|
+
import { capabilitiesDeclareBoardCatalog } from '../a2ui/negotiate.js';
|
|
3
4
|
import { UI_EXT, UI_MIME } from './constants.js';
|
|
4
5
|
import { PKG } from './page.js';
|
|
5
6
|
import { registerRelay } from './tools.js';
|
|
6
7
|
|
|
7
8
|
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
|
|
|
9
|
-
const clientRendersBoards = (capabilities) => Boolean(capabilities?.extensions?.[UI_EXT]);
|
|
10
|
+
const clientRendersBoards = (capabilities) => Boolean(capabilities?.extensions?.[UI_EXT]) || capabilitiesDeclareBoardCatalog(capabilities);
|
|
10
11
|
|
|
11
12
|
/** @param {Parameters<typeof registerRelay>[1]} [options] */
|
|
12
13
|
export function createRelayServer(options = {}) {
|
package/src/mcp/token.js
CHANGED
|
@@ -6,18 +6,43 @@ import { HOME } from '../store.js';
|
|
|
6
6
|
|
|
7
7
|
const KEY_FILE = path.join(HOME, 'mcp-key');
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
export function loadServerKey(file = KEY_FILE) {
|
|
9
|
+
const readKey = (file) => {
|
|
11
10
|
try {
|
|
12
|
-
|
|
13
|
-
if (existing) return existing;
|
|
11
|
+
return fs.readFileSync(file, 'utf8').trim();
|
|
14
12
|
} catch {
|
|
15
|
-
|
|
13
|
+
return '';
|
|
16
14
|
}
|
|
17
|
-
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The server's HMAC key: a random value kept in the relay home, created on first use.
|
|
19
|
+
* Two servers starting together both try to create it; the exclusive create lets one
|
|
20
|
+
* win and the other read what the winner wrote, so they never hold different keys.
|
|
21
|
+
*/
|
|
22
|
+
export function loadServerKey(file = KEY_FILE) {
|
|
23
|
+
const existing = readKey(file);
|
|
24
|
+
if (existing) return existing;
|
|
18
25
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
19
|
-
|
|
20
|
-
|
|
26
|
+
const key = crypto.randomBytes(32).toString('hex');
|
|
27
|
+
const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}`;
|
|
28
|
+
fs.writeFileSync(tmp, `${key}\n`, { mode: 0o600 });
|
|
29
|
+
try {
|
|
30
|
+
// link() fails when the key already exists and never exposes a half-written file.
|
|
31
|
+
fs.linkSync(tmp, file);
|
|
32
|
+
return key;
|
|
33
|
+
} catch (e) {
|
|
34
|
+
if (e.code === 'EEXIST') return readKey(file) || key;
|
|
35
|
+
// A filesystem without hard links: fall back to an exclusive create.
|
|
36
|
+
try {
|
|
37
|
+
fs.writeFileSync(file, `${key}\n`, { mode: 0o600, flag: 'wx' });
|
|
38
|
+
return key;
|
|
39
|
+
} catch (again) {
|
|
40
|
+
if (again.code !== 'EEXIST') throw again;
|
|
41
|
+
return readKey(file) || key;
|
|
42
|
+
}
|
|
43
|
+
} finally {
|
|
44
|
+
fs.rmSync(tmp, { force: true });
|
|
45
|
+
}
|
|
21
46
|
}
|
|
22
47
|
|
|
23
48
|
export const boardToken = (key, boardId) => crypto.createHmac('sha256', key).update(String(boardId)).digest('hex');
|
package/src/mcp/tools.js
CHANGED
|
@@ -2,11 +2,14 @@
|
|
|
2
2
|
import { registerAppResource, registerAppTool } from '@modelcontextprotocol/ext-apps/server';
|
|
3
3
|
import fs from 'node:fs';
|
|
4
4
|
import path from 'node:path';
|
|
5
|
+
import { A2UI_MIME, BOARD_CATALOG_ID } from '../a2ui/board-constants.js';
|
|
6
|
+
import { wantsA2ui } from '../a2ui/negotiate.js';
|
|
7
|
+
import { toA2ui } from '../a2ui/to-a2ui.js';
|
|
5
8
|
import { renderAgentTopic, topicIndex } from '../cli/agent-topics.js';
|
|
6
9
|
import { lookupSchema } from '../spec/index.js';
|
|
7
10
|
import { sleep } from '../util.js';
|
|
8
11
|
import {
|
|
9
|
-
boardResult, createMcpBoard, errorResult,
|
|
12
|
+
boardResult, createMcpBoard, errorResult, handleSurfaceAction, isFinal, resultOf, saveDraft, specError, submitBoard,
|
|
10
13
|
} from './boards.js';
|
|
11
14
|
import { BOARD_URI, MAX_WAIT_SECONDS, TOOL, UI_MIME, VENDOR_URI_PREFIX } from './constants.js';
|
|
12
15
|
import { BOARD_RESOURCE_META, boardPage, DOCS_DIR, vendorChunk, vendorText, VENDOR_FILES } from './page.js';
|
|
@@ -73,7 +76,7 @@ function registerBoardTools({ server, options, store, key }) {
|
|
|
73
76
|
}
|
|
74
77
|
const result = boardResult(made.record, made.spec, made.mode);
|
|
75
78
|
if (options.linkUrl) result.structuredContent = { .../** @type {object} */ (result.structuredContent), url: options.linkUrl(made.record.id) };
|
|
76
|
-
result._meta = { ...appMeta(['model', 'app']), relay: { token: boardToken(key, made.record.id) } };
|
|
79
|
+
result._meta = { ...appMeta(['model', 'app']), relay: { token: boardToken(key, made.record.id) }, 'relay/a2ui': { catalogIds: [BOARD_CATALOG_ID] } };
|
|
77
80
|
return result;
|
|
78
81
|
};
|
|
79
82
|
registerAppTool(server, TOOL.board, { title: 'Relay board', description: BOARD_DESCRIPTION, inputSchema: boardInput, _meta: modelMeta }, openBoard(false));
|
|
@@ -131,18 +134,23 @@ function registerAppTools({ server, options, store, key }) {
|
|
|
131
134
|
return act(record, args);
|
|
132
135
|
});
|
|
133
136
|
|
|
134
|
-
appTool(TOOL.view, { description: 'The board
|
|
137
|
+
appTool(TOOL.view, { description: 'The board, for the board iframe; for a host that declared the board catalog, A2UI messages.', inputSchema: viewInput }, async (args, ctx) => {
|
|
135
138
|
const { record, error } = await guard(args);
|
|
136
139
|
if (error) return error;
|
|
140
|
+
const caller = { capabilities: server.server.getClientCapabilities(), meta: ctx?.mcpReq?._meta };
|
|
141
|
+
if (wantsA2ui(caller)) {
|
|
142
|
+
const messages = toA2ui(record.spec, { surfaceId: `relay-${record.id}`, draft: record.draft });
|
|
143
|
+
return { content: [{ type: 'resource', resource: { uri: `a2ui://relay/board/${record.id}`, mimeType: A2UI_MIME, text: JSON.stringify(messages) } }] };
|
|
144
|
+
}
|
|
137
145
|
const vendorUrls = options.assetUrl ? Object.fromEntries(VENDOR_FILES.map((f) => [f, options.assetUrl(f)])) : undefined;
|
|
138
146
|
return json({ boardId: record.id }, { boardId: record.id, spec: record.spec, draft: record.draft ?? null, finished: Boolean(record.result), vendorUrls });
|
|
139
147
|
});
|
|
140
148
|
appTool(TOOL.draft, { description: 'Saves the answers so far.', inputSchema: draftInput }, onOpenBoard(async (record, args) => {
|
|
141
|
-
await saveDraft(store, record.id, args.draft);
|
|
149
|
+
await saveDraft(store, record.id, args.draft, record.spec);
|
|
142
150
|
return text('saved');
|
|
143
151
|
}));
|
|
144
|
-
appTool(TOOL.a2uiAction, { description: '
|
|
145
|
-
const outcome = await
|
|
152
|
+
appTool(TOOL.a2uiAction, { description: 'A renderer event: a button click from an a2ui block, or relay.submit and relay.draft from an A2UI board surface.', inputSchema: actionInput }, onOpenBoard(async (record, args) => {
|
|
153
|
+
const outcome = await handleSurfaceAction(store, record, args);
|
|
146
154
|
return outcome.ok ? text('recorded') : errorResult(`relay: ${outcome.error}`);
|
|
147
155
|
}));
|
|
148
156
|
appTool(TOOL.submit, { description: 'Stores the final answers.', inputSchema: submitInput }, (args) => oneAtATime(args.boardId, async () => {
|
|
@@ -61,6 +61,18 @@
|
|
|
61
61
|
q.total = Number.isFinite(rq.total) && rq.total > 0 ? Math.floor(rq.total) : 100;
|
|
62
62
|
if (rq.unit !== undefined) q.unit = String(rq.unit);
|
|
63
63
|
}
|
|
64
|
+
if (type === 'pick') {
|
|
65
|
+
const tiles = Array.isArray(rq.items) ? rq.items : [];
|
|
66
|
+
q.items = tiles.map((t) => (t && typeof t === 'object'
|
|
67
|
+
? { ...t, id: String(t.id != null ? t.id : t.title || ''), title: String(t.title != null ? t.title : t.id || '') }
|
|
68
|
+
: { id: String(t), title: String(t) }));
|
|
69
|
+
q.min = Number.isInteger(rq.min) && rq.min >= 0 ? Math.min(rq.min, q.items.length) : 0;
|
|
70
|
+
q.max = Number.isInteger(rq.max) && rq.max >= 1 ? Math.min(rq.max, q.items.length) : q.items.length;
|
|
71
|
+
q.itemNote = rq.itemNote !== false;
|
|
72
|
+
q.overall = rq.overall !== false;
|
|
73
|
+
q.note = false;
|
|
74
|
+
if (q.min > 0) q.required = true;
|
|
75
|
+
}
|
|
64
76
|
if (type === 'scale') {
|
|
65
77
|
q.min = Number.isFinite(rq.min) ? rq.min : 1;
|
|
66
78
|
q.max = Number.isFinite(rq.max) ? rq.max : Math.max(5, q.min + 1);
|
|
@@ -33,6 +33,7 @@
|
|
|
33
33
|
else if (q.type === 'rank') control.append(controlRank(q));
|
|
34
34
|
else if (q.type === 'checklist') control.append(controlChecklist(q));
|
|
35
35
|
else if (q.type === 'allocate') control.append(controlAllocate(q));
|
|
36
|
+
else if (q.type === 'pick') control.append(window.RelayPick.control(q, state, { onChange: () => clearErr(q.id) }));
|
|
36
37
|
else control.append(controlText(q, q.type === 'textarea'));
|
|
37
38
|
card.append(control);
|
|
38
39
|
if (q.note) {
|
|
@@ -80,7 +81,7 @@
|
|
|
80
81
|
let firstBad = null;
|
|
81
82
|
for (const q of QS) {
|
|
82
83
|
const required = q.required || !spec.allowPartial;
|
|
83
|
-
const bad = required && getValue(q) === undefined;
|
|
84
|
+
const bad = required && (getValue(q) === undefined || (q.type === 'pick' && window.RelayPick.short(q, state.answers[q.id])));
|
|
84
85
|
cards[q.id].classList.toggle('error', bad);
|
|
85
86
|
if (bad && !firstBad) firstBad = cards[q.id];
|
|
86
87
|
}
|
|
@@ -38,6 +38,7 @@
|
|
|
38
38
|
}
|
|
39
39
|
for (const q of QS) if (q.type === 'allocate') state.answers[q.id] = seedAllocate(q, state.answers[q.id]);
|
|
40
40
|
for (const q of QS) if (q.type === 'checklist') state.answers[q.id] = seedChecklist(q, state.answers[q.id]);
|
|
41
|
+
for (const q of QS) if (q.type === 'pick') state.answers[q.id] = window.RelayPick.seed(q, state.answers[q.id]);
|
|
41
42
|
}
|
|
42
43
|
function seedAllocate(q, prior) {
|
|
43
44
|
const m = prior && typeof prior === 'object' && !Array.isArray(prior) ? prior : {};
|
|
@@ -82,6 +83,8 @@
|
|
|
82
83
|
const sum = Object.values(m).reduce((a, n) => a + (Number(n) || 0), 0);
|
|
83
84
|
return sum > 0 ? { ...m } : undefined;
|
|
84
85
|
}
|
|
86
|
+
case 'pick':
|
|
87
|
+
return window.RelayPick.value(q, v);
|
|
85
88
|
default: {
|
|
86
89
|
const t = typeof v === 'string' ? v.trim() : '';
|
|
87
90
|
return t || undefined;
|