@johnhenry/wsh 0.49.0 → 0.51.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.
@@ -35,10 +35,12 @@ async function toBytes(data) {
35
35
  * @param {{ remote?: { address?: string, headers?: object }, dataStreams?: boolean }} [options] - what the host knows about the peer
36
36
  * (`address` keys the password-failure throttle; the default key is shared by every socket without one).
37
37
  * `dataStreams: false` serves this connection without client-opened data streams (exec output rides SessionData), for a
38
- * client that cannot open them (the Rust client over WebSocket, #132).
38
+ * client that cannot open them (the Rust client over WebSocket, #132). `sealSession: 'require'` makes THIS connection serve nothing
39
+ * until it is sealed, whatever the host's own setting (it can only strengthen it; a host with no host key, or with data streams, refuses to
40
+ * attach it: `ready` rejects). It is what `@johnhenry/wsh/duplex` asks of a transport it cannot vouch for.
39
41
  * @returns {Promise<{ close(): void }>} resolves once the connection is attached; `close()` drops it
40
42
  */
41
- export function bindSocket(socket, ready, { remote = {}, dataStreams } = {}) {
43
+ export function bindSocket(socket, ready, { remote = {}, dataStreams, sealSession } = {}) {
42
44
  if (!socket || typeof socket.send !== 'function' || typeof socket.close !== 'function') {
43
45
  throw new TypeError('accept: socket must be a WebSocket-like duplex with send() and close()');
44
46
  }
@@ -74,6 +76,7 @@ export function bindSocket(socket, ready, { remote = {}, dataStreams } = {}) {
74
76
  send: write,
75
77
  remote: { address: remote.address, headers: remote.headers ?? {} },
76
78
  dataStreams,
79
+ ...(sealSession !== undefined ? { sealSession } : {}),
77
80
  closeTransport: () => { try { socket.close(1000); } catch { /* already closed */ } },
78
81
  });
79
82
  });
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 });