@johnhenry/wsh 0.50.0 → 0.52.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/src/page-host.mjs CHANGED
@@ -75,6 +75,8 @@ function exposedRoots(window, expose) {
75
75
  const authorizers = new Map();
76
76
  const eventFields = {};
77
77
  const handles = {};
78
+ const types = {};
79
+ const mcpTools = [];
78
80
  let limits;
79
81
  for (const name of names) {
80
82
  const cfg = expose[name];
@@ -97,12 +99,25 @@ function exposedRoots(window, expose) {
97
99
  allow[op].push(op === 'on' && entry.startsWith('@') ? `${name}${entry}` : `${name}.${entry}`);
98
100
  }
99
101
  }
102
+ // Type texts for the far side's `.d.ts`, with the same relative paths (`'app.cart.add'`, `'app.bus@ready'`, `'@hashchange'` for the root itself): host-authored text, checked by `exposeObjects`.
103
+ if (cfg.types !== undefined && !isObj(cfg.types)) throw new TypeError(`createPageHost: expose.${name}.types must be an object of paths`);
104
+ for (const [path, spec] of Object.entries(cfg.types ?? {})) types[path.startsWith('@') ? `${name}${path}` : `${name}.${path}`] = spec;
100
105
  for (const [type, fields] of Object.entries(cfg.eventFields ?? {})) eventFields[type] = [...new Set([...(eventFields[type] ?? []), ...(Array.isArray(fields) ? fields : [])])];
101
106
  if (cfg.authorize !== undefined) { if (typeof cfg.authorize !== 'function') throw new TypeError(`createPageHost: expose.${name}.authorize must be a function`); authorizers.set(name, cfg.authorize); }
102
107
  if (cfg.limits !== undefined) limits = { ...limits, ...cfg.limits };
108
+ // An MCP face for named paths of this root (#219): `mcp: { tools: [{ name, description, call: 'app.cart.add', inputSchema }, { name, description, get: 'document.title' }] }`, paths relative to the root.
109
+ // Off unless written; each tool names one path that the allow-lists above also name. It is served on the `mcp` channel beside the page's WebMCP tools.
110
+ if (cfg.mcp !== undefined) {
111
+ if (!isObj(cfg.mcp) || Object.keys(cfg.mcp).some((k) => k !== 'tools') || !Array.isArray(cfg.mcp.tools)) throw new TypeError(`createPageHost: expose.${name}.mcp must be { tools: [...] }: name each path that becomes a tool (nothing is a tool by being allowed)`);
112
+ for (const tool of cfg.mcp.tools) {
113
+ if (!isObj(tool)) throw new TypeError(`createPageHost: expose.${name}.mcp.tools entries must be objects`);
114
+ const qualify = (v) => (typeof v === 'string' ? `${name}.${v}` : v);
115
+ mcpTools.push({ ...tool, ...(tool.call !== undefined ? { call: qualify(tool.call) } : {}), ...(tool.get !== undefined ? { get: qualify(tool.get) } : {}) });
116
+ }
117
+ }
103
118
  }
104
119
  const authorize = authorizers.size ? (who, op) => (authorizers.has(op.root) ? authorizers.get(op.root)(who, { ...op, path: op.path }) : true) : undefined;
105
- return { roots, allow, authorize, limits, eventFields, handles };
120
+ return { roots, allow, authorize, limits, eventFields, handles, types, mcp: mcpTools.length ? { tools: mcpTools } : undefined };
106
121
  }
107
122
 
