@ractive-ch/tab-mcp-client 0.22.0 → 0.24.0-rc.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.
- package/CHANGELOG.md +51 -0
- package/README.md +80 -32
- package/cdn/connection-vxpnd3ex.min.js +17 -0
- package/cdn/{connection-m0e4xvcy.min.js.map → connection-vxpnd3ex.min.js.map} +5 -5
- package/cdn/tab-mcp-client.min.js +3 -3
- package/cdn/tab-mcp-client.min.js.map +3 -3
- package/cdn/webmcp-jtsqzqas.min.js +4 -0
- package/cdn/webmcp-jtsqzqas.min.js.map +11 -0
- package/{connection-fnkfrvpc.js → connection-gqec88qp.js} +23 -10
- package/connection-gqec88qp.js.map +16 -0
- package/connection.d.ts +8 -4
- package/extension.d.ts +10 -0
- package/extension.js +3 -1
- package/extension.js.map +3 -3
- package/handshake.d.ts +26 -7
- package/index.js +15 -6
- package/index.js.map +3 -3
- package/mapping.d.ts +10 -1
- package/mcp.d.ts +8 -2
- package/package.json +1 -1
- package/react.d.ts +1 -1
- package/react.js.map +1 -1
- package/skill/SKILL.md +31 -21
- package/skill/references/react.md +3 -3
- package/tab-mcp.d.ts +1 -1
- package/types.d.ts +27 -12
- package/{webmcp-7yspbk3q.js → webmcp-ctk4bd8c.js} +8 -9
- package/webmcp-ctk4bd8c.js.map +11 -0
- package/webmcp.d.ts +5 -4
- package/cdn/connection-m0e4xvcy.min.js +0 -17
- package/cdn/webmcp-vqs5smxj.min.js +0 -4
- package/cdn/webmcp-vqs5smxj.min.js.map +0 -11
- package/connection-fnkfrvpc.js.map +0 -16
- package/webmcp-7yspbk3q.js.map +0 -11
package/skill/SKILL.md
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: tab-mcp
|
|
3
|
-
description: Add tab-mcp to a web app so that AI apps (Claude, ChatGPT, Claude Code, Codex) can call the page's functions as MCP tools while it is open in a browser tab. Covers installing @ractive-ch/tab-mcp-client, registering tools WebMCP-style, the React bindings, the connect and pairing flow (by code or by sign-in), confirmation for consequential tools, registering the same tools with the browser's WebMCP (`webmcp:
|
|
3
|
+
description: Add tab-mcp to a web app so that AI apps (Claude, ChatGPT, Claude Code, Codex) can call the page's functions as MCP tools while it is open in a browser tab. Covers installing @ractive-ch/tab-mcp-client, registering tools WebMCP-style, the React bindings, the connect and pairing flow (by code or by sign-in), confirmation for consequential tools, registering the same tools with the browser's WebMCP (on by default; `webmcp: false`), serving them to the site's own assistant without a relay (`serve`), security defaults and running a tab-mcp relay. Use when the user wants to expose a web page's features to AI apps over MCP, mentions tab-mcp, WebMCP or registerTool, "Connect your AI app", or needs to self-host the tab-mcp relay.
|
|
4
4
|
license: MIT
|
|
5
5
|
compatibility: Browser library for any web page (ES modules); the relay needs Bun 1.4.4+ or Docker.
|
|
6
6
|
---
|
|
7
7
|
|
|
8
8
|
# Add tab-mcp to a web app
|
|
9
9
|
|
|
10
|
-
This skill describes `@ractive-ch/tab-mcp-client` 0.
|
|
10
|
+
This skill describes `@ractive-ch/tab-mcp-client` 0.24.0-rc.1. The package's
|
|
11
11
|
[README](../README.md)
|
|
12
12
|
is the full reference; read the section you need there when this skill is not enough. Its
|
|
13
13
|
[CHANGELOG](../CHANGELOG.md)
|
|
@@ -33,8 +33,8 @@ Facts to keep in mind:
|
|
|
33
33
|
- The page needs a relay that allows its origin; run one (section 7).
|
|
34
34
|
- [WebMCP](https://webmachinelearning.github.io/webmcp/) (`document.modelContext`) is the
|
|
35
35
|
browser's own API for tools that agents in the browser call. tab-mcp is for AI apps
|
|
36
|
-
outside the browser.
|
|
37
|
-
(section 5). A page that only registers WebMCP tools natively needs no library: the tab-mcp browser extension passes them on to an AI app through a relay.
|
|
36
|
+
outside the browser. Unless `webmcp: false`, the library offers the page's tools both
|
|
37
|
+
ways (section 5). A page that only registers WebMCP tools natively needs no library: the tab-mcp browser extension passes them on to an AI app through a relay.
|
|
38
38
|
- tab-mcp fits state that lives only in the browser, and acting as the signed-in user in
|
|
39
39
|
their open tab. If the state lives on the site's server, suggest an MCP server on that
|
|
40
40
|
backend instead: it works without an open tab and without a relay.
|
|
@@ -49,7 +49,7 @@ Without a bundler, import the self-contained build from a CDN:
|
|
|
49
49
|
|
|
50
50
|
```html
|
|
51
51
|
<script type="module">
|
|
52
|
-
import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.
|
|
52
|
+
import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.24.0-rc.1/cdn/tab-mcp-client.min.js";
|
|
53
53
|
</script>
|
|
54
54
|
```
|
|
55
55
|
|
|
@@ -114,7 +114,9 @@ Rules for tools:
|
|
|
114
114
|
- Write `description` for a model: what the tool does, its units, an example.
|
|
115
115
|
- `execute` results: a string becomes one text block; an MCP result (`content` an array
|
|
116
116
|
of MCP content blocks: `text`, `image`, `audio`, `resource_link`, `resource`) is passed
|
|
117
|
-
through (use it for images
|
|
117
|
+
through (use it for images; an AI app through the tab-mcp browser extension gets them
|
|
118
|
+
too, from the release after 0.23 on; any other WebMCP caller gets the text, each image
|
|
119
|
+
a line that says it was left out); any other JSON value, also an object whose `content` holds
|
|
118
120
|
something else, is sent as JSON text and, for objects, as `structuredContent`.
|
|
119
121
|
Annotation hints must be `true` or `false`; anything else is a `TypeError`. A thrown error becomes an error
|
|
120
122
|
result with its message, so throw errors that tell the model what to do.
|
|
@@ -123,9 +125,11 @@ Rules for tools:
|
|
|
123
125
|
`{ kind: "relay", grantId, id, host, name? }` for an AI app (verified `host`, declared
|
|
124
126
|
`name`), `{ kind: "local", id, name? }` for the site's own assistant on a served port
|
|
125
127
|
(what the page passed to `serve`, section 3), or `{ kind: "webmcp", via?, name?,
|
|
126
|
-
host? }` for a WebMCP caller: `via: "tab-mcp-extension"` with the AI app's
|
|
128
|
+
host?, allowed? }` for a WebMCP caller: `via: "tab-mcp-extension"` with the AI app's
|
|
127
129
|
`name` and verified `host` when the tab-mcp browser extension ran the call for an AI
|
|
128
|
-
app connected to it (section 5),
|
|
130
|
+
app connected to it (section 5), and `allowed: true` only when the user allowed that
|
|
131
|
+
call there (`false` for a read-only tool it ran unasked; `via` alone is no "allowed"),
|
|
132
|
+
else nothing more is known (an agent in the browser,
|
|
129
133
|
another extension, an `exposedTo` origin: the page cannot tell which). Check `client.kind`
|
|
130
134
|
before reading `host`; a label for a log, e.g. `kind === "relay" ? name ?? host :
|
|
131
135
|
kind === "local" ? name ?? id : via ? (name ?? host) + " through the tab-mcp browser
|
|
@@ -261,7 +265,7 @@ const served = await mcp.serve(port, {
|
|
|
261
265
|
- `served.close()` (or `options.signal`) ends it; close it when the channel is gone.
|
|
262
266
|
Without `relay`, `connect()`, `showConnectDialog()` and `disconnectAll()` reject with a
|
|
263
267
|
`TypeError` and React's `ConnectButton` renders nothing. `serve`, the relay and
|
|
264
|
-
|
|
268
|
+
the WebMCP mirror can be used together: one registration reaches all three.
|
|
265
269
|
|
|
266
270
|
## 4. Consequential tools
|
|
267
271
|
|
|
@@ -314,7 +318,7 @@ calls are declined.
|
|
|
314
318
|
## 5. WebMCP: agents in the browser
|
|
315
319
|
|
|
316
320
|
```ts
|
|
317
|
-
const mcp = new TabMcp({ relay, server
|
|
321
|
+
const mcp = new TabMcp({ relay, server }); // the mirror is on unless webmcp: false
|
|
318
322
|
await mcp.registerTool(deleteNoteTool); // an AI app is asked; an unvouched WebMCP call is not
|
|
319
323
|
```
|
|
320
324
|
|
|
@@ -330,11 +334,13 @@ Whether anyone asks before a tool that asks runs, and who, depends on the caller
|
|
|
330
334
|
| Another extension passing on an AI app's calls | no, unless that extension lets it | that extension, if it asks; the page's `onConfirm` if any; never the library's dialog |
|
|
331
335
|
| A document of an origin in the tool's `exposedTo` | no, not in the page | only the page's `onConfirm`, if any |
|
|
332
336
|
|
|
333
|
-
-
|
|
334
|
-
`document.modelContext.registerTool()`, where the
|
|
335
|
-
the WebMCP origin trial, or `chrome://flags/#enable-webmcp-testing
|
|
336
|
-
browser
|
|
337
|
-
|
|
337
|
+
- The library also registers each tool with the browser's native
|
|
338
|
+
`document.modelContext.registerTool()`, where the tab has it (in Chrome: sites in
|
|
339
|
+
the WebMCP origin trial, or `chrome://flags/#enable-webmcp-testing`; where the
|
|
340
|
+
browser has none, the tab-mcp browser extension's own). On by default (since client
|
|
341
|
+
0.23, DEC-222); `webmcp: false` turns it off. Agents in the
|
|
342
|
+
browser (built in, or an extension) call the mirrored tools without pairing: ask the
|
|
343
|
+
user whether that is wanted, and set `webmcp: false` when it is not.
|
|
338
344
|
- Every tool goes there, tools with `consequentialHint` or `destructiveHint` included
|
|
339
345
|
(since client 0.20, DEC-209): hiding them did not stop an agent that drives the tab, it
|
|
340
346
|
clicked the page's own controls instead, with no question. `callers` without
|
|
@@ -344,17 +350,19 @@ Whether anyone asks before a tool that asks runs, and who, depends on the caller
|
|
|
344
350
|
drives the tab clicked "Allow once" in the dialog itself. For another extension or an
|
|
345
351
|
`exposedTo` origin the dialog was a real check, and it is gone too. Such a tool is
|
|
346
352
|
registered with `consequentialHint: true`, so a caller that heeds it asks its user.
|
|
347
|
-
The page's `onConfirm` still gets the call (`client.kind === "webmcp"
|
|
353
|
+
The page's `onConfirm` still gets the call (`client.kind === "webmcp"`; no `via`, or
|
|
354
|
+
`via` with `allowed: false` for a read-only call the tab-mcp browser extension ran unasked):
|
|
348
355
|
decide there in code (refuse, or a rule), never by showing something, which an agent
|
|
349
356
|
can click too. Without `onConfirm` the call runs. A tool that must not run on such a
|
|
350
357
|
caller's word leaves `"webmcp"` out of `callers`, and gets no `exposedTo` (the library
|
|
351
358
|
warns in the console about a tool that asks with `exposedTo` on a page without
|
|
352
359
|
`onConfirm`).
|
|
353
|
-
- **The tab-mcp browser extension.**
|
|
354
|
-
shake hands. A call the user has just allowed in the extension (asked in its side
|
|
360
|
+
- **The tab-mcp browser extension.** Unless `webmcp: false`, the page and the extension
|
|
361
|
+
shake hands; it sees the page's tools only through the mirror. A call the user has just allowed in the extension (asked in its side
|
|
355
362
|
panel, or covered by its "Always allow" switch; the same tool, equal arguments, within
|
|
356
363
|
2 seconds) runs without `onConfirm`, so `onConfirm` is not a hook that sees every
|
|
357
|
-
call; its caller is `{ kind: "webmcp", via: "tab-mcp-extension", name, host
|
|
364
|
+
call; its caller is `{ kind: "webmcp", via: "tab-mcp-extension", name, host,
|
|
365
|
+
allowed: true }`.
|
|
358
366
|
`trustExtension: false` on `TabMcp` hands such a call to `onConfirm` like an
|
|
359
367
|
unvouched one; without `onConfirm` it then runs as well, so the option only matters
|
|
360
368
|
to a page with an `onConfirm`. `mcp.extension` (event `extensionchange`, React:
|
|
@@ -373,10 +381,12 @@ Whether anyone asks before a tool that asks runs, and who, depends on the caller
|
|
|
373
381
|
bare `UnknownError`. Two cases still reject: a call the browser cancelled
|
|
374
382
|
(`AbortError`), and a call when the library's lazily loaded part cannot be loaded (a
|
|
375
383
|
new deploy while the page stays open, the network); reloading the page fixes that.
|
|
376
|
-
- Only the
|
|
384
|
+
- Only the object behind `Document.prototype`'s getter is used (the browser's, or the
|
|
385
|
+
one a browser extension such as tab-mcp's put there), never a `document.modelContext`
|
|
386
|
+
a page script defines (a polyfill such as `@mcp-b/global`). A failed
|
|
377
387
|
native registration (a name already registered natively, a frame without
|
|
378
388
|
`allow="tools"`) only warns in the console; the tool stays offered through the relay.
|
|
379
|
-
A page that registers tools natively itself
|
|
389
|
+
A page that registers tools natively itself sets `webmcp: false` or uses other names.
|
|
380
390
|
- The tab-mcp browser extension offers mirrored tools like any page tool, so an AI app connected to
|
|
381
391
|
both the page and the extension sees them twice.
|
|
382
392
|
|
|
@@ -47,13 +47,13 @@ function TodoList() {
|
|
|
47
47
|
Keep the state in a store, or the current value in a ref beside the state, changed by
|
|
48
48
|
one function that the page's own UI uses too
|
|
49
49
|
([Tools in a `useState` app](../../README.md#tools-in-a-usestate-app)).
|
|
50
|
-
-
|
|
51
|
-
ask included; the library shows an unvouched WebMCP call no question (the provider's
|
|
50
|
+
- The provider registers the tools with the browser's WebMCP too (unless `webmcp: false`),
|
|
51
|
+
tools that ask included; the library shows an unvouched WebMCP call no question (the provider's
|
|
52
52
|
`onConfirm`, if given, still decides in code); `useTool(tool, { callers: ["relay",
|
|
53
53
|
"local"] })` keeps one out (SKILL.md, section 5).
|
|
54
54
|
- `useToolCalls({ limit })` lists the AI app's recent calls; `ConnectButton` opens the
|
|
55
55
|
dialog and labels itself by state.
|
|
56
56
|
- The module starts with `"use client"`: in Next.js's app router the provider renders on
|
|
57
57
|
the client and never connects on the server.
|
|
58
|
-
[examples/react-todo](https://github.com/ractive/tab-mcp/tree/client-v0.
|
|
58
|
+
[examples/react-todo](https://github.com/ractive/tab-mcp/tree/client-v0.24.0-rc.1/examples/react-todo)
|
|
59
59
|
is a complete app.
|
package/tab-mcp.d.ts
CHANGED
|
@@ -48,7 +48,7 @@ type Listener<K extends keyof TabMcpEventMap> = (event: TabMcpEventMap[K]) => vo
|
|
|
48
48
|
export declare class TabMcp extends EventTarget {
|
|
49
49
|
#private;
|
|
50
50
|
/**
|
|
51
|
-
*
|
|
51
|
+
* Unless `webmcp: false`: the tab-mcp browser extension while it serves this
|
|
52
52
|
* page, with the AI apps that reach the page's tools through it (DEC-207);
|
|
53
53
|
* `extensionchange` says when it changes. `undefined` without it, while
|
|
54
54
|
* its AI access is off, and without WebMCP. Declared only: the mirror's
|
package/types.d.ts
CHANGED
|
@@ -42,27 +42,39 @@ export interface RelayClient {
|
|
|
42
42
|
}
|
|
43
43
|
/**
|
|
44
44
|
* Whatever calls a mirrored tool through the browser's WebMCP
|
|
45
|
-
* (`webmcp:
|
|
45
|
+
* (unless `webmcp: false`): an agent in the browser, which may drive the tab,
|
|
46
46
|
* another extension that passes on an AI app's calls, or a document of an
|
|
47
47
|
* origin in the tool's `exposedTo`. Not paired and not identified: nothing
|
|
48
48
|
* more is known, and the page cannot tell these apart, unless the tab-mcp
|
|
49
|
-
* browser extension vouched for the call (DEC-207)
|
|
50
|
-
*
|
|
51
|
-
* `onConfirm` decides, in code.
|
|
49
|
+
* browser extension vouched for the call (DEC-207) or claimed it (DEC-224).
|
|
50
|
+
* The library never shows such a call its confirmation (DEC-215): only the
|
|
51
|
+
* page's own `onConfirm` decides, in code (not for a vouched call).
|
|
52
52
|
*/
|
|
53
53
|
export interface WebMcpClient {
|
|
54
54
|
kind: "webmcp";
|
|
55
55
|
/**
|
|
56
56
|
* Set when the tab-mcp browser extension ran this call for an AI app
|
|
57
|
-
* connected to it
|
|
58
|
-
* not ask
|
|
59
|
-
*
|
|
57
|
+
* connected to it: after the user allowed the call there (a vouch: the
|
|
58
|
+
* page did not ask, no `onConfirm`), or without a question, the tool
|
|
59
|
+
* being read-only for it (a claim: `onConfirm` decides a tool that asks,
|
|
60
|
+
* as for any WebMCP call). Absent for every other agent in the browser,
|
|
61
|
+
* and with `trustExtension: false`. Alone it does not say that the user
|
|
62
|
+
* allowed the call: `allowed` does.
|
|
60
63
|
*/
|
|
61
64
|
via?: "tab-mcp-extension";
|
|
62
65
|
/** With `via`: the AI app's own name for itself, as the extension knows it. */
|
|
63
66
|
name?: string;
|
|
64
67
|
/** With `via`: the host of the AI app's client id, as the relay verified it for the extension. */
|
|
65
68
|
host?: string;
|
|
69
|
+
/**
|
|
70
|
+
* With `via`: `true` when the user allowed this very call in the
|
|
71
|
+
* extension (asked, or the tool allowed for the site; a vouch, DEC-207),
|
|
72
|
+
* `false` when the extension ran it without asking, the tool being
|
|
73
|
+
* read-only for it (a claim, DEC-224). Only a call with `true` skips
|
|
74
|
+
* `onConfirm`; so a page that asks in `execute` itself skips its question
|
|
75
|
+
* only for `allowed: true`, never for `via` alone.
|
|
76
|
+
*/
|
|
77
|
+
allowed?: boolean;
|
|
66
78
|
}
|
|
67
79
|
/**
|
|
68
80
|
* The tab-mcp browser extension, as it tells a page that offers its tools
|
|
@@ -204,7 +216,7 @@ export interface RegisterToolOptions {
|
|
|
204
216
|
/**
|
|
205
217
|
* Which callers see the tool: `"relay"` (AI apps through the relay),
|
|
206
218
|
* `"local"` (this site's own assistant over `serve`), `"webmcp"` (whatever
|
|
207
|
-
* calls through the browser's WebMCP,
|
|
219
|
+
* calls through the browser's WebMCP, unless `TabMcpOptions.webmcp` is `false`). Others neither list nor
|
|
208
220
|
* call it: for them it does not exist. By default all of them, tools that
|
|
209
221
|
* ask included (DEC-209). Leave a caller out for privacy or identity, e.g.
|
|
210
222
|
* `["local"]` for data the site's own assistant may read but an AI app
|
|
@@ -407,7 +419,8 @@ export interface TabMcpOptions {
|
|
|
407
419
|
/**
|
|
408
420
|
* Also register the tools with the browser's own WebMCP
|
|
409
421
|
* (`document.modelContext.registerTool()`), where it has it, so that agents
|
|
410
|
-
* in the browser can call them, without pairing.
|
|
422
|
+
* in the browser can call them, without pairing. On by default; `false`
|
|
423
|
+
* keeps every tool out of WebMCP and the page out of the handshake. Every
|
|
411
424
|
* tool goes there unless its `callers` leave `"webmcp"` out, tools that ask
|
|
412
425
|
* included, marked `consequentialHint` (a tool marked only
|
|
413
426
|
* `destructiveHint` too: WebMCP has no `destructiveHint`; DEC-209), so
|
|
@@ -423,10 +436,12 @@ export interface TabMcpOptions {
|
|
|
423
436
|
*/
|
|
424
437
|
webmcp?: boolean;
|
|
425
438
|
/**
|
|
426
|
-
*
|
|
439
|
+
* Unless `webmcp: false`: a WebMCP call the tab-mcp browser extension vouches
|
|
427
440
|
* for runs without `onConfirm` (the user allowed exactly that call there,
|
|
428
|
-
* a moment before)
|
|
429
|
-
*
|
|
441
|
+
* a moment before), and one it vouches for or claims names its AI app and
|
|
442
|
+
* resolves with the whole MCP result, pictures included (DEC-224). On by
|
|
443
|
+
* default; `false` treats both as any other WebMCP call: `onConfirm`
|
|
444
|
+
* decides, without one it runs (DEC-215), the result as text. `extension`
|
|
430
445
|
* is reported either way.
|
|
431
446
|
*/
|
|
432
447
|
trustExtension?: boolean;
|
|
@@ -41,10 +41,7 @@ class Handshake {
|
|
|
41
41
|
type,
|
|
42
42
|
library: page.version,
|
|
43
43
|
app: page.app,
|
|
44
|
-
apps: page.mcp.grants.slice(0, MAX_APPS).map((g) => ({
|
|
45
|
-
name: g.client.name,
|
|
46
|
-
host: g.client.host
|
|
47
|
-
}))
|
|
44
|
+
apps: this.#pages.filter((p) => p.app === page.app).flatMap((p) => p.mcp.grants).slice(0, MAX_APPS).map((g) => ({ name: g.client.name, host: g.client.host }))
|
|
48
45
|
})
|
|
49
46
|
}));
|
|
50
47
|
}
|
|
@@ -57,7 +54,7 @@ class Handshake {
|
|
|
57
54
|
}
|
|
58
55
|
if (!isObject(m) || m["v"] !== 1)
|
|
59
56
|
return;
|
|
60
|
-
if (m["type"] === "vouch")
|
|
57
|
+
if (m["type"] === "vouch" || m["type"] === "claim")
|
|
61
58
|
this.#vouch(m);
|
|
62
59
|
else if (m["type"] === "withdraw")
|
|
63
60
|
this.#vouches = this.#vouches.filter((v) => v.nonce !== m["nonce"]);
|
|
@@ -93,7 +90,9 @@ class Handshake {
|
|
|
93
90
|
args: canonical(m["arguments"]),
|
|
94
91
|
nonce,
|
|
95
92
|
app,
|
|
96
|
-
at: now()
|
|
93
|
+
at: now(),
|
|
94
|
+
allowed: m["type"] === "vouch",
|
|
95
|
+
whole: m["result"] === "mcp"
|
|
97
96
|
});
|
|
98
97
|
if (this.#vouches.length > MAX_VOUCHES)
|
|
99
98
|
this.#vouches.shift();
|
|
@@ -108,7 +107,7 @@ class Handshake {
|
|
|
108
107
|
this.#drop();
|
|
109
108
|
const args = canonical(input);
|
|
110
109
|
const i = this.#vouches.findIndex((v) => v.tool === tool && v.args === args);
|
|
111
|
-
return i < 0 ? undefined : this.#vouches.splice(i, 1)[0]
|
|
110
|
+
return i < 0 ? undefined : this.#vouches.splice(i, 1)[0];
|
|
112
111
|
}
|
|
113
112
|
}
|
|
114
113
|
function extensionOf(m) {
|
|
@@ -237,5 +236,5 @@ export {
|
|
|
237
236
|
mirror
|
|
238
237
|
};
|
|
239
238
|
|
|
240
|
-
//# debugId=
|
|
241
|
-
//# sourceMappingURL=webmcp-
|
|
239
|
+
//# debugId=BC86E1E1DA7D9F9D64756E2164756E21
|
|
240
|
+
//# sourceMappingURL=webmcp-ctk4bd8c.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/handshake.ts", "../src/webmcp.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * The page's side of the handshake with the tab-mcp browser extension\n * (DEC-207), in the WebMCP mirror's chunk: only a page that mirrors its\n * tools into WebMCP (unless `webmcp: false`) takes part.\n *\n * Plain DOM events on `document`, each with a JSON string as `detail`\n * (objects do not cross between a content script's world and the page's in\n * every browser): `tab-mcp-page` from the page, `tab-mcp-extension` from\n * the extension. Every message has `v: 1` and a `type`; a message of\n * another version, an unknown type or a malformed one is ignored, and so\n * are unknown fields.\n *\n * - The page announces itself (`hello`: the library's version, the app id,\n * the AI apps connected to it directly) when it starts, again (`update`)\n * when those apps change, and answers the extension's `hello` with an\n * `update`. It marks `<html data-tab-mcp-handshake>`, so that an\n * extension that starts later (its content script comes at\n * `document_idle`, or with a click) knows it may speak without having\n * heard the `hello`.\n * - The extension says what it is and which AI apps are connected to it\n * (`hello`, `update`), and, right before it runs a page tool the user\n * allowed there, `vouch`: the tool, the exact arguments, a nonce and the\n * AI app; right before one it runs without asking (read-only for it),\n * `claim` with the same fields (DEC-224); once that call ended or failed,\n * `withdraw` with the nonce, and one still unused is dropped. With\n * `result: \"mcp\"` on either, the call resolves with the whole MCP result\n * (pictures too), which the extension passes on; without it (an older\n * extension), with the value any WebMCP caller gets. A `claim` only\n * names the caller and asks for the whole result: `onConfirm` decides as\n * for any WebMCP call. It speaks only while it serves the\n * page (DEC-221): while its AI access is off the page hears nothing, as\n * without the extension, except `on: false` once if it was told \"on\".\n * - Each side cuts the other's list of AI apps to 64 and sends no more.\n *\n * No proof of who sent what: anything that could fake the extension runs in\n * the page already, where it could skip any check. A convenience between\n * two parts the user trusts, not a security boundary.\n */\n\nimport type { RegisteredTool, ToolRegistry } from \"./registry.ts\";\nimport type { BrowserExtension, Grant } from \"./types.ts\";\n\n/** From the page to the extension. */\nexport const PAGE_EVENT = \"tab-mcp-page\";\n/** From the extension to the page. */\nexport const EXTENSION_EVENT = \"tab-mcp-extension\";\n/** On `<html>`: this page takes part (for an extension that starts later). */\nexport const MARK = \"data-tab-mcp-handshake\";\n/** A vouch is kept this long (milliseconds), then dropped unused. */\nexport const VOUCH_MS = 2_000;\n/** At most this many vouches wait; beyond, the oldest goes. */\nconst MAX_VOUCHES = 16;\n/** Texts from the extension are taken up to these lengths, apps up to this count either way. */\nconst MAX_TEXT = 256;\nconst MAX_APPS = 64;\n\n/** One `TabMcp` of the page, as the handshake sees it. */\nexport interface HandshakePage {\n\t/** The library's version. */\n\treadonly version: string;\n\treadonly app: string;\n\treadonly registry: ToolRegistry;\n\t/** Vouches are taken for its tools (`trustExtension`). */\n\treadonly trust: boolean;\n\t/** The `TabMcp`: its `grants` and `grantschange`. */\n\treadonly mcp: EventTarget & { readonly grants: readonly Grant[] };\n\t/** The extension's state changed. */\n\tset(extension: BrowserExtension | undefined): void;\n}\n\n/** The AI app a vouched call came from. */\nexport interface VouchedBy {\n\tname: string;\n\thost: string;\n}\n\n/** A call the extension announced, as its WebMCP call takes it. */\nexport interface Vouched {\n\tapp: VouchedBy;\n\t/**\n\t * The user allowed it in the extension (`vouch`): it runs without\n\t * `onConfirm`. `false` for a `claim`, a call the extension made without\n\t * asking (it took the tool for read-only): `onConfirm` decides as for\n\t * any WebMCP call.\n\t */\n\tallowed: boolean;\n\t/** The extension takes the whole MCP result (`result: \"mcp\"`, DEC-224). */\n\twhole: boolean;\n}\n\ninterface Vouch extends Vouched {\n\ttool: RegisteredTool;\n\t/** The arguments, canonical (`canonical`). */\n\targs: string;\n\tnonce: string;\n\tat: number;\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst text = (value: unknown): value is string =>\n\ttypeof value === \"string\" && value.length <= MAX_TEXT;\n\n/** An AI app as the extension names it; `undefined` if it is malformed. */\nfunction appOf(value: unknown): VouchedBy | undefined {\n\treturn isObject(value) && text(value[\"name\"]) && text(value[\"host\"])\n\t\t? { name: value[\"name\"], host: value[\"host\"] }\n\t\t: undefined;\n}\n\n/**\n * `value` as JSON with the keys of every object sorted: two argument\n * objects are equal when their canonical forms are.\n */\nexport function canonical(value: unknown): string {\n\treturn (\n\t\tJSON.stringify(value, (_key, v: unknown) =>\n\t\t\tisObject(v)\n\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\tObject.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n\t\t\t\t\t)\n\t\t\t\t: v,\n\t\t) ?? \"\"\n\t);\n}\n\n/** Monotonic milliseconds: a vouch's age must not follow the wall clock. */\nconst now = () => performance.now();\n\nclass Handshake {\n\treadonly #doc: Document;\n\treadonly #pages: HandshakePage[] = [];\n\t#extension: BrowserExtension | undefined;\n\t#vouches: Vouch[] = [];\n\n\tconstructor(doc: Document) {\n\t\tthis.#doc = doc;\n\t\tdoc.addEventListener(EXTENSION_EVENT, (event) =>\n\t\t\tthis.#heard((event as CustomEvent).detail),\n\t\t);\n\t\tdoc.documentElement?.setAttribute(MARK, \"1\");\n\t}\n\n\tjoin(page: HandshakePage): void {\n\t\tthis.#pages.push(page);\n\t\tif (this.#extension !== undefined) page.set(this.#extension);\n\t\tpage.mcp.addEventListener(\"grantschange\", () => this.#say(page, \"update\"));\n\t\tthis.#say(page, \"hello\");\n\t}\n\n\t#say(page: HandshakePage, type: \"hello\" | \"update\"): void {\n\t\t// The document's own `CustomEvent`: a document may take only events\n\t\t// of its realm.\n\t\tconst Custom = this.#doc.defaultView?.CustomEvent ?? CustomEvent;\n\t\tthis.#doc.dispatchEvent(\n\t\t\tnew Custom(PAGE_EVENT, {\n\t\t\t\tdetail: JSON.stringify({\n\t\t\t\t\tv: 1,\n\t\t\t\t\ttype,\n\t\t\t\t\tlibrary: page.version,\n\t\t\t\t\tapp: page.app,\n\t\t\t\t\t// Of every `TabMcp` of this app: the extension keeps one list\n\t\t\t\t\t// per app, and one made and dropped (React's strict mode, a\n\t\t\t\t\t// provider whose relay changed) has none. Capped as the\n\t\t\t\t\t// extension cuts what it hears: more would not be heard anyway.\n\t\t\t\t\tapps: this.#pages\n\t\t\t\t\t\t.filter((p) => p.app === page.app)\n\t\t\t\t\t\t.flatMap((p) => p.mcp.grants)\n\t\t\t\t\t\t.slice(0, MAX_APPS)\n\t\t\t\t\t\t.map((g) => ({ name: g.client.name, host: g.client.host })),\n\t\t\t\t}),\n\t\t\t}),\n\t\t);\n\t}\n\n\t#heard(detail: unknown): void {\n\t\tlet m: unknown;\n\t\ttry {\n\t\t\tm = typeof detail === \"string\" ? JSON.parse(detail) : undefined;\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tif (!isObject(m) || m[\"v\"] !== 1) return;\n\t\tif (m[\"type\"] === \"vouch\" || m[\"type\"] === \"claim\") this.#vouch(m);\n\t\t// The call it was for ended or never reached the page: an unused vouch\n\t\t// must not wait its 2 s for another caller.\n\t\telse if (m[\"type\"] === \"withdraw\")\n\t\t\tthis.#vouches = this.#vouches.filter((v) => v.nonce !== m[\"nonce\"]);\n\t\telse if (m[\"type\"] === \"hello\" || m[\"type\"] === \"update\") {\n\t\t\tconst extension = extensionOf(m);\n\t\t\tif (extension === null) return;\n\t\t\tif (canonical(extension) !== canonical(this.#extension)) {\n\t\t\t\tthis.#extension = extension;\n\t\t\t\tfor (const page of this.#pages) page.set(extension);\n\t\t\t}\n\t\t\tif (m[\"type\"] === \"hello\")\n\t\t\t\tfor (const page of this.#pages) this.#say(page, \"update\");\n\t\t}\n\t}\n\n\t/**\n\t * A vouch, kept for the tool registered under its name now, by a page\n\t * that takes vouches: a tool registered anew after this does not get it.\n\t */\n\t#vouch(m: Record<string, unknown>): void {\n\t\tconst app = appOf(m[\"app\"]);\n\t\tconst name = m[\"tool\"];\n\t\tconst nonce = m[\"nonce\"];\n\t\tif (\n\t\t\tapp === undefined ||\n\t\t\ttypeof name !== \"string\" ||\n\t\t\ttypeof nonce !== \"string\" ||\n\t\t\t!isObject(m[\"arguments\"])\n\t\t)\n\t\t\treturn;\n\t\tthis.#drop();\n\t\t// The same vouch heard twice counts once.\n\t\tif (this.#vouches.some((v) => v.nonce === nonce)) return;\n\t\tfor (const page of this.#pages) {\n\t\t\tconst tool = page.trust ? page.registry.get(name) : undefined;\n\t\t\tif (tool === undefined) continue;\n\t\t\tthis.#vouches.push({\n\t\t\t\ttool,\n\t\t\t\targs: canonical(m[\"arguments\"]),\n\t\t\t\tnonce,\n\t\t\t\tapp,\n\t\t\t\tat: now(),\n\t\t\t\tallowed: m[\"type\"] === \"vouch\",\n\t\t\t\twhole: m[\"result\"] === \"mcp\",\n\t\t\t});\n\t\t\tif (this.#vouches.length > MAX_VOUCHES) this.#vouches.shift();\n\t\t\treturn;\n\t\t}\n\t}\n\n\t/** Forget the vouches older than `VOUCH_MS`. */\n\t#drop(): void {\n\t\tconst t = now();\n\t\tthis.#vouches = this.#vouches.filter((v) => t - v.at <= VOUCH_MS);\n\t}\n\n\t/**\n\t * The vouch or claim for this call of `tool` with `input`, used up;\n\t * `undefined` if there is none (the call is any WebMCP call).\n\t */\n\ttake(tool: RegisteredTool, input: unknown): Vouched | undefined {\n\t\tthis.#drop();\n\t\tconst args = canonical(input);\n\t\tconst i = this.#vouches.findIndex(\n\t\t\t(v) => v.tool === tool && v.args === args,\n\t\t);\n\t\treturn i < 0 ? undefined : this.#vouches.splice(i, 1)[0];\n\t}\n}\n\n/**\n * The extension's state from its `hello` or `update`: `undefined` when it\n * does not serve the page now, `null` when the message is malformed.\n */\nfunction extensionOf(\n\tm: Record<string, unknown>,\n): BrowserExtension | undefined | null {\n\tif (m[\"on\"] !== true) return m[\"on\"] === false ? undefined : null;\n\tconst { name, apps } = m;\n\tif (!text(name) || !Array.isArray(apps)) return null;\n\tconst list = apps.slice(0, MAX_APPS).map(appOf);\n\tif (list.some((a) => a === undefined)) return null;\n\treturn Object.freeze({\n\t\tname,\n\t\tapps: Object.freeze(list.map((a) => Object.freeze(a as VouchedBy))),\n\t\twhileInFront: m[\"whileInFront\"] !== false,\n\t});\n}\n\nconst handshakes = new WeakMap<Document, Handshake>();\n\n/**\n * The handshake of the page's top-level document, which `page` joins; the\n * extension speaks only to the top frame. `undefined` in a frame or\n * without a document.\n */\nexport function joinHandshake(page: HandshakePage): Handshake | undefined {\n\tconst doc = globalThis.document;\n\tif (doc === undefined || globalThis.top !== globalThis.window)\n\t\treturn undefined;\n\tlet handshake = handshakes.get(doc);\n\tif (handshake === undefined) {\n\t\thandshake = new Handshake(doc);\n\t\thandshakes.set(doc, handshake);\n\t}\n\thandshake.join(page);\n\treturn handshake;\n}\n",
|
|
6
|
+
"/**\n * Mirroring the tools into the browser's own WebMCP (iteration 25, DEC-115,\n * DEC-119, DEC-143): unless `webmcp: false`, 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 and runs it. The handshake with the tab-mcp browser\n * extension (`handshake.ts`, DEC-207) is here too: only a page that mirrors\n * takes part.\n */\n\nimport {\n\ttype HandshakePage,\n\tjoinHandshake,\n\ttype Vouched,\n} from \"./handshake.ts\";\nimport type { RegisteredTool, ToolRegistry } from \"./registry.ts\";\nimport type { BrowserExtension } from \"./types.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/**\n * Runs a call of a mirrored tool; `signal` is the browser's, if it gives\n * one; `by`: the tab-mcp browser extension announced it for an AI app\n * (a vouch or a claim).\n */\nexport type WebMcpCall = (\n\ttool: RegisteredTool,\n\tinput: unknown,\n\tsignal: unknown,\n\tby: Vouched | undefined,\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: every tool, unless its `callers` leave `\"webmcp\"` out (DEC-165,\n * DEC-209). A tool that asks is marked `consequentialHint`, so that the agent\n * asks its user; MCP's `destructiveHint` counts as `consequentialHint`\n * (DEC-143). The page's `onConfirm` decides such a call, never the library's\n * dialog (DEC-215). Every failure of the native `registerTool()`\n * stays here: warned once per name, the tool still offered through the relay.\n * The page joins the handshake with the tab-mcp browser extension: `mcp`\n * is its `TabMcp`, `app` its app id, `options` its options\n * (`trustExtension`, and `onConfirm` for the warning below), `version` the\n * library's. A tool that asks, mirrored with an `exposedTo` that names\n * other origins on a page without `onConfirm`, is warned about once per\n * name (`warnUnasked`): documents of those origins can run it, and the\n * library asks no WebMCP caller (DEC-215). The extension's state is `mcp.extension`, defined\n * here on the instance (the core only declares it, for its bytes), and\n * `extensionchange` is sent here.\n */\nexport function mirror(\n\tregistry: ToolRegistry,\n\tcontext: ModelContext,\n\tcall: WebMcpCall,\n\tmcp: HandshakePage[\"mcp\"],\n\tapp: string,\n\toptions: { trustExtension?: boolean; onConfirm?: unknown },\n\tversion: string,\n): void {\n\tlet state: BrowserExtension | undefined;\n\tObject.defineProperty(mcp, \"extension\", {\n\t\tget: () => state,\n\t\tconfigurable: true,\n\t});\n\tlet handshake: ReturnType<typeof joinHandshake>;\n\ttry {\n\t\thandshake = joinHandshake({\n\t\t\tversion,\n\t\t\tapp,\n\t\t\tregistry,\n\t\t\ttrust: options.trustExtension !== false,\n\t\t\tmcp,\n\t\t\tset: (extension) => {\n\t\t\t\tstate = extension;\n\t\t\t\tmcp.dispatchEvent(\n\t\t\t\t\tnew CustomEvent(\"extensionchange\", { detail: { extension } }),\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\t} catch (error) {\n\t\t// The tools are mirrored all the same; no call is vouched for.\n\t\tconsole.warn(\"tab-mcp: no handshake with the browser extension:\", error);\n\t}\n\tconst mirrors = new Map<RegisteredTool, AbortController>();\n\tconst warned = new Set<string>();\n\tconst unasked = new Set<string>();\n\t/**\n\t * The warning about a tool that asks with `exposedTo` (DEC-215), once its\n\t * native registration succeeded (so Chrome accepted every origin), once\n\t * per name. Decided then: a handler the page removes later is not\n\t * caught. Never throws, whatever `exposedTo` holds.\n\t */\n\tconst warnUnasked = (tool: RegisteredTool, asks: boolean | undefined) => {\n\t\ttry {\n\t\t\t// React's provider always passes a handler; `own` says whether the\n\t\t\t// page gave one.\n\t\t\tconst ask = options.onConfirm as { own?: boolean } | undefined;\n\t\t\tconst page = globalThis.document?.location?.origin;\n\t\t\tconst others = (\n\t\t\t\tArray.isArray(tool.exposedTo) ? tool.exposedTo : []\n\t\t\t).filter((entry: unknown) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn new URL(String(entry)).origin !== page;\n\t\t\t\t} catch {\n\t\t\t\t\treturn false; // the browser refuses it anyway\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (\n\t\t\t\tasks !== true ||\n\t\t\t\tothers.length === 0 ||\n\t\t\t\t(ask && ask.own !== false) ||\n\t\t\t\tunasked.has(tool.name)\n\t\t\t)\n\t\t\t\treturn;\n\t\t\tunasked.add(tool.name);\n\t\t\tconsole.warn(\n\t\t\t\t`tab-mcp: ${tool.name} asks before it runs, but documents of ${others.join(\", \")} (its exposedTo) can call it through WebMCP without a question: the library asks no WebMCP caller. Refuse such calls in onConfirm, or leave exposedTo off.`,\n\t\t\t);\n\t\t} catch {\n\t\t\t// a warning never stops the mirror\n\t\t}\n\t};\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\") ?? true)) continue;\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\t// The vouch is looked up as the call arrives: it was\n\t\t\t\t\t\t\t\t// sent right before the extension made the call.\n\t\t\t\t\t\t\t\texecute: (input: unknown, options?: { signal?: unknown }) =>\n\t\t\t\t\t\t\t\t\tcall(\n\t\t\t\t\t\t\t\t\t\ttool,\n\t\t\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\t\t\toptions?.signal,\n\t\t\t\t\t\t\t\t\t\thandshake?.take(tool, input),\n\t\t\t\t\t\t\t\t\t),\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.then(() => {\n\t\t\t\t\tif (!signal.aborted) warnUnasked(tool, consequential);\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"
|
|
7
|
+
],
|
|
8
|
+
"mappings": ";AA2CO,IAAM,aAAa;AAEnB,IAAM,kBAAkB;AAExB,IAAM,OAAO;AAEb,IAAM,WAAW;AAExB,IAAM,cAAc;AAEpB,IAAM,WAAW;AACjB,IAAM,WAAW;AA4CjB,IAAM,WAAW,CAAC,UACjB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAEpE,IAAM,OAAO,CAAC,UACb,OAAO,UAAU,YAAY,MAAM,UAAU;AAG9C,SAAS,KAAK,CAAC,OAAuC;AAAA,EACrD,OAAO,SAAS,KAAK,KAAK,KAAK,MAAM,OAAO,KAAK,KAAK,MAAM,OAAO,IAChE,EAAE,MAAM,MAAM,SAAS,MAAM,MAAM,QAAQ,IAC3C;AAAA;AAOG,SAAS,SAAS,CAAC,OAAwB;AAAA,EACjD,OACC,KAAK,UAAU,OAAO,CAAC,MAAM,MAC5B,SAAS,CAAC,IACP,OAAO,YACP,OAAO,QAAQ,CAAC,EAAE,KAAK,EAAE,KAAK,OAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE,CAClE,IACC,CACJ,KAAK;AAAA;AAKP,IAAM,MAAM,MAAM,YAAY,IAAI;AAAA;AAElC,MAAM,UAAU;AAAA,EACN;AAAA,EACA,SAA0B,CAAC;AAAA,EACpC;AAAA,EACA,WAAoB,C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AAA,QACX,IAAI,CAAC,OAAO;AAAA,UAAS,YAAY,MAAM,aAAa;AAAA,OACpD,EACA,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;",
|
|
9
|
+
"debugId": "BC86E1E1DA7D9F9D64756E2164756E21",
|
|
10
|
+
"names": []
|
|
11
|
+
}
|
package/webmcp.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Mirroring the tools into the browser's own WebMCP (iteration 25, DEC-115,
|
|
3
|
-
* DEC-119, DEC-143):
|
|
3
|
+
* DEC-119, DEC-143): unless `webmcp: false`, each tool that is offered there is
|
|
4
4
|
* also registered with `document.modelContext.registerTool()`, under its own
|
|
5
5
|
* `AbortController`, aborted when the tool leaves the registry. A chunk of
|
|
6
6
|
* its own (DEC-171), loaded by a `TabMcp` whose constructor found native
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* extension (`handshake.ts`, DEC-207) is here too: only a page that mirrors
|
|
10
10
|
* takes part.
|
|
11
11
|
*/
|
|
12
|
-
import { type HandshakePage, type
|
|
12
|
+
import { type HandshakePage, type Vouched } from "./handshake.js";
|
|
13
13
|
import type { RegisteredTool, ToolRegistry } from "./registry.js";
|
|
14
14
|
/** What the library uses of the browser's `ModelContext`. */
|
|
15
15
|
export interface ModelContext {
|
|
@@ -20,9 +20,10 @@ export interface ModelContext {
|
|
|
20
20
|
}
|
|
21
21
|
/**
|
|
22
22
|
* Runs a call of a mirrored tool; `signal` is the browser's, if it gives
|
|
23
|
-
* one; `by`: the
|
|
23
|
+
* one; `by`: the tab-mcp browser extension announced it for an AI app
|
|
24
|
+
* (a vouch or a claim).
|
|
24
25
|
*/
|
|
25
|
-
export type WebMcpCall = (tool: RegisteredTool, input: unknown, signal: unknown, by:
|
|
26
|
+
export type WebMcpCall = (tool: RegisteredTool, input: unknown, signal: unknown, by: Vouched | undefined) => Promise<unknown>;
|
|
26
27
|
/**
|
|
27
28
|
* Mirror `registry`'s tools into `context`, now and whenever the registry
|
|
28
29
|
* changes: every tool, unless its `callers` leave `"webmcp"` out (DEC-165,
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
var Et=/^(?:\d{1,4}x\d{1,4}|any)$/;function At(e){let{src:t,mimeType:n,sizes:r,theme:o}=e;if(typeof t!=="string")return;let a=/^https?:/i.test(t)&&t.length<=2048,s=/^data:image\/(?:png|jpeg|gif|webp|x-icon|vnd\.microsoft\.icon)[;,]/i.test(t)&&t.length<=16384;if(!a&&!s)return;let i={src:t};if(typeof n==="string"&&/^image\/[\w.+-]+$/i.test(n))i.mimeType=n.toLowerCase();let u=Array.isArray(r)?r.map((v)=>String(v).toLowerCase()).filter((v)=>Et.test(v)):[];if(u.length>0)i.sizes=u;if(o==="light"||o==="dark")i.theme=o;return i}function Ae(e){let t=[];for(let n of e){let r=typeof n==="object"&&n!==null?At(n):void 0;if(r!==void 0)t.push(r);if(t.length===8)break}return t}function we(e=globalThis.document){try{let t=e?.querySelectorAll('link[rel~="icon" i], link[rel~="apple-touch-icon" i]');return Ae([...t??[]].filter((n)=>n.getAttribute("href")?.trim()).map((n)=>{let r={src:n.href};if(n.type)r.mimeType=n.type;let o=n.getAttribute("sizes");if(o)r.sizes=o.trim().split(/\s+/);let a=/prefers-color-scheme:\s*(light|dark)/i.exec(n.media);if(a)r.theme=a[1]?.toLowerCase();return r}))}catch{return[]}}function ue(e,t){let n=typeof e;if(n!==typeof t)return!1;let r=Array.isArray(e),o=Array.isArray(t);if(r!==o)return!1;if(r){let a=e.length;if(a!==t.length)return!1;for(let s=0;s<a;s++)if(!ue(e[s],t[s]))return!1;return!0}if(n==="object"){if(!e||!t)return e===t;let a=Object.keys(e),s=Object.keys(t);if(a.length!==s.length)return!1;for(let u of a){if(!Object.prototype.hasOwnProperty.call(t,u))return!1;if(!ue(e[u],t[u]))return!1}return!0}return e===t}function J(e){return encodeURI(Ot(e)).replace(/#/g,"%23")}function Ot(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Pt=/^[A-Za-z0-9._~!$&'()*+,;=:@/?-]$/,Nt=/^%[0-9A-Fa-f]{2}$/,jt=/^[A-Za-z0-9._~-]$/;function qt(e){let t="";for(let n=0;n<e.length;){let r=e[n],o=e.slice(n,n+3);if(r==="%"&&Nt.test(o)){let s=String.fromCharCode(parseInt(o.slice(1),16));t+=jt.test(s)?s:o.toUpperCase(),n+=3;continue}let a=String.fromCodePoint(e.codePointAt(n));t+=Pt.test(a)?a:encodeURIComponent(a),n+=a.length}return t}function $e(e,t){let n=new URL(e,t.href);return n.hash=n.hash?qt(n.hash.slice(1)):"",n}var Ht={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},zt={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Dt={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,dependentRequired:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},Bt=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function Z(e,t=Object.create(null),n=Bt,r=""){if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e.$id||e.id;if(a){let s=$e(a,n);if(s.hash.length>1)t[s.href]=e;else if(s.hash="",r==="")n=s;else Z(e,t,n)}}else if(e!==!0&&e!==!1)return t;let o=n.href+(r?"#"+r:"");if(t[o]!==void 0&&t[o]!==e)throw Error(`Duplicate schema URI "${o}".`);if(t[o]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0)Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:o});if(e.$ref&&e.__absolute_ref__===void 0){let a=$e(e.$ref,n);Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:a.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let a=$e(e.$recursiveRef,n);Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:a.href})}if(e.$anchor){let a=$e("#"+e.$anchor,n);t[a.href]=e}for(let a in e){if(Dt[a])continue;let s=`${r}/${J(a)}`,i=e[a];if(Array.isArray(i)){if(Ht[a]){let u=i.length;for(let v=0;v<u;v++)Z(i[v],t,n,`${s}/${v}`)}}else if(zt[a])for(let u in i)Z(i[u],t,n,`${s}/${J(u)}`);else Z(i,t,n,s)}return t}var Jt=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Ut=[0,31,28,31,30,31,30,31,31,30,31,30,31],Vt=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|([+-])(\d\d):(\d\d))?$/i,Ze=/^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i,Gt=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4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/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Kt=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Yt=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Xt=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Zt=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Qt=/^("(?:[\x20-\x21\x23-\x5b\x5d-\x7e]|\\[\x20-\x7e])*"|[a-z0-9.!#$%&'*+/=?^_`{|}~-]+)@(.+)$/i,Lt=(e)=>{let t=e.match(Qt);if(!t)return!1;let n=t[1],r=t[2];if(!n||!r||n.length>64||r.length>253)return!1;if(n[0]!=='"'&&(n[0]==="."||n.endsWith(".")||n.includes("..")))return!1;if(r.startsWith("[")&&r.endsWith("]")){let o=r.slice(1,-1);if(/^ipv6:/i.test(o))return Le.test(o.slice(5));return Qe.test(o)}return Ze.test(r)},Qe=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Le=/^((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:\d+S)?|\d+S))?|T(?:\d+H(?:\d+M(?:\d+S)?)?|\d+M(?:\d+S)?|\d+S)))$/.test(e);function G(e){return e.test.bind(e)}var Oe={date:et,time:tt.bind(void 0,!0),"date-time":rn,duration:en,uri:an,"uri-reference":G(Gt),"uri-template":G(Wt),url:G(Ft),email:Lt,hostname:G(Ze),ipv4:G(Qe),ipv6:G(Le),regex:un,uuid:G(Kt),"json-pointer":G(Yt),"json-pointer-uri-fragment":G(Xt),"relative-json-pointer":G(Zt)};function tn(e){return e%4===0&&(e%100!==0||e%400===0)}function et(e){let t=e.match(Jt);if(!t)return!1;let n=t[1],r=t[2],o=t[3];if(!n||!r||!o)return!1;let a=+n,s=+r,i=+o,u=s==2&&tn(a)?29:Ut[s];return s>=1&&s<=12&&i>=1&&u!==void 0&&i<=u}function tt(e,t){let n=t.match(Vt);if(!n)return!1;let r=n[1],o=n[2],a=n[3];if(!r||!o||!a)return!1;let s=+r,i=+o,u=+a,v=n[5],k=n[6],M=+(n[7]??0),S=+(n[8]??0);if(s>23||i>59||u>60||M>23||S>59||e&&v===void 0)return!1;if(u<60)return!0;let N=k==="+"?1:k==="-"?-1:0;return(s*60+i-N*(M*60+S)+1440)%1440===1439}var nn=/t|\s/i;function rn(e){let[t,n,r]=e.split(nn);return t!==void 0&&n!==void 0&&r===void 0&&et(t)&&tt(!0,n)}var on=/\/|:/,sn=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function an(e){return on.test(e)&&sn.test(e)}var dn=/[^\\]\\Z/;function un(e){if(dn.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}}function nt(e){let t=0,n=e.length,r=0,o;while(r<n)if(t++,o=e.charCodeAt(r++),o>=55296&&o<=56319&&r<n){if(o=e.charCodeAt(r),(o&64512)==56320)r++}return t}function oe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function rt(e){let t=Math.abs(e).toString().split("e"),n=t[0],r=t[1]??"0",o=n.indexOf("."),a=o===-1?0:n.length-o-1;return[BigInt(n.replace(".","")),Number(r)-a]}function ln(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return!1;let[n,r]=rt(e),[o,a]=rt(t),s=r-a;if(s>=0)return n*10n**BigInt(s)%o===0n;return n%(o*10n**BigInt(-s))===0n}function j(e,t,n="2019-09",r=Z(t),o=!0,a=null,s="#",i="#",u=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};let v=typeof e,k;switch(v){case"boolean":case"number":case"string":k=v;break;case"object":if(e===null)k="null";else if(Array.isArray(e))k="array";else k="object";break;default:throw Error(`Instances of "${v}" type are not supported.`)}let{$ref:M,$recursiveRef:S,$recursiveAnchor:N,type:_,const:O,enum:q,required:U,not:f,anyOf:y,allOf:g,oneOf:w,if:h,then:R,else:A,format:E,properties:d,patternProperties:C,additionalProperties:H,unevaluatedProperties:z,minProperties:X,maxProperties:V,propertyNames:ee,dependentRequired:te,dependentSchemas:Ve,dependencies:Ie,prefixItems:Me,items:ce,additionalItems:Ge,unevaluatedItems:We,contains:Fe,minContains:K,maxContains:Se,minItems:Ce,maxItems:_e,uniqueItems:Ct,minimum:ne,maximum:re,exclusiveMinimum:pe,exclusiveMaximum:me,multipleOf:Ee,minLength:ye,maxLength:ge,pattern:Ke,__absolute_ref__:he,__absolute_recursive_ref__:_t}=t,c=[];if(N===!0&&a===null)a=t;if(S==="#"){let T=a===null?r[_t]:a,m=`${i}/$recursiveRef`,I=j(e,a===null?t:a,n,r,o,T,s,m,u);if(!I.valid)c.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:m,error:"A subschema had errors."},...I.errors)}if(M!==void 0){let m=r[he||M];if(m===void 0){let l=`Unresolved $ref "${M}".`;if(he&&he!==M)l+=` Absolute URI "${he}".`;throw l+=`
|
|
2
|
-
Known schemas:
|
|
3
|
-
- ${Object.keys(r).join(`
|
|
4
|
-
- `)}`,Error(l)}let I=`${i}/$ref`,p=j(e,m,n,r,o,a,s,I,u);if(!p.valid)c.push({instanceLocation:s,keyword:"$ref",keywordLocation:I,error:"A subschema had errors."},...p.errors);if(n==="4"||n==="7")return{valid:c.length===0,errors:c}}if(Array.isArray(_)){let T=_.length,m=!1;for(let I=0;I<T;I++)if(k===_[I]||_[I]==="integer"&&k==="number"&&e%1===0&&e===e){m=!0;break}if(!m)c.push({instanceLocation:s,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${k}" is invalid. Expected "${_.join('", "')}".`})}else if(_==="integer"){if(k!=="number"||e%1||e!==e)c.push({instanceLocation:s,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${k}" is invalid. Expected "${_}".`})}else if(_!==void 0&&k!==_)c.push({instanceLocation:s,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${k}" is invalid. Expected "${_}".`});if(O!==void 0){if(k==="object"||k==="array"){if(!ue(e,O))c.push({instanceLocation:s,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(O)}.`})}else if(e!==O)c.push({instanceLocation:s,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(O)}.`})}if(q!==void 0){if(k==="object"||k==="array"){if(!q.some((T)=>ue(e,T)))c.push({instanceLocation:s,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(q)}.`})}else if(!q.some((T)=>e===T))c.push({instanceLocation:s,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(q)}.`})}if(f!==void 0){let T=`${i}/not`;if(j(e,f,n,r,o,a,s,T).valid)c.push({instanceLocation:s,keyword:"not",keywordLocation:T,error:'Instance matched "not" schema.'})}let be=[];if(y!==void 0){let T=`${i}/anyOf`,m=c.length,I=!1;for(let[p,l]of y.entries()){let x=Object.create(u),b=j(e,l,n,r,o,N===!0?a:null,s,`${T}/${p}`,x);if(c.push(...b.errors),I=I||b.valid,b.valid)be.push(x)}if(I)c.length=m;else c.splice(m,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:T,error:"Instance does not match any subschemas."})}if(g!==void 0){let T=`${i}/allOf`,m=c.length,I=!0;for(let[p,l]of g.entries()){let x=Object.create(u),b=j(e,l,n,r,o,N===!0?a:null,s,`${T}/${p}`,x);if(c.push(...b.errors),I=I&&b.valid,b.valid)be.push(x)}if(I)c.length=m;else c.splice(m,0,{instanceLocation:s,keyword:"allOf",keywordLocation:T,error:"Instance does not match every subschema."})}if(w!==void 0){let T=`${i}/oneOf`,m=c.length,I=w.filter((p,l)=>{let x=Object.create(u),b=j(e,p,n,r,o,N===!0?a:null,s,`${T}/${l}`,x);if(c.push(...b.errors),b.valid)be.push(x);return b.valid}).length;if(I===1)c.length=m;else c.splice(m,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:T,error:`Instance does not match exactly one subschema (${I} matches).`})}if(k==="object"||k==="array")Object.assign(u,...be);if(h!==void 0){let T=`${i}/if`,m=Object.create(null);if(j(e,h,n,r,o,a,s,T,m).valid){if(Object.assign(u,m),R!==void 0){let p=j(e,R,n,r,o,a,s,`${i}/then`,u);if(!p.valid)c.push({instanceLocation:s,keyword:"if",keywordLocation:T,error:'Instance does not match "then" schema.'},...p.errors)}}else if(A!==void 0){let p=j(e,A,n,r,o,a,s,`${i}/else`,u);if(!p.valid)c.push({instanceLocation:s,keyword:"if",keywordLocation:T,error:'Instance does not match "else" schema.'},...p.errors)}}if(k==="object"){if(U!==void 0){for(let p of U)if(!oe(e,p))c.push({instanceLocation:s,keyword:"required",keywordLocation:`${i}/required`,error:`Instance does not have required property "${p}".`})}let T=Object.keys(e);if(X!==void 0&&T.length<X)c.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${i}/minProperties`,error:`Instance does not have at least ${X} properties.`});if(V!==void 0&&T.length>V)c.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${i}/maxProperties`,error:`Instance does not have at least ${V} properties.`});if(ee!==void 0){let p=`${i}/propertyNames`;for(let l in e){let x=`${s}/${J(l)}`,b=j(l,ee,n,r,o,a,x,p);if(!b.valid)c.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:p,error:`Property name "${l}" does not match schema.`},...b.errors)}}if(te!==void 0){let p=`${i}/dependantRequired`;for(let l in te)if(oe(e,l)){let x=te[l];for(let b of x)if(!oe(e,b))c.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:p,error:`Instance has "${l}" but does not have "${b}".`})}}if(Ve!==void 0)for(let[p,l]of Object.entries(Ve)){let x=`${i}/dependentSchemas`;if(oe(e,p)){let b=j(e,l,n,r,o,a,s,`${x}/${J(p)}`,u);if(!b.valid)c.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:x,error:`Instance has "${p}" but does not match dependant schema.`},...b.errors)}}if(Ie!==void 0){let p=`${i}/dependencies`;for(let l in Ie)if(oe(e,l)){let x=Ie[l];if(Array.isArray(x)){for(let b of x)if(!oe(e,b))c.push({instanceLocation:s,keyword:"dependencies",keywordLocation:p,error:`Instance has "${l}" but does not have "${b}".`})}else{let b=j(e,x,n,r,o,a,s,`${p}/${J(l)}`);if(!b.valid)c.push({instanceLocation:s,keyword:"dependencies",keywordLocation:p,error:`Instance has "${l}" but does not match dependant schema.`},...b.errors)}}}let m=Object.create(null),I=!1;if(d!==void 0){let p=`${i}/properties`;for(let[l,x]of Object.entries(d)){if(!oe(e,l))continue;let b=`${s}/${J(l)}`,D=j(e[l],x,n,r,o,a,b,`${p}/${J(l)}`);if(m[l]=!0,D.valid)u[l]=!0;else if(I=o,c.push({instanceLocation:s,keyword:"properties",keywordLocation:p,error:`Property "${l}" does not match schema.`},...D.errors),I)break}}if(!I&&C!==void 0){let p=`${i}/patternProperties`;for(let[l,x]of Object.entries(C)){let b=new RegExp(l,"u");for(let D in e){if(!b.test(D))continue;let Ye=`${s}/${J(D)}`,Xe=j(e[D],x,n,r,o,a,Ye,`${p}/${J(l)}`);if(m[D]=!0,Xe.valid)u[D]=!0;else I=o,c.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:p,error:`Property "${D}" matches pattern "${l}" but does not match associated schema.`},...Xe.errors)}}}if(!I&&H!==void 0){let p=`${i}/additionalProperties`;for(let l in e){if(m[l])continue;let x=`${s}/${J(l)}`,b=j(e[l],H,n,r,o,a,x,p);if(b.valid)u[l]=!0;else I=o,c.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:p,error:`Property "${l}" does not match additional properties schema.`},...b.errors)}}else if(!I&&z!==void 0){let p=`${i}/unevaluatedProperties`;for(let l in e)if(!u[l]){let x=`${s}/${J(l)}`,b=j(e[l],z,n,r,o,a,x,p);if(b.valid)u[l]=!0;else c.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:p,error:`Property "${l}" does not match unevaluated properties schema.`},...b.errors)}}}else if(k==="array"){if(_e!==void 0&&e.length>_e)c.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${i}/maxItems`,error:`Array has too many items (${e.length} > ${_e}).`});if(Ce!==void 0&&e.length<Ce)c.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${i}/minItems`,error:`Array has too few items (${e.length} < ${Ce}).`});let T=e.length,m=0,I=!1;if(Me!==void 0){let p=`${i}/prefixItems`,l=Math.min(Me.length,T);for(;m<l;m++){let x=j(e[m],Me[m],n,r,o,a,`${s}/${m}`,`${p}/${m}`);if(u[m]=!0,!x.valid){if(I=o,c.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:p,error:"Items did not match schema."},...x.errors),I)break}}}if(ce!==void 0){let p=`${i}/items`;if(Array.isArray(ce)){let l=Math.min(ce.length,T);for(;m<l;m++){let x=j(e[m],ce[m],n,r,o,a,`${s}/${m}`,`${p}/${m}`);if(u[m]=!0,!x.valid){if(I=o,c.push({instanceLocation:s,keyword:"items",keywordLocation:p,error:"Items did not match schema."},...x.errors),I)break}}}else for(;m<T;m++){let l=j(e[m],ce,n,r,o,a,`${s}/${m}`,p);if(u[m]=!0,!l.valid){if(I=o,c.push({instanceLocation:s,keyword:"items",keywordLocation:p,error:"Items did not match schema."},...l.errors),I)break}}if(!I&&Ge!==void 0){let l=`${i}/additionalItems`;for(;m<T;m++){let x=j(e[m],Ge,n,r,o,a,`${s}/${m}`,l);if(u[m]=!0,!x.valid)I=o,c.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:l,error:"Items did not match additional items schema."},...x.errors)}}}if(Fe!==void 0)if(T===0&&K===void 0)c.push({instanceLocation:s,keyword:"contains",keywordLocation:`${i}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(K!==void 0&&T<K)c.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array has less items (${T}) than minContains (${K}).`});else{let p=`${i}/contains`,l=c.length,x=0;for(let b=0;b<T;b++){let D=j(e[b],Fe,n,r,o,a,`${s}/${b}`,p);if(D.valid)u[b]=!0,x++;else c.push(...D.errors)}if(x>=(K||0))c.length=l;if(K===void 0&&x===0)c.splice(l,0,{instanceLocation:s,keyword:"contains",keywordLocation:p,error:"Array does not contain item matching schema."});else if(K!==void 0&&x<K)c.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array must contain at least ${K} items matching schema. Only ${x} items were found.`});else if(Se!==void 0&&x>Se)c.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${i}/maxContains`,error:`Array may contain at most ${Se} items matching schema. ${x} items were found.`})}if(!I&&We!==void 0){let p=`${i}/unevaluatedItems`;for(m;m<T;m++){if(u[m])continue;let l=j(e[m],We,n,r,o,a,`${s}/${m}`,p);if(u[m]=!0,!l.valid)c.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:p,error:"Items did not match unevaluated items schema."},...l.errors)}}if(Ct)for(let p=0;p<T;p++){let l=e[p],x=typeof l==="object"&&l!==null;for(let b=0;b<T;b++){if(p===b)continue;let D=e[b];if(l===D||x&&(typeof D==="object"&&D!==null)&&ue(l,D))c.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${i}/uniqueItems`,error:`Duplicate items at indexes ${p} and ${b}.`}),p=Number.MAX_SAFE_INTEGER,b=Number.MAX_SAFE_INTEGER}}}else if(k==="number"){if(n==="4"){if(ne!==void 0&&(pe===!0&&e<=ne||e<ne))c.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${e} is less than ${pe?"or equal to ":""} ${ne}.`});if(re!==void 0&&(me===!0&&e>=re||e>re))c.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${e} is greater than ${me?"or equal to ":""} ${re}.`})}else{if(ne!==void 0&&e<ne)c.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${e} is less than ${ne}.`});if(re!==void 0&&e>re)c.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${e} is greater than ${re}.`});if(pe!==void 0&&e<=pe)c.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${i}/exclusiveMinimum`,error:`${e} is less than ${pe}.`});if(me!==void 0&&e>=me)c.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${i}/exclusiveMaximum`,error:`${e} is greater than or equal to ${me}.`})}if(Ee!==void 0){if(!ln(e,Ee))c.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${i}/multipleOf`,error:`${e} is not a multiple of ${Ee}.`})}}else if(k==="string"){let T=ye===void 0&&ge===void 0?0:nt(e);if(ye!==void 0&&T<ye)c.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${i}/minLength`,error:`String is too short (${T} < ${ye}).`});if(ge!==void 0&&T>ge)c.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${i}/maxLength`,error:`String is too long (${T} > ${ge}).`});if(Ke!==void 0&&!new RegExp(Ke,"u").test(e))c.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${i}/pattern`,error:"String does not match pattern."});if(E!==void 0&&Oe[E]&&!Oe[E](e))c.push({instanceLocation:s,keyword:"format",keywordLocation:`${i}/format`,error:`String does not match format "${E}".`})}return{valid:c.length===0,errors:c}}var ot="ch.ractive.tab-mcp/annotations",fn=["readOnlyHint","untrustedContentHint","consequentialHint","debugging"],cn=["destructiveHint","idempotentHint","openWorldHint"];function st(e){let t={};if(e.readOnlyHint===!0)t.readOnlyHint=!0,t.destructiveHint=!1;else if(e.readOnlyHint===!1)t.readOnlyHint=!1;if(e.consequentialHint===!0)t.destructiveHint=!0;if(e.untrustedContentHint===!0)t.openWorldHint=!0;for(let o of cn){let a=e[o];if(a!==void 0)t[o]=a}let n={};for(let o of fn){let a=e[o];if(a!==void 0)n[o]=a}let r={};if(Object.keys(t).length>0)r.annotations=t;if(Object.keys(n).length>0)r.meta=n;return r}function it(e){let t=e._meta??{},n=t["ch.ractive.tab-mcp/annotations"];return{...e,_meta:{...t,["ch.ractive.tab-mcp/annotations"]:{...Y(n)?n:{},untrustedContentHint:!0}}}}function se(e){return{content:[{type:"text",text:e}],isError:!0}}function Y(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var le=(e)=>typeof e==="string";function pn(e){if(!Y(e))return!1;switch(e.type){case"text":return le(e.text);case"image":case"audio":return le(e.data)&&le(e.mimeType);case"resource_link":return le(e.uri)&&le(e.name);case"resource":return Y(e.resource)&&le(e.resource.uri);default:return!1}}var mn=new Set(["content","structuredContent","isError","_meta","resultType"]);function at(e){if(!Y(e)||!Array.isArray(e.content))return!1;let{content:t,isError:n,structuredContent:r,_meta:o}=e;return(t.length>0?t.every(pn):Object.keys(e).every((a)=>mn.has(a)))&&(n===void 0||typeof n==="boolean")&&(r===void 0||Y(r))&&(o===void 0||Y(o))}function dt(e){if(typeof e==="string")return{content:[{type:"text",text:e}]};if(e===void 0)return{content:[]};if(at(e))return e;let t;try{t=JSON.stringify(e)}catch{}if(t===void 0)return se("The tool returned a value that is not JSON.");let n={content:[{type:"text",text:t}]},r=JSON.parse(t);if(Y(r))n.structuredContent=r;return n}function Pe(e,t=!1){return e.content.map((n)=>Y(n)&&n.type==="text"&&typeof n.text==="string"?n.text:t?`[${Y(n)?String(n.type):"A"} content left out: WebMCP results are text.]`:"").filter((n)=>n!=="").join(`
|
|
5
|
-
`)}function ut(e){if(at(e))return e.structuredContent??(Pe(e,!0)||"Done.");return e===void 0?"Done.":e}function lt(e){let t=e instanceof Error?e.message:String(e);return se(t||"The tool failed.")}var ie="2026-07-28",Q="io.modelcontextprotocol/protocolVersion",xe="io.modelcontextprotocol/clientCapabilities",ft="io.modelcontextprotocol/clientInfo",ct="io.modelcontextprotocol/serverInfo",Ne="io.modelcontextprotocol/subscriptionId",yn=-32020,pt=-32022,gn="The page may ask the user to allow each call, usually in the page's browser tab.",hn=0,mt=new WeakMap;function je(e){let t=mt.get(e);if(t!==void 0)return t;let n=e.inputSchema,r=yt(n,"inputSchema");if(e.outputSchema!==void 0)yt(e.outputSchema,"outputSchema");let o=(a)=>j(a,n,"2020-12",r,!1);return mt.set(e,o),o}class ve extends Error{what;constructor(e,t){super(t);this.what=e}}function yt(e,t){let n;try{n=Z(e)}catch(r){let o=r instanceof Error?r.message:String(r);throw new ve(t,o.split(`
|
|
6
|
-
`)[0]??"")}for(let r of Object.values(n)){if(typeof r!=="object"||r.$ref===void 0)continue;let o=r.__absolute_ref__;if(n[o??r.$ref]===void 0)throw new ve(t,`$ref ${JSON.stringify(r.$ref)} does not resolve`)}return n}function gt(e,t,n=""){let r=t instanceof Error?t.message:String(t),o=t instanceof ve?t.what:"inputSchema";return TypeError(`registerTool: the ${o} of ${e}: ${r}${n}`)}function bn(e){let t=[];for(let n of e.list())try{je(n)}catch(r){e.remove(n),t.push(gt(n.name,r,"; the tool was unregistered"))}return e.setCompiler((n)=>{try{je(n)}catch(r){throw gt(n.name,r)}}),t}function ht(e){try{return structuredClone(e)}catch{return e}}var wn=new TextEncoder;function L(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function qe(e,t){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}})}function B(e,t,n,r,o){let a={code:n,message:r};if(o!==void 0)a.data=o;return qe(e,{jsonrpc:"2.0",id:t,error:a})}function W(e,t,n){return B(400,e,yn,`Bad Request: the request headers and body disagree: ${n}`,{mismatch:{header:t,body:n}})}function ae(e){return wn.encode(`event: message
|
|
7
|
-
data: ${JSON.stringify(e)}
|
|
8
|
-
|
|
9
|
-
`)}var bt={"content-type":"text/event-stream","cache-control":"no-cache"};function $n(e){return(e??"").split(";")[0]?.trim().toLowerCase()==="application/json"}function xn(e){if(!(e.startsWith("=?base64?")&&e.endsWith("?=")))return e;let t=e.slice(9,-2);if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return;try{let n=atob(t),r=Uint8Array.from(n,(o)=>o.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return}}function vn(e){if(!(Q in e))return{key:Q,problem:"missing"};if(!(xe in e))return{key:xe,problem:"missing"};if(typeof e[Q]!=="string")return{key:Q,problem:"expected a protocol version string"};if(!L(e[xe]))return{key:xe,problem:"expected an object"};let t=e[ft];if(t!==void 0&&!(L(t)&&typeof t.name==="string"&&typeof t.version==="string"))return{key:ft,problem:"expected {name, version}"};return}function Tn(e){let t=e.notifications;return L(t)&&t.toolsListChanged===!0?{toolsListChanged:!0}:{}}function kn(e,t){let n;try{n=je(e)(t)}catch(o){let a=o instanceof Error?o.message:String(o);return`The input schema of tool ${e.name} cannot be used: ${a}`}if(n.valid)return;let r=n.errors.filter((o)=>o.keyword!=="properties"&&o.keyword!=="$ref").map((o)=>`${o.instanceLocation} ${o.error}`).slice(0,5).join("; ");return`Input validation error: Invalid arguments for tool ${e.name}: ${r||"the arguments do not match the schema"}`}async function wt(e,t,n,r,o,a){let s={id:++hn,tool:t.name,arguments:ht(n),client:{...o}};if(t.title!==void 0)s.title=t.title;let i=Date.now();e.observe?.start(s);let u={outcome:"error",result:se("Internal error")};try{if(u=await In(e,t,n,r,o),t.annotations.untrustedContentHint===!0)u.result=it(u.result);let v=r.aborted?void 0:a?.(u.result);if(v!==void 0)u={outcome:"error",result:v}}finally{e.observe?.end({id:s.id,tool:t.name,client:{...o},outcome:u.outcome,result:ht(u.result),durationMs:Date.now()-i})}return u}var Rn="The user was asked and did not answer.";async function In(e,t,n,r,o){let a=(S,N,_)=>({outcome:S,result:se(N),stop:_}),s=kn(t,n);if(s!==void 0)return a("error",s,"invalid");let i=new Promise((S,N)=>{if(r.aborted)N(r.reason);r.addEventListener("abort",()=>N(r.reason))});i.catch(()=>{});let{consequentialHint:u,destructiveHint:v}=t.annotations;if((o.kind==="webmcp"?u??v:u)===!0){let S={tool:{name:t.name,description:t.description},arguments:n,client:o,signal:r};if(t.title!==void 0)S.tool.title=t.title;let N=!1;try{N=await Promise.race([e.confirm(S),i])}catch{N=!1}if(N!==!0){if(r.aborted)return a("cancelled","The call was cancelled.","cancelled");return N==="unanswered"?a("unanswered",Rn,"unanswered"):a("declined","The user did not allow this call.","declined")}}if(r.aborted)return a("cancelled","Cancelled","cancelled");if(e.tools.get(t.name)!==t)return a("error","The tool is no longer available","gone");let M;try{let S=await Promise.race([t.execute(n,{signal:r,client:o}),i]);M={outcome:"ok",result:dt(S),returned:{value:S}}}catch(S){M={outcome:"error",result:lt(S)}}if(r.aborted)return{...M,outcome:"cancelled",stop:"cancelled"};if(M.result.isError===!0)M.outcome="error";return M}async function He(e,t,n,r,o){let a=(u)=>({error:u}),s=`The tool ${t.name} is no longer available.`;if(e.tools.get(t.name)!==t)return a(s);if(!L(n))return a("The input must be an object.");let i=await wt(e,t,n,r instanceof AbortSignal?r:new AbortController().signal,o);if(i.stop==="cancelled")throw new DOMException("Cancelled","AbortError");if(i.stop==="declined")return a(`The user did not allow ${t.name} to run.`);if(i.stop==="unanswered")return a(`The user did not answer whether ${t.name} may run.`);if(i.stop==="gone")return a(s);if(i.result.isError===!0)return a(Pe(i.result)||"The tool failed.");return ut(i.returned?.value)}function Te(e){let{tools:t,server:n}=e,r={name:n.name,version:n.version};if(n.title!==void 0)r.title=n.title;let o=Ae(n.icons??[]),a=o.length>0?{...r,icons:o}:r,s=new Set,i=!1,u=(f={})=>({...f,[ct]:r});function v(f,y,g=u()){return{jsonrpc:"2.0",id:f,result:{...y,resultType:"complete",_meta:g}}}function k(){return t.list().map((f)=>{let y={name:f.name};if(f.title!==void 0)y.title=f.title;if(y.description=f.annotations.consequentialHint===!0&&!e.ownConfirm?`${f.description} ${gn}`:f.description,y.inputSchema=f.inputSchema,f.outputSchema!==void 0)y.outputSchema=f.outputSchema;let{annotations:g,meta:w}=st(f.annotations);if(g!==void 0)y.annotations=g;if(w!==void 0)y._meta={[ot]:w};return y})}let M=(f)=>({kind:"invalid",message:f});async function S(f,y,g,w){let h=f.name;if(typeof h!=="string")return M("Invalid params: name must be a string");let R=t.get(h);if(R===void 0)return M(`Tool ${h} not found`);let A=f.arguments??{};if(!L(A))return M("Invalid params: arguments must be an object");return{kind:"result",result:(await wt(e,R,A,y,e.client(g),w)).result}}function N(f,y,g,w){let h=(d)=>ae(v(f,d,u(d._meta))),R,A=(d)=>{let C;try{C=h(d)}catch{return se("The tool returned a result that is not JSON.")}let H=e.maxBodyBytes?.();if(H!==void 0&&C.byteLength>H)return se(`The result is ${C.byteLength} bytes; the relay passes on at most ${H}.`);R={result:d,event:C};return},E=new ReadableStream({start:(d)=>{let C=(H)=>{if(g.aborted)return;try{d.enqueue(H()),d.close()}catch{}};S(y,g,w,A).then((H)=>C(()=>H.kind==="invalid"?ae({jsonrpc:"2.0",id:f,error:{code:-32602,message:H.message}}):H.result===R?.result?R.event:h(H.result)),()=>C(()=>ae({jsonrpc:"2.0",id:f,error:{code:-32603,message:"Internal error"}})))}});return new Response(E,{status:200,headers:bt})}function _(f,y,g){let w=Tn(y),h={jsonrpc:"2.0",id:f,result:{resultType:"complete",_meta:u({[Ne]:f})}},R,A=new ReadableStream({start:(E)=>{if(E.enqueue(ae({jsonrpc:"2.0",method:"notifications/subscriptions/acknowledged",params:{notifications:w,_meta:{[Ne]:f}}})),Object.keys(w).length===0){E.enqueue(ae(h)),E.close();return}let d={id:f,send:(C)=>{try{E.enqueue(ae(C))}catch{s.delete(d)}},end:()=>{s.delete(d);try{E.enqueue(ae(h)),E.close()}catch{}}};R=d,s.add(d),g.addEventListener("abort",()=>{s.delete(d);try{E.close()}catch{}})},cancel:()=>{if(R!==void 0)s.delete(R)}});return new Response(A,{status:200,headers:bt})}function O(f,y){if(Array.isArray(y))return B(400,null,-32600,"Bad Request: JSON-RPC batches are not supported by this endpoint");if(!L(y)||y.jsonrpc!=="2.0")return B(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let{method:g,id:w}=y;if(typeof g!=="string")return"result"in y||"error"in y?B(400,null,-32600,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"):B(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let h=f.headers.get("mcp-protocol-version"),R=f.headers.get("mcp-method"),A=L(y.params)?y.params:{},E=L(A._meta)?A._meta:void 0,d=E!==void 0&&Q in E,C=typeof E?.[Q]==="string"?E[Q]:void 0,H=h!==null&&h>=ie;if(w===void 0){if(C!==void 0&&h!==null&&h!==C)return W(null,h,`the notification envelope names protocol version ${C} but the MCP-Protocol-Version header names ${h}`);if((d||H)&&R!==null&&R!==g)return W(null,R,`the notification body names method ${g} but the Mcp-Method header names ${R}`);return"notification"}if(typeof w!=="string"&&typeof w!=="number")return B(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let z=w;if(!d||g==="initialize"&&(C===void 0||C<ie)){if(g==="initialize"){if(H)return W(z,h,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let V=typeof A.protocolVersion==="string"?A.protocolVersion:void 0;return q(z,V)}if(H){let V=E===void 0?["_meta"]:[Q];return B(400,z,-32602,`Invalid params: the MCP-Protocol-Version header names protocol revision ${h}, but the request is missing the required per-request envelope key(s): ${V.join(", ")}`,{envelope:{missing:V}})}return q(z,h??void 0)}let X=vn(E);if(X!==void 0)return B(400,z,-32602,`Invalid _meta envelope for protocol revision ${ie}: ${X.key}: ${X.problem}`,{envelope:X});if(h!==null&&C!==void 0&&h!==C)return W(z,h,`the body envelope names protocol version ${C} but the MCP-Protocol-Version header names ${h}`);if(R!==null&&R!==g)return W(z,R,`the body names method ${g} but the Mcp-Method header names ${R}`);if(C!==ie)return q(z,C);if(h===null)return W(z,"(missing)",`the body envelope names protocol version ${C} but the required MCP-Protocol-Version header is absent`);if(R===null)return W(z,"(missing)",`the body names method ${g} but the required Mcp-Method header is absent`);if(g==="tools/call"&&typeof A.name==="string"){let V=A.name,ee=f.headers.get("mcp-name");if(ee===null)return W(z,"(missing)",`the body carries params.name="${V}" but the required Mcp-Name header is absent`);let te=xn(ee);if(te===void 0)return W(z,ee,"the Mcp-Name header carries an invalid Base64 sentinel value");if(te!==V)return W(z,ee,`the body carries params.name="${V}" but the Mcp-Name header names "${te}"`)}return{id:z,method:g,params:A}}function q(f,y){return y===void 0?B(400,f,pt,"Unsupported protocol version: the request did not name a protocol version",{supported:[ie]}):B(400,f,pt,`Unsupported protocol version: ${y}`,{supported:[ie],requested:y})}async function U(f,y){if(f.method.toUpperCase()!=="POST")return B(405,null,-32000,"Method not allowed.");if(!$n(f.headers.get("content-type")))return B(415,null,-32000,"Unsupported Media Type: Content-Type must be application/json");let g;try{g=JSON.parse(y.body??await f.text())}catch{return B(400,null,-32700,"Parse error: the request body is not valid JSON")}let w=O(f,g);if(w instanceof Response)return w;if(w==="notification")return new Response(null,{status:202});let{id:h,method:R,params:A}=w;switch(R){case"server/discover":{let E={supportedVersions:[ie],capabilities:{tools:{listChanged:!0}}};if(n.instructions!==void 0)E.instructions=n.instructions;return E.ttlMs=0,E.cacheScope="private",qe(200,v(h,E,{[ct]:a}))}case"tools/list":return qe(200,v(h,{tools:k(),ttlMs:0,cacheScope:"private"}));case"tools/call":return N(h,A,f.signal,y.grant);case"subscriptions/listen":return _(h,A,f.signal);default:return B(404,h,-32601,"Method not found")}}return{handle:(f,y)=>U(f,y).catch(()=>B(500,null,-32603,"Internal server error")),toolsChanged(){if(i)return;i=!0,queueMicrotask(()=>{i=!1;for(let f of[...s])f.send({jsonrpc:"2.0",method:"notifications/tools/list_changed",params:{_meta:{[Ne]:f.id}}})})},close(){for(let f of[...s])f.end()}}}var ke="tab-mcp.v1",Mn=new Set(["start","used","expired"]);function fe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var P=(e)=>typeof e==="string";function $t(e){if(!fe(e)||!P(e.grantId)||!P(e.createdAt))return!1;let t=e.client;return fe(t)&&P(t.id)&&P(t.name)&&P(t.host)}function Sn(e){if(!fe(e))return!1;return["maxMessageBytes","maxBodyBytes","requestTimeoutMs","idleTimeoutMs","heartbeatMs","keepAliveMs","maxConcurrentRequests"].every((t)=>typeof e[t]==="number")}function Cn(e){return fe(e)&&Object.values(e).every(P)}function xt(e){let t;try{t=JSON.parse(e)}catch{return}if(!fe(t))return;switch(t.type){case"session":return P(t.sessionId)&&P(t.address)&&P(t.origin)&&P(t.expiresAt)&&Sn(t.limits)&&Array.isArray(t.grants)&&t.grants.every($t)&&(t.appName===void 0||P(t.appName))&&(t.pairing===void 0||P(t.pairing))?t:void 0;case"ping":return typeof t.t==="number"?t:void 0;case"bye":return{type:"bye",reason:P(t.reason)?t.reason:""};case"http.request":return P(t.id)&&P(t.method)&&P(t.path)&&Cn(t.headers)&&P(t.body)&&fe(t.grant)&&P(t.grant.grantId)&&P(t.grant.clientId)?t:void 0;case"http.cancel":return P(t.id)?t:void 0;case"pairing.code":{if(!P(t.code)||!P(t.expiresAt))return;let n={type:"pairing.code",code:t.code,expiresAt:t.expiresAt},r=t.reason;if(typeof r==="string"&&Mn.has(r))n.reason=r;return n}case"pairing.open":{let n=t.expiresInMs;if(typeof n==="number"&&Number.isFinite(n)&&n>=0&&n<=2147483647)return{type:"pairing.open",expiresAt:new Date(Date.now()+n).toISOString()};return P(t.expiresAt)&&!Number.isNaN(Date.parse(t.expiresAt))?{type:"pairing.open",expiresAt:t.expiresAt}:void 0}case"grant.added":return $t(t.grant)?t:void 0;case"grant.removed":return P(t.grantId)?{type:"grant.removed",grantId:t.grantId,reason:P(t.reason)?t.reason:""}:void 0;case"identity.bound":return typeof t.round==="number"?{type:"identity.bound",round:t.round}:{type:"identity.bound"};case"error":return P(t.code)?t:void 0;default:return}}function _n(e,t){let n=(r)=>r&&(r.callers?.includes(t)??!0);return{list:()=>e.list().filter(n),get:(r)=>{let o=e.get(r);return n(o)?o:void 0}}}function Je(e,t,n){let r=t.list();return e.onChange(()=>{let o=t.list();if(o.length===r.length&&o.every((a,s)=>a===r[s]))return;r=o,n()})}function Re(e,t){return{tools:t==="webmcp"?e.registry:_n(e.registry,t),confirm:(n)=>e.confirm(n),ownConfirm:!!e.onConfirm(),observe:{start:(n)=>e.toolCallStarted(n),end:(n)=>e.toolCallEnded(n)}}}var En=["content-type","cache-control"];function*Be(e,t){let n=0;while(n<e.length){let r=Math.min(n+t,e.length),o=e.charCodeAt(r-1);if(r<e.length&&o>=55296&&o<=56319)r+=r-1>n?-1:1;yield e.slice(n,r),n=r}}var An=-31002,On="The page did not answer in time.";function Pn(e){try{let t=JSON.parse(e)?.id;return typeof t==="string"||typeof t==="number"?t:null}catch{return null}}function Ue(e){let{handler:t,send:n,timeoutMs:r}=e,o=new Map,a=!1;async function s(i){let u=new AbortController;o.get(i.id)?.abort(),o.set(i.id,u);let v=()=>!a&&o.get(i.id)===u&&!u.signal.aborted,k=!1,M="",S=Object.entries(i.headers).some(([_,O])=>_.toLowerCase()==="mcp-method"&&O==="subscriptions/listen"),N=r===void 0||S?void 0:setTimeout(()=>{if(!v())return;u.abort();let _=JSON.stringify({jsonrpc:"2.0",id:Pn(i.body),error:{code:An,message:On}});if(!k){n({type:"http.response",id:i.id,status:200,headers:{"content-type":"application/json"},body:_});return}if(M===""||M===`
|
|
10
|
-
|
|
11
|
-
`)n({type:"http.response.chunk",id:i.id,data:`event: message
|
|
12
|
-
data: ${_}
|
|
13
|
-
|
|
14
|
-
`});n({type:"http.response.end",id:i.id})},r);try{let _=new Request(`https://tab.invalid${i.path}`,{method:i.method,headers:i.headers,signal:u.signal}),O=await t.handle(_,{grant:i.grant,body:i.body});if(!v()){await O.body?.cancel().catch(()=>{});return}let q={};for(let w of En){let h=O.headers.get(w);if(h!==null)q[w]=h}let U=(q["content-type"]??"").startsWith("text/event-stream"),f=e.maxChunk();if(!U||O.body===null){let w=await O.text();if(!v())return;if(w.length<=f){n({type:"http.response",id:i.id,status:O.status,headers:q,body:w});return}n({type:"http.response.start",id:i.id,status:O.status,headers:q});for(let h of Be(w,f)){if(!v())break;n({type:"http.response.chunk",id:i.id,data:h})}if(v())n({type:"http.response.end",id:i.id});return}n({type:"http.response.start",id:i.id,status:O.status,headers:q}),k=!0;let y=O.body.getReader(),g=new TextDecoder;u.signal.addEventListener("abort",()=>{y.cancel().catch(()=>{})});for(;;){let{done:w,value:h}=await y.read();if(w||!v())break;let R=g.decode(h,{stream:!0});if(R!=="")M=(M+R).slice(-2);for(let A of Be(R,f))n({type:"http.response.chunk",id:i.id,data:A})}if(v())n({type:"http.response.end",id:i.id})}catch(_){if(v())e.error(_ instanceof Error?_:Error(String(_))),n({type:"http.response",id:i.id,status:500,headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32603,message:"Internal server error"}})})}finally{if(clearTimeout(N),o.get(i.id)===u)o.delete(i.id)}}return{request(i){if(!a)s(i)},cancel(i){o.get(i)?.abort(),o.delete(i)},close(){if(a)return;a=!0;for(let i of o.values())i.abort();o.clear()}}}var Nn=65536,vt=64,jn=300000,Tt=128,ze=new WeakSet,qn=0,F=(e)=>typeof e==="string";function De(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Hn(e,t,n){let r=n?.client;if(!De(r)||!F(r.id)||r.id===""||r.name!==void 0&&!F(r.name))throw TypeError("serve: client needs an id (and may have a name)");let o=n.maxChunk??Nn;if(!Number.isInteger(o)||o<vt)throw TypeError(`serve: maxChunk must be a whole number of at least ${vt}`);let a=n.requestTimeoutMs??jn;if(typeof a!=="number"||!(a>0)||a>=2147483648)throw TypeError("serve: requestTimeoutMs must be milliseconds above 0 and below 2^31");let s=n.onConfirm;if(s!==void 0&&typeof s!=="function")throw TypeError("serve: onConfirm must be a function");if(typeof t?.postMessage!=="function"||!("onmessage"in t))throw TypeError("serve: the port needs postMessage and onmessage");if(ze.has(t))throw new DOMException("serve: this port is served already; close that first","InvalidStateError");let i={kind:"local",id:r.id};if(r.name!==void 0&&r.name!=="")i.name=r.name;let u={grantId:`local:${++qn}`,clientId:r.id,scopes:["tools"]},v=!1,k=(y)=>{if(v)return!1;try{return t.postMessage(y),!0}catch{return!1}},M=Re(e,"local");if(s!==void 0)M.confirm=(y)=>Promise.resolve().then(()=>s(y)).then((g)=>g==="unanswered"?g:g===!0),M.ownConfirm=!0;let S=Te({...M,server:{...e.server,icons:e.server.icons??we()},client:()=>({...i})}),N=Je(e.registry,M.tools,()=>S.toolsChanged()),_=Ue({handler:S,send:k,maxChunk:()=>o,error:(y)=>e.error(y),timeoutMs:a}),O=(y,g)=>{let w={type:"error",code:"bad_message",message:y};if(F(g)&&g.length<=Tt)w.id=g;k(w)},q=(y)=>{if(v)return;let g=y?.data;if(!De(g)||!F(g.type)){O("not a message");return}let w=g.id;switch(g.type){case"http.request":{let{method:h,path:R,headers:A,body:E}=g;if(!F(w)||w===""||w.length>Tt||!F(h)||!F(R)||!R.startsWith("/")||!De(A)||!Object.values(A).every(F)||!F(E)){O("malformed http.request",w);return}_.request({type:"http.request",id:w,method:h,path:R,headers:A,body:E,grant:u});return}case"http.cancel":if(F(w))_.cancel(w);else O("malformed http.cancel");return;case"error":return;default:O(`unexpected ${g.type.slice(0,64)}`,w)}},U=t,f=()=>{if(v)return;if(n.signal?.removeEventListener("abort",f),U.removeEventListener?.("close",f),N(),_.close(),S.close(),ze.delete(t))k({type:"bye",reason:"closed"});if(v=!0,t.onmessage===q)t.onmessage=null};if(n.signal?.aborted===!0)return f(),{close:f};return n.signal?.addEventListener("abort",f),U.addEventListener?.("close",f),ze.add(t),t.onmessage=q,{close:f}}function zn(e){let t="",n=0,r=0;for(let o of e){n=n<<8|o,r+=8;while(r>=5)r-=5,t+="abcdefghijklmnopqrstuvwxyz234567"[n>>>r&31];n&=(1<<r)-1}if(r>0)t+="abcdefghijklmnopqrstuvwxyz234567"[n<<5-r&31];return t}async function Dn(e,t=globalThis.crypto?.subtle??null){if(t===null)return;try{let n=await t.digest("SHA-256",new TextEncoder().encode(e));return zn(new Uint8Array(n))}catch{return}}function wr(e,t,n,r,o){let a=Re(e,"webmcp");return o===void 0?He({...a,confirm:e.onConfirm()??(()=>!0)},t,n,r,{kind:"webmcp"}):He({...a,confirm:()=>!0},t,n,r,{kind:"webmcp",via:"tab-mcp-extension",name:o.name,host:o.host})}var Bn=15000,kt={1000:"closed",1001:"shutdown",1008:"policy",1009:"too_large",1011:"shutdown",1012:"shutdown",1013:"shutdown",4001:"expired",4002:"idle",4003:"heartbeat",4004:"shutdown",4005:"replaced",4008:"rate_limited"},Rt={replaced:"replaced",expired:"expired",idle:"idle",shutdown:"shutdown"};function de(e,t){return Object.assign(Error(e),{reason:t})}var It=512,Mt=6,St=64,Jn=It+Mt*St;function Un(e){let t=Math.floor((e-It)/Mt);return t>=St?t:void 0}var Vn=1e4;function Gn(e,t,n){let r,o=!1,a=Number.NEGATIVE_INFINITY,s;try{if(e!==void 0&&typeof BroadcastChannel==="function")r=new BroadcastChannel(e),r.onmessage=(i)=>{let u=i.data;if(!o||u?.type!=="claimed"||u.address!==void 0&&u.address!==t)return;a=Date.now(),s?.()}}catch{r=void 0}return{claimed(){o=!0;try{r?.postMessage({type:"claimed",address:t})}catch{}},heard(){if(Date.now()-a<=Vn)return Promise.resolve(!0);if(r===void 0)return Promise.resolve(!1);return new Promise((i)=>{let u=setTimeout(()=>i(!1),n);s=()=>{clearTimeout(u),i(!0)}})},close(){r?.close()}}}function $r(e,t,n,r,o){return new Promise((a,s)=>{let i=["grantschange","statechange","error"],u=(M)=>{clearTimeout(k);for(let S of i)e.removeEventListener(S,v);if(M)s(M);else a()},v=(M)=>{let S=M?.detail?.error;if(n())u();else if((S?.code==="store_unavailable"||S?.code==="unknown_id")&&(S.for===void 0||S.for===t.type&&S.grantId===t.grantId))u(S);else if(!r())u(new DOMException("TabMcp: the session ended before the relay answered","NetworkError"))},k=setTimeout(()=>u(new DOMException("TabMcp: the relay did not answer","TimeoutError")),o);for(let M of i)e.addEventListener(M,v);v()})}function xr(e){let t=globalThis,n=globalThis.document,r=()=>{if(n?.visibilityState!=="hidden")e()};return n?.addEventListener("visibilitychange",r),t.addEventListener?.("online",e),()=>{n?.removeEventListener("visibilitychange",r),t.removeEventListener?.("online",e)}}function vr(e,t,n,r){let o=r.revokeAll===!0,a=new WebSocket(t,ke),s="opening",i,u=65536,v,k,M=0,S=Gn(e.tabs,r.address,r.siblingGraceMs),N,_,O=new Promise((d,C)=>{N=d,_=C});O.catch(()=>{});let q=setTimeout(()=>{h(de("The relay did not answer in time.","network"))},Bn),U=Re(e,"relay"),f=Te({...U,server:{...e.server,icons:e.server.icons??we()},client:(d)=>e.clientFor(d),maxBodyBytes:()=>v}),y=Je(e.registry,U.tools,()=>f.toolsChanged());function g(d){if(a.readyState!==WebSocket.OPEN)return!1;try{return a.send(JSON.stringify(d)),!0}catch{return!1}}function w(){if(M<=0)return;clearTimeout(k),k=setTimeout(()=>{i??="heartbeat",R(4003);try{a.close()}catch{}},M*2.5)}function h(d){if(s!=="opening")return;R(0),_(d);try{a.close()}catch{}}function R(d){if(s==="closed")return;let C=s==="ready";if(s="closed",clearTimeout(q),clearTimeout(k),y(),A.close(),f.close(),C){let H=i??kt[d]??(d===1006?"network":"closed");if(e.closed(H,d),H==="replaced"){S.heard().then((z)=>{S.close(),e.replaced({sibling:z})});return}}S.close()}let A=Ue({handler:f,send:g,maxChunk:()=>u,error:(d)=>e.error(d)});function E(d){if(s==="opening"){if(d.type==="session"){let C=Un(d.limits.maxMessageBytes);if(C===void 0){h(de(`The relay's message limit (${d.limits.maxMessageBytes} bytes) is too small; tab-mcp needs at least ${Jn}.`,"policy"));return}if(o&&d.grants.length>0){h(de("The relay did not revoke the address's grants (it needs tab-mcp 0.5 or later).","policy"));return}u=C,v=d.limits.maxBodyBytes,s="ready",clearTimeout(q),M=d.limits.heartbeatMs,w(),S.claimed(),N(e.sessionStarted(d))}else if(d.type==="error")h(de(`The relay refused the connection: ${d.message||d.code}`,d.code==="rate_limited"?"rate_limited":"policy"));else if(d.type==="bye")h(de(`The relay ended the connection: ${d.reason}`,Rt[d.reason]??"closed"));return}if(s!=="ready")return;switch(d.type){case"ping":w(),g({type:"pong",t:d.t});return;case"http.request":A.request(d);return;case"http.cancel":A.cancel(d.id);return;case"pairing.code":e.pairingCode(d.reason===void 0?{code:d.code,expiresAt:d.expiresAt}:{code:d.code,expiresAt:d.expiresAt,reason:d.reason});return;case"pairing.open":e.pairingOpen(d.expiresAt);return;case"grant.added":e.grantAdded(d.grant);return;case"grant.removed":e.grantRemoved(d.grantId);return;case"identity.bound":e.identityResult(!0,d.round);return;case"bye":if(i=Rt[d.reason]??"closed",i==="replaced")R(4005);return;case"error":if(d.code==="identity_refused"){e.identityResult(!1,typeof d.round==="number"?d.round:void 0,d.message);return}if(d.code==="unknown_id"&&d.for==="grant.revoke"&&typeof d.grantId==="string")e.grantRemoved(d.grantId);e.error(Object.assign(Error(`Relay error ${d.code}: ${d.message}`),{code:d.code},typeof d.for==="string"?{for:d.for}:{},typeof d.grantId==="string"?{grantId:d.grantId}:{}));return;case"session":return}}return a.addEventListener("open",()=>{if(a.protocol!==""&&a.protocol!==ke){h(de(`The relay speaks ${a.protocol}, not ${ke}.`,"policy"));return}g({type:"hello",library:e.library,app:e.appName===void 0?{id:e.app}:{id:e.app,name:e.appName},secret:n,...o?{revokeAll:!0}:{}})}),a.addEventListener("message",(d)=>{if(typeof d.data!=="string")return;let C=xt(d.data);if(C===void 0)return;if(s==="ready")w();E(C)}),a.addEventListener("close",(d)=>{if(s==="opening"){R(d.code);let C=d.code===1006||d.code===1002;_(de(C?"Could not connect to the relay (refused, unreachable, or this page's origin is not allowed).":`The relay closed the connection (${d.code}${d.reason?`: ${d.reason}`:""}).`,kt[d.code]??(C?"network":"closed")));return}R(d.code)}),{ready:O,send:g,close(d){if(s==="closed")return;if(s==="opening"){h(new DOMException("The connection was cancelled","AbortError"));return}i=d,g({type:"bye",reason:"user"}),R(1000);try{a.close(1000,"bye")}catch{}}}}export{Jn as MIN_MESSAGE_BYTES,Vn as SIBLING_WINDOW_MS,Dn as addressIdOf,$r as answer,wr as callFromWebMcp,Un as chunkSize,bn as compileRegistry,xr as onWake,vr as openConnection,Be as pieces,Hn as servePort};
|
|
15
|
-
|
|
16
|
-
//# debugId=9EC9A7C83CEB560164756E2164756E21
|
|
17
|
-
//# sourceMappingURL=connection-m0e4xvcy.min.js.map
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var m=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),y=(e)=>typeof e==="string"&&e.length<=256;function C(e){return m(e)&&y(e.name)&&y(e.host)?{name:e.name,host:e.host}:void 0}function g(e){return JSON.stringify(e,(n,o)=>m(o)?Object.fromEntries(Object.entries(o).sort(([s],[r])=>s<r?-1:s>r?1:0)):o)??""}var T=()=>performance.now();class H{#o;#n=[];#t;#e=[];constructor(e){this.#o=e,e.addEventListener("tab-mcp-extension",(n)=>this.#i(n.detail)),e.documentElement?.setAttribute("data-tab-mcp-handshake","1")}join(e){if(this.#n.push(e),this.#t!==void 0)e.set(this.#t);e.mcp.addEventListener("grantschange",()=>this.#s(e,"update")),this.#s(e,"hello")}#s(e,n){let o=this.#o.defaultView?.CustomEvent??CustomEvent;this.#o.dispatchEvent(new o("tab-mcp-page",{detail:JSON.stringify({v:1,type:n,library:e.version,app:e.app,apps:e.mcp.grants.slice(0,64).map((s)=>({name:s.client.name,host:s.client.host}))})}))}#i(e){let n;try{n=typeof e==="string"?JSON.parse(e):void 0}catch{return}if(!m(n)||n.v!==1)return;if(n.type==="vouch")this.#a(n);else if(n.type==="withdraw")this.#e=this.#e.filter((o)=>o.nonce!==n.nonce);else if(n.type==="hello"||n.type==="update"){let o=v(n);if(o===null)return;if(g(o)!==g(this.#t)){this.#t=o;for(let s of this.#n)s.set(o)}if(n.type==="hello")for(let s of this.#n)this.#s(s,"update")}}#a(e){let n=C(e.app),{tool:o,nonce:s}=e;if(n===void 0||typeof o!=="string"||typeof s!=="string"||!m(e.arguments))return;if(this.#r(),this.#e.some((r)=>r.nonce===s))return;for(let r of this.#n){let c=r.trust?r.registry.get(o):void 0;if(c===void 0)continue;if(this.#e.push({tool:c,args:g(e.arguments),nonce:s,app:n,at:T()}),this.#e.length>16)this.#e.shift();return}}#r(){let e=T();this.#e=this.#e.filter((n)=>e-n.at<=2000)}take(e,n){this.#r();let o=g(n),s=this.#e.findIndex((r)=>r.tool===e&&r.args===o);return s<0?void 0:this.#e.splice(s,1)[0]?.app}}function v(e){if(e.on!==!0)return e.on===!1?void 0:null;let{name:n,apps:o}=e;if(!y(n)||!Array.isArray(o))return null;let s=o.slice(0,64).map(C);if(s.some((r)=>r===void 0))return null;return Object.freeze({name:n,apps:Object.freeze(s.map((r)=>Object.freeze(r))),whileInFront:e.whileInFront!==!1})}var A=new WeakMap;function P(e){let n=globalThis.document;if(n===void 0||globalThis.top!==globalThis.window)return;let o=A.get(n);if(o===void 0)o=new H(n),A.set(n,o);return o.join(e),o}var O=["readOnlyHint","untrustedContentHint","consequentialHint","debugging"];function _(e,n,o,s,r,c,S){let w;Object.defineProperty(s,"extension",{get:()=>w,configurable:!0});let k;try{k=P({version:S,app:r,registry:e,trust:c.trustExtension!==!1,mcp:s,set:(t)=>{w=t,s.dispatchEvent(new CustomEvent("extensionchange",{detail:{extension:t}}))}})}catch(t){console.warn("tab-mcp: no handshake with the browser extension:",t)}let u=new Map,b=new Set,x=new Set,M=(t,i)=>{try{let l=c.onConfirm,h=globalThis.document?.location?.origin,d=(Array.isArray(t.exposedTo)?t.exposedTo:[]).filter((f)=>{try{return new URL(String(f)).origin!==h}catch{return!1}});if(i!==!0||d.length===0||l&&l.own!==!1||x.has(t.name))return;x.add(t.name),console.warn(`tab-mcp: ${t.name} asks before it runs, but documents of ${d.join(", ")} (its exposedTo) can call it through WebMCP without a question: the library asks no WebMCP caller. Refuse such calls in onConfirm, or leave exposedTo off.`)}catch{}},E=()=>{for(let[t,i]of u){if(e.get(t.name)===t)continue;i.abort(),u.delete(t)}for(let t of e.list()){let{annotations:i,callers:l}=t,h=i.consequentialHint??i.destructiveHint;if(u.has(t)||!(l?.includes("webmcp")??!0))continue;let d=new AbortController;u.set(t,d);let f={consequentialHint:h};for(let a of O)f[a]??=i[a];let{signal:p}=d;Promise.resolve().then(()=>p.aborted||n.registerTool({name:t.name,title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:f,execute:(a,R)=>o(t,a,R?.signal,k?.take(t,a))},{signal:p,exposedTo:t.exposedTo})).then(()=>{if(!p.aborted)M(t,h)}).catch((a)=>{if(p.aborted)return;if(b.has(t.name))return;b.add(t.name),console.warn(`tab-mcp: ${t.name} is not offered through WebMCP:`,a)})}};e.onChange(E),E()}export{_ as mirror};
|
|
2
|
-
|
|
3
|
-
//# debugId=3CC1FE038CA43E8F64756E2164756E21
|
|
4
|
-
//# sourceMappingURL=webmcp-vqs5smxj.min.js.map
|