@ractive-ch/tab-mcp-client 0.14.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +538 -126
- package/always-allowed.d.ts +25 -6
- package/cdn/confirm-y30cx7e1.min.js +4 -0
- package/cdn/confirm-y30cx7e1.min.js.map +10 -0
- package/cdn/connect-bbhj2y7w.min.js +6 -0
- package/cdn/connect-bbhj2y7w.min.js.map +12 -0
- package/cdn/connection-0y7ngtq7.min.js +17 -0
- package/cdn/connection-0y7ngtq7.min.js.map +22 -0
- package/cdn/index-vt5zk9me.min.js +91 -0
- package/cdn/index-vt5zk9me.min.js.map +13 -0
- package/cdn/tab-mcp-client.min.js +3 -3
- package/cdn/tab-mcp-client.min.js.map +6 -6
- package/confirm-fgnjgd08.js +263 -0
- package/confirm-fgnjgd08.js.map +10 -0
- package/confirm.d.ts +54 -0
- package/connect-8jpb0k29.js +484 -0
- package/connect-8jpb0k29.js.map +10 -0
- package/connect.d.ts +40 -0
- package/{connection-eqsag07j.js → connection-1d8rxgbq.js} +515 -242
- package/connection-1d8rxgbq.js.map +16 -0
- package/connection.d.ts +9 -9
- package/dialog.d.ts +83 -0
- package/{index-nmn1j689.js → index-5jyqehpk.js} +14 -10
- package/index-5jyqehpk.js.map +11 -0
- package/index-jnz7w9xa.js +392 -0
- package/index-jnz7w9xa.js.map +12 -0
- package/index.d.ts +1 -1
- package/index.js +285 -244
- package/index.js.map +6 -6
- package/mapping.d.ts +37 -4
- package/mcp.d.ts +23 -8
- package/package.json +5 -1
- package/react.d.ts +13 -12
- package/react.js +20 -14
- package/react.js.map +3 -3
- package/registry.d.ts +12 -5
- package/secret.d.ts +5 -2
- package/serve.d.ts +68 -0
- package/setup.d.ts +15 -25
- package/setup.js +1 -1
- package/strings.d.ts +107 -0
- package/tab-mcp.d.ts +76 -36
- package/tunnel.d.ts +74 -0
- package/tunnel.js +263 -0
- package/tunnel.js.map +10 -0
- package/types.d.ts +206 -73
- package/webmcp.d.ts +13 -18
- package/cdn/connection-dweyrdbn.min.js +0 -12
- package/cdn/connection-dweyrdbn.min.js.map +0 -21
- package/cdn/ui-5zecjy7s.min.js +0 -86
- package/cdn/ui-5zecjy7s.min.js.map +0 -14
- package/connection-eqsag07j.js.map +0 -15
- package/index-nmn1j689.js.map +0 -11
- package/ui-4qv8d1a3.js +0 -781
- package/ui-4qv8d1a3.js.map +0 -11
- package/ui.d.ts +0 -83
package/README.md
CHANGED
|
@@ -6,9 +6,11 @@ Offer a web page's functions as [MCP](https://modelcontextprotocol.io) tools to
|
|
|
6
6
|
gets an address. The user adds that address to their AI app and types a pairing code
|
|
7
7
|
from the page; the AI app then calls the page's tools while the tab stays open. Nothing
|
|
8
8
|
is installed on the user's computer. With `webmcp: true` the library also registers the
|
|
9
|
-
tools with the browser's own [WebMCP](#webmcp), for agents in the browser.
|
|
9
|
+
tools with the browser's own [WebMCP](#webmcp), for agents in the browser. A site's own
|
|
10
|
+
assistant can call the same tools over a port, without a relay:
|
|
11
|
+
[Your own assistant on the page](#your-own-assistant-on-the-page).
|
|
10
12
|
|
|
11
|
-
**Status: 0.
|
|
13
|
+
**Status: 0.16.0.** Until 1.0, a new minor version can still change the API. Which AI apps
|
|
12
14
|
work is listed in [compatibility](https://github.com/ractive/tab-mcp/blob/main/docs/compatibility.md).
|
|
13
15
|
|
|
14
16
|
## You need a relay
|
|
@@ -24,12 +26,15 @@ docker run --rm -p 8080:8080 \
|
|
|
24
26
|
-e TAB_MCP_PUBLIC_URL=http://localhost:8080 \
|
|
25
27
|
-e TAB_MCP_ALLOWED_ORIGINS=http://localhost:3000 \
|
|
26
28
|
-e TAB_MCP_STORE=memory \
|
|
27
|
-
ractive/tab-mcp:0.
|
|
29
|
+
ractive/tab-mcp:0.10.1
|
|
28
30
|
```
|
|
29
31
|
|
|
30
32
|
For production, see
|
|
31
33
|
[self-hosting](https://github.com/ractive/tab-mcp/blob/main/docs/self-hosting.md).
|
|
32
34
|
|
|
35
|
+
A page that offers its tools only to its own assistant (`serve`) or to agents in the
|
|
36
|
+
browser (`webmcp`) needs no relay: leave `relay` out.
|
|
37
|
+
|
|
33
38
|
## Install
|
|
34
39
|
|
|
35
40
|
```sh
|
|
@@ -40,7 +45,7 @@ Or without a bundler, from a CDN as an ES module:
|
|
|
40
45
|
|
|
41
46
|
```html
|
|
42
47
|
<script type="module">
|
|
43
|
-
import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.
|
|
48
|
+
import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.16.0/cdn/tab-mcp-client.min.js";
|
|
44
49
|
</script>
|
|
45
50
|
```
|
|
46
51
|
|
|
@@ -83,26 +88,65 @@ PNG, JPEG, GIF, WebP or ICO `data:` URIs up to 16 KiB (no inline SVG). They go o
|
|
|
83
88
|
|
|
84
89
|
### Tools
|
|
85
90
|
|
|
86
|
-
`registerTool(tool, { signal,
|
|
87
|
-
`registerTool` (`
|
|
91
|
+
`registerTool(tool, { signal, callers, exposedTo })` takes a tool in the shape of the
|
|
92
|
+
WebMCP draft's `registerTool` (`callers`: [which callers see a tool](#which-callers-see-a-tool);
|
|
93
|
+
`exposedTo`: see [WebMCP](#webmcp)):
|
|
88
94
|
|
|
89
95
|
- `name` (1-128 characters of `A-Z a-z 0-9 _ - .`), `title`, `description` (not empty);
|
|
90
96
|
- `inputSchema`: a JSON Schema with `"type": "object"`. Arguments are checked against it
|
|
91
97
|
before `execute` runs. `registerTool` rejects a schema the validator cannot use (a
|
|
92
|
-
pattern that is not a regular expression, a `$ref` that does not resolve
|
|
98
|
+
pattern that is not a regular expression, a `$ref` that does not resolve; values of
|
|
99
|
+
`default`, `examples`, `const` and `enum` are data and are not read as schema). The
|
|
93
100
|
validator itself is loaded by `connect()`: from then on it checks each schema at
|
|
94
101
|
registration too, and a tool registered earlier whose schema it refuses (for example a
|
|
95
102
|
`$ref` next to a nested `$id`) is unregistered, with the reason in the event `error`;
|
|
103
|
+
- `outputSchema` (optional): a JSON Schema with `"type": "object"` for the result, listed
|
|
104
|
+
to AI apps (`tools/list`) and passed on to WebMCP. `registerTool` checks it as it checks
|
|
105
|
+
`inputSchema` (an AI app compiles it when it lists the tools, and one that does not
|
|
106
|
+
compile can cost the whole list), but results are not checked against it. An AI app
|
|
107
|
+
expects every result of such a tool to carry
|
|
108
|
+
`structuredContent` that matches it (the MCP SDK's client refuses one without), so
|
|
109
|
+
`execute` returns a plain object, not a string;
|
|
96
110
|
- `execute(input, { signal, client })`: runs the tool. `signal` aborts when the caller
|
|
97
|
-
gives up
|
|
98
|
-
|
|
99
|
-
|
|
111
|
+
gives up (or a served call takes too long); the call ends then, also if `execute` does
|
|
112
|
+
not stop, and what it returns later is dropped. `client` names the caller: `{ kind: "relay", grantId, id, host, name? }` for
|
|
113
|
+
an AI app through the relay (`id`, verified `host`, declared `name`),
|
|
114
|
+
`{ kind: "local", id, name? }` for the site's own assistant on a served port, with the
|
|
115
|
+
`id` and `name` the page gave `serve` ([Your own assistant](#your-own-assistant-on-the-page)),
|
|
116
|
+
or `{ kind: "webmcp" }` for an agent in the browser ([WebMCP](#webmcp)), of which nothing
|
|
100
117
|
more is known. Check `client.kind` before you read `host`. Return a
|
|
101
|
-
string (one text block), an MCP result with
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
118
|
+
string (one text block), an MCP result (passed through with its `_meta`: an object
|
|
119
|
+
whose `content` is an array of MCP content blocks, each with `type` `text`, `image`,
|
|
120
|
+
`audio`, `resource_link` or `resource` and the fields that type needs), or any other JSON value (sent as JSON text,
|
|
121
|
+
and as `structuredContent` when that JSON is an object; a `Date` becomes a string, so
|
|
122
|
+
it has none). Data that only looks like a result, such as a ProseMirror document with
|
|
123
|
+
its `content` array, is sent as JSON. A thrown error becomes an error result with its
|
|
124
|
+
message;
|
|
125
|
+
- `annotations`: the WebMCP hints `readOnlyHint`, `consequentialHint`,
|
|
126
|
+
`untrustedContentHint` and `debugging` (a tool meant for the page's developers), and
|
|
127
|
+
the MCP hints `destructiveHint`, `idempotentHint`, `openWorldHint`. A hint must be
|
|
128
|
+
`true` or `false`: `registerTool` rejects any other value with a `TypeError`, since a
|
|
129
|
+
`consequentialHint: "true"` that was dropped would run the tool without asking. MCP has
|
|
130
|
+
no `untrustedContentHint`: every result of such a tool carries a marker in its `_meta`
|
|
131
|
+
([untrusted results](#untrusted-results)).
|
|
132
|
+
|
|
133
|
+
Where `registerTool` differs from the WebMCP draft's (of 12 November 2026), so that code
|
|
134
|
+
written for the native API behaves differently here:
|
|
135
|
+
|
|
136
|
+
- An invalid name, an empty description or an invalid schema is a `TypeError`; the
|
|
137
|
+
draft rejects the first two with an `InvalidStateError`. A duplicate name is an
|
|
138
|
+
`InvalidStateError` in both.
|
|
139
|
+
- `inputSchema` and `outputSchema` need `"type": "object"`, as MCP does; the draft takes
|
|
140
|
+
any object. The library also checks `inputSchema`'s patterns and `$ref`s (above).
|
|
141
|
+
- The library checks the arguments against `inputSchema` before `execute` runs; the
|
|
142
|
+
draft leaves that to the page.
|
|
143
|
+
- `execute` may return an MCP result; through WebMCP it goes out as its
|
|
144
|
+
`structuredContent` or its text ([WebMCP](#webmcp)).
|
|
145
|
+
- `exposedTo` matters only for WebMCP: it is passed on to the native registration of a
|
|
146
|
+
mirrored tool, and AI apps never see it.
|
|
147
|
+
|
|
148
|
+
An already aborted `signal` rejects with its reason and registers nothing, as in the
|
|
149
|
+
draft.
|
|
106
150
|
|
|
107
151
|
In TypeScript, `Tool<Input>` types the `input` of `execute`, and `registerTool` and
|
|
108
152
|
`useTool` infer it from the tool or take it explicitly
|
|
@@ -123,26 +167,42 @@ where the browser has it, so that agents in the browser can call them: an agent
|
|
|
123
167
|
into the browser, or an extension. Off by default. Turning it on is a change in what the
|
|
124
168
|
page exposes: any agent in the browser can then call the mirrored tools without pairing.
|
|
125
169
|
Chrome has WebMCP for sites in its
|
|
126
|
-
[origin trial](https://developer.chrome.com/blog/ai-webmcp-origin-trial) (
|
|
127
|
-
|
|
128
|
-
([Chrome's WebMCP docs](https://developer.chrome.com/docs/ai/webmcp)).
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
170
|
+
[origin trial](https://developer.chrome.com/blog/ai-webmcp-origin-trial) (Chrome 149 to
|
|
171
|
+
162; a site needs a trial token) and with `chrome://flags/#enable-webmcp-testing`
|
|
172
|
+
([Chrome's WebMCP docs](https://developer.chrome.com/docs/ai/webmcp)). Without either,
|
|
173
|
+
`webmcp: true` does nothing. Each `new TabMcp` looks for WebMCP when it is made, so a
|
|
174
|
+
trial token that a script adds later counts for a `TabMcp` made after it.
|
|
175
|
+
|
|
176
|
+
- Tools marked `consequentialHint`, or MCP's `destructiveHint`, are left out unless
|
|
177
|
+
their registration lists `"webmcp"` in `callers` (`{ callers: ["relay", "webmcp"] }`):
|
|
178
|
+
an agent in the browser often drives the very tab it calls into, so it can click Allow
|
|
179
|
+
in the page's confirmation itself. `callers` without `"webmcp"` keeps any tool out of
|
|
180
|
+
WebMCP ([which callers see a tool](#which-callers-see-a-tool)). A tool marked only
|
|
181
|
+
`destructiveHint: true` is registered natively with `consequentialHint: true`, since
|
|
182
|
+
WebMCP has no `destructiveHint` (DEC-022 maps the other way).
|
|
183
|
+
- The native registration gets the WebMCP fields: `name`, `title`, `description`,
|
|
184
|
+
`inputSchema`, `outputSchema` and the WebMCP hints, and `exposedTo` from
|
|
185
|
+
`registerTool`'s options (origins of other documents in the tab that may see the
|
|
186
|
+
tool; the browser checks it, and an invalid list only warns, as below).
|
|
134
187
|
- A WebMCP call takes the same path as an AI app's: the arguments are checked against
|
|
135
188
|
`inputSchema` (Chrome does not check them), a consequential tool asks (`onConfirm`, or
|
|
136
189
|
the library's dialog, which names the caller "An agent in this browser"), and
|
|
137
|
-
`toolcall` and `toolcallend` fire with `client: { kind: "webmcp" }`. "
|
|
190
|
+
`toolcall` and `toolcallend` fire with `client: { kind: "webmcp" }`. "Allow until reload" is
|
|
138
191
|
never offered or applied for these calls: there is no identity to remember it for.
|
|
139
|
-
- The call resolves with what `execute` returned
|
|
192
|
+
- The call resolves with what `execute` returned, which the browser hands the agent as
|
|
193
|
+
JSON text. An MCP result goes out as its `structuredContent` if it has one, else as
|
|
194
|
+
its text blocks, one per line, each other block (an image, a resource) as a line that
|
|
195
|
+
says it was left out: WebMCP results are text, and an image as base64 inside JSON
|
|
196
|
+
costs the agent tokens for nothing. Nothing (`undefined`), which the browser cannot
|
|
197
|
+
serialize, and an empty MCP result resolve as `"Done."`.
|
|
198
|
+
- A failure resolves too, as
|
|
140
199
|
`{ error: "<message>" }`, so that the agent can read it: invalid arguments (the same
|
|
141
200
|
message as for an AI app), "Don't allow" (`The user did not allow <tool> to run.`), a
|
|
142
201
|
question not answered (`The user did not answer whether <tool> may run.`), a tool that
|
|
143
202
|
is gone, an error thrown by `execute` (its message) and an MCP result with
|
|
144
|
-
`isError: true` (its text). A rejection would not help:
|
|
145
|
-
every rejection as
|
|
203
|
+
`isError: true` (its text). A rejection would not help: the draft hands the agent
|
|
204
|
+
every rejection as an `OperationError` without its message, on purpose (a failure the
|
|
205
|
+
agent should read belongs in the result), and Chrome 156 as `UnknownError`. Two cases still
|
|
146
206
|
reject: a call the browser cancelled (`AbortError`), since its caller no longer waits
|
|
147
207
|
for an answer, and a call made when the library's lazily loaded part cannot be loaded
|
|
148
208
|
(a new deploy with other chunk names while the page stays open, the network, a
|
|
@@ -158,14 +218,245 @@ Chrome has WebMCP for sites in its
|
|
|
158
218
|
schema.
|
|
159
219
|
- A failed native registration only warns in the console, once per tool, and the tool
|
|
160
220
|
stays offered through the relay; it is tried again only when the tool is registered
|
|
161
|
-
again
|
|
221
|
+
again (a browser that unregisters a tool some time after its abort would refuse a
|
|
222
|
+
registration of the same name at once after it, as a duplicate; Chrome unregisters at
|
|
223
|
+
once): a name the page or another script already registered
|
|
162
224
|
natively keeps its owner, and a frame without `allow="tools"` refuses all. The other
|
|
163
225
|
way round, once a name is mirrored, the page's own native `registerTool()` of that name
|
|
164
226
|
fails: a page that registers tools natively itself leaves `webmcp` off or uses other
|
|
165
227
|
names.
|
|
166
|
-
-
|
|
167
|
-
|
|
168
|
-
the extension.
|
|
228
|
+
- tab-mcp for Chrome offers mirrored tools like any page tool, since it cannot know
|
|
229
|
+
whether the AI app is also paired with the page, so an AI app connected to the page and
|
|
230
|
+
to the extension sees such a tool twice.
|
|
231
|
+
|
|
232
|
+
### Your own assistant on the page
|
|
233
|
+
|
|
234
|
+
A site with its own AI assistant can let it use the page's tools without a relay,
|
|
235
|
+
pairing or an address. `mcp.serve(port, { client })` answers MCP requests on a message
|
|
236
|
+
port, and `createTunnelFetch` (`@ractive-ch/tab-mcp-client/tunnel`) is a `fetch` for the
|
|
237
|
+
other end. The port carries the relay's `http.*` messages
|
|
238
|
+
([protocol](https://github.com/ractive/tab-mcp/blob/main/docs/protocol.md#the-tunnel-without-a-relay))
|
|
239
|
+
as plain objects, so anything that passes them on in order will do. A usual setup: the
|
|
240
|
+
assistant's chat runs in an iframe on the page, and its backend, which already holds a
|
|
241
|
+
WebSocket to that chat, runs the MCP client.
|
|
242
|
+
|
|
243
|
+
The page, without `relay`:
|
|
244
|
+
|
|
245
|
+
```ts
|
|
246
|
+
import { TabMcp } from "@ractive-ch/tab-mcp-client";
|
|
247
|
+
|
|
248
|
+
const mcp = new TabMcp({ server: { name: "shop", version: "1.0.0" } });
|
|
249
|
+
await mcp.registerTool({ name: "add_to_cart", description: "…", execute: addToCart });
|
|
250
|
+
|
|
251
|
+
const chat = document.querySelector<HTMLIFrameElement>("#chat")!;
|
|
252
|
+
let served: { close(): void } | undefined;
|
|
253
|
+
addEventListener("message", async (event) => {
|
|
254
|
+
// Only the chat's frame, on the chat's origin, gets a port.
|
|
255
|
+
if (event.origin !== "https://chat.example" || event.source !== chat.contentWindow) return;
|
|
256
|
+
if (event.data?.type !== "tools-wanted") return;
|
|
257
|
+
const { port1, port2 } = new MessageChannel();
|
|
258
|
+
served?.close(); // the chat asked again (it reloaded): the old port is dead
|
|
259
|
+
served = await mcp.serve(port1, {
|
|
260
|
+
client: { id: "assistant", name: "Example assistant" },
|
|
261
|
+
// Consequential tools ask in the chat, in the user's language (below).
|
|
262
|
+
onConfirm: (request) => askInChat(request),
|
|
263
|
+
});
|
|
264
|
+
chat.contentWindow!.postMessage({ type: "tools-port" }, "https://chat.example", [port2]);
|
|
265
|
+
});
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
The chat in the iframe passes the messages on between the port and its WebSocket:
|
|
269
|
+
|
|
270
|
+
```ts
|
|
271
|
+
parent.postMessage({ type: "tools-wanted" }, "https://shop.example");
|
|
272
|
+
addEventListener("message", (event) => {
|
|
273
|
+
if (event.origin !== "https://shop.example" || event.data?.type !== "tools-port") return;
|
|
274
|
+
const [port] = event.ports;
|
|
275
|
+
port.onmessage = (e) => socket.send(JSON.stringify({ tunnel: e.data }));
|
|
276
|
+
socket.addEventListener("message", (e) => {
|
|
277
|
+
const message = JSON.parse(e.data);
|
|
278
|
+
if (message.tunnel) port.postMessage(message.tunnel);
|
|
279
|
+
});
|
|
280
|
+
});
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
The backend (Bun, Node or anything with `fetch`'s `Request` and `Response`) makes the
|
|
284
|
+
tunnel's end on its WebSocket:
|
|
285
|
+
|
|
286
|
+
```ts
|
|
287
|
+
import { createTunnelFetch } from "@ractive-ch/tab-mcp-client/tunnel";
|
|
288
|
+
|
|
289
|
+
const tunnel = createTunnelFetch({
|
|
290
|
+
send: (message) => socket.send(JSON.stringify({ tunnel: message })),
|
|
291
|
+
});
|
|
292
|
+
socket.on("message", (data) => {
|
|
293
|
+
const message = JSON.parse(String(data));
|
|
294
|
+
if (message.tunnel) tunnel.receive(message.tunnel);
|
|
295
|
+
});
|
|
296
|
+
socket.on("close", () => tunnel.close());
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
#### The backend and an agent framework
|
|
300
|
+
|
|
301
|
+
An agent framework's own MCP client may not speak MCP 2026-07-28, the only version the
|
|
302
|
+
page speaks. Use the MCP SDK's client (`@modelcontextprotocol/client`), pinned to that
|
|
303
|
+
version, next to the framework, and hand the framework the page's tools as plain function
|
|
304
|
+
tools: most frameworks take a function tool as a name, a description, a JSON Schema and a
|
|
305
|
+
function. This recipe is tested in the repository
|
|
306
|
+
([`packages/tab-mcp-client/test/assistant-backend.ts`](https://github.com/ractive/tab-mcp/blob/main/packages/tab-mcp-client/test/assistant-backend.ts)):
|
|
307
|
+
|
|
308
|
+
```ts
|
|
309
|
+
import {
|
|
310
|
+
Client,
|
|
311
|
+
StreamableHTTPClientTransport,
|
|
312
|
+
} from "@modelcontextprotocol/client";
|
|
313
|
+
import type { TunnelFetch } from "@ractive-ch/tab-mcp-client/tunnel";
|
|
314
|
+
|
|
315
|
+
/** A function tool as agent frameworks take one: a name, a description, a JSON Schema and a function. */
|
|
316
|
+
export interface PageTool {
|
|
317
|
+
name: string;
|
|
318
|
+
description: string;
|
|
319
|
+
inputSchema: Record<string, unknown>;
|
|
320
|
+
run(args: Record<string, unknown>): Promise<string>;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
const ANNOTATIONS = "ch.ractive.tab-mcp/annotations";
|
|
324
|
+
|
|
325
|
+
export async function pageTools(
|
|
326
|
+
tunnel: TunnelFetch,
|
|
327
|
+
): Promise<{ tools: PageTool[]; close(): Promise<void> }> {
|
|
328
|
+
// The page speaks MCP 2026-07-28 only: pin it, or the SDK starts with an older version.
|
|
329
|
+
const client = new Client(
|
|
330
|
+
{ name: "assistant", version: "1.0.0" },
|
|
331
|
+
{ versionNegotiation: { mode: { pin: "2026-07-28" } } },
|
|
332
|
+
);
|
|
333
|
+
// The URL is never fetched; only its path reaches the page.
|
|
334
|
+
await client.connect(
|
|
335
|
+
new StreamableHTTPClientTransport(new URL("https://tab.invalid/mcp"), {
|
|
336
|
+
fetch: tunnel.fetch,
|
|
337
|
+
}),
|
|
338
|
+
);
|
|
339
|
+
const { tools } = await client.listTools();
|
|
340
|
+
return {
|
|
341
|
+
tools: tools.map((tool) => ({
|
|
342
|
+
name: tool.name,
|
|
343
|
+
description: tool.description ?? "",
|
|
344
|
+
inputSchema: tool.inputSchema,
|
|
345
|
+
async run(args) {
|
|
346
|
+
const result = await client.callTool({
|
|
347
|
+
name: tool.name,
|
|
348
|
+
arguments: args,
|
|
349
|
+
});
|
|
350
|
+
const text = result.content
|
|
351
|
+
.map((block) =>
|
|
352
|
+
block.type === "text" ? block.text : `[${block.type}]`,
|
|
353
|
+
)
|
|
354
|
+
.join("\n");
|
|
355
|
+
if (result.isError === true) return `The tool failed: ${text}`;
|
|
356
|
+
// Text from third parties (reviews, messages): say so to the model.
|
|
357
|
+
const hints = result._meta?.[ANNOTATIONS] as
|
|
358
|
+
| { untrustedContentHint?: boolean }
|
|
359
|
+
| undefined;
|
|
360
|
+
return hints?.untrustedContentHint === true
|
|
361
|
+
? `<untrusted-content>\n${text}\n</untrusted-content>`
|
|
362
|
+
: text;
|
|
363
|
+
},
|
|
364
|
+
})),
|
|
365
|
+
close: () => client.close(),
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
`const { tools, close } = await pageTools(tunnel)` lists the tools once; give each to the
|
|
371
|
+
framework with `inputSchema` as its parameters and `run` as its function. List them again
|
|
372
|
+
for a new conversation, or when the page's tools change
|
|
373
|
+
(`notifications/tools/list_changed` on a `subscriptions/listen` stream).
|
|
374
|
+
|
|
375
|
+
**Page context.** The server's `instructions` reach the assistant once, when its client
|
|
376
|
+
connects (`server/discover`), and MCP has no notification for instructions that changed.
|
|
377
|
+
What changes with the page (the product shown, the cart, the user's selection) belongs in
|
|
378
|
+
a read-only tool such as `get_page_context` (`readOnlyHint: true`, perhaps
|
|
379
|
+
`callers: ["local"]`) that the model calls when it needs it.
|
|
380
|
+
|
|
381
|
+
#### Asking in your chat
|
|
382
|
+
|
|
383
|
+
A consequential tool asks before every call. For the calls through one port, `serve`'s
|
|
384
|
+
`onConfirm` asks instead of the page's `onConfirm` and the library's dialog; calls through
|
|
385
|
+
the relay and WebMCP keep those. That is the recommended way for a site's own assistant:
|
|
386
|
+
the question appears where the user talks to the assistant, in the user's language. It
|
|
387
|
+
answers as the page's `onConfirm` does: `true`, `false` or `"unanswered"`; anything else,
|
|
388
|
+
and a throw, is a refusal. `request.signal` aborts when the call is cancelled, takes longer
|
|
389
|
+
than `requestTimeoutMs` or the serve closes: take the question away then.
|
|
390
|
+
|
|
391
|
+
The answer has to come from the user's click, in UI that the assistant cannot answer for
|
|
392
|
+
it. The library does not send the question over the port, because the other end of the
|
|
393
|
+
port is the caller that wants the tool to run: a model that injected text told to say yes
|
|
394
|
+
would answer it. If the chat in the iframe shows the question, give it the question on a
|
|
395
|
+
channel of its own, and let only a click on its buttons answer, never a message from the
|
|
396
|
+
backend.
|
|
397
|
+
|
|
398
|
+
Do not answer `true` for `client.kind === "local"` to skip the question. Tool results carry
|
|
399
|
+
text the site did not write (reviews, messages, other users' posts) into the model, and
|
|
400
|
+
that text can tell the model to call a consequential tool. The question is the one check
|
|
401
|
+
between that text and the tool.
|
|
402
|
+
|
|
403
|
+
#### Which callers see a tool
|
|
404
|
+
|
|
405
|
+
`registerTool(tool, { callers })` lists the callers that see a tool: `"relay"` (AI apps
|
|
406
|
+
through the relay), `"local"` (a served port) and `"webmcp"` (agents in the browser). By
|
|
407
|
+
default all of them, except that a consequential tool goes to WebMCP only when `"webmcp"`
|
|
408
|
+
is listed ([WebMCP](#webmcp)). For a caller that is not listed the tool does not exist:
|
|
409
|
+
`tools/list` leaves it out, `notifications/tools/list_changed` does not fire for it, and a
|
|
410
|
+
call gets the same error as a call of an unknown tool. `{ callers: ["local"] }` keeps a
|
|
411
|
+
tool for the site's own assistant, `{ callers: ["relay", "webmcp"] }` keeps it from the
|
|
412
|
+
port.
|
|
413
|
+
|
|
414
|
+
#### Untrusted results
|
|
415
|
+
|
|
416
|
+
A tool marked `untrustedContentHint` returns text the page did not write. MCP has no such
|
|
417
|
+
hint: in `tools/list` the tool has `annotations.openWorldHint: true` and the original hints
|
|
418
|
+
in `_meta["ch.ractive.tab-mcp/annotations"]` (for example
|
|
419
|
+
`{ "readOnlyHint": true, "untrustedContentHint": true }`). Every result of such a tool
|
|
420
|
+
carries `_meta["ch.ractive.tab-mcp/annotations"]: { "untrustedContentHint": true }` too,
|
|
421
|
+
through the relay and through a port, next to the tool's own `_meta`. A consumer reads the
|
|
422
|
+
marker on the result, so it needs no list at hand, and keeps such text apart from its
|
|
423
|
+
instructions, as the recipe does with a delimited block.
|
|
424
|
+
|
|
425
|
+
#### More about `serve`
|
|
426
|
+
|
|
427
|
+
- **A port is a key.** Whoever holds the other end calls the tools without pairing, and
|
|
428
|
+
the library cannot check who that is. Hand a port only to a frame whose origin you
|
|
429
|
+
checked, as above, and send it with that origin as the target, never `"*"`.
|
|
430
|
+
- Calls arrive with `client: { kind: "local", id, name }`, as given to `serve`. A `grant`
|
|
431
|
+
in a message is ignored, so the other end cannot pass for an AI app of the relay.
|
|
432
|
+
- Without `serve`'s `onConfirm`, a consequential call through the port asks the page's
|
|
433
|
+
`onConfirm` or the library's dialog, which names the caller "Example assistant (this
|
|
434
|
+
site's assistant)" and never offers "Allow until reload".
|
|
435
|
+
- `requestTimeoutMs` (300 s by default, as `createTunnelFetch`; below 2^31 ms) limits each
|
|
436
|
+
request on the page's side: on expiry the call is aborted (`execute`'s signal and the
|
|
437
|
+
question's), `toolcallend` says `cancelled`, a later answer of the tool is dropped, and
|
|
438
|
+
the other end gets the JSON-RPC error `-31002`, as from `createTunnelFetch`'s own limit.
|
|
439
|
+
A `subscriptions/listen` stream is not limited.
|
|
440
|
+
- `serve` resolves with `{ close() }`; `options.signal` does the same. Closing aborts the
|
|
441
|
+
calls in flight and tells the other end (`bye`), whose requests then end at once with
|
|
442
|
+
`-31003`. Close a serve whose port is dead, as above: its calls, listen streams and an
|
|
443
|
+
open confirmation would stay otherwise. Where the port fires `close` when its other end
|
|
444
|
+
goes away (Bun does; Chrome only with the `MessagePortCloseEvent` Blink feature), the
|
|
445
|
+
serve closes itself then. `serve` may be called for several ports (each port once at a
|
|
446
|
+
time), and next to a relay connection and `webmcp: true`: one registration reaches all
|
|
447
|
+
three.
|
|
448
|
+
- A port has none of the relay's limits: no cap on requests in flight, listen streams,
|
|
449
|
+
body size or rate. The other end is the site's own code (threat model A15). The
|
|
450
|
+
confirmations of consequential calls are shown one at a time, however many arrive.
|
|
451
|
+
- `createTunnelFetch` answers a request that takes longer than its `requestTimeoutMs`
|
|
452
|
+
(300 s by default; a `subscriptions/listen` stream is not limited) with the JSON-RPC
|
|
453
|
+
error `-31002`, and every request after `close()` with `-31003`, at HTTP 200 like the
|
|
454
|
+
relay: the MCP client reads an error, not a network failure. Only an aborted `signal`
|
|
455
|
+
rejects. Call `close()` when the channel to the page is gone; a closed tunnel stays
|
|
456
|
+
closed, so a new channel (or a new `serve`) gets a new `createTunnelFetch`.
|
|
457
|
+
- Without `relay`, `connect()`, `showConnectDialog()` and `newAddress()` reject with a
|
|
458
|
+
`TypeError`, nothing is read from or written to `localStorage`, `mcp.hasRelay` is
|
|
459
|
+
`false`, and React's `ConnectButton` renders nothing.
|
|
169
460
|
|
|
170
461
|
### Consequential tools
|
|
171
462
|
|
|
@@ -174,22 +465,39 @@ asks the user before every call ("Don't allow" or "Allow"), showing the AI app a
|
|
|
174
465
|
arguments. A refusal reaches the AI app as an error result, and so does a call whose tool
|
|
175
466
|
was removed while the user was asked.
|
|
176
467
|
|
|
177
|
-
`alwaysAllow: true` adds "
|
|
178
|
-
AI app until the page is reloaded or the app is disconnected.
|
|
468
|
+
`alwaysAllow: true` adds "Allow until reload", which lets that tool run without asking for
|
|
469
|
+
that AI app, with any arguments, until the page is reloaded or the app is disconnected.
|
|
470
|
+
The connect dialog lists such tools under the app ("Runs without asking: …") with "Ask
|
|
471
|
+
again", and a tool registered again unchanged (React's `useTool` on a remount) keeps its
|
|
472
|
+
entry; one whose title or description changed is asked again. It is off by default: it
|
|
179
473
|
lifts the only brake at run time, which is what a prompt injection needs, and the relay
|
|
180
474
|
cannot help, since its one OAuth scope (`tools`) covers every tool of the page. Consent
|
|
181
475
|
per tool is the page's. Turn it on only for tools whose calls the user need not check one
|
|
182
476
|
by one.
|
|
183
477
|
|
|
184
478
|
Tools are called while the user is in the AI app, so the dialog often opens in a tab in
|
|
185
|
-
the background. "Allow" and "
|
|
186
|
-
visible and focused for
|
|
479
|
+
the background. "Allow" and "Allow until reload" can be clicked only once the page has
|
|
480
|
+
been visible and focused for 750 ms with the dialog open; leaving the page
|
|
187
481
|
disables them and coming back starts the wait again, so the click that brings the page
|
|
188
|
-
forward cannot approve.
|
|
482
|
+
forward cannot approve. One confirmation is shown at a time; the others wait, the shown
|
|
483
|
+
one says how many, and each starts its own wait when it is shown (and again when another
|
|
484
|
+
dialog of the page closes over it), so the second click of a double click cannot approve
|
|
485
|
+
the next call. A call cancelled while it waits is never shown. When the arguments do not
|
|
486
|
+
fit their box (`min(50vh, 24rem)`), the approving buttons also wait until the box has been
|
|
487
|
+
scrolled to its end, and the dialog says so: the AI app chooses the order of the keys, so
|
|
488
|
+
what matters may come last. Before the wait has run out, Enter or Space on a button and
|
|
489
|
+
Escape do nothing, so typing meant for the page cannot refuse a call the user has not
|
|
490
|
+
seen; a click on "Don't allow" works at once. Characters that are invisible, blank (such as U+00A0, U+3000 or
|
|
189
491
|
U+2800) or change the text direction (such as U+202E) are shown in the arguments and the
|
|
190
492
|
AI app's name as `\uXXXX`, so the AI app cannot make them look like something else; the
|
|
191
493
|
tool gets the arguments unchanged.
|
|
192
494
|
|
|
495
|
+
While a confirmation is open in a hidden tab, the tab's title starts with "Allow? – ", so
|
|
496
|
+
the user can find the tab that asks; the title is put back when the tab is shown or the
|
|
497
|
+
dialog closes (unless the page changed it meanwhile). In `tools/list`, the description of
|
|
498
|
+
a consequential tool ends with "The page may ask the user to allow
|
|
499
|
+
each call, usually in the page's browser tab.", so the AI app can tell the user where to look while it waits.
|
|
500
|
+
|
|
193
501
|
Pass `onConfirm` to ask in your own UI (it is asked every time; remember answers there if
|
|
194
502
|
you want to). Show the verified `client.host` next to the name the AI app declares, as the
|
|
195
503
|
library's dialog does, since anyone can declare any name. Escape the arguments and the
|
|
@@ -204,7 +512,8 @@ const mcp = new TabMcp({
|
|
|
204
512
|
server: { name: "calculator", version: "1.0.0" },
|
|
205
513
|
onConfirm: (request) => {
|
|
206
514
|
const { tool, arguments: args, client, signal } = request;
|
|
207
|
-
// An agent in the browser (`webmcp`)
|
|
515
|
+
// An agent in the browser (`webmcp`), or the site's own assistant (`local`) on a
|
|
516
|
+
// port served without its own onConfirm: the library's own dialog.
|
|
208
517
|
if (client.kind !== "relay") return mcp.confirmInPage(request);
|
|
209
518
|
const name = client.name ? escapeInvisible(client.name) : undefined;
|
|
210
519
|
const app = name ? `${name} (${client.host})` : client.host;
|
|
@@ -219,8 +528,8 @@ asked and did not answer, e.g. your question timed out. The AI app then reads "T
|
|
|
219
528
|
asked and did not answer." instead of "The user declined", and `toolcallend` has the
|
|
220
529
|
outcome `unanswered`. Any other value, and a throw, is a refusal.
|
|
221
530
|
|
|
222
|
-
`mcp.confirmInPage(request)` is the library's own dialog, for an
|
|
223
|
-
handles only some calls itself.
|
|
531
|
+
`mcp.confirmInPage(request, { document })` is the library's own dialog, for an
|
|
532
|
+
`onConfirm` that handles only some calls itself (`document` defaults to the global one).
|
|
224
533
|
|
|
225
534
|
### Connecting and pairing
|
|
226
535
|
|
|
@@ -229,25 +538,40 @@ handles only some calls itself.
|
|
|
229
538
|
opens the "Connect your AI app" dialog. A script's `element.click()` has no user
|
|
230
539
|
activation, so tests and browser automation see "connect() must be called from a
|
|
231
540
|
user action"; a click through Playwright or the DevTools protocol has one, and
|
|
232
|
-
`connect({ resume: true })` skips the check.
|
|
233
|
-
|
|
234
|
-
|
|
541
|
+
`connect({ resume: true })` skips the check. When it cannot connect, the dialog says
|
|
542
|
+
why in plain words ("Could not connect. Check your internet connection.", "Too many
|
|
543
|
+
attempts…", "The connection was refused.", or "Not connected." when the click had no
|
|
544
|
+
user activation) and offers "Connect again", which connects from its own click; the
|
|
545
|
+
error itself goes to the console (`console.warn`). After a disconnect it says why
|
|
546
|
+
("The session ended." for `expired` and `idle`) and offers the same button. While the
|
|
547
|
+
library reconnects by itself, it says "Connection lost. Reconnecting…", and "Connect
|
|
548
|
+
again" tries at once.
|
|
549
|
+
2. The dialog shows the address with Copy and, right below it, "How do I add it?" (closed;
|
|
550
|
+
open, its steps would push the code out of view): short instructions for Claude,
|
|
551
|
+
ChatGPT, Claude Code and Codex. The commands for Claude Code and Codex each have a
|
|
552
|
+
Copy. They name the
|
|
235
553
|
server by a label made from `server.name` that every shell reads as one plain word:
|
|
236
554
|
lower case, letters without marks, each run of other characters as `-`, at most 40
|
|
237
555
|
characters, `tools` if nothing is left ("Bücher" gives `bucher`). The address goes
|
|
238
556
|
into a command only if it has nothing but plain URL characters; otherwise the help
|
|
239
|
-
shows the steps without commands.
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
557
|
+
shows the steps without commands. Each entry ends with the step that starts the
|
|
558
|
+
sign-in: `/mcp` and Authenticate in Claude Code, `codex mcp login <name>` as the third
|
|
559
|
+
line of Codex's command. Codex 0.163 needs its feature `mcp_2026_07_28` for the relay's MCP
|
|
560
|
+
revision, so its command turns that on first. The steps are the minimum; the link at
|
|
561
|
+
the end of the help leads to the guide with the rest (ChatGPT's Mac app, turning the
|
|
562
|
+
Codex feature off, what to do when it fails). A page can link its own guide and give
|
|
563
|
+
its own steps (`ui.setup`, see [Texts and help of the dialogs](#texts-and-help-of-the-dialogs)).
|
|
564
|
+
The user adds the address to their AI app.
|
|
243
565
|
3. The AI app opens the relay's sign-in page in the browser. The dialog shows a 6-digit
|
|
244
566
|
code with a Copy button, which the user types or pastes there. The code changes every
|
|
245
567
|
2 minutes and after each use.
|
|
246
568
|
4. Once the AI app connects, the dialog says so at the top: a check mark, "Claude
|
|
247
|
-
(claude.ai) is connected" and what to do next (close it and ask the app to use the
|
|
569
|
+
(claude.ai) is connected" (every connected app is named) and what to do next (close it and ask the app to use the
|
|
248
570
|
page's tools); screen readers hear the same. The setup (address, code, help) moves
|
|
249
571
|
behind "Connect another app", closed, so the next code does not appear in view; the
|
|
250
|
-
connected app is listed with a Disconnect button
|
|
572
|
+
connected app is listed with a Disconnect button (and the tools it may run without
|
|
573
|
+
asking, with "Ask again"), and "Done" closes the dialog. A Disconnect the relay could
|
|
574
|
+
not save says so in the list ("The relay could not save this. Try again.").
|
|
251
575
|
Opened again while an app is connected, the dialog starts like this, with the focus
|
|
252
576
|
on Done.
|
|
253
577
|
|
|
@@ -273,35 +597,50 @@ key yourself; the name is URI-encoded, and renaming it changes the address). A s
|
|
|
273
597
|
existing page keeps its address; on a site with several pages the first one to connect
|
|
274
598
|
keeps it, the others get new ones. The old key stays for pages still on 0.4.
|
|
275
599
|
|
|
276
|
-
"New address" in the dialog
|
|
277
|
-
|
|
600
|
+
"New address" in the dialog (at the end of the setup, below the code, with a line on what
|
|
601
|
+
it does; not next to Copy, since with no app connected it changes the address at once)
|
|
602
|
+
calls `newAddress()`, which disconnects every
|
|
603
|
+
app and makes a new address; when apps are connected, the dialog asks first. It first
|
|
604
|
+
takes the old address back: it connects with the stored secret, and the relay revokes
|
|
605
|
+
every grant of the address in
|
|
606
|
+
the same step (`hello.revokeAll`), whether the page was connected or not. Then it makes
|
|
607
|
+
the new secret, clears `grants`, and connects with it if the page was connected,
|
|
608
|
+
connecting or reconnecting (or taken over). A page that never had a secret makes one
|
|
609
|
+
without connecting. If the old address cannot be taken back (the relay is unreachable,
|
|
610
|
+
or someone takes it over again first), it rejects and keeps the old secret, so calling
|
|
611
|
+
it again tries again. A second call while it runs returns the same promise; `connect()`
|
|
612
|
+
meanwhile waits for it and then connects with the new address. The relay's
|
|
278
613
|
sign-in page points users to it when someone else may be guessing codes. A page with its
|
|
279
614
|
own UI calls `newAddress()` from a click. Connected apps keep working after a reload once the page connects
|
|
280
615
|
again; while the page is closed, they get "the page is not open".
|
|
281
616
|
|
|
282
617
|
When another tab or program connects with the same address, it takes the address over:
|
|
283
|
-
the page gets `disconnected` with reason `replaced` at once, then the
|
|
618
|
+
the page gets `statechange` to `disconnected` with reason `replaced` at once, then the
|
|
619
|
+
event `replaced`,
|
|
284
620
|
and does not reconnect by itself. Tabs of the same page say on a `BroadcastChannel` (per
|
|
285
|
-
relay and storage key; it carries
|
|
286
|
-
accepted their session, so `replaced` says which it probably
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
621
|
+
relay and storage key; it carries the address id, which is part of the address, never
|
|
622
|
+
the secret) when the relay accepted their session, so `replaced` says which it probably
|
|
623
|
+
was:
|
|
624
|
+
|
|
625
|
+
- `event.detail.sibling` is `true`: a tab of the same page in this browser said within
|
|
626
|
+
the last 10 seconds that it claimed this tab's address, after this tab's own session
|
|
627
|
+
started (a claim of another address, or one heard while this tab was still connecting,
|
|
628
|
+
does not count; a claim without an address, from a tab still on 0.15 or older, does). That message usually comes just after the takeover, so the
|
|
290
629
|
library waits up to a second for it, and `replaced` may come that much after
|
|
291
|
-
`
|
|
630
|
+
the `statechange`. The usual cause, and harmless. Once the page has opened the default
|
|
292
631
|
dialog, the library shows "Opened in another tab".
|
|
293
632
|
- `false`: none did (or the browser has no `BroadcastChannel`). It may be a program with
|
|
294
633
|
a copy of the address secret, and the AI apps paired with the address now talk to it.
|
|
295
634
|
The library shows "Another tab or program took over this page" with "New address".
|
|
296
635
|
|
|
297
|
-
After a takeover, `newAddress()` (from the `replaced` listener, before it, or later
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
the
|
|
636
|
+
After a takeover, `newAddress()` (from the `replaced` listener, before it, or later, also
|
|
637
|
+
after a reload) takes the address back as above and makes the new address only once the
|
|
638
|
+
relay confirmed that no grant is left. If the address is taken over again before that,
|
|
639
|
+
it rejects with an error whose `reason` is `"replaced"` and keeps the old secret, so
|
|
640
|
+
calling it again takes it back again. A relay of 0.4 or older cannot take an address
|
|
641
|
+
back: `newAddress()` rejects there with `reason` `"policy"`. When the takeover ended a
|
|
642
|
+
session of this page, it then connects with the new address; the default notice opens
|
|
643
|
+
the connect dialog to add it to the AI apps.
|
|
305
644
|
|
|
306
645
|
The default dialog closes when the page is replaced, and the notice appears also when the
|
|
307
646
|
dialog is closed, but only once the page has opened the dialog: a page that connects on
|
|
@@ -344,16 +683,21 @@ third-party script, another page on the same origin) or access to the device can
|
|
|
344
683
|
pair with.
|
|
345
684
|
|
|
346
685
|
When the connection breaks (reason `network`, `heartbeat` or `shutdown`: a dropped
|
|
347
|
-
network, a phone pausing the tab in the background, a relay restart
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
686
|
+
network, a phone pausing the tab in the background, a relay restart; close codes 1001,
|
|
687
|
+
1011, 1012 and 1013 from a proxy in front of the relay count as `shutdown`), the library
|
|
688
|
+
connects again by itself: after about 5, 10, 20 and 40 seconds, then about every 60
|
|
689
|
+
seconds (each wait varies by up to 20 %, so that the tabs of a restarted relay do not all
|
|
690
|
+
come back at once), and at once when the tab comes back to the front or the network
|
|
691
|
+
returns. Meanwhile `state` is `reconnecting` (while it waits and while it makes an
|
|
692
|
+
attempt), `reconnecting` says which attempt is next and when, and `statechange` fires
|
|
693
|
+
for each attempt it schedules; the `statechange` that leaves `connected` carries the
|
|
694
|
+
`reason`. Calling `connect()` meanwhile tries at once. It never reconnects after `disconnect()`, a new address,
|
|
353
695
|
another tab taking over the address (`replaced`), an expired or idle session, or a
|
|
354
696
|
refusal by the relay, and an attempt the relay refuses stops it (an unreachable relay is
|
|
355
|
-
tried again); the event `error` then says why,
|
|
356
|
-
|
|
697
|
+
tried again); the event `error` then says why, with `state` already `disconnected`, just
|
|
698
|
+
before the `statechange` to `disconnected`, also when a `connect()` of the page waits on
|
|
699
|
+
that attempt and rejects with the same error. `reconnect: false` turns it off; the waits
|
|
700
|
+
are fixed.
|
|
357
701
|
|
|
358
702
|
### Keeping AI access on after a reload
|
|
359
703
|
|
|
@@ -363,11 +707,12 @@ AI access on, remember the user's choice and connect on load:
|
|
|
363
707
|
|
|
364
708
|
```ts
|
|
365
709
|
const key = "my-page:ai-on";
|
|
366
|
-
|
|
367
|
-
|
|
710
|
+
// On once an AI app is paired: opening the dialog and closing it again does not count.
|
|
711
|
+
mcp.addEventListener("grantschange", () => {
|
|
712
|
+
if (mcp.grants.length > 0) localStorage.setItem(key, "1");
|
|
368
713
|
});
|
|
369
714
|
// Turned off by the user (`disconnect()`): stay off after the next reload.
|
|
370
|
-
mcp.addEventListener("
|
|
715
|
+
mcp.addEventListener("statechange", (e) => {
|
|
371
716
|
if (e.detail.reason === "user") localStorage.removeItem(key);
|
|
372
717
|
});
|
|
373
718
|
turnOffButton.onclick = () => mcp.disconnect();
|
|
@@ -403,33 +748,76 @@ const mcp = new TabMcp({
|
|
|
403
748
|
});
|
|
404
749
|
|
|
405
750
|
// In your logout: the relay ends every AI connection of this page at once.
|
|
406
|
-
logoutButton.onclick = () => {
|
|
407
|
-
//
|
|
408
|
-
|
|
751
|
+
logoutButton.onclick = () => {
|
|
752
|
+
mcp.signOut().catch(() => {}); // settles once the relay removed the grants
|
|
753
|
+
// then your own logout
|
|
754
|
+
};
|
|
755
|
+
// After a sign-in without a reload: "bound", "refused" or "none".
|
|
756
|
+
const identity = await mcp.refreshIdentity();
|
|
409
757
|
```
|
|
410
758
|
|
|
411
759
|
The library asks the function after every connect. `identity` (`none`, `pending`,
|
|
412
760
|
`bound`, `refused`, with the reason in `identityMessage`) and the event
|
|
413
|
-
`identitychange` tell you whether the relay accepted it; when the function or the relay does not answer within
|
|
761
|
+
`identitychange` tell you whether the relay accepted it; when the function or the relay does not answer within 15 s (counted from when the function is asked), it goes back to `none`. `signOut()` and `refreshIdentity()` reject with an `InvalidStateError` while the page is not connected (`signOut()` also on a relay that pairs by code); `identity` is cleared either way. An AI app signed in as someone else gets "This AI tool is logged in as someone other
|
|
414
762
|
than the page."
|
|
415
763
|
|
|
764
|
+
The connect dialog follows `identity`: it shows the address and "When your AI app asks,
|
|
765
|
+
sign in with the account you use on this page" only once it is `bound`. Until then it
|
|
766
|
+
says what is missing: "Checking your sign-in…" (`pending`), "Sign in to this page first."
|
|
767
|
+
(`none`), or that the sign-in was not accepted, with `identityMessage` (`refused`).
|
|
768
|
+
|
|
416
769
|
### Your own UI
|
|
417
770
|
|
|
418
|
-
Instead of `showConnectDialog()`, use
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
`
|
|
771
|
+
Instead of `showConnectDialog()`, use the methods, properties and events below.
|
|
772
|
+
|
|
773
|
+
| Methods | |
|
|
774
|
+
|---|---|
|
|
775
|
+
| `connect(options?)` | resolves with the session (`SessionInfo`) |
|
|
776
|
+
| `disconnect()` | ends the session at once |
|
|
777
|
+
| `newAddress()` | resolves once the new address is in use (connected again if it was on) |
|
|
778
|
+
| `startPairing()`, `stopPairing()` | codes come only while pairing is on |
|
|
779
|
+
| `revoke(grantId)` | resolves once the relay removed the grant |
|
|
780
|
+
| `signOut()` | resolves once the relay removed the grants (identity binding) |
|
|
781
|
+
| `refreshIdentity()` | resolves with the new `identity`; a `TypeError` without `identityAssertion` |
|
|
782
|
+
|
|
783
|
+
A method that asks the relay rejects with an `InvalidStateError` while the page is not
|
|
784
|
+
connected, and when the session ends before the relay answered. `revoke()` and `signOut()`
|
|
785
|
+
also reject with the relay's refusal (its `code` is `store_unavailable` when the relay
|
|
786
|
+
could not save the change: try again; `unknown_id` for a grant the relay does not know),
|
|
787
|
+
and with a `TimeoutError` when the relay has not answered within 15 s.
|
|
788
|
+
|
|
789
|
+
The properties are `state` (`disconnected`, `connecting`, `connected`, `reconnecting`),
|
|
790
|
+
`session` (while connected; `session.address` is the MCP address, `session.appName` the
|
|
791
|
+
name the relay shows), `reconnecting` (the next attempt, while `state` is
|
|
792
|
+
`reconnecting`), `pairingCode`, `grants`, `identity`, `identityMessage`, `tools` and
|
|
793
|
+
`hasRelay`.
|
|
794
|
+
|
|
795
|
+
Every event's `detail` is an object. A change event names the new values like the
|
|
796
|
+
properties (`grantschange` has `grants`), and a value that is gone is `undefined`:
|
|
797
|
+
|
|
798
|
+
| Event | `detail` |
|
|
799
|
+
|---|---|
|
|
800
|
+
| `statechange` | `{ state, reason? }`: `reason` when a session ended, or when `disconnect()` or `newAddress()` ended connecting or reconnecting; also for each reconnect attempt |
|
|
801
|
+
| `grantschange` | `{ grants }` |
|
|
802
|
+
| `pairingcode` | `{ pairingCode }` |
|
|
803
|
+
| `identitychange` | `{ identity, identityMessage }` |
|
|
804
|
+
| `toolschange` | `{ tools }` |
|
|
805
|
+
| `replaced` | `{ sibling }` (see above) |
|
|
806
|
+
| `error` | `{ error }` |
|
|
807
|
+
| `toolcall`, `toolcallend` | the call, see below | For an activity log, `toolcall`
|
|
424
808
|
and `toolcallend` report every call by an AI app (or, with `webmcp`, an agent in the
|
|
425
|
-
browser): its id, tool, arguments and caller as it starts, then its outcome (`ok`,
|
|
809
|
+
browser, or the assistant on a served port): its id, tool, arguments and caller as it starts, then its outcome (`ok`,
|
|
426
810
|
`error`, `declined`, `unanswered` or `cancelled`), result and duration.
|
|
427
811
|
|
|
428
812
|
```ts
|
|
429
813
|
mcp.addEventListener("toolcallend", (e) => {
|
|
430
814
|
const { tool, client, outcome, durationMs } = e.detail;
|
|
431
815
|
const who =
|
|
432
|
-
client.kind === "relay"
|
|
816
|
+
client.kind === "relay"
|
|
817
|
+
? (client.name ?? client.host)
|
|
818
|
+
: client.kind === "local"
|
|
819
|
+
? (client.name ?? client.id)
|
|
820
|
+
: "An agent in this browser";
|
|
433
821
|
log(`${who}: ${tool} ${outcome} in ${durationMs} ms`);
|
|
434
822
|
});
|
|
435
823
|
```
|
|
@@ -441,7 +829,7 @@ add it?", as data for your own UI. An entry of its own, out of the core, and not
|
|
|
441
829
|
build. `setupInstructions(serverName, address)` returns one entry per AI app (Claude,
|
|
442
830
|
ChatGPT, Claude Code, Codex, in that order): `id` (`claude`, `chatgpt`, `claude-code`,
|
|
443
831
|
`codex`), `app` (its name as shown), `text` (what to do), `command` (lines to run, for
|
|
444
|
-
Claude Code and Codex) and `note` (text and code parts, for Codex). Every string is plain
|
|
832
|
+
Claude Code and Codex) and `note` (text and code parts, for Claude Code and Codex). Every string is plain
|
|
445
833
|
text: set it with `textContent`. The commands name the server by a label made from
|
|
446
834
|
`serverName` and contain the address only when every shell reads both as plain words (see
|
|
447
835
|
step 2 above), so they are safe to show with a Copy button; for an address that is not
|
|
@@ -463,14 +851,55 @@ for (const { app, text, command, note } of setupInstructions("notes", session.ad
|
|
|
463
851
|
guide.href = SETUP_GUIDE;
|
|
464
852
|
```
|
|
465
853
|
|
|
854
|
+
### Texts and help of the dialogs
|
|
855
|
+
|
|
856
|
+
Every text of the dialogs is in one table, [`src/strings.ts`](src/strings.ts) (the type
|
|
857
|
+
`DialogStrings`). Pass your own for some or all keys as `ui.strings`; the rest stay
|
|
858
|
+
English. `{name}` placeholders are filled in: names of tools and AI apps (isolated, so
|
|
859
|
+
they cannot reorder your sentence), the code, counts. Where English needs two forms there
|
|
860
|
+
are two keys (`waitingOne`, `waitingMany`). `lang` and `dir` are the language and direction
|
|
861
|
+
set on every dialog: set them with your texts.
|
|
862
|
+
|
|
863
|
+
`ui.setup` changes the help in the connect dialog: `guide` is the link at its end
|
|
864
|
+
(default the guide on ractive.ch; `null` for none, for example on your own relay, and
|
|
865
|
+
then your own `instructions` too, since the default steps refer to the guide), and
|
|
866
|
+
`instructions(serverName, address)` returns the steps per AI app, each `{ app, text,
|
|
867
|
+
command?, note? }` (default `setupInstructions` of `@ractive-ch/tab-mcp-client/setup`,
|
|
868
|
+
which you can filter or extend).
|
|
869
|
+
|
|
870
|
+
```ts
|
|
871
|
+
import { setupInstructions } from "@ractive-ch/tab-mcp-client/setup";
|
|
872
|
+
|
|
873
|
+
const mcp = new TabMcp({
|
|
874
|
+
relay: "https://relay.example",
|
|
875
|
+
server: { name: "notizen", version: "1.0.0" },
|
|
876
|
+
ui: {
|
|
877
|
+
strings: {
|
|
878
|
+
lang: "de",
|
|
879
|
+
connectTitle: "KI-App verbinden",
|
|
880
|
+
confirmTitle: "{tool} erlauben?",
|
|
881
|
+
allow: "Erlauben",
|
|
882
|
+
deny: "Nicht erlauben",
|
|
883
|
+
},
|
|
884
|
+
setup: {
|
|
885
|
+
guide: "https://example.com/hilfe/ki",
|
|
886
|
+
instructions: (name, address) =>
|
|
887
|
+
setupInstructions(name, address).filter((step) => step.id !== "codex"),
|
|
888
|
+
},
|
|
889
|
+
},
|
|
890
|
+
});
|
|
891
|
+
```
|
|
892
|
+
|
|
466
893
|
### Styling the default dialogs
|
|
467
894
|
|
|
468
895
|
The default dialogs bring their own stylesheet, a constructed stylesheet added to
|
|
469
896
|
`document.adoptedStyleSheets`, so a strict CSP needs no `style-src` exception. It uses
|
|
470
897
|
the page's font and system colours, and follows the page's `color-scheme`: declare
|
|
471
898
|
`color-scheme: light dark` (or `<meta name="color-scheme" content="light dark">`) and the
|
|
472
|
-
dialogs are dark in dark mode. They fit a
|
|
473
|
-
|
|
899
|
+
dialogs are dark in dark mode. They fit a 320 px wide screen (below 30rem the code's Copy
|
|
900
|
+
goes under the code), and they open without animation when the user prefers reduced
|
|
901
|
+
motion. The page's rules for elements (`button { … }`, `p { color: … }`, a reset) do not
|
|
902
|
+
reach into them, nor does `body { pointer-events: none }` of a modal layer (Radix, shadcn).
|
|
474
903
|
|
|
475
904
|
To adjust single values, set these custom properties on `:root` or on `.tab-mcp-dialog`:
|
|
476
905
|
|
|
@@ -495,34 +924,14 @@ To adjust single values, set these custom properties on `:root` or on `.tab-mcp-
|
|
|
495
924
|
| `--tab-mcp-title-size` | `1.25em` | |
|
|
496
925
|
| `--tab-mcp-mono` | `ui-monospace, …, monospace` | the address, the code, the arguments |
|
|
497
926
|
| `--tab-mcp-code-size` | `2em` | the pairing code |
|
|
498
|
-
| `--tab-mcp-arguments-height` | `
|
|
499
|
-
|
|
500
|
-
For more,
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
`
|
|
505
|
-
|
|
506
|
-
of them. A page rule of one element and one pseudo-class still changes a property that the
|
|
507
|
-
dialogs set only in their base rules (for example `button:hover { padding: 0 }`). Write
|
|
508
|
-
overrides outside cascade layers: the dialogs' rules are not in a layer, so they win over
|
|
509
|
-
any layered rule. All dialogs are `dialog.tab-mcp-dialog`; the connect dialog is
|
|
510
|
-
`.tab-mcp-connect` (with `.tab-mcp-status`, `.tab-mcp-address`, `.tab-mcp-code`,
|
|
511
|
-
`.tab-mcp-code-value`, `.tab-mcp-code-used`, `.tab-mcp-help`, `.tab-mcp-apps`,
|
|
512
|
-
`.tab-mcp-app`, `.tab-mcp-new-address-question`, `.tab-mcp-actions`; once an app is
|
|
513
|
-
connected `.tab-mcp-success`, with `.tab-mcp-success-icon` (the check mark, an inline
|
|
514
|
-
`svg` in `currentColor`), `.tab-mcp-success-title` and `.tab-mcp-success-next`, and the
|
|
515
|
-
button `.tab-mcp-setup-toggle`, "Connect another app", with `aria-expanded`, which shows
|
|
516
|
-
and hides `.tab-mcp-setup`, the address, code and help), the confirmation is
|
|
517
|
-
`.tab-mcp-confirm` (with `.tab-mcp-description`, `.tab-mcp-arguments`,
|
|
518
|
-
`.tab-mcp-always-note`, and the buttons `.tab-mcp-deny`, `.tab-mcp-allow`,
|
|
519
|
-
`.tab-mcp-always`, with `alwaysAllow`), and the notice after `replaced` is
|
|
520
|
-
`.tab-mcp-replaced` (with `.tab-mcp-description`, `.tab-mcp-status`, and the buttons
|
|
521
|
-
`.tab-mcp-replaced-close` and `.tab-mcp-new-address`). Buttons are `.tab-mcp-primary` (the one
|
|
522
|
-
next step: Copy the address until an app is connected, then Done, "Don't allow", the safe choice, and the notice's "New
|
|
523
|
-
address", or its "Close" after a sibling tab), `.tab-mcp-danger` (Disconnect and
|
|
524
|
-
"Disconnect and get new address") or plain; every Copy button is also `.tab-mcp-copy`, and
|
|
525
|
-
the Disconnect buttons in the apps list are `.tab-mcp-disconnect`. For example:
|
|
927
|
+
| `--tab-mcp-arguments-height` | `min(50vh, 24rem)` | the arguments scroll beyond this |
|
|
928
|
+
|
|
929
|
+
For more, override with two classes, `.tab-mcp-dialog .tab-mcp-x`, outside cascade layers;
|
|
930
|
+
a rule with one class does not win. The class names that stay are the dialogs:
|
|
931
|
+
`.tab-mcp-dialog` (all of them), `.tab-mcp-connect`, `.tab-mcp-confirm` and
|
|
932
|
+
`.tab-mcp-replaced`; and the kinds of button: `.tab-mcp-primary` (the one next step),
|
|
933
|
+
`.tab-mcp-danger` (what disconnects apps) and `.tab-mcp-copy` (every Copy). Other class
|
|
934
|
+
names inside the dialogs may change with any release. For example:
|
|
526
935
|
|
|
527
936
|
```css
|
|
528
937
|
:root {
|
|
@@ -568,20 +977,23 @@ function TodoList() {
|
|
|
568
977
|
its first render. A changed `relay` or `server.name` makes a new one (with a warning);
|
|
569
978
|
other changes are ignored, except that `onConfirm` and `identityAssertion` are always
|
|
570
979
|
the latest ones, also when added or removed after the first render (without
|
|
571
|
-
`onConfirm`, the library's dialog asks). It disconnects its instance when it unmounts
|
|
980
|
+
`onConfirm`, the library's dialog asks). It disconnects its instance when it unmounts (a moment later, so that StrictMode's
|
|
981
|
+
simulated unmount does not cancel a `connect()` a child started). `<TabMcpProvider
|
|
572
982
|
client={mcp}>` uses an instance of your own instead (and leaves it connected).
|
|
573
983
|
- `useTabMcp()` returns the instance, for everything the hooks do not cover
|
|
574
984
|
(`newAddress()`, `signOut()`, `refreshIdentity()`, `revoke()`, …).
|
|
575
|
-
- `useTabMcpState()` returns `{ state,
|
|
576
|
-
identityMessage, reconnecting, tools }` through `useSyncExternalStore`: the component
|
|
985
|
+
- `useTabMcpState()` returns `{ state, session, grants, pairingCode, identity,
|
|
986
|
+
identityMessage, reconnecting, tools }` (the address is `session?.address`) through `useSyncExternalStore`: the component
|
|
577
987
|
renders again only when one of them changed. On the server and during hydration it is
|
|
578
988
|
`disconnected`.
|
|
579
|
-
- `useTool(tool,
|
|
989
|
+
- `useTool(tool, options?)` registers the tool while the component is mounted and
|
|
580
990
|
removes it on unmount. `execute` is always the latest closure, so it may use the
|
|
581
991
|
component's current props and state without registering again; the tool is registered
|
|
582
|
-
again only when its name, title, description, input schema or annotations
|
|
583
|
-
`options.
|
|
584
|
-
|
|
992
|
+
again only when its name, title, description, input or output schema or annotations
|
|
993
|
+
change, or `options.callers` or `options.exposedTo` (by value: a new array with the same
|
|
994
|
+
entries is no change; [which callers see a tool](#which-callers-see-a-tool),
|
|
995
|
+
[WebMCP](#webmcp), whose `webmcp` on the provider turns it on). Registered again unchanged, a tool allowed until reload stays
|
|
996
|
+
allowed. StrictMode's double mount registers it once at a time. A duplicate name or an
|
|
585
997
|
invalid tool is thrown from the component's render, for an error boundary. Tools that
|
|
586
998
|
read state right after another tool changed it should read it from a store (as the
|
|
587
999
|
example does) or a ref ([Tools in a `useState` app](#tools-in-a-usestate-app)), not
|