@khanglvm/relay 0.20.2 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +2 -2
  2. package/docs/AGENT.md +56 -83
  3. package/docs/SETUP.md +3 -2
  4. package/package.json +12 -5
  5. package/skills/relay/SKILL.md +45 -145
  6. package/src/cli/agent-topics.js +84 -0
  7. package/src/cli/config.js +26 -2
  8. package/src/cli/index.js +3 -5
  9. package/src/cli/mcp.js +4 -2
  10. package/src/cli/skill.js +21 -22
  11. package/src/mcp/boards.js +173 -0
  12. package/src/mcp/config.js +20 -0
  13. package/src/mcp/constants.js +31 -0
  14. package/src/mcp/index.js +5 -0
  15. package/src/mcp/page.js +59 -0
  16. package/src/mcp/schemas.js +42 -0
  17. package/src/mcp/serve.js +116 -0
  18. package/src/mcp/server.js +23 -0
  19. package/src/mcp/store.js +35 -0
  20. package/src/mcp/token.js +31 -0
  21. package/src/mcp/tools.js +171 -0
  22. package/src/mcp-ui/board/block-ctx.js +22 -0
  23. package/src/mcp-ui/board/bridge.js +12 -2
  24. package/src/mcp-ui/board/core.js +2 -0
  25. package/src/mcp-ui/board/lifecycle.js +47 -9
  26. package/src/mcp-ui/board/render.js +36 -44
  27. package/src/mcp-ui/board/vendors.js +56 -11
  28. package/src/spec/blocks/chart.js +8 -4
  29. package/src/spec/constants.js +19 -0
  30. package/src/spec/index.js +1 -0
  31. package/src/spec/lookup.js +78 -0
  32. package/src/spec/normalize.js +9 -4
  33. package/src/spec/ready.js +15 -1
  34. package/src/ui/manifest.js +1 -1
  35. package/types/cli/agent-topics.d.ts +46 -0
  36. package/types/mcp/boards.d.ts +168 -0
  37. package/types/{mcp.d.ts → mcp/config.d.ts} +1 -8
  38. package/types/mcp/constants.d.ts +21 -0
  39. package/types/mcp/index.d.ts +4 -0
  40. package/types/mcp/page.d.ts +27 -0
  41. package/types/mcp/schemas.d.ts +46 -0
  42. package/types/mcp/serve.d.ts +16 -0
  43. package/types/mcp/server.d.ts +4 -0
  44. package/types/mcp/store.d.ts +52 -0
  45. package/types/mcp/token.d.ts +5 -0
  46. package/types/mcp/tools.d.ts +17 -0
  47. package/types/server/result.d.ts +10 -0
  48. package/types/server/sanitize.d.ts +6 -0
  49. package/types/spec/blocks/chart.d.ts +1 -1
  50. package/types/spec/constants.d.ts +14 -0
  51. package/types/spec/index.d.ts +1 -0
  52. package/types/spec/lookup.d.ts +57 -0
  53. package/types/spec/ready.d.ts +2 -0
  54. package/src/mcp.js +0 -483
@@ -0,0 +1,57 @@
1
+ export declare const BLOCK_FIELDS: {
2
+ markdown: string[];
3
+ mermaid: string[];
4
+ graphviz: string[];
5
+ plantuml: string[];
6
+ chart: string[];
7
+ table: string[];
8
+ code: string[];
9
+ diff: string[];
10
+ 'git-conflict': string[];
11
+ video: string[];
12
+ pdf: string[];
13
+ html: string[];
14
+ image: string[];
15
+ palette: string[];
16
+ kpi: string[];
17
+ typography: string[];
18
+ compare: string[];
19
+ a2ui: string[];
20
+ };
21
+ export declare const QUESTION_FIELDS: {
22
+ single: string[];
23
+ multi: string[];
24
+ yesno: string[];
25
+ text: string[];
26
+ textarea: string[];
27
+ scale: string[];
28
+ color: string[];
29
+ rank: string[];
30
+ checklist: string[];
31
+ allocate: string[];
32
+ };
33
+ /** The property names the schema defines for blocks and for questions. */
34
+ export declare function schemaFieldNames(): {
35
+ block: string[];
36
+ question: string[];
37
+ };
38
+ /**
39
+ * The fields of one block or question type, or null when the name is neither.
40
+ * A name that is both (`code` is only a block; `color` only a question) never
41
+ * collides today; a block wins if one ever does.
42
+ */
43
+ export declare function lookupSchema(name: any): {
44
+ kind: string;
45
+ type: string;
46
+ fields: {
47
+ [k: string]: any;
48
+ };
49
+ required?: undefined;
50
+ } | {
51
+ kind: string;
52
+ type: string;
53
+ required: string[];
54
+ fields: {
55
+ [k: string]: any;
56
+ };
57
+ };
@@ -1 +1,3 @@
1
+ /** True when the error comes from the checker's own environment and says nothing about the diagram. */
2
+ export declare function isCheckerFailure(err: any): boolean;
1
3
  export declare function assertSpecReady(spec: any): Promise<any>;