108
123
  /**
@@ -162,6 +177,9 @@ function createDomIndicator(window, { name }) {
162
177
  * and whose origin is reported. Passing it exposes nothing by itself.
163
178
  * @param {string | { url: string, id?: string }} options.relay - a pipe relay (`@johnhenry/wsh/pipe-relay`): its `ws://` / `wss://` URL, and
164
179
  * optionally the rendezvous id (default: a fresh random one, exposed as `host.rendezvousId`)
180
+ * @param {string | { url: string }} [options.connect] - the dial-out form, OFF unless written and not together with `relay`: the `ws://` / `wss://` URL of an operator that
181
+ * WAITS (it listens, and logs in as the client over what it accepts). Dialled exactly as written (no role or rendezvous id is added), never logged, no user name,
182
+ * password or fragment in it. The login, sealing, approval, indicator and Stop are the same as behind a relay; there is no `operatorUrl` (it is `null`).
165
183
  * @param {Record<string, { mode?: 'values', allow?: { get?: string[], call?: string[], set?: string[] }, authorize?: Function, limits?: object, object?: object }>} [options.expose]
166
184
  * object access, off unless written: named roots (`window` is the window passed; another name needs `object`), each with its allow-lists by
167
185
  * operation (paths relative to the root: `'document.title'`, `'app.**'`; nothing allowed by default). `mode: 'handles'` is this root's own opt-in to handles (`nodes: true` a second one, for nodes and the window graph).
@@ -193,7 +211,7 @@ function createDomIndicator(window, { name }) {
193
211
  * @param {(line: string) => void} [options.onLog]
194
212
  */
