@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 +1 -1
- package/docs/AGENT.md +22 -61
- package/docs/SETUP.md +3 -2
- package/package.json +12 -5
- package/skills/relay/SKILL.md +3 -1
- package/src/cli/mcp.js +4 -2
- package/src/mcp/boards.js +173 -0
- package/src/mcp/config.js +20 -0
- package/src/mcp/constants.js +31 -0
- package/src/mcp/index.js +5 -0
- package/src/mcp/page.js +59 -0
- package/src/mcp/schemas.js +42 -0
- package/src/mcp/serve.js +116 -0
- package/src/mcp/server.js +23 -0
- package/src/mcp/store.js +35 -0
- package/src/mcp/token.js +31 -0
- package/src/mcp/tools.js +171 -0
- package/src/mcp-ui/board/block-ctx.js +22 -0
- package/src/mcp-ui/board/bridge.js +12 -2
- package/src/mcp-ui/board/core.js +2 -0
- package/src/mcp-ui/board/lifecycle.js +47 -9
- package/src/mcp-ui/board/render.js +36 -44
- package/src/mcp-ui/board/vendors.js +56 -11
- package/src/ui/manifest.js +1 -1
- package/types/cli/agent-topics.d.ts +46 -0
- package/types/mcp/boards.d.ts +168 -0
- package/types/{mcp.d.ts → mcp/config.d.ts} +1 -8
- package/types/mcp/constants.d.ts +21 -0
- package/types/mcp/index.d.ts +4 -0
- package/types/mcp/page.d.ts +27 -0
- package/types/mcp/schemas.d.ts +46 -0
- package/types/mcp/serve.d.ts +16 -0
- package/types/mcp/server.d.ts +4 -0
- package/types/mcp/store.d.ts +52 -0
- package/types/mcp/token.d.ts +5 -0
- package/types/mcp/tools.d.ts +17 -0
- package/types/server/result.d.ts +10 -0
- package/types/server/sanitize.d.ts +6 -0
- package/src/mcp.js +0 -483
package/src/mcp/serve.js
ADDED
|
@@ -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) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[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
|
+
}
|
package/src/mcp/store.js
ADDED
|
@@ -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
|
+
}
|
package/src/mcp/token.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// The per-board token an iframe presents to the app-only tools.
|
|
2
|
+
import crypto from 'node:crypto';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { HOME } from '../store.js';
|
|
6
|
+
|
|
7
|
+
const KEY_FILE = path.join(HOME, 'mcp-key');
|
|
8
|
+
|
|
9
|
+
/** The server's HMAC key: a random value kept in the relay home, created on first use. */
|
|
10
|
+
export function loadServerKey(file = KEY_FILE) {
|
|
11
|
+
try {
|
|
12
|
+
const existing = fs.readFileSync(file, 'utf8').trim();
|
|
13
|
+
if (existing) return existing;
|
|
14
|
+
} catch {
|
|
15
|
+
// first run: create it below
|
|
16
|
+
}
|
|
17
|
+
const key = crypto.randomBytes(32).toString('hex');
|
|
18
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
19
|
+
fs.writeFileSync(file, key + '\n', { mode: 0o600 });
|
|
20
|
+
return key;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const boardToken = (key, boardId) => crypto.createHmac('sha256', key).update(String(boardId)).digest('hex');
|
|
24
|
+
|
|
25
|
+
/** Constant-time comparison, so a wrong token leaks nothing about the right one. */
|
|
26
|
+
export function tokenValid(key, boardId, token) {
|
|
27
|
+
if (typeof token !== 'string') return false;
|
|
28
|
+
const want = Buffer.from(boardToken(key, boardId));
|
|
29
|
+
const got = Buffer.from(token);
|
|
30
|
+
return want.length === got.length && crypto.timingSafeEqual(want, got);
|
|
31
|
+
}
|
package/src/mcp/tools.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// registerRelay: the relay tools and the board resource on any MCP server.
|
|
2
|
+
import { registerAppResource, registerAppTool } from '@modelcontextprotocol/ext-apps/server';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { renderAgentTopic, topicIndex } from '../cli/agent-topics.js';
|
|
6
|
+
import { lookupSchema } from '../spec/index.js';
|
|
7
|
+
import { sleep } from '../util.js';
|
|
8
|
+
import {
|
|
9
|
+
boardResult, createMcpBoard, errorResult, isFinal, recordEvent, resultOf, saveDraft, specError, submitBoard,
|
|
10
|
+
} from './boards.js';
|
|
11
|
+
import { BOARD_URI, MAX_WAIT_SECONDS, TOOL, UI_MIME, VENDOR_URI_PREFIX } from './constants.js';
|
|
12
|
+
import { BOARD_RESOURCE_META, boardPage, DOCS_DIR, vendorChunk, vendorText, VENDOR_FILES } from './page.js';
|
|
13
|
+
import { actionInput, aliasInput, assetInput, boardInput, draftInput, helpInput, resultInput, submitInput, viewInput } from './schemas.js';
|
|
14
|
+
import { fileStore } from './store.js';
|
|
15
|
+
import { boardToken, loadServerKey, tokenValid } from './token.js';
|
|
16
|
+
|
|
17
|
+
const BOARD_DESCRIPTION = `Put a board in front of the person and collect their answers. It renders inline; the result is a summary with the boardId. Read the outcome with relay_result.
|
|
18
|
+
Spec: {title, intro?, blocks?:[...], questions?:[...]}. With no questions the board is display-only and needs no reply.
|
|
19
|
+
Question: {id,type,label,required?,options?:[{value,label,description?,blocks?}|"text"]}. Types: single multi yesno text textarea scale(min,max) color rank checklist allocate(total).
|
|
20
|
+
Blocks: markdown(md|mdFile) code(code|codeFile) diff(diffFile) image(src,alt?,pins?) compare(before,after) chart(kind,labels,series:[{label,data}]) table(columns,rows) kpi(items) mermaid(code) graphviz(dot) html palette video pdf a2ui(express). Local files take absolute paths; inline boards cannot open local links, so embed file content.
|
|
21
|
+
Blocks go on the board, on a question, or on an option. Use ids that stay stable.
|
|
22
|
+
For exact fields call relay_help {topic: questions|blocks|annotate|lifecycle|a2ui|sharing|mcp} or {schema:"chart"}.`;
|
|
23
|
+
|
|
24
|
+
const readDoc = (file) => fs.readFileSync(path.join(DOCS_DIR, file), 'utf8');
|
|
25
|
+
/** @returns {import('./boards.js').ToolResult} */
|
|
26
|
+
const text = (t) => ({ content: [{ type: 'text', text: t }] });
|
|
27
|
+
/** @returns {import('./boards.js').ToolResult} */
|
|
28
|
+
const json = (value, structured) => ({ content: [{ type: 'text', text: JSON.stringify(value) }], ...(structured ? { structuredContent: structured } : {}) });
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Adds the relay tools and the board resource to `server`.
|
|
32
|
+
*
|
|
33
|
+
* @param {any} server an McpServer
|
|
34
|
+
* @param {object} [options]
|
|
35
|
+
* @param {import('./store.js').RelayStore} [options.store] where boards live; defaults to the relay home on disk
|
|
36
|
+
* @param {string | Buffer} [options.tokenKey] the secret behind board tokens; defaults to a key file in the relay home
|
|
37
|
+
* @param {(name: string) => string} [options.assetUrl] URL of a vendor file, for hosts that can fetch it
|
|
38
|
+
* @param {(boardId: string) => string} [options.linkUrl] a URL where a person can open the board outside the host
|
|
39
|
+
* @returns the app-only tools, so a server can hide them from a client that cannot render the board
|
|
40
|
+
*/
|
|
41
|
+
export function registerRelay(server, options = {}) {
|
|
42
|
+
const ctx = { server, options, store: options.store ?? fileStore(), key: options.tokenKey ?? loadServerKey() };
|
|
43
|
+
registerBoardTools(ctx);
|
|
44
|
+
registerReadTools(ctx);
|
|
45
|
+
const appTools = registerAppTools(ctx);
|
|
46
|
+
registerResources(server);
|
|
47
|
+
return appTools;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Every app call reads a board and writes it back whole. Two clicks forwarded at once,
|
|
51
|
+
// or a draft racing the submit, would otherwise drop one write. The queue is per
|
|
52
|
+
// process, not per server, because the HTTP transport builds a server per request.
|
|
53
|
+
const boardQueues = new Map();
|
|
54
|
+
function oneAtATime(boardId, task) {
|
|
55
|
+
const key = String(boardId);
|
|
56
|
+
const run = (boardQueues.get(key) ?? Promise.resolve()).then(task);
|
|
57
|
+
const tail = run.catch(() => {});
|
|
58
|
+
boardQueues.set(key, tail);
|
|
59
|
+
tail.then(() => { if (boardQueues.get(key) === tail) boardQueues.delete(key); });
|
|
60
|
+
return run;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const appMeta = (visibility) => ({ ui: { resourceUri: BOARD_URI, visibility } });
|
|
64
|
+
const modelMeta = { ...appMeta(['model', 'app']), 'openai/outputTemplate': BOARD_URI };
|
|
65
|
+
|
|
66
|
+
function registerBoardTools({ server, options, store, key }) {
|
|
67
|
+
const openBoard = (displayOnly) => async (args) => {
|
|
68
|
+
let made;
|
|
69
|
+
try {
|
|
70
|
+
made = await createMcpBoard(store, args, { displayOnly });
|
|
71
|
+
} catch (err) {
|
|
72
|
+
return specError(err);
|
|
73
|
+
}
|
|
74
|
+
const result = boardResult(made.record, made.spec, made.mode);
|
|
75
|
+
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) } };
|
|
77
|
+
return result;
|
|
78
|
+
};
|
|
79
|
+
registerAppTool(server, TOOL.board, { title: 'Relay board', description: BOARD_DESCRIPTION, inputSchema: boardInput, _meta: modelMeta }, openBoard(false));
|
|
80
|
+
registerAppTool(server, TOOL.ask, { description: 'Deprecated alias of relay_board.', inputSchema: aliasInput, _meta: modelMeta }, openBoard(false));
|
|
81
|
+
registerAppTool(server, TOOL.show, { description: 'Deprecated alias of relay_board for a display-only board.', inputSchema: aliasInput, _meta: modelMeta }, openBoard(true));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function registerReadTools({ server, store }) {
|
|
85
|
+
const modelOnly = { ui: { visibility: ['model'] } };
|
|
86
|
+
registerAppTool(server, TOOL.help, {
|
|
87
|
+
description: 'Exact Relay field shapes. topic: questions, blocks, annotate, lifecycle, a2ui, sharing, mcp. schema: one block or question type.',
|
|
88
|
+
inputSchema: helpInput,
|
|
89
|
+
_meta: modelOnly,
|
|
90
|
+
}, ({ topic, schema }) => {
|
|
91
|
+
if (schema) {
|
|
92
|
+
const found = lookupSchema(schema);
|
|
93
|
+
return found ? json(found) : errorResult(`relay: no block or question type "${schema}". ${topicIndex()}`);
|
|
94
|
+
}
|
|
95
|
+
return text(topic ? renderAgentTopic(topic, readDoc) : topicIndex());
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
registerAppTool(server, TOOL.result, {
|
|
99
|
+
description: 'The answers on a board (answers, notes, comment, annotations, blockEdits), or its draft while the person is still filling it in. Pass wait_seconds to block until they submit.',
|
|
100
|
+
inputSchema: resultInput,
|
|
101
|
+
_meta: modelOnly,
|
|
102
|
+
}, async ({ boardId, wait_seconds = 0 }, ctx) => {
|
|
103
|
+
const deadline = Date.now() + Math.min(wait_seconds, MAX_WAIT_SECONDS) * 1000;
|
|
104
|
+
for (;;) {
|
|
105
|
+
const record = await store.get(boardId);
|
|
106
|
+
if (!record) return errorResult(`relay: no board "${boardId}"`);
|
|
107
|
+
if (isFinal(record) || Date.now() >= deadline || ctx?.mcpReq?.signal?.aborted) {
|
|
108
|
+
const out = resultOf(record);
|
|
109
|
+
return json(out, { boardId, status: out.status });
|
|
110
|
+
}
|
|
111
|
+
await sleep(500);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function registerAppTools({ server, options, store, key }) {
|
|
117
|
+
const appTools = [];
|
|
118
|
+
const appTool = (name, config, cb) => appTools.push(registerAppTool(server, name, { ...config, _meta: { ui: { visibility: ['app'] } } }, cb));
|
|
119
|
+
|
|
120
|
+
/** The board a valid token opens, or an error result. */
|
|
121
|
+
const guard = async (args) => {
|
|
122
|
+
if (!tokenValid(key, args.boardId, args.token)) return { error: errorResult('relay: board token mismatch') };
|
|
123
|
+
const record = await store.get(args.boardId);
|
|
124
|
+
return record ? { record } : { error: errorResult('relay: board not found') };
|
|
125
|
+
};
|
|
126
|
+
/** An app tool that acts on one unfinished board. */
|
|
127
|
+
const onOpenBoard = (act) => (args) => oneAtATime(args.boardId, async () => {
|
|
128
|
+
const { record, error } = await guard(args);
|
|
129
|
+
if (error) return error;
|
|
130
|
+
if (isFinal(record)) return errorResult('relay: board is finished');
|
|
131
|
+
return act(record, args);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
appTool(TOOL.view, { description: 'The board spec, for the board iframe.', inputSchema: viewInput }, async (args) => {
|
|
135
|
+
const { record, error } = await guard(args);
|
|
136
|
+
if (error) return error;
|
|
137
|
+
const vendorUrls = options.assetUrl ? Object.fromEntries(VENDOR_FILES.map((f) => [f, options.assetUrl(f)])) : undefined;
|
|
138
|
+
return json({ boardId: record.id }, { boardId: record.id, spec: record.spec, draft: record.draft ?? null, finished: Boolean(record.result), vendorUrls });
|
|
139
|
+
});
|
|
140
|
+
appTool(TOOL.draft, { description: 'Saves the answers so far.', inputSchema: draftInput }, onOpenBoard(async (record, args) => {
|
|
141
|
+
await saveDraft(store, record.id, args.draft);
|
|
142
|
+
return text('saved');
|
|
143
|
+
}));
|
|
144
|
+
appTool(TOOL.a2uiAction, { description: 'Records a button click from an a2ui block.', inputSchema: actionInput }, onOpenBoard(async (record, args) => {
|
|
145
|
+
const outcome = await recordEvent(store, record, args);
|
|
146
|
+
return outcome.ok ? text('recorded') : errorResult(`relay: ${outcome.error}`);
|
|
147
|
+
}));
|
|
148
|
+
appTool(TOOL.submit, { description: 'Stores the final answers.', inputSchema: submitInput }, (args) => oneAtATime(args.boardId, async () => {
|
|
149
|
+
const { record, error } = await guard(args);
|
|
150
|
+
if (error) return error;
|
|
151
|
+
const outcome = await submitBoard(store, record, args.payload);
|
|
152
|
+
return outcome.ok ? json({ status: outcome.status }) : errorResult(`relay: ${outcome.error}`);
|
|
153
|
+
}));
|
|
154
|
+
appTool(TOOL.asset, { description: 'One chunk of a vendored library, for hosts that refuse resources/read.', inputSchema: assetInput }, ({ name, index }) => {
|
|
155
|
+
const chunk = vendorChunk(name, index);
|
|
156
|
+
return chunk ? json({ name, index, count: chunk.count }, chunk) : errorResult(`relay: no asset "${name}" chunk ${index}`);
|
|
157
|
+
});
|
|
158
|
+
return appTools;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function registerResources(server) {
|
|
162
|
+
registerAppResource(server, 'Relay board', BOARD_URI, { mimeType: UI_MIME, description: 'The interactive board shown by relay_board.', _meta: { ui: BOARD_RESOURCE_META } }, () => ({
|
|
163
|
+
contents: [{ uri: BOARD_URI, mimeType: UI_MIME, text: boardPage(), _meta: { ui: BOARD_RESOURCE_META } }],
|
|
164
|
+
}));
|
|
165
|
+
for (const file of VENDOR_FILES) {
|
|
166
|
+
const uri = VENDOR_URI_PREFIX + file;
|
|
167
|
+
server.registerResource(`vendor ${file}`, uri, { mimeType: 'application/javascript' }, () => ({
|
|
168
|
+
contents: [{ uri, mimeType: 'application/javascript', text: vendorText(file) }],
|
|
169
|
+
}));
|
|
170
|
+
}
|
|
171
|
+
}
|
|
@@ -1,3 +1,23 @@
|
|
|
1
|
+
// A button click in an a2ui block reaches the agent before the person submits.
|
|
2
|
+
// Events already in the stored snapshot were sent when they happened.
|
|
3
|
+
function forwardA2uiEvents(blockId, before, after) {
|
|
4
|
+
if (!BOARD.token || !after || after.type !== 'a2ui' || !Array.isArray(after.events)) return;
|
|
5
|
+
for (const e of unsentA2uiEvents(before, after.events)) {
|
|
6
|
+
callServerTool('a2ui_action', { boardId: BOARD.id, token: BOARD.token, blockId, name: e.name, context: e.context }).catch(() => {});
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
// A snapshot keeps only the newest events, so once it is full a click drops the
|
|
10
|
+
// oldest one and the count stays the same. What was sent is the longest run at
|
|
11
|
+
// the start of the new list that also ends the old one.
|
|
12
|
+
function unsentA2uiEvents(before, events) {
|
|
13
|
+
const prior = before && Array.isArray(before.events) ? before.events.map((e) => JSON.stringify(e)) : [];
|
|
14
|
+
const next = events.map((e) => JSON.stringify(e));
|
|
15
|
+
for (let kept = Math.min(prior.length, next.length); kept > 0; kept--) {
|
|
16
|
+
if (next.slice(0, kept).every((e, i) => e === prior[prior.length - kept + i])) return events.slice(kept);
|
|
17
|
+
}
|
|
18
|
+
return events;
|
|
19
|
+
}
|
|
20
|
+
|
|
1
21
|
function blockCtx(questionId) {
|
|
2
22
|
return {
|
|
3
23
|
theme: effectiveTheme,
|
|
@@ -14,8 +34,10 @@
|
|
|
14
34
|
},
|
|
15
35
|
edits: state.blockEdits,
|
|
16
36
|
onBlockEdit: (blockId, codeOrNull) => {
|
|
37
|
+
const before = state.blockEdits[blockId];
|
|
17
38
|
if (codeOrNull === null || codeOrNull === undefined) delete state.blockEdits[blockId];
|
|
18
39
|
else state.blockEdits[blockId] = codeOrNull;
|
|
40
|
+
forwardA2uiEvents(blockId, before, codeOrNull);
|
|
19
41
|
},
|
|
20
42
|
};
|
|
21
43
|
}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
// host frame gone — nothing we can do
|
|
15
15
|
}
|
|
16
16
|
}
|
|
17
|
-
function request(method, params) {
|
|
17
|
+
function request(method, params, timeoutMs = 15000) {
|
|
18
18
|
const id = 'rly-' + (++rpcSeq);
|
|
19
19
|
return new Promise((resolve, reject) => {
|
|
20
20
|
pending.set(id, { resolve, reject });
|
|
@@ -25,9 +25,19 @@
|
|
|
25
25
|
pending.delete(id);
|
|
26
26
|
reject(new Error('timeout: ' + method));
|
|
27
27
|
}
|
|
28
|
-
},
|
|
28
|
+
}, timeoutMs);
|
|
29
29
|
});
|
|
30
30
|
}
|
|
31
|
+
// Calls one of the relay server's tools through the host. A tool-level error
|
|
32
|
+
// rejects, so callers handle "the host refused" and "the server said no" alike.
|
|
33
|
+
async function callServerTool(name, args, timeoutMs) {
|
|
34
|
+
const res = await request('tools/call', { name, arguments: args }, timeoutMs);
|
|
35
|
+
if (!res || res.isError) {
|
|
36
|
+
const msg = res && Array.isArray(res.content) && res.content[0] && res.content[0].text;
|
|
37
|
+
throw new Error(msg || 'tool failed: ' + name);
|
|
38
|
+
}
|
|
39
|
+
return res.structuredContent || {};
|
|
40
|
+
}
|
|
31
41
|
function notify(method, params) {
|
|
32
42
|
post({ jsonrpc: '2.0', method, params: params || {} });
|
|
33
43
|
}
|
package/src/mcp-ui/board/core.js
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
try { return JSON.parse(document.getElementById('boot').textContent); } catch { return {}; }
|
|
3
3
|
})();
|
|
4
4
|
const PROTOCOL = '2025-06-18';
|
|
5
|
+
// Set from the relay_board tool result; every server call for this board presents it.
|
|
6
|
+
const BOARD = { id: null, token: null };
|
|
5
7
|
|
|
6
8
|
// ---------- tiny DOM helper (mirrors app.js / blocks.js) ----------
|
|
7
9
|
function el(tag, attrs = {}, ...children) {
|
|
@@ -54,21 +54,59 @@
|
|
|
54
54
|
previewTimer = setTimeout(() => { previewTimer = null; if (!booted && !submitted) render(); }, 120);
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
// The
|
|
58
|
-
//
|
|
59
|
-
//
|
|
57
|
+
// The tool result carries only the board id and token. The spec comes from
|
|
58
|
+
// relay_view, already normalized by the server. A host that will not run app
|
|
59
|
+
// tool calls still gets a board: the raw tool input is the fallback, held for
|
|
60
|
+
// a moment so the server's version wins when both arrive.
|
|
61
|
+
let rawInput = null;
|
|
60
62
|
let rawInputTimer = null;
|
|
61
|
-
|
|
63
|
+
const DRAFT_EVERY_MS = 4000;
|
|
64
|
+
let lastDraft = '';
|
|
65
|
+
|
|
66
|
+
function startDraftSync() {
|
|
67
|
+
setInterval(() => {
|
|
68
|
+
if (!booted || submitted || !BOARD.token || spec.responseRequired === false) return;
|
|
69
|
+
const body = JSON.stringify(payload());
|
|
70
|
+
if (body === lastDraft) return;
|
|
71
|
+
lastDraft = body;
|
|
72
|
+
callServerTool('relay_draft', { boardId: BOARD.id, token: BOARD.token, draft: JSON.parse(body) }).catch(() => {});
|
|
73
|
+
}, DRAFT_EVERY_MS);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function bootFromServer(result) {
|
|
77
|
+
const sc = result && result.structuredContent;
|
|
78
|
+
const token = result && result._meta && result._meta.relay && result._meta.relay.token;
|
|
79
|
+
if (!sc || !sc.boardId || !token) return false;
|
|
80
|
+
BOARD.id = sc.boardId;
|
|
81
|
+
BOARD.token = token;
|
|
82
|
+
try {
|
|
83
|
+
const view = await callServerTool('relay_view', { boardId: BOARD.id, token: BOARD.token });
|
|
84
|
+
if (!view.spec) return false;
|
|
85
|
+
vendorUrls = view.vendorUrls || null;
|
|
86
|
+
await boot(view.spec, true);
|
|
87
|
+
if (view.finished) {
|
|
88
|
+
submitted = true;
|
|
89
|
+
showDone(true, false);
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
startDraftSync();
|
|
93
|
+
return true;
|
|
94
|
+
} catch {
|
|
95
|
+
BOARD.token = null;
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
onNotify('ui/notifications/tool-result', async (p) => {
|
|
62
101
|
if (rawInputTimer) { clearTimeout(rawInputTimer); rawInputTimer = null; }
|
|
63
|
-
|
|
64
|
-
if (
|
|
65
|
-
// Some hosts may echo the spec at the top level of structuredContent.
|
|
66
|
-
if (sc && Array.isArray(sc.questions)) return boot(sc, true);
|
|
102
|
+
if (booted) return;
|
|
103
|
+
if (!(await bootFromServer(p)) && rawInput) boot(rawInput, false);
|
|
67
104
|
});
|
|
68
105
|
onNotify('ui/notifications/tool-input', (p) => {
|
|
69
106
|
const args = p && p.arguments;
|
|
70
107
|
if (!args || typeof args !== 'object' || booted || rawInputTimer) return;
|
|
71
|
-
|
|
108
|
+
rawInput = args;
|
|
109
|
+
rawInputTimer = setTimeout(() => { rawInputTimer = null; boot(args, false); }, 1500);
|
|
72
110
|
});
|
|
73
111
|
onNotify('ui/notifications/tool-input-partial', (p) => {
|
|
74
112
|
const args = p && p.arguments;
|
|
@@ -119,63 +119,55 @@
|
|
|
119
119
|
return lines.join('\n');
|
|
120
120
|
}
|
|
121
121
|
|
|
122
|
+
// The full answers go to the server, which keeps them for relay_result; the
|
|
123
|
+
// agent gets a one-line nudge. A host that refuses app tool calls gets the
|
|
124
|
+
// whole transcript as the message instead, so the answers still arrive.
|
|
122
125
|
async function onSubmit(submitBtn, saveEl) {
|
|
123
126
|
if (submitted) return;
|
|
124
127
|
if (!validate()) return;
|
|
125
128
|
submitBtn.disabled = true;
|
|
126
129
|
submitBtn.textContent = 'Submitting…';
|
|
127
130
|
const data = payload();
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
const messageContent = [{ type: 'text', text }];
|
|
140
|
-
for (const a of data.annotations || []) {
|
|
141
|
-
const crop = a && a.target && a.target.crop;
|
|
142
|
-
if (!crop || typeof crop.data !== 'string' || !crop.data) continue;
|
|
143
|
-
messageContent.push({ type: 'image', data: crop.data, mimeType: crop.mime || 'image/png' });
|
|
131
|
+
const stored = BOARD.token ? await storeSubmission(data) : false;
|
|
132
|
+
const text = stored
|
|
133
|
+
? 'Relay board ' + BOARD.id + ' submitted. Read it with relay_result {"boardId":"' + BOARD.id + '"}.'
|
|
134
|
+
: summarize(data);
|
|
135
|
+
const content = [{ type: 'text', text }];
|
|
136
|
+
if (!stored) {
|
|
137
|
+
for (const a of data.annotations || []) {
|
|
138
|
+
const crop = a && a.target && a.target.crop;
|
|
139
|
+
if (!crop || typeof crop.data !== 'string' || !crop.data) continue;
|
|
140
|
+
content.push({ type: 'image', data: crop.data, mimeType: crop.mime || 'image/png' });
|
|
141
|
+
}
|
|
144
142
|
}
|
|
145
|
-
|
|
146
|
-
|
|
143
|
+
const messageDelivered = await sendUserMessage(content, text);
|
|
144
|
+
submitted = true;
|
|
145
|
+
showDone(messageDelivered, stored);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function storeSubmission(data) {
|
|
147
149
|
try {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
// the transcript as a user message first to wake the agent reliably.
|
|
151
|
-
await request('ui/message', { role: 'user', content: messageContent });
|
|
152
|
-
messageDelivered = true;
|
|
150
|
+
await callServerTool('relay_submit', { boardId: BOARD.id, token: BOARD.token, payload: data });
|
|
151
|
+
return true;
|
|
153
152
|
} catch {
|
|
154
|
-
|
|
155
|
-
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// A completed relay form is a user reply, so it goes as a user message to wake
|
|
158
|
+
// the agent. Older hosts reject image content or the content array; each retry
|
|
159
|
+
// keeps the text.
|
|
160
|
+
async function sendUserMessage(content, text) {
|
|
161
|
+
const attempts = [content, [{ type: 'text', text }], { type: 'text', text }];
|
|
162
|
+
for (const attempt of attempts) {
|
|
156
163
|
try {
|
|
157
|
-
await request('ui/message', { role: 'user', content:
|
|
158
|
-
|
|
164
|
+
await request('ui/message', { role: 'user', content: attempt });
|
|
165
|
+
return true;
|
|
159
166
|
} catch {
|
|
160
|
-
try
|
|
161
|
-
await request('ui/message', { role: 'user', content: { type: 'text', text } });
|
|
162
|
-
messageDelivered = true;
|
|
163
|
-
} catch { /* app-initiated messages unavailable */ }
|
|
167
|
+
// try a simpler shape
|
|
164
168
|
}
|
|
165
169
|
}
|
|
166
|
-
|
|
167
|
-
// Keep the structured payload available to hosts that attach app context.
|
|
168
|
-
// This is best-effort because context updates are intentionally silent.
|
|
169
|
-
await request('ui/update-model-context', { content: messageContent, structuredContent: structured });
|
|
170
|
-
contextDelivered = true;
|
|
171
|
-
} catch {
|
|
172
|
-
try {
|
|
173
|
-
await request('ui/update-model-context', { content: [{ type: 'text', text }], structuredContent: structured });
|
|
174
|
-
contextDelivered = true;
|
|
175
|
-
} catch { /* ui/message may still have delivered the result */ }
|
|
176
|
-
}
|
|
177
|
-
submitted = true;
|
|
178
|
-
showDone(messageDelivered, contextDelivered);
|
|
170
|
+
return false;
|
|
179
171
|
}
|
|
180
172
|
|
|
181
173
|
function showDone(messageDelivered, contextDelivered) {
|