@johnhenry/wsh 0.47.0 → 0.49.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.
@@ -0,0 +1,184 @@
1
+ /**
2
+ * MCP over any duplex (#220). The handler of `webmcpTools` (and any rpc handler of the `mcp` protocol written as `(channel, ctx) => void`)
3
+ * serves MCP on a channel; over wsh that channel is an `RpcChannel` of the `mcp` rpc protocol. `serveMcpOverDuplex` gives the same handler
4
+ * a channel made of nothing but two functions you already have: `send(message)` for what goes to the far side, and `receive(message)` for
5
+ * what comes from it, so a transport that is not wsh at all (a mesh channel, a `MessagePort`, a data channel, a test) can carry it.
6
+ *
7
+ * ```js
8
+ * import { webmcpTools, serveMcpOverDuplex } from '@johnhenry/wsh/page';
9
+ * const handler = webmcpTools({ window, allow: ['search'], approve: 'consequential' });
10
+ * const session = serveMcpOverDuplex(handler, { send: (message) => meshChannel.send(message), who: { podId } });
11
+ * meshChannel.onmessage = (message) => session.receive(message);
12
+ * meshChannel.onclose = () => session.close('the peer left');
13
+ * ```
14
+ *
15
+ * WHAT THE FAR SIDE SPEAKS: plain MCP, that is JSON-RPC 2.0 messages as JavaScript objects (`{ jsonrpc: '2.0', id, method, params }`,
16
+ * `{ jsonrpc: '2.0', id, result }` or `{ jsonrpc: '2.0', id, error: { code, message, data? } }`, and notifications with no `id`): an MCP SDK
17
+ * `Client` can be connected to it through any `Transport` that moves those objects. Encoding them (JSON text, CBOR, structured clone) is the
18
+ * transport's business; this file sees objects. No batches (MCP no longer has them), no ids but strings and integers, one answer per id.
19
+ *
20
+ * WHAT IS THE HANDLER'S, UNCHANGED: the allow-list of tools, the bounds on tools, schemas, arguments and results, the approval of the
21
+ * person at the page (`approve`, `prompt`), the `onCall` events and the labelling of every result as untrusted page content. WHAT THIS
22
+ * ADDS: the bounds of the seam itself (the size of a message in either direction, the requests running at once, one id one request), and
23
+ * the refusal of anything that is not a JSON-RPC 2.0 message from the far side.
24
+ *
25
+ * It does NOT authenticate the far side or seal anything: whoever the transport says is on the other end is `who`, and `permits` is
26
+ * whatever that transport's grants allow. Those are the adapter's to establish and say; they are not in the messages.
27
+ */
28
+
29
+ import { RpcError, RPC_ERROR } from './rpc.mjs';
30
+ import { callerIdentity } from './key-names.mjs';
31
+
32
+ const DEFAULT_MAX_MESSAGE_BYTES = 1024 * 1024;
33
+ const DEFAULT_MAX_INFLIGHT = 64;
34
+ const MAX_ID_CHARS = 256;
35
+
36
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
37
+
38
+ /** UTF-8 length of the JSON of `value` (the size of the message on a JSON transport), or -1 when it has none. */
39
+ function jsonBytes(value) {
40
+ let s;
41
+ try { s = JSON.stringify(value); } catch { return -1; }
42
+ if (typeof s !== 'string') return -1;
43
+ let n = 0;
44
+ for (let i = 0; i < s.length; i++) {
45
+ const c = s.charCodeAt(i);
46
+ if (c < 0x80) n += 1;
47
+ else if (c < 0x800) n += 2;
48
+ else if (c >= 0xd800 && c <= 0xdbff) { n += 4; i++; } else n += 3;
49
+ }
50
+ return n;
51
+ }
52
+
53
+ const validId = (id) => (typeof id === 'string' && id.length >= 1 && id.length <= MAX_ID_CHARS) || (Number.isSafeInteger(id));
54
+
55
+ /**
56
+ * Serve an MCP handler over a duplex.
57
+ *
58
+ * @param {(channel: object, ctx?: object) => void} handler what `webmcpTools(...)` returns, or any handler written for an rpc channel of the `mcp` protocol
59
+ * @param {object} options
60
+ * @param {(message: object) => void | Promise<void>} options.send writes a JSON-RPC 2.0 message to the far side; a throw (or a rejection) ends the session
61
+ * @param {{ username?: string | null, fingerprint?: string | null, podId?: string | null }} [options.who] who is on the far side, as the transport knows
62
+ * it: the handler's prompt, `onCall` events and `closeSessions(reason, fingerprint)` see it (`fingerprint` and `podId` agree, see `callerIdentity`)
63
+ * @param {(request: { kind: string, [field: string]: unknown }) => boolean} [options.permits] the far side's grants, asked afresh for each tool
64
+ * (`{ kind: 'mcp-tool', tool }`); with none, nothing narrows the handler's own allow-list. `@johnhenry/wsh/capabilities`'s `permits` fits: `(req) => permits(caps, req)`
65
+ * @param {number} [options.maxMessageBytes=1048576] the largest message, JSON-encoded, in either direction
66
+ * @param {number} [options.maxInflight=64] requests of the far side being answered at once, of any kind
67
+ * @returns {{ receive(message: unknown): void, close(reason?: string): void, readonly closed: boolean, readonly who: object | undefined }}
68
+ */
69
+ export function serveMcpOverDuplex(handler, options = {}) {
70
+ if (typeof handler !== 'function') throw new TypeError('serveMcpOverDuplex: the handler must be a function (channel, ctx), what webmcpTools() returns');
71
+ const { send, who, permits, maxMessageBytes = DEFAULT_MAX_MESSAGE_BYTES, maxInflight = DEFAULT_MAX_INFLIGHT } = options;
72
+ if (typeof send !== 'function') throw new TypeError('serveMcpOverDuplex: send(message) is required');
73
+ if (permits !== undefined && typeof permits !== 'function') throw new TypeError('serveMcpOverDuplex: permits must be a function');
74
+ if (!Number.isSafeInteger(maxMessageBytes) || maxMessageBytes < 256) throw new TypeError('serveMcpOverDuplex: maxMessageBytes must be a whole number of at least 256');
75
+ if (!Number.isSafeInteger(maxInflight) || maxInflight < 1) throw new TypeError('serveMcpOverDuplex: maxInflight must be a positive whole number');
76
+ const identity = callerIdentity(who);
77
+
78
+ let closed = false;
79
+ const requestHandlers = new Map();
80
+ const notificationHandlers = new Map();
81
+ /** id -> its AbortController, for what is being answered. */
82
+ const inflight = new Map();
83
+
84
+ const fail = (reason) => { try { session.close(reason); } catch { /* already closing */ } };
85
+ /** Write one message; a throw or rejection of the transport ends the session. Resolves when written. */
86
+ async function write(message) {
87
+ if (closed) return;
88
+ const size = jsonBytes(message);
89
+ if (size < 0) throw new TypeError('the message cannot be serialised as JSON');
90
+ if (size > maxMessageBytes) throw new RpcError(RPC_ERROR.INTERNAL, `refused: a message of ${size} bytes is larger than maxMessageBytes (${maxMessageBytes})`, { reason: 'message-too-large' });
91
+ try { await send(message); } catch (e) { fail('the transport failed to send'); throw e; }
92
+ }
93
+ const respond = (id, body) => write({ jsonrpc: '2.0', id, ...body }).catch(() => {});
94
+ const refuse = (id, code, message, data) => respond(id, { error: { code, message, ...(data !== undefined ? { data } : {}) } });
95
+
96
+ /** The channel the handler is given: the part of an `RpcChannel` that an MCP handler uses. */
97
+ const channel = {
98
+ maxMessageBytes,
99
+ onRequest(method, fn) { requestHandlers.set(method, fn); },
100
+ onNotification(method, fn) { notificationHandlers.set(method, fn); },
101
+ notify: (method, params) => write({ jsonrpc: '2.0', method, ...(params !== undefined ? { params } : {}) }),
102
+ request: () => Promise.reject(new RpcError(RPC_ERROR.METHOD_NOT_FOUND, 'this side serves MCP and asks the far side nothing')),
103
+ close: async (reason) => { session.close(reason); },
104
+ onClose: null,
105
+ get closed() { return closed; },
106
+ };
107
+
108
+ async function dispatch(id, method, params) {
109
+ const fn = requestHandlers.get(method);
110
+ if (!fn) { await refuse(id, RPC_ERROR.METHOD_NOT_FOUND, `method not found: ${method}`); return; }
111
+ const ctl = new AbortController();
112
+ inflight.set(id, ctl);
113
+ try {
114
+ const result = await fn(params, { id, signal: ctl.signal });
115
+ // A cancelled request is not answered: the far side said it no longer wants the answer.
116
+ if (!closed && !ctl.signal.aborted) {
117
+ const body = { jsonrpc: '2.0', id, result: result === undefined ? {} : result };
118
+ const size = jsonBytes(body);
119
+ if (size < 0) await refuse(id, RPC_ERROR.INTERNAL, 'the answer cannot be serialised as JSON');
120
+ else if (size > maxMessageBytes) await refuse(id, RPC_ERROR.INTERNAL, `refused: the answer is ${size} bytes, larger than maxMessageBytes (${maxMessageBytes})`, { reason: 'message-too-large' });
121
+ else await write(body).catch(() => {});
122
+ }
123
+ } catch (e) {
124
+ if (!closed && !ctl.signal.aborted) {
125
+ if (e instanceof RpcError) await refuse(id, e.code, e.message, e.toJSON().data);
126
+ else await refuse(id, RPC_ERROR.INTERNAL, String(e?.message ?? e));
127
+ }
128
+ } finally {
129
+ inflight.delete(id);
130
+ }
131
+ }
132
+
133
+ const session = {
134
+ /** Hand over one message from the far side. Never throws: what cannot be answered is refused or dropped. */
135
+ receive(message) {
136
+ if (closed) return;
137
+ if (!isObject(message) || message.jsonrpc !== '2.0') {
138
+ // An id we can read is answered; anything else is dropped (there is no one to tell).
139
+ if (isObject(message) && validId(message.id)) void refuse(message.id, RPC_ERROR.INVALID_REQUEST, 'not a JSON-RPC 2.0 message (batches are not supported)');
140
+ else if (Array.isArray(message) || message === null || typeof message !== 'object') void refuse(null, RPC_ERROR.INVALID_REQUEST, 'not a JSON-RPC 2.0 message (batches are not supported)');
141
+ return;
142
+ }
143
+ const size = jsonBytes(message);
144
+ if (size < 0 || size > maxMessageBytes) {
145
+ void refuse(validId(message.id) ? message.id : null, RPC_ERROR.INVALID_REQUEST, `refused: a message larger than maxMessageBytes (${maxMessageBytes})`, { reason: 'message-too-large' });
146
+ return;
147
+ }
148
+ const hasId = Object.hasOwn(message, 'id');
149
+ if (typeof message.method !== 'string') {
150
+ // A response (or error) of the far side: nothing here asked it anything.
151
+ if (hasId && !('result' in message) && !('error' in message)) void refuse(validId(message.id) ? message.id : null, RPC_ERROR.INVALID_REQUEST, 'a request needs a method');
152
+ return;
153
+ }
154
+ if (message.params !== undefined && !isObject(message.params)) {
155
+ if (hasId) void refuse(validId(message.id) ? message.id : null, RPC_ERROR.INVALID_REQUEST, 'params must be an object');
156
+ return;
157
+ }
158
+ if (!hasId) {
159
+ // A notification. Cancellation is the one the seam knows: it aborts the request the far side names.
160
+ if (message.method === 'notifications/cancelled') inflight.get(message.params?.requestId)?.abort(new Error('cancelled by the caller'));
161
+ try { notificationHandlers.get(message.method)?.(message.params); } catch { /* a notification has no one to tell */ }
162
+ return;
163
+ }
164
+ if (!validId(message.id)) { void refuse(null, RPC_ERROR.INVALID_REQUEST, 'a request id is a string or a whole number'); return; }
165
+ if (inflight.has(message.id)) { void refuse(message.id, RPC_ERROR.INVALID_REQUEST, `request id ${JSON.stringify(message.id)} is still in flight`); return; }
166
+ if (inflight.size >= maxInflight) { void refuse(message.id, RPC_ERROR.STREAM_LIMIT, `refused: maxInflight: more than ${maxInflight} requests at once`, { limit: 'maxInflight' }); return; }
167
+ void dispatch(message.id, message.method, message.params);
168
+ },
169
+
170
+ /** End the session: running calls are aborted, the handler's watchers are removed, nothing more is answered. */
171
+ close(reason = 'closed') {
172
+ if (closed) return;
173
+ closed = true;
174
+ for (const ctl of inflight.values()) ctl.abort(new Error(`the session ended (${reason})`));
175
+ try { channel.onClose?.(reason); } catch { /* the handler's own */ }
176
+ },
177
+
178
+ get closed() { return closed; },
179
+ get who() { return identity; },
180
+ };
181
+
182
+ handler(channel, { ...(identity ? { who: identity, user: identity.username, fingerprint: identity.fingerprint } : {}), ...(permits ? { permits } : {}) });
183
+ return session;
184
+ }
@@ -90,6 +90,11 @@ export interface WshMemoryHostOptions {
90
90
  sealSession?: false | 'offer' | 'require';
91
91
  /** #163: told once per connection this host turned away (a key it does not allow, a plain client on a host that requires a sealed session, ...), with a stable reason code. */
92
92
  onRefused?: WshOnRefused;
93
+ /**
94
+ * Called once per connection when its session has been sealed (after login). With `sealSession: 'require'` a login is not yet a session
95
+ * that can do anything: `auth.authorize(who)` is told `who.sealRequired: true`, and audit or an indicator belongs here instead.
96
+ */
97
+ onSealed?: (who: { username: string | null; fingerprint: string | null }) => void;
93
98
  /**
94
99
  * #121: execution targets, each with its own `exec`, `pty`, `fs` and `endpoints` and an `authorize(who, { target, kind })`.
95
100
  * A client names one in `Open`, `FileOp` or `OpenEndpoint` and lists what it may use with `listTargets()`. Off unless given:
@@ -180,7 +180,8 @@ function createRegistry(sessions, log) {
180
180
  * @param {(line: string) => void} [options.onLog]
181
181
  */
182
182
  export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions, rpc, rpcMaxMessageBytes = RPC_DEFAULT_MAX_MESSAGE, rpcMaxInflight = 64, sessions, endpoints, dataStreams = true, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, sealSession = false, onLog = () => {},
183
- onShare, onRefused, targets, requireTarget, usernamePattern } = {}) {
183
+ onShare, onRefused, onSealed, targets, requireTarget, usernamePattern } = {}) {
184
+ if (onSealed !== undefined && typeof onSealed !== 'function') throw new TypeError('createMemoryHost: onSealed must be a function');
184
185
  resolveUsernamePattern(usernamePattern, 'createMemoryHost');
185
186
  validateOnShare(onShare, 'createMemoryHost');
186
187
  validateOnRefused(onRefused, 'createMemoryHost');
@@ -217,7 +218,7 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
217
218
 
218
219
  const ready = Promise.all([buildAuthorizer(auth, { log: onLog }), hostKeyReady]).then(([authorize, hostKeyResolved]) => createConnectionFactory({
219
220
  authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
220
- methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, onShare, onRefused,
221
+ methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, onShare, onRefused, onSealed,
221
222
  targets: targetTable, requireTarget: mustHaveTarget, usernamePattern,
222
223
  gateway: gatewayCfg, createGatewaySession: gatewayCfg ? createEndpointGatewaySession : undefined, sessions: registry, relay: null,
223
224
  }));