195
213
  export async function createPageHost(options = {}) {
196
- const { window, relay, name, authorizedKeys, mcp, expose, indicator = true, unattended = false, hostKey, hostKeyStore, onSession, onSessionEnd, onRefused, onClose, reconnect = true, onLog = () => {} } = options;
214
+ const { window, relay, connect, name, authorizedKeys, mcp, expose, indicator = true, unattended = false, hostKey, hostKeyStore, onSession, onSessionEnd, onRefused, onClose, reconnect = true, onLog = () => {} } = options;
197
215
  if (!window || (typeof window !== 'object' && typeof window !== 'function')) {
198
216
  throw new TypeError('createPageHost: window is required: it is the realm served and the only thing this reads (pass `window`, an iframe\'s contentWindow, or a worker\'s self)');
199
217
  }
@@ -215,18 +233,32 @@ export async function createPageHost(options = {}) {
215
233
  if (!unattended) throw new TypeError('createPageHost: this window has no document to draw the indicator in: supply indicator callbacks, or say unattended: true');
216
234
  }
217
235
  if (!doc && !unattended && !callbacks) throw new TypeError('createPageHost: this window has no document: supply indicator callbacks, or say unattended: true');
218
- if (mcp && (mcp.approve ?? 'consequential') !== 'never' && !doc && !mcp.prompt && !unattended) {
236
+ if ((mcp || exposed?.mcp) && (mcp?.approve ?? 'consequential') !== 'never' && !doc && !mcp?.prompt && !unattended) {
219
237
  throw new TypeError("createPageHost: this window has no document to ask the person in: supply mcp.prompt, mcp.approve: 'never', or unattended: true");
220
238
  }
221
239
  if (typeof window.WebSocket !== 'function') throw new TypeError('createPageHost: window.WebSocket is needed to dial the relay');
222
240
  for (const [k, fn] of Object.entries({ onSession, onSessionEnd, onRefused, onClose })) if (fn !== undefined && typeof fn !== 'function') throw new TypeError(`createPageHost: ${k} must be a function`);
223
241
  if (hostKeyStore !== undefined && (typeof hostKeyStore?.load !== 'function' || typeof hostKeyStore?.save !== 'function')) throw new TypeError('createPageHost: hostKeyStore needs load() and save(keyPair)');
224
242
 
225
- const relayOptions = typeof relay === 'string' ? { url: relay } : relay;
226
- if (!isObj(relayOptions) || typeof relayOptions.url !== 'string') throw new TypeError('createPageHost: relay is required: the ws:// or wss:// URL of a pipe relay (or { url, id })');
227
- const rendezvousId = relayOptions.id ?? randomRendezvousId(window.crypto);
228
- const hostUrl = pipeUrl(relayOptions.url, rendezvousId, 'host');
229
- const operatorUrl = pipeUrl(relayOptions.url, rendezvousId, 'operator');
243
+ // Where the page dials: a pipe relay (the default form: the operator dials the same relay and the rendezvous id pairs them), or, only when `connect` is written, an
244
+ // endpoint of an operator that WAITS. Exactly one; neither is dialled until createPageHost is called with it.
245
+ if (relay !== undefined && connect !== undefined) throw new TypeError('createPageHost: give relay or connect, not both: relay is a pipe relay the operator also dials, connect is an operator that listens');
246
+ let hostUrl; let operatorUrl = null; let rendezvousId = null;
247
+ if (connect !== undefined) {
248
+ const connectUrl = typeof connect === 'string' ? connect : isObj(connect) && Object.keys(connect).every((k) => k === 'url') ? connect.url : undefined;
249
+ let parsed = null;
250
+ try { parsed = typeof connectUrl === 'string' ? new URL(connectUrl) : null; } catch { parsed = null; }
251
+ if (!parsed || (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') || parsed.username !== '' || parsed.password !== '' || parsed.hash !== '' || connectUrl.includes('#')) {
252
+ throw new TypeError('createPageHost: connect must be the ws:// or wss:// URL of an operator that listens (or { url }), with no user name, password or fragment in it');
253
+ }
254
+ hostUrl = connectUrl; // dialled as written: no role or rendezvous id is added, and the URL is never logged (its query may be a secret)
255
+ } else {
256
+ const relayOptions = typeof relay === 'string' ? { url: relay } : relay;
257
+ if (!isObj(relayOptions) || typeof relayOptions.url !== 'string') throw new TypeError('createPageHost: relay is required: the ws:// or wss:// URL of a pipe relay (or { url, id }), or connect: the URL of an operator that listens');
258
+ rendezvousId = relayOptions.id ?? randomRendezvousId(window.crypto);
259
+ hostUrl = pipeUrl(relayOptions.url, rendezvousId, 'host');
260
+ operatorUrl = pipeUrl(relayOptions.url, rendezvousId, 'operator');
261
+ }
230
262
 
231
263
  const timers = timersOf(window, options.timers);
232
264
  const origin = readOrigin(window);
@@ -258,18 +290,23 @@ export async function createPageHost(options = {}) {
258
290
  let watch = null;
259
291
  let unlisten = null;
260
292
 
261
- const mcpHandler = mcp ? webmcpTools({
262
- ...mcp, window, timers: options.timers, server: { name, ...(mcp.server ?? {}) },
263
- // Nobody is in front of an unattended window: without a prompt of the embedder's, what needs approval is denied.
264
- prompt: mcp.prompt ?? (unattended ? () => false : undefined),
265
- guard: () => gone() ?? mcp.guard?.() ?? null,
266
- }) : null;
267
293
  const objectsHandler = exposed ? exposeObjects({
268
- roots: exposed.roots, allow: exposed.allow, authorize: exposed.authorize, limits: exposed.limits, eventFields: exposed.eventFields, handles: exposed.handles, timers,
294
+ roots: exposed.roots, allow: exposed.allow, authorize: exposed.authorize, limits: exposed.limits, eventFields: exposed.eventFields, handles: exposed.handles, types: exposed.types, mcp: exposed.mcp, timers,
269
295
  // Handle ids come from the served window's own CSPRNG.
270
296
  random: (n) => window.crypto.getRandomValues(new Uint8Array(n)),
271
297
  guard: () => gone(),
272
298
  }) : null;
299
+ // The tools of the `mcp` channel: the page's WebMCP tools (`mcp.allow`) and the paths the host named as tools (`expose.ROOT.mcp.tools`). One handler, so one approval, one set of
300
+ // bounds, one label; a tool made from a path is allowed by being named in `expose`, and still needs the key's `mcp:TOOL` and `objects:ROOT:OP` capabilities.
301
+ const objectTools = objectsHandler?.mcpTools ?? [];
302
+ const mcpHandler = mcp || objectTools.length ? webmcpTools({
303
+ ...(mcp ?? {}), window, timers: options.timers, server: { name, ...(mcp?.server ?? {}) },
304
+ allow: [...(mcp?.allow ?? []), ...(objectsHandler?.mcpToolNames ?? [])],
305
+ tools: [...(mcp?.tools ?? []), ...objectTools],
306
+ // Nobody is in front of an unattended window: without a prompt of the embedder's, what needs approval is denied.
307
+ prompt: mcp?.prompt ?? (unattended ? () => false : undefined),
308
+ guard: () => gone() ?? mcp?.guard?.() ?? null,
309
+ }) : null;
273
310
  /** What each handler tells and ends: the sessions of a key, or all of them. */
274
311
  const closeSessions = async (reason, fingerprint) => {
275
312
  const counts = await Promise.all([mcpHandler, objectsHandler].filter(Boolean).map((h) => h.closeSessions(reason, fingerprint).catch(() => 0)));
@@ -322,7 +359,7 @@ export async function createPageHost(options = {}) {
322
359
  let socket;
323
360
  try { socket = new window.WebSocket(hostUrl); } catch (e) { onLog(`dialing the relay failed: ${e?.message ?? e}`); schedule(false); return; }
324
361
  halfSocket = socket;
325
- onLog('dialed the relay, waiting for an operator');
362
+ onLog(operatorUrl === null ? 'dialed the operator endpoint, waiting for it to log in' : 'dialed the relay, waiting for an operator');
326
363
  let served = false;
327
364
  void memory.accept(socket, { remote: { address: 'relay' } }).catch((e) => onLog(`accept failed: ${e?.message ?? e}`));
328
365
  const onEnd = () => {
package/src/webmcp.mjs CHANGED
@@ -24,6 +24,12 @@ import { RpcError, RPC_ERROR } from './rpc.mjs';
24
24
  import { callerIdentity } from './key-names.mjs';
25
25
 
26
26
  const TOOL_NAME_RE = /^[A-Za-z0-9_.-]{1,128}$/;
27
+ /**
28
+ * The key of the part of a tool definition that only the host's own code may set: `{ caller?: true, validate?(input) => string | null, available?({ permits }) => boolean }`.
29
+ * `caller` makes `execute` receive `{ who, permits }` of the session beside its signal; `validate` is run on the arguments before the person is asked; `available` hides the
30
+ * tool from a session whose key may not use it. Honoured only for the definitions passed in `webmcpTools({ tools })`.
31
+ */
32
+ export const INTERNAL_TOOL = Symbol.for('wsh.webmcp.internal');
27
33
  const APPROVE_MODES = new Set(['never', 'consequential', 'always']);
28
34
  const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
29
35
 
@@ -90,7 +96,7 @@ export function timersOf(window, injected = {}) {
90
96
  * annotations?, execute }`. The schemas are copied as JSON (the draft does the same at registration). Throws a `TypeError` that
91
97
  * says what is wrong.
92
98
  */
93
- export function normalizeTool(tool, who = 'webmcp') {
99
+ export function normalizeTool(tool, who = 'webmcp', { internal = false } = {}) {
94
100
  if (!isObj(tool)) throw new TypeError(`${who}: a tool must be an object { name, description, execute, ... }`);
95
101
  if (typeof tool.name !== 'string' || !TOOL_NAME_RE.test(tool.name)) throw new TypeError(`${who}: tool name ${JSON.stringify(tool.name)} must be 1-128 characters of letters, digits, "_", "-" and "."`);
96
102
  if (typeof tool.description !== 'string' || tool.description === '') throw new TypeError(`${who}: tool "${tool.name}" needs a description`);
@@ -103,7 +109,11 @@ export function normalizeTool(tool, who = 'webmcp') {
103
109
  return JSON.parse(s);
104
110
  };
105
111
  const annotations = copy(tool.annotations, 'annotations') ?? {};
112
+ // What the host's own code attaches to a tool it passes in `webmcpTools({ tools })` (an object path made into a tool, `objects-mcp.mjs`): never copied from a tool the
113
+ // page registers itself, so page code cannot ask for who is calling or for the key's grants.
114
+ const hostPart = internal && isObj(tool[INTERNAL_TOOL]) ? { [INTERNAL_TOOL]: tool[INTERNAL_TOOL] } : {};
106
115
  return {
116
+ ...hostPart,
107
117
  name: tool.name,
108
118
  ...(typeof tool.title === 'string' && tool.title ? { title: tool.title } : {}),
109
119
  description: tool.description,
@@ -423,7 +433,7 @@ export function webmcpTools(options = {}) {
423
433
  }
424
434
  const explicit = new Map();
425
435
  for (const t of tools) {
426
- const entry = normalizeTool(t, 'webmcpTools');
436
+ const entry = normalizeTool(t, 'webmcpTools', { internal: true });
427
437
  if (explicit.has(entry.name)) throw new TypeError(`webmcpTools: tool "${entry.name}" is listed twice`);
428
438
  explicit.set(entry.name, entry);
429
439
  }
@@ -449,6 +459,8 @@ export function webmcpTools(options = {}) {
449
459
  // The hook is told which it is: `mcp-tool` is listing a tool, `mcp-call` is running one (`op` says the same as `'list'` / `'call'`),
450
460
  // so an adapter may scope them apart. The notation's `mcp:TOOL` covers both.
451
461
  if (permits && !permits({ kind, op: kind === 'mcp-call' ? 'call' : 'list', tool: tool.name })) continue;
462
+ // A tool made from an object path is also limited by what the key may do on that root (`objects:ROOT:OP`): both notations must permit it.
463
+ if (tool[INTERNAL_TOOL]?.available && !tool[INTERNAL_TOOL].available({ permits })) continue;
452
464
  const bad = unlistable(tool, limits);
453
465
  if (bad) { emit({ outcome: 'unlisted', name: tool.name, limit: bad.limit, detail: bad.detail }); continue; }
454
466
  if (out.length >= limits.maxTools) { emit({ outcome: 'unlisted', name: tool.name, limit: 'maxTools', detail: `more than ${limits.maxTools} tools` }); continue; }
@@ -517,7 +529,8 @@ export function webmcpTools(options = {}) {
517
529
  const text = jsonOrNull(args) ?? '';
518
530
  if (utf8Length(text) > limits.maxInputBytes) throw fail('maxInputBytes', `the arguments are larger than ${limits.maxInputBytes} bytes`, { name });
519
531
  if (session.inflight.size >= limits.maxInflight) throw fail('maxInflight', `more than ${limits.maxInflight} calls in flight`, { name });
520
- const problem = checkInput(tool.inputSchema, args);
532
+ const host = tool[INTERNAL_TOOL];
533
+ const problem = checkInput(tool.inputSchema, args) ?? (host?.validate ? host.validate(args) : null);
521
534
  if (problem) throw new RpcError(RPC_ERROR.INVALID_PARAMS, `invalid arguments: ${problem}`);
522
535
 
523
536
  const ctl = new AbortController();
@@ -542,7 +555,7 @@ export function webmcpTools(options = {}) {
542
555
  timedOut.catch(() => {});
543
556
  let value;
544
557
  try {
545
- value = await Promise.race([Promise.resolve().then(() => tool.execute(args, { signal: ctl.signal })), timedOut]);
558
+ value = await Promise.race([Promise.resolve().then(() => tool.execute(args, { signal: ctl.signal, ...(host?.caller ? { who, permits } : {}) })), timedOut]);
546
559
  } catch (e) {
547
560
  if (rpc.signal.aborted) throw e;
548
561
  emit({ outcome: 'error', name, who });