package/src/mcp.js DELETED
@@ -1,483 +0,0 @@
1
- // code-craft: allow-size one MCP server: tool schemas, the stdio loop and the App resource share one request handler.
2
- // mcp.js — relay as an MCP App (SEP-1865, extension "io.modelcontextprotocol/ui").
3
- //
4
- // `rly mcp` starts an MCP server over stdio with no npm runtime dependencies.
5
- // Register it with a host that supports MCP Apps (Claude desktop/mobile, Codex,
6
- // …) and relay's boards render INLINE in the conversation instead of opening a
7
- // browser tab:
8
- //
9
- // • the server declares a UI resource ui://relay/board (text/html;profile=mcp-app)
10
- // • the tools `relay_ask` / `relay_show` link to it via _meta.ui.resourceUri
11
- // • calling a tool returns the (normalized) board spec as structuredContent;
12
- // the host renders the resource in a sandboxed iframe and forwards the spec
13
- // • the iframe collects the user's answers and sends them back as a user
14
- // message; it also syncs model context when the host supports it
15
- //
16
- // Framing is the MCP stdio transport: newline-delimited JSON-RPC, one message
17
- // per line, never embedded newlines. stdout carries ONLY protocol messages;
18
- // everything else goes to stderr.
19
- import fs from 'node:fs';
20
- import path from 'node:path';
21
- import http from 'node:http';
22
- import crypto from 'node:crypto';
23
- import { fileURLToPath } from 'node:url';
24
- import { assertSpecReady, normalizeSpec, SPEC_SCHEMA } from './spec/index.js';
25
- import { CliError } from './util.js';
26
- import { fillPage, SRC_DIR } from './ui/manifest.js';
27
-
28
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
29
- const PKG_ROOT = path.join(__dirname, '..');
30
- const VENDOR_DIR = path.join(PKG_ROOT, 'vendor');
31
- const PKG = JSON.parse(fs.readFileSync(path.join(PKG_ROOT, 'package.json'), 'utf8'));
32
-
33
- const UI_EXT = 'io.modelcontextprotocol/ui';
34
- const UI_MIME = 'text/html;profile=mcp-app';
35
- const BOARD_URI = 'ui://relay/board';
36
- const VENDOR_PREFIX = 'ui://relay/vendor/';
37
- // Echoed back to the client when it doesn't pin a version we recognize.
38
- const DEFAULT_PROTOCOL = '2025-06-18';
39
- const DEFAULT_HTTP_PORT = 4319;
40
-
41
- const escapeHtml = (s) =>
42
- String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
43
-
44
- // ---------- UI asset assembly (cached for the process lifetime) ----------
45
- const _cache = new Map();
46
- function readAsset(file) {
47
- if (_cache.has(file)) return _cache.get(file);
48
- let content = '';
49
- try { content = fs.readFileSync(path.join(SRC_DIR, file), 'utf8'); } catch { content = ''; }
50
- _cache.set(file, content);
51
- return content;
52
- }
53
-
54
- // The single self-contained board page served as the ui:// resource: the shared
55
- // stylesheet + block renderer + the MCP-app client, all inlined (no /vendor or
56
- // /api routes exist in the sandbox; vendors load over the bridge on demand).
57
- function buildBoardPage() {
58
- if (_cache.has('__page__')) return _cache.get('__page__');
59
- const boot = { version: PKG.version, boardId: 'mcp-' + Date.now().toString(36) };
60
- const page = fillPage(
61
- readAsset('mcp-ui/index.html'),
62
- { title: 'Relay', bootJson: JSON.stringify(boot).replace(/</g, '\\u003c'), entry: 'board' },
63
- readAsset,
64
- );
65
- _cache.set('__page__', page);
66
- return page;
67
- }
68
-
69
- function vendorText(name) {
70
- // No traversal: only a bare filename inside VENDOR_DIR.
71
- if (!/^[\w.-]+$/.test(name)) return null;
72
- const target = path.join(VENDOR_DIR, name);
73
- if (target !== VENDOR_DIR && !target.startsWith(VENDOR_DIR + path.sep)) return null;
74
- try { return fs.readFileSync(target, 'utf8'); } catch { return null; }
75
- }
76
-
77
- // ---------- tool + resource descriptors ----------
78
- // The board spec, as the tool input schema: SPEC_SCHEMA minus the result-only
79
- // fields (annotations / blockEdits are returned, never supplied).
80
- function inputSchema() {
81
- const props = { ...SPEC_SCHEMA.properties };
82
- delete props.annotations;
83
- delete props.blockEdits;
84
- return { type: 'object', properties: props, anyOf: SPEC_SCHEMA.anyOf };
85
- }
86
-
87
- // _meta linking a tool to the UI resource. We emit the field under several keys
88
- // for cross-host compatibility: the spec's `_meta.ui`, the extension-id key, and
89
- // OpenAI's `openai/outputTemplate` (ChatGPT / Codex Apps SDK).
90
- function uiToolMeta() {
91
- const ui = { resourceUri: BOARD_URI, visibility: ['model', 'app'] };
92
- return { ui, [UI_EXT]: ui, 'openai/outputTemplate': BOARD_URI };
93
- }
94
-
95
- function tools() {
96
- const schema = inputSchema();
97
- return [
98
- {
99
- name: 'relay_ask',
100
- description:
101
- 'Ask the user structured questions on an interactive board rendered inline in this app — real form controls (single/multi choice, yes/no, scale, text) plus rich blocks (markdown, code, diff, table, chart, mermaid, graphviz, image, html). Use this instead of asking questions in plain text whenever you need decisions, requirements, or feedback. The user fills it in and submits; their answers come back to you. Pass a board spec (see inputSchema).',
102
- inputSchema: schema,
103
- _meta: uiToolMeta(),
104
- },
105
- {
106
- name: 'relay_show',
107
- description:
108
- 'Present work to the user on an inline display-only board — a plan, architecture diagram, data, diff, prototype, or image — using rich blocks. It returns immediately and does not ask the user to acknowledge. Set responseRequired:true only when feedback or acknowledgement is actually needed.',
109
- inputSchema: schema,
110
- _meta: uiToolMeta(),
111
- },
112
- ];
113
- }
114
-
115
- function resources() {
116
- return [
117
- {
118
- uri: BOARD_URI,
119
- name: 'Relay board',
120
- description: 'The interactive relay board UI (rendered inline by relay_ask / relay_show).',
121
- mimeType: UI_MIME,
122
- _meta: { ui: resourceMeta() },
123
- },
124
- ];
125
- }
126
-
127
- // Per-resource UI hints (CSP / framing). Hosts that ignore these still work; the
128
- // frame allowances cover YouTube/Vimeo `video` blocks and blob: html previews.
129
- function resourceMeta() {
130
- return {
131
- prefersBorder: false,
132
- csp: {
133
- connectDomains: [],
134
- resourceDomains: ['https://*', 'data:', 'blob:'],
135
- frameDomains: ['https://www.youtube-nocookie.com', 'https://player.vimeo.com', 'blob:', 'data:'],
136
- },
137
- };
138
- }
139
-
140
- // ---------- request routing ----------
141
- async function buildResult(method, params, clientProtocol) {
142
- switch (method) {
143
- case 'initialize':
144
- return {
145
- protocolVersion: typeof params.protocolVersion === 'string' ? params.protocolVersion : DEFAULT_PROTOCOL,
146
- capabilities: {
147
- tools: { listChanged: false },
148
- resources: { listChanged: false },
149
- experimental: {},
150
- extensions: { [UI_EXT]: { mimeTypes: [UI_MIME] } },
151
- },
152
- serverInfo: { name: 'relay', version: PKG.version },
153
- instructions:
154
- 'relay renders boards inline. Call relay_ask to collect decisions/feedback and wait for its user-message submission. Call relay_show to present plans/diagrams/data without waiting; it is display-only unless responseRequired:true is explicit.',
155
- };
156
- case 'ping':
157
- return {};
158
- case 'tools/list':
159
- return { tools: tools() };
160
- case 'resources/list':
161
- return { resources: resources() };
162
- case 'resources/templates/list':
163
- return { resourceTemplates: [] };
164
- case 'prompts/list':
165
- return { prompts: [] };
166
- case 'resources/read':
167
- return readResource(params);
168
- case 'tools/call':
169
- return callTool(params);
170
- default: {
171
- const err = /** @type {Error & { code?: number }} */ (new Error('method not found: ' + method));
172
- err.code = -32601;
173
- throw err;
174
- }
175
- }
176
- }
177
-
178
- function readResource(params) {
179
- const uri = params && params.uri;
180
- if (uri === BOARD_URI) {
181
- return { contents: [{ uri: BOARD_URI, mimeType: UI_MIME, text: buildBoardPage(), _meta: { ui: resourceMeta() } }] };
182
- }
183
- if (typeof uri === 'string' && uri.startsWith(VENDOR_PREFIX)) {
184
- const name = uri.slice(VENDOR_PREFIX.length);
185
- const text = vendorText(name);
186
- if (text == null) { const e = /** @type {Error & { code?: number }} */ (new Error('vendor not found: ' + name)); e.code = -32002; throw e; }
187
- return { contents: [{ uri, mimeType: 'application/javascript', text }] };
188
- }
189
- const e = /** @type {Error & { code?: number }} */ (new Error('resource not found: ' + uri));
190
- e.code = -32002;
191
- throw e;
192
- }
193
-
194
- // A tool call: normalize the spec and hand it to the host as structuredContent.
195
- // The host renders ui://relay/board and forwards this spec to the iframe, which
196
- // collects the answers and returns them via a UI-originated user message (with
197
- // ui/update-model-context as a best-effort context sync). Spec errors come back
198
- // as an isError tool result (not a protocol error) so the model can see and fix
199
- // them.
200
- async function callTool(params) {
201
- const name = params && params.name;
202
- if (name !== 'relay_ask' && name !== 'relay_show') {
203
- return { content: [{ type: 'text', text: 'unknown tool: ' + name }], isError: true };
204
- }
205
- const args = (params && params.arguments && typeof params.arguments === 'object') ? params.arguments : {};
206
- const normalizedArgs = name === 'relay_show' && args.responseRequired === undefined
207
- ? { ...args, responseRequired: false }
208
- : args;
209
- let spec;
210
- try {
211
- spec = normalizeSpec(normalizedArgs);
212
- await assertSpecReady(spec);
213
- } catch (err) {
214
- const msg = err instanceof CliError ? err.message : String((err && err.message) || err);
215
- return { content: [{ type: 'text', text: 'relay: invalid board spec — ' + msg }], isError: true };
216
- }
217
- return {
218
- content: [{ type: 'text', text: boardText(spec) }],
219
- structuredContent: { spec, mode: name === 'relay_show' ? 'show' : 'ask' },
220
- _meta: { ui: { resourceUri: BOARD_URI }, [UI_EXT]: { resourceUri: BOARD_URI } },
221
- };
222
- }
223
-
224
- // The tool-result text. Beyond announcing the board, it carries a readable
225
- // rendering of the questions as a GRACEFUL FALLBACK: on a surface that can't show
226
- // the interactive board (some mobile/remote-control views), the user can still
227
- // answer in chat and the model has the questions to work from. The model should
228
- // PREFER the rendered board (wait for the submission) and only fall back to chat
229
- // when the board clearly didn't render for the user.
230
- function boardText(spec) {
231
- const nQ = spec.questions.length;
232
- if (spec.responseRequired === false) {
233
- return `Relay board "${spec.title}" is now displayed to the user. No acknowledgement is requested; continue your work without waiting.`;
234
- }
235
- if (!nQ) {
236
- return `Relay board "${spec.title}" is now displayed to the user. They can review it and acknowledge; any feedback will be delivered back to you.`;
237
- }
238
- const lines = [];
239
- lines.push(`Relay board "${spec.title}" is now displayed to the user (${nQ} question${nQ === 1 ? '' : 's'}). Prefer the interactive board — wait for their submission; do NOT re-ask in plain text.`);
240
- lines.push('');
241
- lines.push('If the board does NOT render on the user\'s surface (e.g. some mobile / remote views) they can answer in chat — the questions are:');
242
- spec.questions.forEach((q, i) => {
243
- let line = `${i + 1}. [${q.id}] ${q.label} (${q.type}`;
244
- if (q.required || spec.allowPartial === false) line += ', required';
245
- line += ')';
246
- if (Array.isArray(q.options) && q.options.length) {
247
- line += ' — options: ' + q.options.map((o) => o.label || o.value).join(' | ') + (q.other ? ' | Other (free text)' : '');
248
- } else if (q.type === 'scale') {
249
- line += ` — ${q.min}…${q.max}`;
250
- }
251
- lines.push(line);
252
- });
253
- return lines.join('\n');
254
- }
255
-
256
- // ---------- stdio loop ----------
257
- export function runMcp() {
258
- // The peer closing stdout (EPIPE) is the only reason to stop writing — NOT a
259
- // `false` return from write(), which just signals backpressure (the 145KB
260
- // board page reliably triggers it). Honoring backpressure as "stop" would
261
- // silently drop every response after a large one.
262
- let stdoutOpen = true;
263
- process.stdout.on('error', () => { stdoutOpen = false; });
264
- const send = (obj) => {
265
- if (!stdoutOpen) return;
266
- try { process.stdout.write(JSON.stringify(obj) + '\n'); }
267
- catch { stdoutOpen = false; }
268
- };
269
-
270
- async function handleLine(line) {
271
- let msg;
272
- try { msg = JSON.parse(line); } catch {
273
- send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } });
274
- return;
275
- }
276
- const messages = Array.isArray(msg) ? msg : [msg];
277
- for (const m of messages) {
278
- if (!m || typeof m !== 'object') continue;
279
- const isRequest = m.id !== undefined && m.id !== null && typeof m.method === 'string';
280
- if (typeof m.method !== 'string') continue; // a response to us — we issue none
281
- let result;
282
- try {
283
- result = await buildResult(m.method, m.params || {});
284
- } catch (err) {
285
- if (isRequest) {
286
- send({ jsonrpc: '2.0', id: m.id, error: { code: err.code || -32603, message: err.message || String(err) } });
287
- }
288
- continue;
289
- }
290
- if (isRequest) send({ jsonrpc: '2.0', id: m.id, result });
291
- }
292
- }
293
-
294
- let buf = '';
295
- let queue = Promise.resolve();
296
- process.stdin.setEncoding('utf8');
297
- process.stdin.on('data', (chunk) => {
298
- buf += chunk;
299
- let idx;
300
- while ((idx = buf.indexOf('\n')) >= 0) {
301
- const line = buf.slice(0, idx);
302
- buf = buf.slice(idx + 1);
303
- const trimmed = line.trim();
304
- if (trimmed) queue = queue.then(() => handleLine(trimmed)).catch(() => {});
305
- }
306
- });
307
-
308
- // Resolve only when the input stream closes (host disconnected). Returning a
309
- // promise that stays pending keeps the CLI's post-run exit timer from firing.
310
- return new Promise((resolve) => {
311
- const finish = () => resolve(0);
312
- process.stdin.on('end', finish);
313
- process.stdin.on('close', finish);
314
- process.on('SIGINT', finish);
315
- process.on('SIGTERM', finish);
316
- });
317
- }
318
-
319
- // ---------- Streamable HTTP transport ----------
320
- // `rly mcp --http` serves the SAME server over MCP's Streamable HTTP transport
321
- // instead of stdio, so a host that connects over the network (Claude web/mobile,
322
- // a remote/custom connector) can render relay boards — not just a local desktop
323
- // host. relay is stateless (each tools/call is self-contained and the board
324
- // state lives in the iframe), so every POST is routed through buildResult and
325
- // answered with a single application/json response; we never need SSE.
326
- //
327
- // • POST <endpoint> — one JSON-RPC request → one JSON response; a
328
- // notification/response → 202 Accepted.
329
- // • GET <endpoint> — 405 (we open no server→client stream).
330
- // • DELETE — 200 (no session state to drop).
331
- // • OPTIONS — CORS preflight (never auth-gated).
332
- //
333
- // Security per the transport spec: bind to localhost by default, validate the
334
- // Origin header (localhost only unless --allow-origin opts in), and support an
335
- // optional bearer token for an exposed endpoint.
336
- const HTTP_PATH = '/mcp';
337
- const MAX_BODY = 16 * 1024 * 1024;
338
-
339
- function corsHeaders(origin) {
340
- return {
341
- 'access-control-allow-origin': origin || '*',
342
- 'access-control-allow-methods': 'GET, POST, DELETE, OPTIONS',
343
- 'access-control-allow-headers': 'content-type, authorization, mcp-session-id, mcp-protocol-version, last-event-id',
344
- 'access-control-expose-headers': 'Mcp-Session-Id',
345
- 'access-control-max-age': '86400',
346
- vary: 'Origin',
347
- };
348
- }
349
-
350
- function originAllowed(origin, allowOrigin) {
351
- if (!origin) return true; // non-browser client sends no Origin
352
- if (allowOrigin === '*') return true;
353
- if (allowOrigin && origin === allowOrigin) return true;
354
- try {
355
- const h = new URL(origin).hostname;
356
- return h === 'localhost' || h === '127.0.0.1' || h === '::1';
357
- } catch {
358
- return false;
359
- }
360
- }
361
-
362
- function safeEqual(a, b) {
363
- const A = Buffer.from(String(a));
364
- const B = Buffer.from(String(b));
365
- if (A.length !== B.length) return false;
366
- try { return crypto.timingSafeEqual(A, B); } catch { return false; }
367
- }
368
-
369
- function healthPage(endpoint) {
370
- return (
371
- '<!doctype html><meta charset="utf-8"><title>relay MCP</title>' +
372
- '<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}' +
373
- 'code{background:#f1efe8;padding:2px 6px;border-radius:5px;font-size:13px}h1{color:#c2674b;font-size:20px}</style>' +
374
- '<h1>relay · MCP Apps server</h1>' +
375
- '<p>This is relay running over the <b>Streamable HTTP</b> MCP transport. Point an MCP host at the endpoint below and call <code>relay_ask</code> / <code>relay_show</code>.</p>' +
376
- '<p>MCP endpoint: <code>' + escapeHtml(endpoint) + '</code></p>' +
377
- '<p>It speaks JSON-RPC over HTTP POST — open it in a browser and you get this page; an MCP client gets the protocol.</p>'
378
- );
379
- }
380
-
381
- export function runMcpHttp({ port = DEFAULT_HTTP_PORT, host = '127.0.0.1', token = '', allowOrigin = '' } = {}) {
382
- const requireAuth = Boolean(token);
383
- const server = http.createServer((req, res) => {
384
- const origin = req.headers.origin || '';
385
- const url = (req.url || '/').split('?')[0];
386
- const base = corsHeaders(origin);
387
-
388
- if (req.method === 'OPTIONS') {
389
- if (!originAllowed(origin, allowOrigin)) { res.writeHead(403); return res.end(); }
390
- res.writeHead(204, base); return res.end();
391
- }
392
- // Health page only at GET / — POST / is still accepted as the MCP endpoint.
393
- if (req.method === 'GET' && url === '/') {
394
- res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
395
- return res.end(healthPage(`http://${host === '0.0.0.0' ? 'localhost' : host}:${port}${HTTP_PATH}`));
396
- }
397
- if (url !== HTTP_PATH && url !== '/') { res.writeHead(404, base); return res.end('not found'); }
398
- if (!originAllowed(origin, allowOrigin)) { res.writeHead(403, base); return res.end('origin not allowed'); }
399
- if (req.method === 'GET') { res.writeHead(405, { ...base, allow: 'POST, DELETE, OPTIONS' }); return res.end(); }
400
- if (req.method === 'DELETE') { res.writeHead(200, { ...base, 'content-type': 'application/json' }); return res.end('{}'); }
401
- if (req.method !== 'POST') { res.writeHead(405, { ...base, allow: 'POST, DELETE, OPTIONS' }); return res.end(); }
402
- if (requireAuth) {
403
- const auth = req.headers.authorization || '';
404
- if (!(auth.startsWith('Bearer ') && safeEqual(auth.slice(7), token))) {
405
- res.writeHead(401, { ...base, 'www-authenticate': 'Bearer' }); return res.end('unauthorized');
406
- }
407
- }
408
-
409
- let body = '';
410
- let aborted = false;
411
- req.on('data', (c) => { body += c; if (body.length > MAX_BODY) { aborted = true; req.destroy(); } });
412
- req.on('end', async () => {
413
- if (aborted) { res.writeHead(413, base); return res.end(); }
414
- let msg;
415
- try { msg = JSON.parse(body); } catch {
416
- res.writeHead(400, { ...base, 'content-type': 'application/json' });
417
- return res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } }));
418
- }
419
- const list = Array.isArray(msg) ? msg : [msg];
420
- const responses = [];
421
- let isInit = false;
422
- for (const m of list) {
423
- if (!m || typeof m !== 'object' || typeof m.method !== 'string') continue;
424
- if (m.method === 'initialize') isInit = true;
425
- const isRequest = m.id !== undefined && m.id !== null;
426
- try {
427
- const result = await buildResult(m.method, m.params || {});
428
- if (isRequest) responses.push({ jsonrpc: '2.0', id: m.id, result });
429
- } catch (err) {
430
- if (isRequest) responses.push({ jsonrpc: '2.0', id: m.id, error: { code: err.code || -32603, message: err.message || String(err) } });
431
- }
432
- }
433
- if (!responses.length) { res.writeHead(202, base); return res.end(); } // notifications/responses only
434
- const headers = { ...base, 'content-type': 'application/json; charset=utf-8' };
435
- if (isInit) headers['mcp-session-id'] = crypto.randomUUID();
436
- res.writeHead(200, headers);
437
- res.end(JSON.stringify(Array.isArray(msg) ? responses : responses[0]));
438
- });
439
- req.on('error', () => { try { res.writeHead(400, base); res.end(); } catch { /* already gone */ } });
440
- });
441
-
442
- return new Promise((resolve) => {
443
- server.on('error', (e) => { process.stderr.write('relay mcp http error: ' + ((e && e.message) || e) + '\n'); resolve(1); });
444
- server.listen(port, host, () => {
445
- const shown = host === '0.0.0.0' ? 'localhost' : host;
446
- process.stderr.write(`relay MCP (Streamable HTTP) listening on http://${shown}:${port}${HTTP_PATH}\n`);
447
- if (!requireAuth && host !== '127.0.0.1' && host !== 'localhost') {
448
- process.stderr.write(' warning: bound to a non-local interface with no --token — anyone who can reach this port can drive relay.\n');
449
- }
450
- });
451
- const stop = () => { try { server.close(); } catch { /* noop */ } resolve(0); };
452
- process.on('SIGINT', stop);
453
- process.on('SIGTERM', stop);
454
- });
455
- }
456
-
457
- // The setup snippet printed by `rly mcp config` / `rly mcp install --print`.
458
- // Returns { json, toml, paths } so the CLI can present per-host instructions.
459
- export function mcpConfig({ command = 'rly', httpPort = DEFAULT_HTTP_PORT } = {}) {
460
- return {
461
- command,
462
- args: ['mcp'],
463
- httpPort,
464
- httpUrl: `http://127.0.0.1:${httpPort}${HTTP_PATH}`,
465
- // Claude Desktop / generic MCP JSON config (claude_desktop_config.json,
466
- // .mcp.json, VS Code mcp.json, …).
467
- json: {
468
- mcpServers: {
469
- relay: { command, args: ['mcp'] },
470
- },
471
- },
472
- // Codex CLI (~/.codex/config.toml).
473
- toml: `[mcp_servers.relay]\ncommand = "${command}"\nargs = ["mcp"]\n`,
474
- // Remote / web+mobile hosts (Claude web/mobile custom connector, etc.):
475
- // run `rly mcp --http` on any reachable address and register the URL.
476
- http: {
477
- run: `${command} mcp --http --port ${httpPort}`,
478
- url: `http://127.0.0.1:${httpPort}${HTTP_PATH}`,
479
- deploy: 'relay only needs its CLI — run `rly mcp --http` wherever the app can reach it. The repo Dockerfile deploys to any free MCP host (mcpdeploy.dev, mcphosting.io, Render/Railway/Fly, or Smithery) with zero config; $PORT is auto-honored. relay is stateless, so one instance serves everyone.',
480
- note: 'Set RLY_MCP_TOKEN for a bearer-protected endpoint. A tunnel (cloudflared/tailscale) is ONLY for exposing a NAT\'d local machine — never required; deploying to a reachable host needs no extra tooling.',
481
- },
482
- };
483
- }