@ractive-ch/tab-mcp-client 0.15.0 → 0.16.1

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 (59) hide show
  1. package/README.md +481 -148
  2. package/always-allowed.d.ts +25 -6
  3. package/cdn/confirm-y30cx7e1.min.js +4 -0
  4. package/cdn/confirm-y30cx7e1.min.js.map +10 -0
  5. package/cdn/connect-bbhj2y7w.min.js +6 -0
  6. package/cdn/connect-bbhj2y7w.min.js.map +12 -0
  7. package/cdn/connection-w97tf22a.min.js +17 -0
  8. package/cdn/connection-w97tf22a.min.js.map +22 -0
  9. package/cdn/index-vt5zk9me.min.js +91 -0
  10. package/cdn/index-vt5zk9me.min.js.map +13 -0
  11. package/cdn/tab-mcp-client.min.js +3 -3
  12. package/cdn/tab-mcp-client.min.js.map +6 -7
  13. package/cdn/webmcp-khy4f5rj.min.js +4 -0
  14. package/cdn/webmcp-khy4f5rj.min.js.map +10 -0
  15. package/confirm-fgnjgd08.js +263 -0
  16. package/confirm-fgnjgd08.js.map +10 -0
  17. package/confirm.d.ts +54 -0
  18. package/connect-8jpb0k29.js +484 -0
  19. package/connect-8jpb0k29.js.map +10 -0
  20. package/connect.d.ts +40 -0
  21. package/{connection-g6wk37yd.js → connection-g91xjjgm.js} +252 -126
  22. package/connection-g91xjjgm.js.map +16 -0
  23. package/connection.d.ts +7 -4
  24. package/dialog.d.ts +83 -0
  25. package/{index-nmn1j689.js → index-5jyqehpk.js} +14 -10
  26. package/index-5jyqehpk.js.map +11 -0
  27. package/index-jnz7w9xa.js +392 -0
  28. package/index-jnz7w9xa.js.map +12 -0
  29. package/index.d.ts +1 -1
  30. package/index.js +234 -263
  31. package/index.js.map +6 -7
  32. package/internal.d.ts +2 -0
  33. package/mapping.d.ts +37 -4
  34. package/mcp.d.ts +28 -8
  35. package/package.json +1 -1
  36. package/protocol.d.ts +8 -0
  37. package/react.d.ts +8 -10
  38. package/react.js +18 -14
  39. package/react.js.map +3 -3
  40. package/registry.d.ts +12 -5
  41. package/secret.d.ts +5 -2
  42. package/serve.d.ts +26 -4
  43. package/setup.d.ts +15 -25
  44. package/setup.js +1 -1
  45. package/strings.d.ts +107 -0
  46. package/tab-mcp.d.ts +63 -35
  47. package/types.d.ts +146 -68
  48. package/webmcp-zq1enyz0.js +57 -0
  49. package/webmcp-zq1enyz0.js.map +10 -0
  50. package/webmcp.d.ts +13 -24
  51. package/cdn/connection-hgt931xk.min.js +0 -12
  52. package/cdn/connection-hgt931xk.min.js.map +0 -22
  53. package/cdn/ui-2nv84ry7.min.js +0 -86
  54. package/cdn/ui-2nv84ry7.min.js.map +0 -14
  55. package/connection-g6wk37yd.js.map +0 -16
  56. package/index-nmn1j689.js.map +0 -11
  57. package/ui-04mwfxm9.js +0 -783
  58. package/ui-04mwfxm9.js.map +0 -11
  59. package/ui.d.ts +0 -83
package/tab-mcp.d.ts CHANGED
@@ -4,6 +4,17 @@
4
4
  * connection and the MCP handler with a dynamic `import()`.
5
5
  */
6
6
  import type { ConfirmRequest, ConnectionState, ConnectOptions, Grant, IdentityState, PairingCode, ReconnectingInfo, RegisterToolOptions, ServeHandle, ServeOptions, SessionInfo, TabMcpEventMap, TabMcpOptions, Tool, TunnelPort } from "./types.js";
7
+ /**
8
+ * The library's waits, in milliseconds: constants for pages (CU 17), which
9
+ * only tests change. `reconnectDelaysMs`: before each reconnect attempt,
10
+ * the last one repeating. `answerTimeoutMs`: for an identity assertion and
11
+ * the relay's answer to it, and for the relay's answer to `revoke()` and
12
+ * `signOut()`.
13
+ */
14
+ export declare const timing: {
15
+ reconnectDelaysMs: number[];
16
+ answerTimeoutMs: number;
17
+ };
7
18
  /** `wss://host/tab` for a relay given as `https://host`, `wss://host` or with `/tab`. */
