@khanglvm/relay 0.20.3 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/docs/AGENT.md +35 -62
- package/docs/SETUP.md +3 -2
- package/package.json +17 -5
- package/schema/spec.v1.json +55 -3
- package/skills/relay/SKILL.md +5 -2
- 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 +23 -3
- package/src/mcp/boards.js +195 -0
- package/src/mcp/config.js +20 -0
- package/src/mcp/constants.js +33 -0
- package/src/mcp/index.js +5 -0
- package/src/mcp/page.js +59 -0
- package/src/mcp/schemas.js +45 -0
- package/src/mcp/serve.js +116 -0
- package/src/mcp/server.js +24 -0
- package/src/mcp/store.js +35 -0
- package/src/mcp/token.js +56 -0
- package/src/mcp/tools.js +179 -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/normalize.js +12 -0
- package/src/mcp-ui/board/render.js +38 -45
- package/src/mcp-ui/board/state.js +3 -0
- package/src/mcp-ui/board/vendors.js +56 -11
- 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 +3 -2
- 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/cli/agent-topics.d.ts +46 -0
- package/types/mcp/boards.d.ts +178 -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 +49 -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 +9 -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/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
- package/src/mcp.js +0 -483
package/src/mcp/page.js
ADDED
|
@@ -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,45 @@
|
|
|
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
|
+
/** A widget button click (`blockId`, `name`, `context`), or a renderer event (`action`, plus the surface's `dataModel`). */
|
|
26
|
+
export const actionInput = z.object({
|
|
27
|
+
boardId,
|
|
28
|
+
token,
|
|
29
|
+
blockId: z.string().optional(),
|
|
30
|
+
name: z.string().optional(),
|
|
31
|
+
context: loose.optional(),
|
|
32
|
+
action: loose.optional(),
|
|
33
|
+
dataModel: loose.optional(),
|
|
34
|
+
});
|
|
35
|
+
export const assetInput = z.object({ name: z.string(), index: z.number().int().min(0).default(0) });
|
|
36
|
+
|
|
37
|
+
export const helpInput = z.object({
|
|
38
|
+
topic: z.enum(Object.keys(AGENT_TOPICS)).optional().describe('Guide topic; omit for the list'),
|
|
39
|
+
schema: z.string().optional().describe('A block or question type, for its exact fields: chart, checklist, ...'),
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
export const resultInput = z.object({
|
|
43
|
+
boardId,
|
|
44
|
+
wait_seconds: z.number().min(0).optional().describe('Block up to this long for the submission; default 0 returns now'),
|
|
45
|
+
});
|
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,24 @@
|
|
|
1
|
+
// Builds an McpServer with the relay tools registered.
|
|
2
|
+
import { McpServer } from '@modelcontextprotocol/server';
|
|
3
|
+
import { capabilitiesDeclareBoardCatalog } from '../a2ui/negotiate.js';
|
|
4
|
+
import { UI_EXT, UI_MIME } from './constants.js';
|
|
5
|
+
import { PKG } from './page.js';
|
|
6
|
+
import { registerRelay } from './tools.js';
|
|
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.';
|
|
9
|
+
|
|
10
|
+
const clientRendersBoards = (capabilities) => Boolean(capabilities?.extensions?.[UI_EXT]) || capabilitiesDeclareBoardCatalog(capabilities);
|
|
11
|
+
|
|
12
|
+
/** @param {Parameters<typeof registerRelay>[1]} [options] */
|
|
13
|
+
export function createRelayServer(options = {}) {
|
|
14
|
+
const server = new McpServer(
|
|
15
|
+
{ name: 'relay', version: PKG.version },
|
|
16
|
+
{ instructions: INSTRUCTIONS, capabilities: { extensions: { [UI_EXT]: { mimeTypes: [UI_MIME] } } } },
|
|
17
|
+
);
|
|
18
|
+
const appTools = registerRelay(server, options);
|
|
19
|
+
// The iframe tools only matter to a host that renders the board; others never see them.
|
|
20
|
+
server.server.oninitialized = () => {
|
|
21
|
+
if (!clientRendersBoards(server.server.getClientCapabilities())) for (const tool of appTools) tool.disable();
|
|
22
|
+
};
|
|
23
|
+
return server;
|
|
24
|
+
}
|
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,56 @@
|
|
|
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
|
+
const readKey = (file) => {
|
|
10
|
+
try {
|
|
11
|
+
return fs.readFileSync(file, 'utf8').trim();
|
|
12
|
+
} catch {
|
|
13
|
+
return '';
|
|
14
|
+
}
|
|
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;
|
|
25
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
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
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export const boardToken = (key, boardId) => crypto.createHmac('sha256', key).update(String(boardId)).digest('hex');
|
|
49
|
+
|
|
50
|
+
/** Constant-time comparison, so a wrong token leaks nothing about the right one. */
|
|
51
|
+
export function tokenValid(key, boardId, token) {
|
|
52
|
+
if (typeof token !== 'string') return false;
|
|
53
|
+
const want = Buffer.from(boardToken(key, boardId));
|
|
54
|
+
const got = Buffer.from(token);
|
|
55
|
+
return want.length === got.length && crypto.timingSafeEqual(want, got);
|
|
56
|
+
}
|
package/src/mcp/tools.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
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 { 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';
|
|
8
|
+
import { renderAgentTopic, topicIndex } from '../cli/agent-topics.js';
|
|
9
|
+
import { lookupSchema } from '../spec/index.js';
|
|
10
|
+
import { sleep } from '../util.js';
|
|
11
|
+
import {
|
|
12
|
+
boardResult, createMcpBoard, errorResult, handleSurfaceAction, isFinal, resultOf, saveDraft, specError, submitBoard,
|
|
13
|
+
} from './boards.js';
|
|
14
|
+
import { BOARD_URI, MAX_WAIT_SECONDS, TOOL, UI_MIME, VENDOR_URI_PREFIX } from './constants.js';
|
|
15
|
+
import { BOARD_RESOURCE_META, boardPage, DOCS_DIR, vendorChunk, vendorText, VENDOR_FILES } from './page.js';
|
|
16
|
+
import { actionInput, aliasInput, assetInput, boardInput, draftInput, helpInput, resultInput, submitInput, viewInput } from './schemas.js';
|
|
17
|
+
import { fileStore } from './store.js';
|
|
18
|
+
import { boardToken, loadServerKey, tokenValid } from './token.js';
|
|
19
|
+
|
|
20
|
+
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.
|
|
21
|
+
Spec: {title, intro?, blocks?:[...], questions?:[...]}. With no questions the board is display-only and needs no reply.
|
|
22
|
+
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).
|
|
23
|
+
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.
|
|
24
|
+
Blocks go on the board, on a question, or on an option. Use ids that stay stable.
|
|
25
|
+
For exact fields call relay_help {topic: questions|blocks|annotate|lifecycle|a2ui|sharing|mcp} or {schema:"chart"}.`;
|
|
26
|
+
|
|
27
|
+
const readDoc = (file) => fs.readFileSync(path.join(DOCS_DIR, file), 'utf8');
|
|
28
|
+
/** @returns {import('./boards.js').ToolResult} */
|
|
29
|
+
const text = (t) => ({ content: [{ type: 'text', text: t }] });
|
|
30
|
+
/** @returns {import('./boards.js').ToolResult} */
|
|
31
|
+
const json = (value, structured) => ({ content: [{ type: 'text', text: JSON.stringify(value) }], ...(structured ? { structuredContent: structured } : {}) });
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Adds the relay tools and the board resource to `server`.
|
|
35
|
+
*
|
|
36
|
+
* @param {any} server an McpServer
|
|
37
|
+
* @param {object} [options]
|
|
38
|
+
* @param {import('./store.js').RelayStore} [options.store] where boards live; defaults to the relay home on disk
|
|
39
|
+
* @param {string | Buffer} [options.tokenKey] the secret behind board tokens; defaults to a key file in the relay home
|
|
40
|
+
* @param {(name: string) => string} [options.assetUrl] URL of a vendor file, for hosts that can fetch it
|
|
41
|
+
* @param {(boardId: string) => string} [options.linkUrl] a URL where a person can open the board outside the host
|
|
42
|
+
* @returns the app-only tools, so a server can hide them from a client that cannot render the board
|
|
43
|
+
*/
|
|
44
|
+
export function registerRelay(server, options = {}) {
|
|
45
|
+
const ctx = { server, options, store: options.store ?? fileStore(), key: options.tokenKey ?? loadServerKey() };
|
|
46
|
+
registerBoardTools(ctx);
|
|
47
|
+
registerReadTools(ctx);
|
|
48
|
+
const appTools = registerAppTools(ctx);
|
|
49
|
+
registerResources(server);
|
|
50
|
+
return appTools;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Every app call reads a board and writes it back whole. Two clicks forwarded at once,
|
|
54
|
+
// or a draft racing the submit, would otherwise drop one write. The queue is per
|
|
55
|
+
// process, not per server, because the HTTP transport builds a server per request.
|
|
56
|
+
const boardQueues = new Map();
|
|
57
|
+
function oneAtATime(boardId, task) {
|
|
58
|
+
const key = String(boardId);
|
|
59
|
+
const run = (boardQueues.get(key) ?? Promise.resolve()).then(task);
|
|
60
|
+
const tail = run.catch(() => {});
|
|
61
|
+
boardQueues.set(key, tail);
|
|
62
|
+
tail.then(() => { if (boardQueues.get(key) === tail) boardQueues.delete(key); });
|
|
63
|
+
return run;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const appMeta = (visibility) => ({ ui: { resourceUri: BOARD_URI, visibility } });
|
|
67
|
+
const modelMeta = { ...appMeta(['model', 'app']), 'openai/outputTemplate': BOARD_URI };
|
|
68
|
+
|
|
69
|
+
function registerBoardTools({ server, options, store, key }) {
|
|
70
|
+
const openBoard = (displayOnly) => async (args) => {
|
|
71
|
+
let made;
|
|
72
|
+
try {
|
|
73
|
+
made = await createMcpBoard(store, args, { displayOnly });
|
|
74
|
+
} catch (err) {
|
|
75
|
+
return specError(err);
|
|
76
|
+
}
|
|
77
|
+
const result = boardResult(made.record, made.spec, made.mode);
|
|
78
|
+
if (options.linkUrl) result.structuredContent = { .../** @type {object} */ (result.structuredContent), url: options.linkUrl(made.record.id) };
|
|
79
|
+
result._meta = { ...appMeta(['model', 'app']), relay: { token: boardToken(key, made.record.id) }, 'relay/a2ui': { catalogIds: [BOARD_CATALOG_ID] } };
|
|
80
|
+
return result;
|
|
81
|
+
};
|
|
82
|
+
registerAppTool(server, TOOL.board, { title: 'Relay board', description: BOARD_DESCRIPTION, inputSchema: boardInput, _meta: modelMeta }, openBoard(false));
|
|
83
|
+
registerAppTool(server, TOOL.ask, { description: 'Deprecated alias of relay_board.', inputSchema: aliasInput, _meta: modelMeta }, openBoard(false));
|
|
84
|
+
registerAppTool(server, TOOL.show, { description: 'Deprecated alias of relay_board for a display-only board.', inputSchema: aliasInput, _meta: modelMeta }, openBoard(true));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function registerReadTools({ server, store }) {
|
|
88
|
+
const modelOnly = { ui: { visibility: ['model'] } };
|
|
89
|
+
registerAppTool(server, TOOL.help, {
|
|
90
|
+
description: 'Exact Relay field shapes. topic: questions, blocks, annotate, lifecycle, a2ui, sharing, mcp. schema: one block or question type.',
|
|
91
|
+
inputSchema: helpInput,
|
|
92
|
+
_meta: modelOnly,
|
|
93
|
+
}, ({ topic, schema }) => {
|
|
94
|
+
if (schema) {
|
|
95
|
+
const found = lookupSchema(schema);
|
|
96
|
+
return found ? json(found) : errorResult(`relay: no block or question type "${schema}". ${topicIndex()}`);
|
|
97
|
+
}
|
|
98
|
+
return text(topic ? renderAgentTopic(topic, readDoc) : topicIndex());
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
registerAppTool(server, TOOL.result, {
|
|
102
|
+
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.',
|
|
103
|
+
inputSchema: resultInput,
|
|
104
|
+
_meta: modelOnly,
|
|
105
|
+
}, async ({ boardId, wait_seconds = 0 }, ctx) => {
|
|
106
|
+
const deadline = Date.now() + Math.min(wait_seconds, MAX_WAIT_SECONDS) * 1000;
|
|
107
|
+
for (;;) {
|
|
108
|
+
const record = await store.get(boardId);
|
|
109
|
+
if (!record) return errorResult(`relay: no board "${boardId}"`);
|
|
110
|
+
if (isFinal(record) || Date.now() >= deadline || ctx?.mcpReq?.signal?.aborted) {
|
|
111
|
+
const out = resultOf(record);
|
|
112
|
+
return json(out, { boardId, status: out.status });
|
|
113
|
+
}
|
|
114
|
+
await sleep(500);
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function registerAppTools({ server, options, store, key }) {
|
|
120
|
+
const appTools = [];
|
|
121
|
+
const appTool = (name, config, cb) => appTools.push(registerAppTool(server, name, { ...config, _meta: { ui: { visibility: ['app'] } } }, cb));
|
|
122
|
+
|
|
123
|
+
/** The board a valid token opens, or an error result. */
|
|
124
|
+
const guard = async (args) => {
|
|
125
|
+
if (!tokenValid(key, args.boardId, args.token)) return { error: errorResult('relay: board token mismatch') };
|
|
126
|
+
const record = await store.get(args.boardId);
|
|
127
|
+
return record ? { record } : { error: errorResult('relay: board not found') };
|
|
128
|
+
};
|
|
129
|
+
/** An app tool that acts on one unfinished board. */
|
|
130
|
+
const onOpenBoard = (act) => (args) => oneAtATime(args.boardId, async () => {
|
|
131
|
+
const { record, error } = await guard(args);
|
|
132
|
+
if (error) return error;
|
|
133
|
+
if (isFinal(record)) return errorResult('relay: board is finished');
|
|
134
|
+
return act(record, args);
|
|
135
|
+
});
|
|
136
|
+
|
|
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) => {
|
|
138
|
+
const { record, error } = await guard(args);
|
|
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
|
+
}
|
|
145
|
+
const vendorUrls = options.assetUrl ? Object.fromEntries(VENDOR_FILES.map((f) => [f, options.assetUrl(f)])) : undefined;
|
|
146
|
+
return json({ boardId: record.id }, { boardId: record.id, spec: record.spec, draft: record.draft ?? null, finished: Boolean(record.result), vendorUrls });
|
|
147
|
+
});
|
|
148
|
+
appTool(TOOL.draft, { description: 'Saves the answers so far.', inputSchema: draftInput }, onOpenBoard(async (record, args) => {
|
|
149
|
+
await saveDraft(store, record.id, args.draft, record.spec);
|
|
150
|
+
return text('saved');
|
|
151
|
+
}));
|
|
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);
|
|
154
|
+
return outcome.ok ? text('recorded') : errorResult(`relay: ${outcome.error}`);
|
|
155
|
+
}));
|
|
156
|
+
appTool(TOOL.submit, { description: 'Stores the final answers.', inputSchema: submitInput }, (args) => oneAtATime(args.boardId, async () => {
|
|
157
|
+
const { record, error } = await guard(args);
|
|
158
|
+
if (error) return error;
|
|
159
|
+
const outcome = await submitBoard(store, record, args.payload);
|
|
160
|
+
return outcome.ok ? json({ status: outcome.status }) : errorResult(`relay: ${outcome.error}`);
|
|
161
|
+
}));
|
|
162
|
+
appTool(TOOL.asset, { description: 'One chunk of a vendored library, for hosts that refuse resources/read.', inputSchema: assetInput }, ({ name, index }) => {
|
|
163
|
+
const chunk = vendorChunk(name, index);
|
|
164
|
+
return chunk ? json({ name, index, count: chunk.count }, chunk) : errorResult(`relay: no asset "${name}" chunk ${index}`);
|
|
165
|
+
});
|
|
166
|
+
return appTools;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function registerResources(server) {
|
|
170
|
+
registerAppResource(server, 'Relay board', BOARD_URI, { mimeType: UI_MIME, description: 'The interactive board shown by relay_board.', _meta: { ui: BOARD_RESOURCE_META } }, () => ({
|
|
171
|
+
contents: [{ uri: BOARD_URI, mimeType: UI_MIME, text: boardPage(), _meta: { ui: BOARD_RESOURCE_META } }],
|
|
172
|
+
}));
|
|
173
|
+
for (const file of VENDOR_FILES) {
|
|
174
|
+
const uri = VENDOR_URI_PREFIX + file;
|
|
175
|
+
server.registerResource(`vendor ${file}`, uri, { mimeType: 'application/javascript' }, () => ({
|
|
176
|
+
contents: [{ uri, mimeType: 'application/javascript', text: vendorText(file) }],
|
|
177
|
+
}));
|
|
178
|
+
}
|
|
179
|
+
}
|
|
@@ -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) {
|