@johnhenry/wsh 0.45.0 → 0.46.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 +337 -35
- package/bin/wsh-mcp.mjs +3 -1
- package/package.json +13 -1
- package/src/cbor.mjs +40 -7
- package/src/client.mjs +79 -20
- package/src/errors.mjs +90 -0
- package/src/host-backends.mjs +23 -0
- package/src/host.d.ts +1 -1
- package/src/index.d.ts +66 -0
- package/src/index.mjs +5 -0
- package/src/key-options.mjs +3 -1
- package/src/mcp-stdio.d.ts +2 -0
- package/src/mcp-stdio.mjs +4 -2
- package/src/memory-host.d.ts +12 -1
- package/src/memory-host.mjs +8 -21
- package/src/objects-core.mjs +805 -0
- package/src/objects.d.ts +152 -0
- package/src/objects.mjs +97 -0
- package/src/page-host.d.ts +213 -0
- package/src/page-host.mjs +381 -0
- package/src/pipe-relay-node.mjs +43 -0
- package/src/pipe-relay.d.ts +19 -4
- package/src/pipe-relay.mjs +108 -39
- package/src/reverse-host.d.ts +4 -0
- package/src/reverse-host.mjs +14 -4
- package/src/rpc-virtual.mjs +127 -0
- package/src/rpc.mjs +34 -2
- package/src/server/connection.mjs +70 -10
- package/src/server/index.d.ts +41 -2
- package/src/server/index.mjs +5 -2
- package/src/server/password.mjs +142 -0
- package/src/server/reverse-host.mjs +7 -2
- package/src/server/username.mjs +57 -0
- package/src/session.mjs +2 -1
- package/src/testing.d.ts +50 -0
- package/src/testing.mjs +27 -0
- package/src/webmcp.mjs +694 -0
package/src/objects.d.ts
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import type { RpcChannel, WshClient } from './index.js';
|
|
2
|
+
|
|
3
|
+
/** The rpc protocol name. */
|
|
4
|
+
export const OBJECTS_PROTOCOL: 'wsh-objects';
|
|
5
|
+
|
|
6
|
+
/** Error codes of the protocol (JSON-RPC's where one fits). */
|
|
7
|
+
export const OBJECTS_ERROR: Readonly<{ INVALID: -32602; LIMIT: -32002; REFUSED: -32003; FAILED: -32000 }>;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A refusal or failure. `reason` names the rule: `always-refused`, `not-allowed`, `needs-listing`, `authorize`, `limit` (then `data.limit` names the bound),
|
|
11
|
+
* `bad-request`, `no-such-root`, `bad-path`, `not-a-function`, `threw`, `gone`, `closed`.
|
|
12
|
+
*/
|
|
13
|
+
export class ObjectsError extends Error {
|
|
14
|
+
constructor(code: number, message: string, data?: { reason?: string; [k: string]: unknown });
|
|
15
|
+
code: number;
|
|
16
|
+
data?: { reason?: string; limit?: string; max?: number; path?: string; op?: string; [k: string]: unknown };
|
|
17
|
+
reason?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** What a remote value that cannot be cloned arrives as: named, never a handle. `kind`: `function`, `symbol`, `bigint`, `number` (too large for the wire), `Date`, `RegExp`, `Error`, `object`. */
|
|
21
|
+
export class NonValue {
|
|
22
|
+
constructor(wire: { u: string; type?: string; text?: string });
|
|
23
|
+
readonly kind: string;
|
|
24
|
+
/** The class name (`HTMLDivElement`) or a function's name. */
|
|
25
|
+
readonly type?: string;
|
|
26
|
+
/** A short safe rendering: a date's ISO string, an error's message. */
|
|
27
|
+
readonly text?: string;
|
|
28
|
+
toString(): string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The bounds, each refused by name (the error says which). */
|
|
32
|
+
export interface ObjectsLimits {
|
|
33
|
+
/** Operations (get / call / construct) in one request. Default 32. */
|
|
34
|
+
maxOps: number;
|
|
35
|
+
/** Arguments of one call. Default 16. */
|
|
36
|
+
maxArgs: number;
|
|
37
|
+
/** How deep a returned or sent value nests. Default 8. */
|
|
38
|
+
maxDepth: number;
|
|
39
|
+
/** Bytes of one returned value and of one sent value. Default 262144 (and under what the transport carries in one message). */
|
|
40
|
+
maxValueBytes: number;
|
|
41
|
+
/** Keys one `describe` lists. Default 200. */
|
|
42
|
+
maxKeys: number;
|
|
43
|
+
/** Requests accepted per second, per channel. Default 50. */
|
|
44
|
+
maxRequestsPerSecond: number;
|
|
45
|
+
/** How long a call that returns a promise is waited for. Default 30000. */
|
|
46
|
+
callTimeoutMs: number;
|
|
47
|
+
}
|
|
48
|
+
export const OBJECTS_DEFAULT_LIMITS: Readonly<ObjectsLimits>;
|
|
49
|
+
|
|
50
|
+
/** Path sequences refused until an allow-list entry names them (a wildcard does not): `document.cookie`, `localStorage`, `sessionStorage`, `indexedDB`, `navigator.credentials`, `fetch`, `XMLHttpRequest`, `postMessage`, `open`. */
|
|
51
|
+
export const NEEDS_LISTING: ReadonlyArray<readonly string[]>;
|
|
52
|
+
|
|
53
|
+
/** Allow-lists by operation: path patterns from a root (`'window.document.title'`, `'window.app.**'`; `*` is one segment, `**` any number). `call` covers `construct`. Nothing is allowed by default. */
|
|
54
|
+
export interface ObjectsAllow {
|
|
55
|
+
get?: string[];
|
|
56
|
+
call?: string[];
|
|
57
|
+
set?: string[];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface ObjectsWho { username: string | null; fingerprint: string | null }
|
|
61
|
+
export interface ObjectsOperation {
|
|
62
|
+
kind: 'get' | 'call' | 'construct' | 'set' | 'describe' | 'snapshot';
|
|
63
|
+
root: string;
|
|
64
|
+
/** The path below the root. */
|
|
65
|
+
path: string[];
|
|
66
|
+
/** The whole path as text: `window.app.cart.add`. */
|
|
67
|
+
text: string;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface ObjectsServerOptions {
|
|
71
|
+
/** The named roots: all that is reachable. */
|
|
72
|
+
roots: Record<string, object>;
|
|
73
|
+
/** `'values'` is the only mode: `'handles'` is refused (not built). */
|
|
74
|
+
mode?: 'values';
|
|
75
|
+
allow?: ObjectsAllow;
|
|
76
|
+
/** Asked for every operation the allow-list let through; anything but `true` (a throw included) refuses. */
|
|
77
|
+
authorize?: (who: ObjectsWho, op: ObjectsOperation) => boolean | Promise<boolean>;
|
|
78
|
+
limits?: Partial<ObjectsLimits>;
|
|
79
|
+
/** Why nothing may be served any more (the window left), else null. */
|
|
80
|
+
guard?: () => string | null;
|
|
81
|
+
/** For `callTimeoutMs`. */
|
|
82
|
+
timers?: { setTimeout(fn: () => void, ms: number): unknown; clearTimeout(id: unknown): void } | null;
|
|
83
|
+
now?: () => number;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** What the core needs of a transport (an `RpcChannel` is one; `createDuplexPeer` makes one from `send` and `receive`). */
|
|
87
|
+
export interface ObjectsPeer {
|
|
88
|
+
onRequest(method: string, handler: (params: any, ctx: { signal?: AbortSignal; progress?: (chunk: unknown) => unknown; who?: ObjectsWho }) => unknown): unknown;
|
|
89
|
+
onNotification?(method: string, handler: (params: any) => void): unknown;
|
|
90
|
+
request(method: string, params?: unknown, options?: { signal?: AbortSignal; onProgress?: (chunk: unknown) => void }): Promise<any>;
|
|
91
|
+
notify(method: string, params?: unknown): unknown;
|
|
92
|
+
onClose: ((reason?: string) => void) | null;
|
|
93
|
+
readonly maxMessageBytes: number;
|
|
94
|
+
close?(reason?: string): unknown;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The transport-neutral server half: roots, allow-lists and limits, attachable to any peer. Knows nothing about wsh. */
|
|
98
|
+
export function createObjectsServer(options: ObjectsServerOptions): {
|
|
99
|
+
attach(peer: Pick<ObjectsPeer, 'onRequest' | 'maxMessageBytes'>, options?: { who?: ObjectsWho }): { limits: ObjectsLimits };
|
|
100
|
+
readonly limits: Readonly<ObjectsLimits>;
|
|
101
|
+
readonly rootNames: string[];
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
/** A peer over `send(message)` and `receive(message)`: the same protocol over any duplex that is not wsh. */
|
|
105
|
+
export function createDuplexPeer(options: { send(message: object): void; maxMessageBytes?: number }): ObjectsPeer & { receive(message: unknown): void; close(reason?: string): void; readonly closed: boolean };
|
|
106
|
+
|
|
107
|
+
/** The client half over any peer: the roots, as lazy references. */
|
|
108
|
+
export function createObjectsClient<T = Record<string, any>>(peer: Pick<ObjectsPeer, 'request'> & Partial<ObjectsPeer>, options?: { timeoutMs?: number }): Promise<T>;
|
|
109
|
+
|
|
110
|
+
/** `exposeObjects`: the rpc handler for `wsh-objects`. Usable as `rpc: { 'wsh-objects': exposeObjects({ roots, allow }) }` in any host. */
|
|
111
|
+
export interface ObjectsHandler {
|
|
112
|
+
(channel: RpcChannel, ctx?: { user?: string | null; fingerprint?: string | null }): void;
|
|
113
|
+
/** Tell every session (or those of one key) why, then end it. Resolves with how many were ended. */
|
|
114
|
+
closeSessions(reason: string, fingerprint?: string): Promise<number>;
|
|
115
|
+
readonly rootNames: string[];
|
|
116
|
+
readonly limits: Readonly<ObjectsLimits>;
|
|
117
|
+
}
|
|
118
|
+
export function exposeObjects(options: ObjectsServerOptions): ObjectsHandler;
|
|
119
|
+
|
|
120
|
+
/** Open `wsh-objects` on a connected client: the roots, as lazy references. Also `client.openObjects()`, which importing this entry point adds. */
|
|
121
|
+
export function openObjects<T = Record<string, any>>(client: WshClient, options?: { timeoutMs?: number }): Promise<T>;
|
|
122
|
+
|
|
123
|
+
declare module './index.js' {
|
|
124
|
+
interface WshClient {
|
|
125
|
+
/**
|
|
126
|
+
* Open the `wsh-objects` channel: the host's named roots as lazy references (`const { window } = await client.openObjects()`). A reference is a path:
|
|
127
|
+
* `window.document.title` sends nothing, `await` sends the whole chain in one request. Needs `import '@johnhenry/wsh/objects'` (which adds this method).
|
|
128
|
+
*/
|
|
129
|
+
openObjects<T = Record<string, any>>(options?: { timeoutMs?: number }): Promise<T>;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The value at a reference, or at a property of it: `await get(ref, 'then')` reaches a property that `ref.then` cannot. */
|
|
134
|
+
export function get(ref: any, ...keys: Array<string | number>): Promise<any>;
|
|
135
|
+
/** Assign a property of a remote object (not `=`: that throws). The reference must be a plain path. */
|
|
136
|
+
export function set(ref: any, key: string | number, value: unknown): Promise<void>;
|
|
137
|
+
/** Call a method reached by name, with plain-data arguments. */
|
|
138
|
+
export function call(ref: any, ...args: unknown[]): Promise<any>;
|
|
139
|
+
/** `new` a constructor reached by name. */
|
|
140
|
+
export function construct(ref: any, ...args: unknown[]): Promise<any>;
|
|
141
|
+
/** A bounded deep copy; subtrees deeper than `depth` are `null`. */
|
|
142
|
+
export function snapshot(ref: any, options?: { depth?: number; maxBytes?: number; signal?: AbortSignal }): Promise<any>;
|
|
143
|
+
/** The shape of an object, for completion: the names and types the allow-list could walk to. */
|
|
144
|
+
export function describe(ref: any, options?: { signal?: AbortSignal }): Promise<{ type: string; keys: Array<{ key: string; type: string; own: boolean }>; truncated?: boolean }>;
|
|
145
|
+
/** End the connection behind what `openObjects()` returned. */
|
|
146
|
+
export function closeObjects(page: unknown): Promise<void>;
|
|
147
|
+
|
|
148
|
+
export function matchPath(pattern: string[], path: string[]): boolean;
|
|
149
|
+
/** A value as plain data (`{ v }`), or a named non-value (`{ u, type?, text? }`). */
|
|
150
|
+
export function toWire(value: unknown, options?: { maxDepth?: number; maxBytes?: number; cut?: boolean }): { v: unknown; truncated?: boolean } | { u: string; type?: string; text?: string };
|
|
151
|
+
/** What may be sent to a host: plain data only, copied; throws an `ObjectsError` for anything else. */
|
|
152
|
+
export function fromWire(value: unknown, options?: { maxDepth?: number; maxBytes?: number }): unknown;
|
package/src/objects.mjs
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@johnhenry/wsh/objects` -- remote objects (#190), `values` mode, as the rpc protocol `wsh-objects`: any object graph can be a named root
|
|
3
|
+
* (a page's `window`, a worker's `self`, a Node object), reached by path, and only plain cloneable values ever cross. Both sides:
|
|
4
|
+
*
|
|
5
|
+
* ```js
|
|
6
|
+
* // the host (any host that takes `rpc`):
|
|
7
|
+
* createMemoryHost({ auth, hostKey: true, dataStreams: false, sealSession: 'require',
|
|
8
|
+
* rpc: { 'wsh-objects': exposeObjects({ roots: { window }, allow: { get: ['window.document.title', 'window.app.**'], call: ['window.app.**'] } }) } });
|
|
9
|
+
*
|
|
10
|
+
* // the far side:
|
|
11
|
+
* import { get, set, call, snapshot, describe } from '@johnhenry/wsh/objects';
|
|
12
|
+
* const page = await client.openObjects(); // { window }: lazy references (this entry point adds `openObjects` to WshClient)
|
|
13
|
+
* await page.window.document.title; // one `resolve` request, whatever the length of the chain
|
|
14
|
+
* await page.window.app.cart.add({ sku: 'A1', qty: 2 }); // a call, with plain-data arguments
|
|
15
|
+
* await set(page.window.document, 'title', 'Paid'); // not `=`: an assignment cannot be awaited or report a refusal
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* The transport-neutral core is `objects-core.mjs`; this file is the wsh adapter (an `RpcChannel` is the seam the core needs) and the client
|
|
19
|
+
* method. Read the README's "Remote objects" section for what an allow-list of paths can and cannot promise.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { RpcError } from './rpc.mjs';
|
|
23
|
+
import { WshClient } from './client.mjs';
|
|
24
|
+
import {
|
|
25
|
+
OBJECTS_PROTOCOL, ObjectsError, createObjectsServer, createObjectsClient,
|
|
26
|
+
} from './objects-core.mjs';
|
|
27
|
+
|
|
28
|
+
export {
|
|
29
|
+
OBJECTS_PROTOCOL, OBJECTS_ERROR, OBJECTS_DEFAULT_LIMITS, NEEDS_LISTING, ObjectsError, NonValue,
|
|
30
|
+
createObjectsServer, createObjectsClient, createDuplexPeer, matchPath, toWire, fromWire,
|
|
31
|
+
get, set, call, construct, snapshot, describe, closeObjects,
|
|
32
|
+
} from './objects-core.mjs';
|
|
33
|
+
|
|
34
|
+
/** Timers for `callTimeoutMs` where the embedder gave none: this module is the Node-or-browser adapter, not the page entry point. */
|
|
35
|
+
const defaultTimers = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (id) => clearTimeout(id) };
|
|
36
|
+
|
|
37
|
+
/** An `RpcChannel` as the core's `Peer`: refusals become `RpcError`s with their reason, so the far side hears the sentence and the rule. */
|
|
38
|
+
function channelPeer(channel) {
|
|
39
|
+
return {
|
|
40
|
+
onRequest: (method, handler) => channel.onRequest(method, async (params, ctx) => {
|
|
41
|
+
try { return await handler(params, ctx); } catch (e) {
|
|
42
|
+
if (e instanceof ObjectsError) throw new RpcError(e.code, e.message, e.data);
|
|
43
|
+
throw e;
|
|
44
|
+
}
|
|
45
|
+
}),
|
|
46
|
+
get maxMessageBytes() { return channel.maxMessageBytes; },
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The rpc handler for `wsh-objects`: `rpc: { 'wsh-objects': exposeObjects({ roots, mode: 'values', allow, authorize, limits }) }`.
|
|
52
|
+
*
|
|
53
|
+
* @param {object} options - as for `createObjectsServer`
|
|
54
|
+
* @param {Record<string, object>} options.roots - the named roots: all that is reachable
|
|
55
|
+
* @param {'values'} [options.mode='values'] - `'handles'` is refused: it is not built
|
|
56
|
+
* @param {{ get?: string[], call?: string[], set?: string[] }} [options.allow] - path patterns by operation, root-qualified (`'window.app.**'`); nothing allowed by default
|
|
57
|
+
* @param {(who: { username: string | null, fingerprint: string | null }, op: { kind: string, root: string, path: string[], text: string }) => boolean | Promise<boolean>} [options.authorize]
|
|
58
|
+
* @param {object} [options.limits] - `maxOps`, `maxArgs`, `maxDepth`, `maxValueBytes`, `maxKeys`, `maxRequestsPerSecond`, `callTimeoutMs`
|
|
59
|
+
*/
|
|
60
|
+
export function exposeObjects(options = {}) {
|
|
61
|
+
const server = createObjectsServer({ timers: defaultTimers, ...options });
|
|
62
|
+
const sessions = new Set();
|
|
63
|
+
const handler = (channel, ctx = {}) => {
|
|
64
|
+
const who = { username: ctx.user ?? null, fingerprint: ctx.fingerprint ?? null };
|
|
65
|
+
server.attach(channelPeer(channel), { who });
|
|
66
|
+
const session = { channel, who };
|
|
67
|
+
sessions.add(session);
|
|
68
|
+
const prior = channel.onClose;
|
|
69
|
+
channel.onClose = (reason) => { sessions.delete(session); try { prior?.(reason); } catch { /* ignore */ } };
|
|
70
|
+
};
|
|
71
|
+
/** Tell every session (or those of one key) why, then end it: used when the page goes away or the person presses Stop. */
|
|
72
|
+
handler.closeSessions = async (reason, fingerprint) => {
|
|
73
|
+
const targets = [...sessions].filter((s) => fingerprint === undefined || s.who.fingerprint === fingerprint);
|
|
74
|
+
await Promise.all(targets.map(async (s) => {
|
|
75
|
+
try { await s.channel.notify('closing', { reason }); } catch { /* going away */ }
|
|
76
|
+
await s.channel.close('objects-host-closing').catch(() => {});
|
|
77
|
+
}));
|
|
78
|
+
return targets.length;
|
|
79
|
+
};
|
|
80
|
+
handler.rootNames = server.rootNames;
|
|
81
|
+
handler.limits = server.limits;
|
|
82
|
+
return handler;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Open the `wsh-objects` channel of a connected client: the roots, as lazy references. */
|
|
86
|
+
export async function openObjects(client, options) {
|
|
87
|
+
if (typeof client?.openRpc !== 'function') throw new TypeError('openObjects: expected a connected WshClient');
|
|
88
|
+
return createObjectsClient(await client.openRpc(OBJECTS_PROTOCOL), options);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// `client.openObjects()`. Added here (and not in client.mjs) so that the objects code is in a page's bundle only when it imports this entry point.
|
|
92
|
+
if (typeof WshClient.prototype.openObjects !== 'function') {
|
|
93
|
+
Object.defineProperty(WshClient.prototype, 'openObjects', {
|
|
94
|
+
value: function openObjectsOfThisClient(options) { return openObjects(this, options); },
|
|
95
|
+
configurable: true, writable: true, enumerable: false,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import type { RpcChannel } from './index.js';
|
|
2
|
+
import type { WshRpcContext } from './server/index.js';
|
|
3
|
+
import type { WshOnRefused } from './host.js';
|
|
4
|
+
import type { ObjectsAllow, ObjectsWho, ObjectsOperation, ObjectsLimits } from './objects.js';
|
|
5
|
+
|
|
6
|
+
export { exposeObjects } from './objects.js';
|
|
7
|
+
|
|
8
|
+
/** The part of a `Window` (or `WorkerGlobalScope`, or a test double) this entry point reads. Everything is optional except what the call needs. */
|
|
9
|
+
export interface WshPageWindow {
|
|
10
|
+
document?: any;
|
|
11
|
+
navigator?: any;
|
|
12
|
+
location?: { origin?: string };
|
|
13
|
+
closed?: boolean;
|
|
14
|
+
WebSocket?: new (url: string) => any;
|
|
15
|
+
setTimeout?: (fn: () => void, ms?: number) => any;
|
|
16
|
+
clearTimeout?: (id: any) => void;
|
|
17
|
+
setInterval?: (fn: () => void, ms?: number) => any;
|
|
18
|
+
clearInterval?: (id: any) => void;
|
|
19
|
+
addEventListener?: (type: string, fn: (ev: any) => void) => void;
|
|
20
|
+
removeEventListener?: (type: string, fn: (ev: any) => void) => void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The timers of the realm that runs this code, when it is not the window's own (an opener serving a popup, a parent serving an iframe). */
|
|
24
|
+
export interface WshPageTimers {
|
|
25
|
+
setTimeout?: (fn: () => void, ms?: number) => any;
|
|
26
|
+
clearTimeout?: (id: any) => void;
|
|
27
|
+
setInterval?: (fn: () => void, ms?: number) => any;
|
|
28
|
+
clearInterval?: (id: any) => void;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A tool as the page passes it to `registerTool` (the WebMCP draft's `ModelContextTool`). */
|
|
32
|
+
export interface WebMcpToolDefinition {
|
|
33
|
+
/** 1-128 characters of letters, digits, `_`, `-` and `.`. */
|
|
34
|
+
name: string;
|
|
35
|
+
title?: string;
|
|
36
|
+
description: string;
|
|
37
|
+
inputSchema?: Record<string, unknown>;
|
|
38
|
+
outputSchema?: Record<string, unknown>;
|
|
39
|
+
annotations?: {
|
|
40
|
+
/** The tool only reads. A tool not marked read-only is consequential: it is asked about under `approve: 'consequential'`. */
|
|
41
|
+
readOnlyHint?: boolean;
|
|
42
|
+
untrustedContentHint?: boolean;
|
|
43
|
+
consequentialHint?: boolean;
|
|
44
|
+
debugging?: boolean;
|
|
45
|
+
};
|
|
46
|
+
execute(input: Record<string, any>, options: { signal: AbortSignal }): unknown | Promise<unknown>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** What `captureWebMcp(window)` recorded. */
|
|
50
|
+
export interface WebMcpCapture {
|
|
51
|
+
list(): WebMcpToolDefinition[];
|
|
52
|
+
get(name: string): WebMcpToolDefinition | undefined;
|
|
53
|
+
/** Told when the set of registered tools changes. Returns the function that stops listening. */
|
|
54
|
+
subscribe(fn: () => void): () => void;
|
|
55
|
+
/** Put every wrapped function back and remove what was provided. The recorded tools stay. */
|
|
56
|
+
restore(): void;
|
|
57
|
+
/** What was wrapped or provided: `document.modelContext`, `navigator.modelContext`, `... (provided)`. */
|
|
58
|
+
readonly installed: string[];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Record the tools the application registers on `window`. Call it BEFORE the application's code. Wraps `registerTool` on
|
|
63
|
+
* `window.document.modelContext` and `window.navigator.modelContext`, honours the registration's abort signal and `unregister()`, and provides
|
|
64
|
+
* a minimal `modelContext` where the browser has none. Calling it again for the same window returns the same capture.
|
|
65
|
+
*/
|
|
66
|
+
export function captureWebMcp(window: WshPageWindow): WebMcpCapture;
|
|
67
|
+
|
|
68
|
+
/** The bounds of the tool server; each is refused by name. */
|
|
69
|
+
export interface WebMcpLimits {
|
|
70
|
+
/** Default 64. Tools beyond it are not listed and cannot be called. */
|
|
71
|
+
maxTools: number;
|
|
72
|
+
/** Default 16384. Bytes of one tool's schemas as JSON; a tool over it is not listed and cannot be called. */
|
|
73
|
+
maxSchemaBytes: number;
|
|
74
|
+
/** Default 65536. Bytes of one call's arguments as JSON. */
|
|
75
|
+
maxInputBytes: number;
|
|
76
|
+
/** Default 262144. Bytes of one result as JSON. */
|
|
77
|
+
maxResultBytes: number;
|
|
78
|
+
/** Default 4. Calls running or waiting for the person's answer, per session. */
|
|
79
|
+
maxInflight: number;
|
|
80
|
+
/** Default 30. Calls started in any 60 seconds, per session (an unknown tool counts). */
|
|
81
|
+
maxCallsPerMinute: number;
|
|
82
|
+
/** Default 120000. A call still running then is aborted and fails. */
|
|
83
|
+
callTimeoutMs: number;
|
|
84
|
+
}
|
|
85
|
+
export const WEBMCP_DEFAULT_LIMITS: Readonly<WebMcpLimits>;
|
|
86
|
+
|
|
87
|
+
/** What the person at the page is asked about. */
|
|
88
|
+
export interface WebMcpCall {
|
|
89
|
+
name: string;
|
|
90
|
+
title: string | null;
|
|
91
|
+
description: string;
|
|
92
|
+
input: Record<string, unknown>;
|
|
93
|
+
consequential: boolean;
|
|
94
|
+
readOnly: boolean;
|
|
95
|
+
}
|
|
96
|
+
export interface WebMcpWho { username: string | null; fingerprint: string | null }
|
|
97
|
+
/** Answers `true` to allow the call; anything else denies. `signal` aborts when the call is cancelled or the session ends. */
|
|
98
|
+
export type WebMcpPrompt = (call: WebMcpCall, who: WebMcpWho, extra: { signal: AbortSignal }) => boolean | Promise<boolean>;
|
|
99
|
+
|
|
100
|
+
export interface WebMcpCallEvent {
|
|
101
|
+
outcome: 'ok' | 'error' | 'denied' | 'approved' | 'refused' | 'unknown' | 'unlisted';
|
|
102
|
+
name?: string;
|
|
103
|
+
who?: WebMcpWho;
|
|
104
|
+
/** For `refused` and `unlisted`: the bound, by name (`maxTools`, `maxSchemaBytes`, `maxInputBytes`, `maxResultBytes`, `maxInflight`, `maxCallsPerMinute`). */
|
|
105
|
+
limit?: string;
|
|
106
|
+
detail?: string;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export interface WebMcpToolsOptions {
|
|
110
|
+
/** The realm whose tools are served. Required. */
|
|
111
|
+
window: WshPageWindow;
|
|
112
|
+
/** Tool names that may be listed and called. Nothing is allowed by default. */
|
|
113
|
+
allow?: string[];
|
|
114
|
+
/** Ask the person at the page: never, for tools not marked read-only (default), or for every call. */
|
|
115
|
+
approve?: 'never' | 'consequential' | 'always';
|
|
116
|
+
/** Asks the person. Without one, a window with a document gets the default dialog; otherwise what needs approval is denied. */
|
|
117
|
+
prompt?: WebMcpPrompt;
|
|
118
|
+
/** The definitions the page passes to `registerTool` (source 1). */
|
|
119
|
+
tools?: WebMcpToolDefinition[];
|
|
120
|
+
/** A capture other than the one `captureWebMcp(window)` made. */
|
|
121
|
+
capture?: { list(): WebMcpToolDefinition[]; subscribe?(fn: () => void): () => void } | null;
|
|
122
|
+
limits?: Partial<WebMcpLimits>;
|
|
123
|
+
onCall?: (event: WebMcpCallEvent) => void;
|
|
124
|
+
/** Returns why the window is gone (every call is then refused), or null. */
|
|
125
|
+
guard?: () => string | null;
|
|
126
|
+
/** The `serverInfo` of `initialize`. */
|
|
127
|
+
server?: { name?: string; version?: string };
|
|
128
|
+
timers?: WshPageTimers;
|
|
129
|
+
now?: () => number;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The `mcp` rpc handler for `createMemoryHost({ rpc: { mcp } })`, `createReverseHost` and so on. It declares itself `capabilityScoped`. */
|
|
133
|
+
export interface WebMcpHandler {
|
|
134
|
+
/** It needs from the host's rpc context only who is calling and `permits` (a host that gives no `permits` serves every allowed tool). */
|
|
135
|
+
(channel: RpcChannel, ctx?: { user?: string | null; fingerprint?: string | null; permits?: (request: { kind: string; [field: string]: unknown }) => boolean }): void;
|
|
136
|
+
capabilityScoped: true;
|
|
137
|
+
/** Tell every session (or those of one key) why, then end it. Resolves with how many were ended. */
|
|
138
|
+
closeSessions(reason: string, fingerprint?: string): Promise<number>;
|
|
139
|
+
/** The tools (as `tools/list` states them) a key with no limits would see now. */
|
|
140
|
+
list(): Promise<object[]>;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The page's WebMCP tools as MCP, an rpc handler for the `mcp` protocol. */
|
|
144
|
+
export function webmcpTools(options: WebMcpToolsOptions): WebMcpHandler;
|
|
145
|
+
|
|
146
|
+
/** The default `prompt`: an accessible modal dialog in `window.document` (a key's fingerprint, the tool, the input as text; Deny has focus; Escape and a timeout deny). */
|
|
147
|
+
export function createDomPrompt(window: WshPageWindow, options?: { timeoutMs?: number; timers?: WshPageTimers }): WebMcpPrompt;
|
|
148
|
+
|
|
149
|
+
export interface WshPageIndicatorCallbacks {
|
|
150
|
+
connected(who: { username: string; fingerprint: string }, control: { stop(): Promise<boolean> }): void;
|
|
151
|
+
disconnected(who: { username: string; fingerprint: string }): void;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export interface WshPageHostOptions {
|
|
155
|
+
/** The realm to serve: required, and the only thing read. Passing it exposes nothing by itself. */
|
|
156
|
+
window: WshPageWindow;
|
|
157
|
+
/** A pipe relay (`@johnhenry/wsh/pipe-relay`): its `ws://` / `wss://` URL, or `{ url, id }` with a rendezvous id of your own. */
|
|
158
|
+
relay: string | { url: string; id?: string };
|
|
159
|
+
/** What this tab is called: shown in the indicator, the `serverInfo.name` of the MCP server. */
|
|
160
|
+
name: string;
|
|
161
|
+
/** Who may log in: `authorized_keys` lines (options such as `capabilities="mcp:search"` apply) or raw 32-byte keys. Required. */
|
|
162
|
+
authorizedKeys: string | Uint8Array | Array<string | Uint8Array>;
|
|
163
|
+
/** The page's WebMCP tools as MCP. At least one of `mcp` and `expose` is needed. */
|
|
164
|
+
mcp?: Omit<WebMcpToolsOptions, 'window' | 'guard' | 'timers'>;
|
|
165
|
+
/**
|
|
166
|
+
* Object access (`wsh-objects`, `values` mode), off unless written: named roots, each with its allow-lists by operation (paths RELATIVE to the root:
|
|
167
|
+
* `'document.title'`, `'app.**'`; nothing allowed by default). A root named `window` is the window that was passed; another name needs `object`.
|
|
168
|
+
* `mode: 'handles'` is refused: not built. See `@johnhenry/wsh/objects`.
|
|
169
|
+
*/
|
|
170
|
+
expose?: Record<string, { mode?: 'values'; allow?: ObjectsAllow; authorize?: (who: ObjectsWho, op: ObjectsOperation) => boolean | Promise<boolean>; limits?: Partial<ObjectsLimits>; object?: object }>;
|
|
171
|
+
/** `true` (default): the badge in `window.document`. Callbacks: for a context with no document, or your own UI. `false` needs `unattended: true`. */
|
|
172
|
+
indicator?: boolean | WshPageIndicatorCallbacks;
|
|
173
|
+
/** Nobody is in front of this window. Allows `indicator: false` and a window with no document; what needs approval is then denied unless `mcp.prompt` answers. */
|
|
174
|
+
unattended?: boolean;
|
|
175
|
+
/** This host's identity: a key pair or a signer. By default a fresh non-extractable key per page load. */
|
|
176
|
+
hostKey?: CryptoKeyPair | { publicKey: Uint8Array | CryptoKey; sign(data: Uint8Array): Promise<Uint8Array> | Uint8Array };
|
|
177
|
+
/** Persist the generated key through a store you inject (a non-extractable `CryptoKeyPair` can be kept in IndexedDB). */
|
|
178
|
+
hostKeyStore?: { load(): Promise<CryptoKeyPair | null | undefined> | CryptoKeyPair | null | undefined; save(pair: CryptoKeyPair): Promise<void> | void };
|
|
179
|
+
/** A key logged in. Return `false` to refuse it (ask the person first). */
|
|
180
|
+
onSession?: (who: { username: string; fingerprint: string }) => boolean | void | Promise<boolean | void>;
|
|
181
|
+
onSessionEnd?: (who: { username: string; fingerprint: string }) => void;
|
|
182
|
+
onRefused?: WshOnRefused;
|
|
183
|
+
/** The host closed itself (the window navigated to another origin, or closed) or was closed. */
|
|
184
|
+
onClose?: (closed: { reason: string }) => void;
|
|
185
|
+
timers?: WshPageTimers;
|
|
186
|
+
/** Dial the relay again after a session or a failed attempt (default true). */
|
|
187
|
+
reconnect?: boolean;
|
|
188
|
+
onLog?: (line: string) => void;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export interface WshPageHost {
|
|
192
|
+
/** The URL an operator dials. Its rendezvous id is the secret that pairs the operator with this page. */
|
|
193
|
+
readonly operatorUrl: string;
|
|
194
|
+
readonly rendezvousId: string;
|
|
195
|
+
readonly name: string;
|
|
196
|
+
/** The origin the host was started in; it closes if the window leaves it. */
|
|
197
|
+
readonly origin: string;
|
|
198
|
+
/** This host's key fingerprint, for the operator to pin (new on every page load unless a key or a `hostKeyStore` was given). */
|
|
199
|
+
readonly fingerprint: string;
|
|
200
|
+
/** Who is connected now. */
|
|
201
|
+
readonly sessions: Array<{ username: string; fingerprint: string; since: number }>;
|
|
202
|
+
readonly closed: boolean;
|
|
203
|
+
/** Why the host closed itself, or null. */
|
|
204
|
+
readonly closedReason: string | null;
|
|
205
|
+
/** End the session of a key, telling the operator why, and refuse that key until this host is closed. Resolves true if a session was ended. */
|
|
206
|
+
revoke(fingerprint: string): Promise<boolean>;
|
|
207
|
+
close(): Promise<void>;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** A page (or any window-shaped realm) as a host behind a pipe relay it chose: key login only, sealed sessions only, the window's WebMCP tools as MCP. */
|
|
211
|
+
export function createPageHost(options: WshPageHostOptions): Promise<WshPageHost>;
|
|
212
|
+
|
|
213
|
+
export type { RpcChannel, WshRpcContext };
|