8
19
  export declare function tabUrl(relay: string): {
9
20
  url: string;
@@ -16,7 +27,7 @@ type Listener<K extends keyof TabMcpEventMap> = (event: TabMcpEventMap[K]) => vo
16
27
  *
17
28
  * ```ts
18
29
  * const mcp = new TabMcp({ relay: "https://relay.example", server: { name: "Calculator", version: "1.0.0" } });
19
- * mcp.registerTool({ name: "add", description: "Add two numbers", execute: ({ a, b }) => Number(a) + Number(b) });
30
+ * await mcp.registerTool({ name: "add", description: "Add two numbers", execute: ({ a, b }) => Number(a) + Number(b) });
20
31
  * button.onclick = () => mcp.showConnectDialog();
21
32
  * ```
22
33
  */
@@ -26,23 +37,21 @@ export declare class TabMcp extends EventTarget {
26
37
  /**
27
38
  * Register a tool (WebMCP shape). Allowed before and after `connect()`;
28
39
  * aborting `options.signal` unregisters it. Rejects with a `TypeError` for
29
- * an invalid tool and an `InvalidStateError` for a duplicate name.
40
+ * an invalid tool and an `InvalidStateError` for a duplicate name (the
41
+ * tool is registered, or refused, before it returns); await it or catch
42
+ * the rejection (DEC-010).
30
43
  */
31
44
  registerTool<Input extends object = Record<string, unknown>>(tool: Tool<Input>, options?: RegisterToolOptions): Promise<void>;
32
45
  /** Names of the registered tools. */
33
46
  get tools(): readonly string[];
34
47
  get state(): ConnectionState;
35
- /** The current session, while connected. */
48
+ /** The current session, while connected: its `address` is the one to give to AI apps. */
36
49
  get session(): SessionInfo | undefined;
37
- /** The MCP address to give to AI apps, while connected. */
38
- get address(): string | undefined;
39
- /** The app name AI apps see when pairing: the relay's (`session.appName`), else the page's own. */
40
- get appName(): string | undefined;
41
50
  /** The AI apps connected to this address (frozen; a new array when they change). */
42
51
  get grants(): readonly Grant[];
43
52
  /**
44
- * While the library connects again by itself after the connection broke:
45
- * the next attempt and when it starts. `undefined` otherwise.
53
+ * While `state` is `reconnecting`: the next (or running) attempt and when
54
+ * it starts. `undefined` otherwise.
46
55
  */
47
56
  get reconnecting(): ReconnectingInfo | undefined;
48
57
  /** Who the relay knows as the page's user (identity binding). */
@@ -51,21 +60,23 @@ export declare class TabMcp extends EventTarget {
51
60
  get identityMessage(): string | undefined;
52
61
  /**
53
62
  * Ask the `identityAssertion` hook again and send the result, e.g. after
54
- * the user signed in without a page load. Resolves `true` once the relay
55
- * accepted it; `false` when nobody is signed in, it was refused, or the
56
- * page is not connected.
63
+ * the user signed in without a page load. Resolves with the outcome, the
64
+ * new `identity`: `bound` once the relay accepted it, `refused`, or `none`
65
+ * when nobody is signed in or no answer came in time. Rejects with an
66
+ * `InvalidStateError` while not connected, and with a `TypeError` without
67
+ * the hook.
57
68
  */
58
- refreshIdentity(): Promise<boolean>;
69
+ refreshIdentity(): Promise<IdentityState>;
59
70
  /**
60
71
  * The page's user signed out: the relay ends every AI connection of this
61
72
  * address at once (identity binding). Call it from the web app's logout.
62
- * Returns `false` when it could not be sent (not connected); the grants
63
- * then stay, but work only while a page signed in as the same person is
64
- * open.
73
+ * `identity` goes to `none` at once. Resolves once the relay removed the
74
+ * grants; rejects with an `InvalidStateError` while not connected to a
75
+ * relay that pairs by sign-in (`session.pairing` is `oidc`), and with a
76
+ * `NetworkError` when the session ends first. Grants that stay work only while a page signed in
77
+ * as the same person is open.
65
78
  */
66
- signOut(): boolean;
67
- /** Whether pairing is on (`startPairing()`). */
68
- get pairing(): boolean;
79
+ signOut(): Promise<void>;
69
80
  /** The pairing code to show, if the relay sent one. */
70
81
  get pairingCode(): PairingCode | undefined;
71
82
  /**
@@ -73,7 +84,7 @@ export declare class TabMcp extends EventTarget {
73
84
  * WebSocket, resolves with the session. Call it from a user action (a
74
85
  * click): where browsers track user activation it is refused otherwise,
75
86
  * unless `options.resume` says the user already chose to keep AI access on.
76
- * While reconnecting (`reconnecting`), it makes the next attempt at once.
87
+ * While `reconnecting`, it makes the next attempt at once.
77
88
  */
78
89
  connect(options?: ConnectOptions): Promise<SessionInfo>;
79
90
  /** Whether this `TabMcp` has a relay; without one, `connect()` rejects. */
@@ -85,7 +96,11 @@ export declare class TabMcp extends EventTarget {
85
96
  * carries the relay's `http.*` messages as plain objects; a `MessagePort`
86
97
  * fits. Whoever holds the other end calls the tools without pairing, as
87
98
  * `options.client` (`kind: "local"`): hand it out only to a frame whose
88
- * origin you checked. Consequential tools still ask. Resolves once the port
99
+ * origin you checked. Consequential tools still ask: `options.onConfirm`
100
+ * for this port's calls (in the site's chat, say), else the page's
101
+ * `onConfirm` or dialog. Each request may take `options.requestTimeoutMs`
102
+ * (300 s). Only tools whose `callers` include `"local"` (by default all)
103
+ * are listed and callable. Resolves once the port
89
104
  * is served; may be called for several ports. Rejects with a `TypeError`
90
105
  * for options it cannot use.
91
106
  */
@@ -93,23 +108,33 @@ export declare class TabMcp extends EventTarget {
93
108
  /** End the session (`bye`). Grants stay: AI apps work again after the next `connect()`. */
94
109
  disconnect(): void;
95
110
  /**
96
- * A new address: revokes every connected app of the old one (while
97
- * connected), makes a new secret, and connects again if it was connected or
98
- * connecting. After `replaced`, it first connects with the old address
99
- * again, so that the relay disconnects the apps that now talk to whoever
100
- * took it over (DEC-095), then connects with the new one. Call it from a
101
- * user action.
111
+ * A new address. If the page has one already, it first takes it back: it
112
+ * connects with the old secret and the relay revokes every grant of it in
113
+ * the same step (`hello.revokeAll`, DEC-095, DEC-136), connected or not,
114
+ * taken over or not. Then it makes a new secret and connects with it if
115
+ * the page was connected, connecting or reconnecting, and resolves once
116
+ * that is done (the new session is `session`). Rejects, and keeps the old
117
+ * secret so that a retry takes it back again, when the old address could
118
+ * not be taken back (relay unreachable, taken over again first). With a
119
+ * relay, every rejection has `addressChanged`: `false` then, `true` when
120
+ * only connecting with the new address failed (without one: a
121
+ * `TypeError`). Call it from a user action.
102
122
  */
103
- newAddress(): Promise<SessionInfo | undefined>;
123
+ newAddress(): Promise<void>;
104
124
  /** The pairing dialog opened: ask the relay for codes (DEC-028). */
105
125
  startPairing(): void;
106
126
  /** The pairing dialog closed: the code becomes invalid. */
107
127
  stopPairing(): void;
108
128
  /**
109
- * Disconnect one AI app: its tokens stop working at once. Works only while
110
- * connected (the relay does it); returns `false` when it could not be sent.
129
+ * Disconnect one AI app: its tokens stop working at once. Resolves once
130
+ * the relay removed the grant (at once for one that is not in `grants`,
131
+ * and when the relay no longer knows it: it leaves `grants` then).
132
+ * Rejects with an `InvalidStateError` while not connected (only the relay
133
+ * can do it), a `NetworkError` when the session ends before the answer,
134
+ * and with the relay's error when it refuses (its `code` is
135
+ * `store_unavailable` when it could not save the change: try again).
111
136
  */
112
- revoke(grantId: string): boolean;
137
+ revoke(grantId: string): Promise<void>;
113
138
  /**
114
139
  * Open the default "Connect your AI app" dialog; connects first if needed
115
140
  * (call it from a click). Resolves when the dialog closes. One dialog at
@@ -127,10 +152,13 @@ export declare class TabMcp extends EventTarget {
127
152
  removeEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions): void;
128
153
  /**
129
154
  * The library's own confirmation: the dialog in the page with Don't allow
130
- * and Allow, and Always allow with `alwaysAllow: true` (what runs without
131
- * `onConfirm`). An `onConfirm`
132
- * may hand some calls to it. Resolves `false` where there is no document.
155
+ * and Allow, and Allow until reload with `alwaysAllow: true` (what runs
156
+ * without `onConfirm`), in `options.document` (default: the global one).
157
+ * An `onConfirm` may hand some calls to it. Resolves `false` where there
158
+ * is no document.
133
159
  */
134
- confirmInPage(request: ConfirmRequest): Promise<boolean>;
160
+ confirmInPage(request: ConfirmRequest, options?: {
161
+ document?: Document;
162
+ }): Promise<boolean>;
135
163
  }
136
164
  export {};
package/types.d.ts CHANGED
@@ -2,6 +2,8 @@
2
2
  * Public types of `@ractive-ch/tab-mcp-client`. Self-contained on purpose: the
3
3
  * published declarations must not import from other workspace packages.
4
4
  */
5
+ import type { DialogStrings } from "./strings.js";
6
+ export type { DialogStrings };
5
7
  /** A JSON Schema document (draft 2020-12) describing a tool's input object. */
6
8
  export type JsonSchema = {
7
9
  [key: string]: unknown;
@@ -84,6 +86,25 @@ export interface ServeOptions {
84
86
  id: string;
85
87
  name?: string;
86
88
  };
89
+ /**
90
+ * Approves the consequential tool calls that come through this port, in
91
+ * place of `TabMcpOptions.onConfirm` and the library's dialog, for
92
+ * example as a question in the site's own chat. Same answers as
93
+ * `onConfirm`; a throw is a refusal. `request.signal` aborts when the call
94
+ * is cancelled, times out or the serve closes. The answer must come from
95
+ * the user: never let the other end of the port answer it, since that is
96
+ * the caller that wants the tool to run. Calls through the relay and
97
+ * WebMCP keep the page's `onConfirm` or dialog.
98
+ */
99
+ onConfirm?: ConfirmHandler;
100
+ /**
101
+ * How long one request may take until its answer has ended, in
102
+ * milliseconds; 300000 by default, as `createTunnelFetch`, below 2^31. On
103
+ * expiry the call is aborted (`execute`'s signal), `toolcallend` says
104
+ * `cancelled`, a late answer is dropped, and the other end gets the
105
+ * JSON-RPC error `-31002`. A `subscriptions/listen` stream is not limited.
106
+ */
107
+ requestTimeoutMs?: number;
87
108
  /** Aborting it stops serving: calls in flight are aborted, the port is let go. */
88
109
  signal?: AbortSignal;
89
110
  /**
@@ -120,22 +141,41 @@ export interface Tool<Input extends object = Record<string, unknown>> {
120
141
  description: string;
121
142
  /** JSON Schema of the input object; defaults to `{ "type": "object" }`. */
122
143
  inputSchema?: JsonSchema;
144
+ /**
145
+ * JSON Schema of the result object (`"type": "object"`), listed to AI apps
146
+ * and passed on to WebMCP. Not checked by the library. MCP wants every
147
+ * result of such a tool to have `structuredContent` that matches it, so
148
+ * `execute` should return a plain object (DEC-023), not a string.
149
+ */
150
+ outputSchema?: JsonSchema;
123
151
  /** Runs the tool. Its return value becomes the result (DEC-023). */
124
152
  execute: (input: Input, options: ToolExecuteOptions) => unknown;
125
153
  annotations?: ToolAnnotations;
126
154
  }
155
+ /** A kind of caller (`ToolCallClient.kind`), for `RegisterToolOptions.callers`. */
156
+ export type ToolCaller = ToolCallClient["kind"];
127
157
  /** Options of `registerTool`. */
128
158
  export interface RegisterToolOptions {
129
- /** Aborting it unregisters the tool. */
159
+ /**
160
+ * Aborting it unregisters the tool. Already aborted: `registerTool`
161
+ * rejects with its reason and registers nothing (as WebMCP).
162
+ */
130
163
  signal?: AbortSignal;
131
164
  /**
132
- * With `TabMcpOptions.webmcp` on: `true` also offers this tool through
133
- * WebMCP when it is consequential, `false` never does. By default only
134
- * tools that are not consequential are offered there. Ignored while
135
- * `webmcp` is off.
165
+ * Which callers see the tool: `"relay"` (AI apps through the relay),
166
+ * `"local"` (this site's own assistant over `serve`), `"webmcp"` (agents
167
+ * in the browser, with `TabMcpOptions.webmcp` on). Others neither list nor
168
+ * call it: for them it does not exist. By default all of them, except
169
+ * that a consequential tool (`consequentialHint` or `destructiveHint`)
170
+ * goes to WebMCP only when `"webmcp"` is listed: an agent that drives
171
+ * this tab can click Allow in the page's confirmation itself.
172
+ */
173
+ callers?: readonly ToolCaller[];
174
+ /**
175
+ * WebMCP's origins of other documents in this tab that may see the tool:
176
+ * passed on to the native `registerTool` of a mirrored tool, which checks
177
+ * it (an invalid list only warns). No effect on AI apps.
136
178
  */
137
- webmcp?: boolean;
138
- /** WebMCP's cross-document exposure; ignored by tab-mcp. */
139
179
  exposedTo?: string[];
140
180
  }
141
181
  /** An icon the AI app may show for the page (MCP `Icon`). */
@@ -164,6 +204,48 @@ export interface ServerInfo {
164
204
  /** Instructions for the model, e.g. how the tools fit together. */
165
205
  instructions?: string;
166
206
  }
207
+ /** A part of a {@link SetupStep}'s note: plain text, or code to show as code. */
208
+ export type SetupNotePart = {
209
+ text: string;
210
+ } | {
211
+ code: string;
212
+ };
213
+ /**
214
+ * How to add the page's address to one AI app, as the connect dialog shows it
215
+ * under "How do I add it?". All strings are plain text.
216
+ */
217
+ export interface SetupStep {
218
+ /** The app's name as shown, such as "Claude Code". */
219
+ app: string;
220
+ /** What to do, a sentence or two. "Run:" when `command` follows. */
221
+ text: string;
222
+ /** Commands to run in a terminal, one per line, shown with a Copy button. */
223
+ command?: string;
224
+ /** Shown after the command (or the text): text and code, in order. */
225
+ note?: SetupNotePart[];
226
+ }
227
+ /** Options of the library's dialogs (`TabMcpOptions.ui`). */
228
+ export interface DialogOptions {
229
+ /**
230
+ * Texts of the dialogs, key by key; the rest stay English. The keys and
231
+ * the English texts are in `src/strings.ts`; `{name}` placeholders are
232
+ * filled in. Set `lang` and `dir` with the texts' language.
233
+ */
234
+ strings?: Partial<DialogStrings>;
235
+ /** The help in the connect dialog ("How do I add it?"). */
236
+ setup?: {
237
+ /**
238
+ * The link at its end; default the guide on ractive.ch, `null` for none
239
+ * (then pass `instructions` too: the default steps refer to the guide).
240
+ */
241
+ guide?: string | null;
242
+ /**
243
+ * The steps per AI app for the page's `server.name` and address;
244
+ * default `setupInstructions` of `@ractive-ch/tab-mcp-client/setup`.
245
+ */
246
+ instructions?: (serverName: string, address: string) => SetupStep[];
247
+ };
248
+ }
167
249
  /** A consequential tool call waiting for the user's approval. */
168
250
  export interface ConfirmRequest {
169
251
  tool: {
@@ -204,20 +286,16 @@ export interface TabMcpOptions {
204
286
  /** Approves consequential tool calls; default: a dialog in the page. */
205
287
  onConfirm?: ConfirmHandler;
206
288
  /**
207
- * How long the page must be visible and focused, with the default
208
- * confirmation open, before "Allow" can be clicked, in milliseconds: 750
209
- * by default, never less than 500. Leaving the page starts it again. The
210
- * constructor throws a `TypeError` for anything but a number of ms.
211
- */
212
- confirmDelayMs?: number;
213
- /**
214
- * Offer "Always allow" in the default confirmation: it lets a tool run
215
- * without asking for one AI app until the page is reloaded or the app is
216
- * disconnected. Off by default (DEC-096): the confirmation then shows only
217
- * "Don't allow" and "Allow", and every call asks. Turn it on only for
218
- * tools whose calls the user does not need to check one by one.
289
+ * Offer "Allow until reload" in the default confirmation: it lets a tool
290
+ * run without asking for one AI app, with any arguments, until the page
291
+ * is reloaded or the app is disconnected; the connect dialog lists it
292
+ * with a reset. Off by default (DEC-096): the confirmation then shows
293
+ * only "Don't allow" and "Allow", and every call asks. Turn it on only
294
+ * for tools whose calls the user does not need to check one by one.
219
295
  */
220
296
  alwaysAllow?: boolean;
297
+ /** Texts and help of the library's dialogs. */
298
+ ui?: DialogOptions;
221
299
  /**
222
300
  * Where the address secret lives; default `localStorage`. `null` keeps it
223
301
  * only for the page's lifetime (a new address on every visit).
@@ -239,39 +317,26 @@ export interface TabMcpOptions {
239
317
  * and by `refreshIdentity()`; only for relays whose site pairs by `oidc`.
240
318
  */
241
319
  identityAssertion?: IdentityAssertionHandler;
242
- /**
243
- * How long to wait for an assertion and the relay's answer to it, from
244
- * when `identityAssertion` is asked, before `identity` goes back to
245
- * `none`, in milliseconds; default 15000.
246
- */
247
- identityTimeoutMs?: number;
248
320
  /**
249
321
  * Connect again by itself after the connection broke (reason `network`,
250
- * `heartbeat` or `shutdown`): after 5, 10, 20 and 40 seconds, then every
251
- * 60 seconds, and at once when the tab comes back to the front or the
252
- * network returns. On by default; `false` leaves it to the page.
322
+ * `heartbeat` or `shutdown`; `state` is `reconnecting` meanwhile): after
323
+ * about 5, 10, 20 and 40 seconds, then every 60 seconds, and at once when
324
+ * the tab comes back to the front or the network returns. On by default;
325
+ * `false` leaves it to the page.
253
326
  */
254
- reconnect?: boolean | ReconnectOptions;
327
+ reconnect?: boolean;
255
328
  /**
256
329
  * Also register the tools with the browser's own WebMCP
257
330
  * (`document.modelContext.registerTool()`), where it has it, so that agents
258
331
  * in the browser can call them, without pairing. Off by default. Tools
259
- * marked `consequentialHint` are left out unless registered with
260
- * `{ webmcp: true }`: an agent that drives this tab can click Allow in the
261
- * page's confirmation itself. A failed native registration only warns in
262
- * the console.
332
+ * marked `consequentialHint` or `destructiveHint` are left out unless
333
+ * their `callers` list `"webmcp"`: an agent that drives this tab can
334
+ * click Allow in the page's confirmation itself. A failed native
335
+ * registration only warns in the console.
263
336
  */
264
337
  webmcp?: boolean;
265
338
  }
266
- /** Options of reconnecting (`TabMcpOptions.reconnect`). */
267
- export interface ReconnectOptions {
268
- /**
269
- * The waits before each attempt in milliseconds; the last one repeats.
270
- * Default `[5000, 10000, 20000, 40000, 60000]`.
271
- */
272
- delaysMs?: readonly number[];
273
- }
274
- /** The library is reconnecting by itself (`reconnecting`). */
339
+ /** The library is reconnecting by itself (`state` is `reconnecting`). */
275
340
  export interface ReconnectingInfo {
276
341
  /** Why the connection ended. */
277
342
  reason: DisconnectReason;
@@ -354,7 +419,12 @@ export interface ConnectOptions {
354
419
  */
355
420
  resume?: boolean;
356
421
  }
357
- export type ConnectionState = "disconnected" | "connecting" | "connected";
422
+ /**
423
+ * The connection to the relay. `reconnecting`: it broke, and the library
424
+ * connects again by itself (waiting for the next attempt or making it;
425
+ * `TabMcp.reconnecting` says which attempt and when).
426
+ */
427
+ export type ConnectionState = "disconnected" | "connecting" | "connected" | "reconnecting";
358
428
  /** Why a session ended. */
359
429
  export type DisconnectReason =
360
430
  /** `disconnect()` was called. */
@@ -367,7 +437,10 @@ export type DisconnectReason =
367
437
  | "expired"
368
438
  /** No AI app used the tools for a long time. */
369
439
  | "idle"
370
- /** The relay is shutting down. */
440
+ /**
441
+ * The relay is shutting down or restarting (also close codes 1001, 1011,
442
+ * 1012 and 1013, which a proxy in front of it sends).
443
+ */
371
444
  | "shutdown"
372
445
  /** The connection stopped answering. */
373
446
  | "heartbeat"
@@ -377,10 +450,15 @@ export type DisconnectReason =
377
450
  | "closed"
378
451
  /** The network connection broke. */
379
452
  | "network";
380
- export interface DisconnectDetail {
381
- reason: DisconnectReason;
382
- /** The WebSocket close code. */
383
- code: number;
453
+ /** The `statechange` event. */
454
+ export interface StateChangeDetail {
455
+ state: ConnectionState;
456
+ /**
457
+ * Why it ended: on the change from `connected` (to `disconnected`, or to
458
+ * `reconnecting` when the connection broke), and when `disconnect()` or
459
+ * `newAddress()` ends connecting or reconnecting (`user`, `new_address`).
460
+ */
461
+ reason?: DisconnectReason;
384
462
  }
385
463
  /** The `replaced` event: who took over the page's address. */
386
464
  export interface ReplacedDetail {
@@ -426,44 +504,44 @@ export interface ToolCallEnd {
426
504
  result: ToolCallResult;
427
505
  durationMs: number;
428
506
  }
429
- /** Events of `TabMcp`. */
507
+ /**
508
+ * Events of `TabMcp`. Every detail is an object; a change event names the
509
+ * new values like the properties they change (`grantschange` has `grants`,
510
+ * the value of `mcp.grants`), and a value that is gone is `undefined`.
511
+ */
430
512
  export interface TabMcpEventMap {
431
- statechange: CustomEvent<{
432
- state: ConnectionState;
433
- }>;
434
- connected: CustomEvent<SessionInfo>;
435
- disconnected: CustomEvent<DisconnectDetail>;
513
+ /**
514
+ * `state` changed (`session` with it), or, while `reconnecting`, the next
515
+ * attempt was scheduled (`mcp.reconnecting`). A refusal that stops
516
+ * reconnecting comes as `error` just before the change to `disconnected`.
517
+ */
518
+ statechange: CustomEvent<StateChangeDetail>;
436
519
  /**
437
520
  * Another tab, or a program with this page's address secret, took over
438
- * the address. It follows `disconnected` (reason `replaced`), up to a second
439
- * later while the library listens for a sibling tab. `sibling` says which it
440
- * probably was.
521
+ * the address. It follows the `statechange` with reason `replaced`, up to
522
+ * a second later while the library listens for a sibling tab. `sibling`
523
+ * says which it probably was.
441
524
  */
442
525
  replaced: CustomEvent<ReplacedDetail>;
443
526
  /** Something went wrong outside a pending promise (e.g. a relay error message). */
444
527
  error: CustomEvent<{
445
528
  error: Error;
446
529
  }>;
447
- /** A new pairing code, or `null` when there is none (any more). */
448
- pairingcode: CustomEvent<PairingCode | null>;
530
+ /** A new pairing code, or `undefined` when there is none (any more). */
531
+ pairingcode: CustomEvent<{
532
+ pairingCode: PairingCode | undefined;
533
+ }>;
449
534
  grantschange: CustomEvent<{
450
535
  grants: readonly Grant[];
451
536
  }>;
452
537
  /** The relay accepted or refused the page's identity, or it was cleared. */
453
538
  identitychange: CustomEvent<{
454
- state: IdentityState;
455
- message?: string;
539
+ identity: IdentityState;
540
+ identityMessage: string | undefined;
456
541
  }>;
457
542
  toolschange: CustomEvent<{
458
543
  tools: readonly string[];
459
544
  }>;
460
- /**
461
- * Reconnecting by itself: the next attempt and when it starts, or `null`
462
- * when it stopped (connected again, `disconnect()`, or the relay refused
463
- * an attempt: then `error` says why just before, unless the attempt was
464
- * the page's own `connect()`, whose promise rejects).
465
- */
466
- reconnecting: CustomEvent<ReconnectingInfo | null>;
467
545
  /** An AI app called a tool (before any confirmation). */
468
546
  toolcall: CustomEvent<ToolCallStart>;
469
547
  /** That call ended; also when the user declined it, did not answer, or the AI app cancelled it. */
@@ -0,0 +1,57 @@
1
+ // src/webmcp.ts
2
+ var HINTS = [
3
+ "readOnlyHint",
4
+ "untrustedContentHint",
5
+ "consequentialHint",
6
+ "debugging"
7
+ ];
8
+ function mirror(registry, context, call) {
9
+ const mirrors = new Map;
10
+ const warned = new Set;
11
+ const sync = () => {
12
+ for (const [tool, controller] of mirrors) {
13
+ if (registry.get(tool.name) === tool)
14
+ continue;
15
+ controller.abort();
16
+ mirrors.delete(tool);
17
+ }
18
+ for (const tool of registry.list()) {
19
+ const { annotations, callers } = tool;
20
+ const consequential = annotations.consequentialHint ?? annotations.destructiveHint;
21
+ if (mirrors.has(tool) || !(callers?.includes("webmcp") ?? !consequential))
22
+ continue;
23
+ const controller = new AbortController;
24
+ mirrors.set(tool, controller);
25
+ const hints = {
26
+ consequentialHint: consequential
27
+ };
28
+ for (const key of HINTS)
29
+ hints[key] ??= annotations[key];
30
+ const { signal } = controller;
31
+ Promise.resolve().then(() => signal.aborted || context.registerTool({
32
+ name: tool.name,
33
+ title: tool.title,
34
+ description: tool.description,
35
+ inputSchema: tool.inputSchema,
36
+ outputSchema: tool.outputSchema,
37
+ annotations: hints,
38
+ execute: (input, options) => call(tool, input, options?.signal)
39
+ }, { signal, exposedTo: tool.exposedTo })).catch((error) => {
40
+ if (signal.aborted)
41
+ return;
42
+ if (warned.has(tool.name))
43
+ return;
44
+ warned.add(tool.name);
45
+ console.warn(`tab-mcp: ${tool.name} is not offered through WebMCP:`, error);
46
+ });
47
+ }
48
+ };
49
+ registry.onChange(sync);
50
+ sync();
51
+ }
52
+ export {
53
+ mirror
54
+ };
55
+
56
+ //# debugId=68007C67B049549964756E2164756E21
57
+ //# sourceMappingURL=webmcp-zq1enyz0.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/webmcp.ts"],
4
+ "sourcesContent": [
5
+ "/**\n * Mirroring the tools into the browser's own WebMCP (iteration 25, DEC-115,\n * DEC-119, DEC-143): with `webmcp: true`, each tool that is offered there is\n * also registered with `document.modelContext.registerTool()`, under its own\n * `AbortController`, aborted when the tool leaves the registry. A chunk of\n * its own (DEC-171), loaded by a `TabMcp` whose constructor found native\n * WebMCP (`nativeContext` in the core); a call loads the connection chunk,\n * which checks, confirms and runs it.\n */\n\nimport type { RegisteredTool, ToolRegistry } from \"./registry.ts\";\n\n/** What the library uses of the browser's `ModelContext`. */\nexport interface ModelContext {\n\tregisterTool(\n\t\ttool: object,\n\t\toptions: { signal: AbortSignal; exposedTo: string[] | undefined },\n\t): unknown;\n}\n\n/** Runs a call of a mirrored tool; `signal` is the browser's, if it gives one. */\nexport type WebMcpCall = (\n\ttool: RegisteredTool,\n\tinput: unknown,\n\tsignal: unknown,\n) => Promise<unknown>;\n\n/** The WebMCP hints; the MCP-only ones are left out. */\nconst HINTS = [\n\t\"readOnlyHint\",\n\t\"untrustedContentHint\",\n\t\"consequentialHint\",\n\t\"debugging\",\n] as const;\n\n/**\n * Mirror `registry`'s tools into `context`, now and whenever the registry\n * changes: those whose `callers` list `\"webmcp\"`, and without `callers` those\n * not marked consequential, where MCP's `destructiveHint` counts as\n * `consequentialHint` (DEC-143, DEC-165). Every failure of the native `registerTool()`\n * stays here: warned once per name, the tool still offered through the relay.\n */\nexport function mirror(\n\tregistry: ToolRegistry,\n\tcontext: ModelContext,\n\tcall: WebMcpCall,\n): void {\n\tconst mirrors = new Map<RegisteredTool, AbortController>();\n\tconst warned = new Set<string>();\n\tconst sync = (): void => {\n\t\tfor (const [tool, controller] of mirrors) {\n\t\t\tif (registry.get(tool.name) === tool) continue;\n\t\t\tcontroller.abort();\n\t\t\tmirrors.delete(tool);\n\t\t}\n\t\tfor (const tool of registry.list()) {\n\t\t\tconst { annotations, callers } = tool;\n\t\t\tconst consequential =\n\t\t\t\tannotations.consequentialHint ?? annotations.destructiveHint;\n\t\t\t// The one place of the rule for WebMCP (the relay and a port: `toolsFor`).\n\t\t\tif (mirrors.has(tool) || !(callers?.includes(\"webmcp\") ?? !consequential))\n\t\t\t\tcontinue;\n\t\t\tconst controller = new AbortController();\n\t\t\tmirrors.set(tool, controller);\n\t\t\tconst hints: Record<string, boolean | undefined> = {\n\t\t\t\tconsequentialHint: consequential,\n\t\t\t};\n\t\t\tfor (const key of HINTS) hints[key] ??= annotations[key];\n\t\t\tconst { signal } = controller;\n\t\t\tPromise.resolve()\n\t\t\t\t// Not once unmirrored: whatever the browser does with an aborted\n\t\t\t\t// signal.\n\t\t\t\t.then(\n\t\t\t\t\t() =>\n\t\t\t\t\t\tsignal.aborted ||\n\t\t\t\t\t\tcontext.registerTool(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\t\t\t// WebIDL dictionaries: `undefined` is the same as left out.\n\t\t\t\t\t\t\t\ttitle: tool.title,\n\t\t\t\t\t\t\t\tdescription: tool.description,\n\t\t\t\t\t\t\t\tinputSchema: tool.inputSchema,\n\t\t\t\t\t\t\t\toutputSchema: tool.outputSchema,\n\t\t\t\t\t\t\t\tannotations: hints,\n\t\t\t\t\t\t\t\texecute: (input: unknown, options?: { signal?: unknown }) =>\n\t\t\t\t\t\t\t\t\tcall(tool, input, options?.signal),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{ signal, exposedTo: tool.exposedTo },\n\t\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.catch((error: unknown) => {\n\t\t\t\t\tif (signal.aborted) return; // unmirrored meanwhile\n\t\t\t\t\tif (warned.has(tool.name)) return;\n\t\t\t\t\twarned.add(tool.name);\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`tab-mcp: ${tool.name} is not offered through WebMCP:`,\n\t\t\t\t\t\terror,\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t}\n\t};\n\tregistry.onChange(sync);\n\tsync();\n}\n"
6
+ ],
7
+ "mappings": ";AA4BA,IAAM,QAAQ;AAAA,EACb;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;AASO,SAAS,MAAM,CACrB,UACA,SACA,MACO;AAAA,EACP,MAAM,UAAU,IAAI;AAAA,EACpB,MAAM,SAAS,IAAI;AAAA,EACnB,MAAM,OAAO,MAAY;AAAA,IACxB,YAAY,MAAM,eAAe,SAAS;AAAA,MACzC,IAAI,SAAS,IAAI,KAAK,IAAI,MAAM;AAAA,QAAM;AAAA,MACtC,WAAW,MAAM;AAAA,MACjB,QAAQ,OAAO,IAAI;AAAA,IACpB;AAAA,IACA,WAAW,QAAQ,SAAS,KAAK,GAAG;AAAA,MACnC,QAAQ,aAAa,YAAY;AAAA,MACjC,MAAM,gBACL,YAAY,qBAAqB,YAAY;AAAA,MAE9C,IAAI,QAAQ,IAAI,IAAI,KAAK,EAAE,SAAS,SAAS,QAAQ,KAAK,CAAC;AAAA,QAC1D;AAAA,MACD,MAAM,aAAa,IAAI;AAAA,MACvB,QAAQ,IAAI,MAAM,UAAU;AAAA,MAC5B,MAAM,QAA6C;AAAA,QAClD,mBAAmB;AAAA,MACpB;AAAA,MACA,WAAW,OAAO;AAAA,QAAO,MAAM,SAAS,YAAY;AAAA,MACpD,QAAQ,WAAW;AAAA,MACnB,QAAQ,QAAQ,EAGd,KACA,MACC,OAAO,WACP,QAAQ,aACP;AAAA,QACC,MAAM,KAAK;AAAA,QAEX,OAAO,KAAK;AAAA,QACZ,aAAa,KAAK;AAAA,QAClB,aAAa,KAAK;AAAA,QAClB,cAAc,KAAK;AAAA,QACnB,aAAa;AAAA,QACb,SAAS,CAAC,OAAgB,YACzB,KAAK,MAAM,OAAO,SAAS,MAAM;AAAA,MACnC,GACA,EAAE,QAAQ,WAAW,KAAK,UAAU,CACrC,CACF,EACC,MAAM,CAAC,UAAmB;AAAA,QAC1B,IAAI,OAAO;AAAA,UAAS;AAAA,QACpB,IAAI,OAAO,IAAI,KAAK,IAAI;AAAA,UAAG;AAAA,QAC3B,OAAO,IAAI,KAAK,IAAI;AAAA,QACpB,QAAQ,KACP,YAAY,KAAK,uCACjB,KACD;AAAA,OACA;AAAA,IACH;AAAA;AAAA,EAED,SAAS,SAAS,IAAI;AAAA,EACtB,KAAK;AAAA;",
8
+ "debugId": "68007C67B049549964756E2164756E21",
9
+ "names": []
10
+ }
package/webmcp.d.ts CHANGED
@@ -1,38 +1,27 @@
1
1
  /**
2
2
  * Mirroring the tools into the browser's own WebMCP (iteration 25, DEC-115,
3
- * DEC-119): with `webmcp: true`, each tool that is offered there is also
4
- * registered with `document.modelContext.registerTool()`, under its own
5
- * `AbortController`, aborted when the tool leaves the registry. Part of the
6
- * core: only the detection, the registrations and the `<html>` attribute;
7
- * a call loads the lazy chunk, which checks, confirms and runs it.
3
+ * DEC-119, DEC-143): with `webmcp: true`, each tool that is offered there is
4
+ * also registered with `document.modelContext.registerTool()`, under its own
5
+ * `AbortController`, aborted when the tool leaves the registry. A chunk of
6
+ * its own (DEC-171), loaded by a `TabMcp` whose constructor found native
7
+ * WebMCP (`nativeContext` in the core); a call loads the connection chunk,
8
+ * which checks, confirms and runs it.
8
9
  */
9
10
  import type { RegisteredTool, ToolRegistry } from "./registry.js";
10
11
  /** What the library uses of the browser's `ModelContext`. */
11
12
  export interface ModelContext {
12
13
  registerTool(tool: object, options: {
13
14
  signal: AbortSignal;
15
+ exposedTo: string[] | undefined;
14
16
  }): unknown;
15
17
  }
16
18
  /** Runs a call of a mirrored tool; `signal` is the browser's, if it gives one. */
17
19
  export type WebMcpCall = (tool: RegisteredTool, input: unknown, signal: unknown) => Promise<unknown>;
18
20
  /**
19
- * Capture `Document.prototype`'s `modelContext` getter and `ModelContext`,
20
- * when the library loads: a page script that runs later cannot put its own
21
- * object in their place (DEC-115). Called again only by the tests.
21
+ * Mirror `registry`'s tools into `context`, now and whenever the registry
22
+ * changes: those whose `callers` list `"webmcp"`, and without `callers` those
23
+ * not marked consequential, where MCP's `destructiveHint` counts as
24
+ * `consequentialHint` (DEC-143, DEC-165). Every failure of the native `registerTool()`
25
+ * stays here: warned once per name, the tool still offered through the relay.
22
26
  */
23
- export declare function capture(): void;
24
- /**
25
- * The browser's own `ModelContext` of this document, through
26
- * `Document.prototype`'s getter: never an own `document.modelContext` (a
27
- * polyfill such as `@mcp-b/global`, or any page script). `undefined` without
28
- * native WebMCP.
29
- */
30
- export declare function nativeContext(): ModelContext | undefined;
31
- /**
32
- * Mirror `registry`'s tools that `offered` accepts into `context`, now and
33
- * whenever the registry changes. Every failure of the native
34
- * `registerTool()` stays here: warned once per name, the tool still offered
35
- * through the relay. A failed registration is tried once more a task later
36
- * (a duplicate right after an abort may be one still on its way out).
37
- */
38
- export declare function mirror(registry: ToolRegistry, context: ModelContext, offered: (tool: RegisteredTool) => boolean, call: WebMcpCall): void;
27
+ export declare function mirror(registry: ToolRegistry, context: ModelContext, call: WebMcpCall): void;