@ractive-ch/tab-mcp-client 0.13.1 → 0.15.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/tab-mcp.d.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * events, the pairing state and the address secret; `connect()` loads the
4
4
  * connection and the MCP handler with a dynamic `import()`.
5
5
  */
6
- import type { ConfirmRequest, ConnectionState, ConnectOptions, Grant, IdentityState, PairingCode, ReconnectingInfo, RegisterToolOptions, SessionInfo, TabMcpEventMap, TabMcpOptions, Tool } from "./types.js";
6
+ import type { ConfirmRequest, ConnectionState, ConnectOptions, Grant, IdentityState, PairingCode, ReconnectingInfo, RegisterToolOptions, ServeHandle, ServeOptions, SessionInfo, TabMcpEventMap, TabMcpOptions, Tool, TunnelPort } from "./types.js";
7
7
  /** `wss://host/tab` for a relay given as `https://host`, `wss://host` or with `/tab`. */
8
8
  export declare function tabUrl(relay: string): {
9
9
  url: string;
@@ -11,7 +11,8 @@ export declare function tabUrl(relay: string): {
11
11
  };
12
12
  type Listener<K extends keyof TabMcpEventMap> = (event: TabMcpEventMap[K]) => void;
13
13
  /**
14
- * Offers a page's tools to AI apps through a tab-mcp relay.
14
+ * Offers a page's tools to AI apps through a tab-mcp relay (and, without
15
+ * `relay`, only through `serve` and WebMCP).
15
16
  *
16
17
  * ```ts
17
18
  * const mcp = new TabMcp({ relay: "https://relay.example", server: { name: "Calculator", version: "1.0.0" } });
@@ -75,6 +76,20 @@ export declare class TabMcp extends EventTarget {
75
76
  * While reconnecting (`reconnecting`), it makes the next attempt at once.
76
77
  */
77
78
  connect(options?: ConnectOptions): Promise<SessionInfo>;
79
+ /** Whether this `TabMcp` has a relay; without one, `connect()` rejects. */
80
+ get hasRelay(): boolean;
81
+ /**
82
+ * Serve the tools over a port, without a relay: for this site's own
83
+ * assistant, e.g. a chat in an iframe whose backend calls the tools through
84
+ * `createTunnelFetch` (`@ractive-ch/tab-mcp-client/tunnel`). The port
85
+ * carries the relay's `http.*` messages as plain objects; a `MessagePort`
86
+ * fits. Whoever holds the other end calls the tools without pairing, as
87
+ * `options.client` (`kind: "local"`): hand it out only to a frame whose
88
+ * origin you checked. Consequential tools still ask. Resolves once the port
89
+ * is served; may be called for several ports. Rejects with a `TypeError`
90
+ * for options it cannot use.
91
+ */
92
+ serve(port: TunnelPort, options: ServeOptions): Promise<ServeHandle>;
78
93
  /** End the session (`bye`). Grants stay: AI apps work again after the next `connect()`. */
79
94
  disconnect(): void;
80
95
  /**
package/tunnel.d.ts ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * `@ractive-ch/tab-mcp-client/tunnel`: the other end of `TabMcp.serve`
3
+ * (iteration 28). A `fetch` function that sends each request as an
4
+ * `http.request` message over a channel of your own (for example a
5
+ * WebSocket from your backend to a chat in the page) and builds the
6
+ * `Response` from the page's `http.response*` messages, so an MCP client
7
+ * reaches the page's tools without a relay:
8
+ *
9
+ * ```ts
10
+ * const tunnel = createTunnelFetch({ send: (message) => socket.send(JSON.stringify(message)) });
11
+ * socket.onmessage = (event) => tunnel.receive(JSON.parse(event.data));
12
+ * socket.onclose = () => tunnel.close();
13
+ * new StreamableHTTPClientTransport(new URL("https://tab.invalid/mcp"), { fetch: tunnel.fetch });
14
+ * ```
15
+ *
16
+ * It needs only `Request`, `Response` and web streams: no DOM, and nothing of
17
+ * Bun or Node. It shares no code with the page's library.
18
+ */
19
+ /** One HTTP request for the page (`docs/protocol.md`; without the relay's `grant`). */
20
+ export interface TunnelRequestMessage {
21
+ type: "http.request";
22
+ /** Unique per `createTunnelFetch`. */
23
+ id: string;
24
+ method: string;
25
+ /** Path and query, e.g. `/mcp`. */
26
+ path: string;
27
+ /** Lower-case names; only the headers the protocol passes on. */
28
+ headers: Record<string, string>;
29
+ body: string;
30
+ }
31
+ /** The caller gave up on a request: the page stops and sends nothing more for it. */
32
+ export interface TunnelCancelMessage {
33
+ type: "http.cancel";
34
+ id: string;
35
+ reason: "client_closed" | "timeout" | "error";
36
+ }
37
+ export interface TunnelFetchOptions {
38
+ /**
39
+ * Sends one message to the page's `serve` (in order, as plain objects on
40
+ * a port, or as JSON on a channel that carries text).
41
+ */
42
+ send(message: TunnelRequestMessage | TunnelCancelMessage): void;
43
+ /**
44
+ * How long a request may take until its response has ended, in
45
+ * milliseconds; 300000 by default, as at the relay. A
46
+ * `subscriptions/listen` stream is not limited.
47
+ */
48
+ requestTimeoutMs?: number;
49
+ }
50
+ export interface TunnelFetch {
51
+ /** `fetch` for an MCP client; only the path and query of the URL are used. */
52
+ fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
53
+ /**
54
+ * Hand it every message from the page's end, as an object
55
+ * (`http.response*`, `error`, `bye`); unknown ones are ignored.
56
+ */
57
+ receive(message: unknown): void;
58
+ /**
59
+ * The page's end is gone, or this end gives up: requests in flight are
60
+ * answered with a JSON-RPC error (`-31003`) and cancelled at the page,
61
+ * and every later request gets that error too. The same happens by itself
62
+ * when the page closes its `serve` (it says `bye`). A closed tunnel stays
63
+ * closed: make a new one for a new `serve`.
64
+ */
65
+ close(reason?: string): void;
66
+ }
67
+ /**
68
+ * The caller's end of the tunnel that `TabMcp.serve` answers. A timeout, a
69
+ * closed tunnel or an invalid answer of the page become JSON-RPC errors with
70
+ * the relay's codes at HTTP 200 (or the last event of a stream that had
71
+ * started), so that an MCP client reads an error, not a network failure, and
72
+ * does not send a `tools/call` again. Only an aborted `signal` rejects.
73
+ */
74
+ export declare function createTunnelFetch(options: TunnelFetchOptions): TunnelFetch;
package/tunnel.js ADDED
@@ -0,0 +1,263 @@
1
+ // src/tunnel.ts
2
+ var TIMEOUT = -31002;
3
+ var GONE = -31003;
4
+ var SEND_FAILED = -31005;
5
+ var BAD_RESPONSE = -31007;
6
+ var HEADERS = new Set([
7
+ "content-type",
8
+ "accept",
9
+ "mcp-protocol-version",
10
+ "mcp-method",
11
+ "mcp-name",
12
+ "traceparent",
13
+ "tracestate"
14
+ ]);
15
+ function isObject(v) {
16
+ return typeof v === "object" && v !== null && !Array.isArray(v);
17
+ }
18
+ function rpcId(body) {
19
+ try {
20
+ const v = JSON.parse(body);
21
+ const id = isObject(v) ? v["id"] : undefined;
22
+ return typeof id === "string" || typeof id === "number" ? id : null;
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+ function rpcError(id, code, message) {
28
+ return JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } });
29
+ }
30
+ function createTunnelFetch(options) {
31
+ const timeoutMs = options.requestTimeoutMs ?? 300000;
32
+ if (typeof options.send !== "function" || typeof timeoutMs !== "number" || !(timeoutMs > 0) || timeoutMs >= 2 ** 31) {
33
+ throw new TypeError("createTunnelFetch: needs send, and requestTimeoutMs in milliseconds (below 2^31)");
34
+ }
35
+ const pending = new Map;
36
+ const encoder = new TextEncoder;
37
+ let closed;
38
+ let last = 0;
39
+ const prefix = Math.random().toString(36).slice(2, 8);
40
+ const cancel = (id, reason) => {
41
+ try {
42
+ options.send({ type: "http.cancel", id, reason });
43
+ } catch {}
44
+ };
45
+ const fail = (id, code, message) => {
46
+ const entry = pending.get(id);
47
+ if (entry === undefined)
48
+ return;
49
+ pending.delete(id);
50
+ entry.release();
51
+ const body = rpcError(entry.rpcId, code, message);
52
+ if (entry.stream === undefined) {
53
+ entry.resolve(new Response(body, {
54
+ status: 200,
55
+ headers: { "content-type": "application/json" }
56
+ }));
57
+ return;
58
+ }
59
+ try {
60
+ if (entry.sse && (entry.tail === "" || entry.tail === `
61
+
62
+ `)) {
63
+ entry.stream.enqueue(encoder.encode(`event: message
64
+ data: ${body}
65
+
66
+ `));
67
+ entry.stream.close();
68
+ } else if (!entry.sse && entry.tail === "") {
69
+ entry.stream.enqueue(encoder.encode(body));
70
+ entry.stream.close();
71
+ } else {
72
+ entry.stream.error(new Error(message));
73
+ }
74
+ } catch {}
75
+ };
76
+ const invalid = (id) => {
77
+ cancel(id, "error");
78
+ fail(id, BAD_RESPONSE, "The page sent an invalid response.");
79
+ };
80
+ async function tunnelFetch(input, init) {
81
+ const request = new Request(input, init);
82
+ const { signal } = request;
83
+ signal.throwIfAborted();
84
+ const body = await request.text();
85
+ signal.throwIfAborted();
86
+ const jsonId = rpcId(body);
87
+ const answer = (code, message) => new Response(rpcError(jsonId, code, message), {
88
+ status: 200,
89
+ headers: { "content-type": "application/json" }
90
+ });
91
+ if (closed !== undefined)
92
+ return answer(GONE, closed);
93
+ const url = new URL(request.url);
94
+ const headers = {};
95
+ request.headers.forEach((value, name) => {
96
+ const lower = name.toLowerCase();
97
+ if (HEADERS.has(lower) || lower.startsWith("mcp-param-"))
98
+ headers[lower] = value;
99
+ });
100
+ const id = `${prefix}-${++last}`;
101
+ return new Promise((resolve, reject) => {
102
+ const onAbort = () => {
103
+ const entry = pending.get(id);
104
+ if (entry === undefined)
105
+ return;
106
+ pending.delete(id);
107
+ entry.release();
108
+ cancel(id, "client_closed");
109
+ if (entry.stream === undefined)
110
+ entry.reject(signal.reason);
111
+ else
112
+ try {
113
+ entry.stream.error(signal.reason);
114
+ } catch {}
115
+ };
116
+ const timer = headers["mcp-method"] === "subscriptions/listen" ? undefined : setTimeout(() => {
117
+ cancel(id, "timeout");
118
+ fail(id, TIMEOUT, "The page did not answer in time.");
119
+ }, timeoutMs);
120
+ signal.addEventListener("abort", onAbort);
121
+ pending.set(id, {
122
+ rpcId: jsonId,
123
+ resolve,
124
+ reject,
125
+ sse: false,
126
+ tail: "",
127
+ release() {
128
+ clearTimeout(timer);
129
+ signal.removeEventListener("abort", onAbort);
130
+ }
131
+ });
132
+ try {
133
+ options.send({
134
+ type: "http.request",
135
+ id,
136
+ method: request.method,
137
+ path: url.pathname + url.search,
138
+ headers,
139
+ body
140
+ });
141
+ } catch {
142
+ fail(id, SEND_FAILED, "The request could not be sent to the page.");
143
+ }
144
+ });
145
+ }
146
+ function end(reason, tellPage) {
147
+ if (closed !== undefined)
148
+ return;
149
+ closed = reason;
150
+ for (const id of [...pending.keys()]) {
151
+ if (tellPage)
152
+ cancel(id, "client_closed");
153
+ fail(id, GONE, reason);
154
+ }
155
+ }
156
+ function receive(message) {
157
+ if (!isObject(message))
158
+ return;
159
+ const { type, id } = message;
160
+ if (type === "bye") {
161
+ end("The page stopped serving its tools.", false);
162
+ return;
163
+ }
164
+ if (typeof id !== "string")
165
+ return;
166
+ const entry = pending.get(id);
167
+ if (entry === undefined)
168
+ return;
169
+ const { status, headers } = message;
170
+ const head = typeof status === "number" && Number.isInteger(status) && status >= 200 && status <= 599 && isObject(headers) && Object.values(headers).every((v) => typeof v === "string");
171
+ switch (type) {
172
+ case "http.response": {
173
+ const { body } = message;
174
+ if (entry.stream !== undefined || !head || typeof body !== "string" || body !== "" && [204, 205, 304].includes(status)) {
175
+ invalid(id);
176
+ return;
177
+ }
178
+ let response;
179
+ try {
180
+ response = new Response(body === "" ? null : body, {
181
+ status,
182
+ headers
183
+ });
184
+ } catch {
185
+ invalid(id);
186
+ return;
187
+ }
188
+ pending.delete(id);
189
+ entry.release();
190
+ entry.resolve(response);
191
+ return;
192
+ }
193
+ case "http.response.start": {
194
+ if (entry.stream !== undefined || !head) {
195
+ invalid(id);
196
+ return;
197
+ }
198
+ let response;
199
+ try {
200
+ response = new Response(new ReadableStream({
201
+ start(controller) {
202
+ entry.stream = controller;
203
+ },
204
+ cancel() {
205
+ if (pending.get(id) !== entry)
206
+ return;
207
+ pending.delete(id);
208
+ entry.release();
209
+ cancel(id, "client_closed");
210
+ }
211
+ }), {
212
+ status,
213
+ headers
214
+ });
215
+ } catch {
216
+ delete entry.stream;
217
+ invalid(id);
218
+ return;
219
+ }
220
+ entry.sse = (headers["content-type"] ?? "").startsWith("text/event-stream");
221
+ entry.resolve(response);
222
+ return;
223
+ }
224
+ case "http.response.chunk": {
225
+ const { data } = message;
226
+ if (entry.stream === undefined || typeof data !== "string") {
227
+ invalid(id);
228
+ return;
229
+ }
230
+ if (data === "")
231
+ return;
232
+ entry.tail = (entry.tail + data).slice(-2);
233
+ entry.stream.enqueue(encoder.encode(data));
234
+ return;
235
+ }
236
+ case "http.response.end":
237
+ if (entry.stream === undefined) {
238
+ invalid(id);
239
+ return;
240
+ }
241
+ pending.delete(id);
242
+ entry.release();
243
+ entry.stream.close();
244
+ return;
245
+ case "error":
246
+ fail(id, BAD_RESPONSE, `The page refused the request: ${typeof message["message"] === "string" ? message["message"].slice(0, 200) : "bad message"}`);
247
+ return;
248
+ }
249
+ }
250
+ return {
251
+ fetch: tunnelFetch,
252
+ receive,
253
+ close(reason) {
254
+ end(reason ?? "The connection to the page was closed.", true);
255
+ }
256
+ };
257
+ }
258
+ export {
259
+ createTunnelFetch
260
+ };
261
+
262
+ //# debugId=33372546E9704AD064756E2164756E21
263
+ //# sourceMappingURL=tunnel.js.map
package/tunnel.js.map ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/tunnel.ts"],
4
+ "sourcesContent": [
5
+ "/**\n * `@ractive-ch/tab-mcp-client/tunnel`: the other end of `TabMcp.serve`\n * (iteration 28). A `fetch` function that sends each request as an\n * `http.request` message over a channel of your own (for example a\n * WebSocket from your backend to a chat in the page) and builds the\n * `Response` from the page's `http.response*` messages, so an MCP client\n * reaches the page's tools without a relay:\n *\n * ```ts\n * const tunnel = createTunnelFetch({ send: (message) => socket.send(JSON.stringify(message)) });\n * socket.onmessage = (event) => tunnel.receive(JSON.parse(event.data));\n * socket.onclose = () => tunnel.close();\n * new StreamableHTTPClientTransport(new URL(\"https://tab.invalid/mcp\"), { fetch: tunnel.fetch });\n * ```\n *\n * It needs only `Request`, `Response` and web streams: no DOM, and nothing of\n * Bun or Node. It shares no code with the page's library.\n */\n\n/** One HTTP request for the page (`docs/protocol.md`; without the relay's `grant`). */\nexport interface TunnelRequestMessage {\n\ttype: \"http.request\";\n\t/** Unique per `createTunnelFetch`. */\n\tid: string;\n\tmethod: string;\n\t/** Path and query, e.g. `/mcp`. */\n\tpath: string;\n\t/** Lower-case names; only the headers the protocol passes on. */\n\theaders: Record<string, string>;\n\tbody: string;\n}\n\n/** The caller gave up on a request: the page stops and sends nothing more for it. */\nexport interface TunnelCancelMessage {\n\ttype: \"http.cancel\";\n\tid: string;\n\treason: \"client_closed\" | \"timeout\" | \"error\";\n}\n\nexport interface TunnelFetchOptions {\n\t/**\n\t * Sends one message to the page's `serve` (in order, as plain objects on\n\t * a port, or as JSON on a channel that carries text).\n\t */\n\tsend(message: TunnelRequestMessage | TunnelCancelMessage): void;\n\t/**\n\t * How long a request may take until its response has ended, in\n\t * milliseconds; 300000 by default, as at the relay. A\n\t * `subscriptions/listen` stream is not limited.\n\t */\n\trequestTimeoutMs?: number;\n}\n\nexport interface TunnelFetch {\n\t/** `fetch` for an MCP client; only the path and query of the URL are used. */\n\tfetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;\n\t/**\n\t * Hand it every message from the page's end, as an object\n\t * (`http.response*`, `error`, `bye`); unknown ones are ignored.\n\t */\n\treceive(message: unknown): void;\n\t/**\n\t * The page's end is gone, or this end gives up: requests in flight are\n\t * answered with a JSON-RPC error (`-31003`) and cancelled at the page,\n\t * and every later request gets that error too. The same happens by itself\n\t * when the page closes its `serve` (it says `bye`). A closed tunnel stays\n\t * closed: make a new one for a new `serve`.\n\t */\n\tclose(reason?: string): void;\n}\n\n/** The relay's error codes (`docs/protocol.md`, \"Errors the relay sends to the AI app\"). */\nconst TIMEOUT = -31002;\nconst GONE = -31003;\nconst SEND_FAILED = -31005;\nconst BAD_RESPONSE = -31007;\n\n/** The request headers the protocol passes on; `mcp-param-*` too. */\nconst HEADERS = new Set([\n\t\"content-type\",\n\t\"accept\",\n\t\"mcp-protocol-version\",\n\t\"mcp-method\",\n\t\"mcp-name\",\n\t\"traceparent\",\n\t\"tracestate\",\n]);\n\ntype RpcId = string | number | null;\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n\treturn typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** The JSON-RPC id of a request body, for the error that answers it. */\nfunction rpcId(body: string): RpcId {\n\ttry {\n\t\tconst v: unknown = JSON.parse(body);\n\t\tconst id = isObject(v) ? v[\"id\"] : undefined;\n\t\treturn typeof id === \"string\" || typeof id === \"number\" ? id : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction rpcError(id: RpcId, code: number, message: string): string {\n\treturn JSON.stringify({ jsonrpc: \"2.0\", id, error: { code, message } });\n}\n\ninterface Pending {\n\trpcId: RpcId;\n\t/** The fetch promise, until the response has started. */\n\tresolve(response: Response): void;\n\treject(reason: unknown): void;\n\t/** The body of a streamed response, once it has started. */\n\tstream?: ReadableStreamDefaultController<Uint8Array>;\n\t/** Whether the streamed response is an event stream (else one body in pieces). */\n\tsse: boolean;\n\t/** The last two characters of the stream so far: empty or a blank line is between two events. */\n\ttail: string;\n\t/** Stop the timer and the abort listener. */\n\trelease(): void;\n}\n\n/**\n * The caller's end of the tunnel that `TabMcp.serve` answers. A timeout, a\n * closed tunnel or an invalid answer of the page become JSON-RPC errors with\n * the relay's codes at HTTP 200 (or the last event of a stream that had\n * started), so that an MCP client reads an error, not a network failure, and\n * does not send a `tools/call` again. Only an aborted `signal` rejects.\n */\nexport function createTunnelFetch(options: TunnelFetchOptions): TunnelFetch {\n\tconst timeoutMs = options.requestTimeoutMs ?? 300_000;\n\tif (\n\t\ttypeof options.send !== \"function\" ||\n\t\ttypeof timeoutMs !== \"number\" ||\n\t\t!(timeoutMs > 0) ||\n\t\t// What `setTimeout` can keep: beyond it (and for Infinity) it fires at once.\n\t\ttimeoutMs >= 2 ** 31\n\t) {\n\t\tthrow new TypeError(\n\t\t\t\"createTunnelFetch: needs send, and requestTimeoutMs in milliseconds (below 2^31)\",\n\t\t);\n\t}\n\tconst pending = new Map<string, Pending>();\n\tconst encoder = new TextEncoder();\n\tlet closed: string | undefined;\n\tlet last = 0;\n\t// Ids of two tunnels over one channel must not meet (a backend that makes\n\t// a new tunnel while the page still answers the old one's requests).\n\tconst prefix = Math.random().toString(36).slice(2, 8);\n\n\tconst cancel = (id: string, reason: TunnelCancelMessage[\"reason\"]): void => {\n\t\ttry {\n\t\t\toptions.send({ type: \"http.cancel\", id, reason });\n\t\t} catch {\n\t\t\t// the channel is gone: nothing to cancel\n\t\t}\n\t};\n\n\t/** End a request with a JSON-RPC error: as its response, or as its stream's last event. */\n\tconst fail = (id: string, code: number, message: string): void => {\n\t\tconst entry = pending.get(id);\n\t\tif (entry === undefined) return;\n\t\tpending.delete(id);\n\t\tentry.release();\n\t\tconst body = rpcError(entry.rpcId, code, message);\n\t\tif (entry.stream === undefined) {\n\t\t\tentry.resolve(\n\t\t\t\tnew Response(body, {\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tif (entry.sse && (entry.tail === \"\" || entry.tail === \"\\n\\n\")) {\n\t\t\t\tentry.stream.enqueue(\n\t\t\t\t\tencoder.encode(`event: message\\ndata: ${body}\\n\\n`),\n\t\t\t\t);\n\t\t\t\tentry.stream.close();\n\t\t\t} else if (!entry.sse && entry.tail === \"\") {\n\t\t\t\t// A body in pieces of which none came yet: the error is the body.\n\t\t\t\tentry.stream.enqueue(encoder.encode(body));\n\t\t\t\tentry.stream.close();\n\t\t\t} else {\n\t\t\t\t// In the middle of an event or a body: nothing readable can follow it.\n\t\t\t\tentry.stream.error(new Error(message));\n\t\t\t}\n\t\t} catch {\n\t\t\t// the reader has gone\n\t\t}\n\t};\n\n\t/** The page broke the protocol for this request. */\n\tconst invalid = (id: string): void => {\n\t\tcancel(id, \"error\");\n\t\tfail(id, BAD_RESPONSE, \"The page sent an invalid response.\");\n\t};\n\n\tasync function tunnelFetch(\n\t\tinput: string | URL | Request,\n\t\tinit?: RequestInit,\n\t): Promise<Response> {\n\t\tconst request = new Request(input, init);\n\t\tconst { signal } = request;\n\t\tsignal.throwIfAborted();\n\t\tconst body = await request.text();\n\t\tsignal.throwIfAborted();\n\t\tconst jsonId = rpcId(body);\n\t\tconst answer = (code: number, message: string) =>\n\t\t\tnew Response(rpcError(jsonId, code, message), {\n\t\t\t\tstatus: 200,\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t});\n\t\tif (closed !== undefined) return answer(GONE, closed);\n\t\tconst url = new URL(request.url);\n\t\tconst headers: Record<string, string> = {};\n\t\trequest.headers.forEach((value, name) => {\n\t\t\tconst lower = name.toLowerCase();\n\t\t\tif (HEADERS.has(lower) || lower.startsWith(\"mcp-param-\"))\n\t\t\t\theaders[lower] = value;\n\t\t});\n\t\tconst id = `${prefix}-${++last}`;\n\t\treturn new Promise<Response>((resolve, reject) => {\n\t\t\tconst onAbort = () => {\n\t\t\t\tconst entry = pending.get(id);\n\t\t\t\tif (entry === undefined) return;\n\t\t\t\tpending.delete(id);\n\t\t\t\tentry.release();\n\t\t\t\tcancel(id, \"client_closed\");\n\t\t\t\tif (entry.stream === undefined) entry.reject(signal.reason);\n\t\t\t\telse\n\t\t\t\t\ttry {\n\t\t\t\t\t\tentry.stream.error(signal.reason);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// the reader has gone\n\t\t\t\t\t}\n\t\t\t};\n\t\t\t// A listen stream stays open for as long as the caller wants it.\n\t\t\tconst timer =\n\t\t\t\theaders[\"mcp-method\"] === \"subscriptions/listen\"\n\t\t\t\t\t? undefined\n\t\t\t\t\t: setTimeout(() => {\n\t\t\t\t\t\t\tcancel(id, \"timeout\");\n\t\t\t\t\t\t\tfail(id, TIMEOUT, \"The page did not answer in time.\");\n\t\t\t\t\t\t}, timeoutMs);\n\t\t\tsignal.addEventListener(\"abort\", onAbort);\n\t\t\tpending.set(id, {\n\t\t\t\trpcId: jsonId,\n\t\t\t\tresolve,\n\t\t\t\treject,\n\t\t\t\tsse: false,\n\t\t\t\ttail: \"\",\n\t\t\t\trelease() {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\t},\n\t\t\t});\n\t\t\ttry {\n\t\t\t\toptions.send({\n\t\t\t\t\ttype: \"http.request\",\n\t\t\t\t\tid,\n\t\t\t\t\tmethod: request.method,\n\t\t\t\t\tpath: url.pathname + url.search,\n\t\t\t\t\theaders,\n\t\t\t\t\tbody,\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\tfail(id, SEND_FAILED, \"The request could not be sent to the page.\");\n\t\t\t}\n\t\t});\n\t}\n\n\t/** No more requests: those in flight end with `-31003`, and so does every later one. */\n\tfunction end(reason: string, tellPage: boolean): void {\n\t\tif (closed !== undefined) return;\n\t\tclosed = reason;\n\t\tfor (const id of [...pending.keys()]) {\n\t\t\tif (tellPage) cancel(id, \"client_closed\");\n\t\t\tfail(id, GONE, reason);\n\t\t}\n\t}\n\n\tfunction receive(message: unknown): void {\n\t\tif (!isObject(message)) return;\n\t\tconst { type, id } = message;\n\t\tif (type === \"bye\") {\n\t\t\t// The page closed its `serve`: nothing will be answered any more.\n\t\t\tend(\"The page stopped serving its tools.\", false);\n\t\t\treturn;\n\t\t}\n\t\tif (typeof id !== \"string\") return;\n\t\tconst entry = pending.get(id);\n\t\tif (entry === undefined) return; // over already: late messages are dropped\n\t\tconst { status, headers } = message;\n\t\tconst head =\n\t\t\ttypeof status === \"number\" &&\n\t\t\tNumber.isInteger(status) &&\n\t\t\tstatus >= 200 &&\n\t\t\tstatus <= 599 &&\n\t\t\tisObject(headers) &&\n\t\t\tObject.values(headers).every((v) => typeof v === \"string\");\n\t\tswitch (type) {\n\t\t\tcase \"http.response\": {\n\t\t\t\tconst { body } = message;\n\t\t\t\tif (\n\t\t\t\t\tentry.stream !== undefined ||\n\t\t\t\t\t!head ||\n\t\t\t\t\ttypeof body !== \"string\" ||\n\t\t\t\t\t// A status without a body, as the relay has it (`-31007`).\n\t\t\t\t\t(body !== \"\" && [204, 205, 304].includes(status as number))\n\t\t\t\t) {\n\t\t\t\t\tinvalid(id);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet response: Response;\n\t\t\t\ttry {\n\t\t\t\t\tresponse = new Response(body === \"\" ? null : body, {\n\t\t\t\t\t\tstatus: status as number,\n\t\t\t\t\t\theaders: headers as Record<string, string>,\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\tinvalid(id); // e.g. a body with status 204\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tpending.delete(id);\n\t\t\t\tentry.release();\n\t\t\t\tentry.resolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"http.response.start\": {\n\t\t\t\tif (entry.stream !== undefined || !head) {\n\t\t\t\t\tinvalid(id);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet response: Response;\n\t\t\t\ttry {\n\t\t\t\t\tresponse = new Response(\n\t\t\t\t\t\tnew ReadableStream<Uint8Array>({\n\t\t\t\t\t\t\tstart(controller) {\n\t\t\t\t\t\t\t\tentry.stream = controller;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcancel() {\n\t\t\t\t\t\t\t\t// The reader gave up: so does the page.\n\t\t\t\t\t\t\t\tif (pending.get(id) !== entry) return;\n\t\t\t\t\t\t\t\tpending.delete(id);\n\t\t\t\t\t\t\t\tentry.release();\n\t\t\t\t\t\t\t\tcancel(id, \"client_closed\");\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstatus: status as number,\n\t\t\t\t\t\t\theaders: headers as Record<string, string>,\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t} catch {\n\t\t\t\t\tdelete entry.stream;\n\t\t\t\t\tinvalid(id);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tentry.sse = (\n\t\t\t\t\t(headers as Record<string, string>)[\"content-type\"] ?? \"\"\n\t\t\t\t).startsWith(\"text/event-stream\");\n\t\t\t\tentry.resolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"http.response.chunk\": {\n\t\t\t\tconst { data } = message;\n\t\t\t\tif (entry.stream === undefined || typeof data !== \"string\") {\n\t\t\t\t\tinvalid(id);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (data === \"\") return;\n\t\t\t\tentry.tail = (entry.tail + data).slice(-2);\n\t\t\t\tentry.stream.enqueue(encoder.encode(data));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"http.response.end\":\n\t\t\t\tif (entry.stream === undefined) {\n\t\t\t\t\tinvalid(id);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tpending.delete(id);\n\t\t\t\tentry.release();\n\t\t\t\tentry.stream.close();\n\t\t\t\treturn;\n\t\t\tcase \"error\":\n\t\t\t\t// `serve` refused the request as sent (`bad_message`).\n\t\t\t\tfail(\n\t\t\t\t\tid,\n\t\t\t\t\tBAD_RESPONSE,\n\t\t\t\t\t`The page refused the request: ${\n\t\t\t\t\t\ttypeof message[\"message\"] === \"string\"\n\t\t\t\t\t\t\t? message[\"message\"].slice(0, 200)\n\t\t\t\t\t\t\t: \"bad message\"\n\t\t\t\t\t}`,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t}\n\t}\n\n\treturn {\n\t\tfetch: tunnelFetch,\n\t\treceive,\n\t\tclose(reason?: string): void {\n\t\t\t// The page is told too, in case the channel still stands.\n\t\t\tend(reason ?? \"The connection to the page was closed.\", true);\n\t\t},\n\t};\n}\n"
6
+ ],
7
+ "mappings": ";AAwEA,IAAM,UAAU;AAChB,IAAM,OAAO;AACb,IAAM,cAAc;AACpB,IAAM,eAAe;AAGrB,IAAM,UAAU,IAAI,IAAI;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,CAAC;AAID,SAAS,QAAQ,CAAC,GAA0C;AAAA,EAC3D,OAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAAA;AAI/D,SAAS,KAAK,CAAC,MAAqB;AAAA,EACnC,IAAI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AA,UACV;AAAA,QACD;AAAA,QACA,QAAQ,OAAO,EAAE;AAAA,QACjB,MAAM,QAAQ;AAAA,QACd,MAAM,OAAO,MAAM;AAAA,QACnB;AAAA,MACD,KAAK;AAAA,QAEJ,KACC,IACA,cACA,iCACC,OAAO,QAAQ,eAAe,WAC3B,QAAQ,WAAW,MAAM,GAAG,GAAG,IAC/B,eAEL;AAAA,QACA;AAAA;AAAA;AAAA,EAIH,OAAO;AAAA,IACN,OAAO;AAAA,IACP;AAAA,IACA,KAAK,CAAC,QAAuB;AAAA,MAE5B,IAAI,UAAU,0CAA0C,IAAI;AAAA;AAAA,EAE9D;AAAA;",
8
+ "debugId": "33372546E9704AD064756E2164756E21",
9
+ "names": []
10
+ }
package/types.d.ts CHANGED
@@ -45,8 +45,58 @@ export interface RelayClient {
45
45
  export interface WebMcpClient {
46
46
  kind: "webmcp";
47
47
  }
48
- /** Who calls a tool: an AI app through the relay, or an agent in the browser (`kind`). */
49
- export type ToolCallClient = RelayClient | WebMcpClient;
48
+ /**
49
+ * This site's own assistant, which the page serves its tools to over a port
50
+ * (`serve`). Not paired: the page chose who holds the other end of the port,
51
+ * and `id` and `name` are what the page said in `serve`.
52
+ */
53
+ export interface LocalClient {
54
+ kind: "local";
55
+ /** `ServeOptions.client.id`. */
56
+ id: string;
57
+ /** `ServeOptions.client.name`. */
58
+ name?: string;
59
+ }
60
+ /**
61
+ * Who calls a tool (`kind`): an AI app through the relay, an agent in the
62
+ * browser, or this site's own assistant over a port.
63
+ */
64
+ export type ToolCallClient = RelayClient | WebMcpClient | LocalClient;
65
+ /**
66
+ * What `serve` talks over: a `MessagePort`, or an object of your own around
67
+ * another channel. The messages are plain objects (`docs/protocol.md`, "The
68
+ * tunnel without a relay"); `serve` sets `onmessage`.
69
+ */
70
+ export interface TunnelPort {
71
+ postMessage(message: unknown): void;
72
+ onmessage: TunnelPortHandler | null;
73
+ }
74
+ /** `TunnelPort.onmessage` (declared as a method, so that a `MessagePort` fits). */
75
+ export type TunnelPortHandler = {
76
+ handler(event: {
77
+ data: unknown;
78
+ }): void;
79
+ }["handler"];
80
+ /** Options of `serve`. */
81
+ export interface ServeOptions {
82
+ /** Who is on the other end: shown in confirmations, passed to `execute` and the events. */
83
+ client: {
84
+ id: string;
85
+ name?: string;
86
+ };
87
+ /** Aborting it stops serving: calls in flight are aborted, the port is let go. */
88
+ signal?: AbortSignal;
89
+ /**
90
+ * The largest piece of a response body in one message, in characters
91
+ * (UTF-16 units); 65536 by default, at least 64. Longer bodies are streamed.
92
+ */
93
+ maxChunk?: number;
94
+ }
95
+ /** What `serve` resolves with. */
96
+ export interface ServeHandle {
97
+ /** Stop serving this port: calls in flight are aborted, the port is let go. */
98
+ close(): void;
99
+ }
50
100
  /** Second argument of `execute`. */
51
101
  export interface ToolExecuteOptions {
52
102
  /**
@@ -54,7 +104,7 @@ export interface ToolExecuteOptions {
54
104
  * (a WebMCP call: when the browser cancels it).
55
105
  */
56
106
  signal: AbortSignal;
57
- /** Who is calling: `client.kind` is `"relay"` or `"webmcp"`. */
107
+ /** Who is calling: `client.kind` is `"relay"`, `"webmcp"` or `"local"`. */
58
108
  client: ToolCallClient;
59
109
  }
60
110
  /**
@@ -126,16 +176,27 @@ export interface ConfirmRequest {
126
176
  /** Aborted when the call is cancelled; close the question then. */
127
177
  signal: AbortSignal;
128
178
  }
179
+ /**
180
+ * The answer to a consequential tool call: `true` runs it, `false` is a
181
+ * refusal, `"unanswered"` says the user was asked and did not answer (e.g. a
182
+ * question of your own that timed out). The AI app is told which.
183
+ */
184
+ export type ConfirmAnswer = boolean | "unanswered";
129
185
  /** Decides whether a consequential tool may run. */
130
- export type ConfirmHandler = (request: ConfirmRequest) => boolean | Promise<boolean>;
186
+ export type ConfirmHandler = (request: ConfirmRequest) => ConfirmAnswer | Promise<ConfirmAnswer>;
131
187
  /** Where the address secret is kept (`localStorage` by default). */
132
188
  export interface SecretStorage {
133
189
  getItem(key: string): string | null;
134
190
  setItem(key: string, value: string): void;
135
191
  }
136
192
  export interface TabMcpOptions {
137
- /** The relay, e.g. `https://relay.example` or `wss://relay.example`. */
138
- relay: string;
193
+ /**
194
+ * The relay, e.g. `https://relay.example` or `wss://relay.example`.
195
+ * Without one the page offers its tools only through `serve` and WebMCP:
196
+ * `connect()`, `showConnectDialog()` and `newAddress()` reject, and no
197
+ * address secret is read or written.
198
+ */
199
+ relay?: string;
139
200
  /** Name, version and instructions of the page's MCP server. */
140
201
  server: ServerInfo;
141
202
  /** The page's app name (e.g. `saturnus`), shown when an AI app pairs; at most 64 characters. */
@@ -344,8 +405,11 @@ export interface ToolCallStart {
344
405
  arguments: Record<string, unknown>;
345
406
  client: ToolCallClient;
346
407
  }
347
- /** How a tool call ended: `declined` by the user, `cancelled` by the AI app. */
348
- export type ToolCallOutcome = "ok" | "error" | "declined" | "cancelled";
408
+ /**
409
+ * How a tool call ended: `declined` by the user, `unanswered` (the user was
410
+ * asked and did not answer, see `ConfirmAnswer`), `cancelled` by the AI app.
411
+ */
412
+ export type ToolCallOutcome = "ok" | "error" | "declined" | "unanswered" | "cancelled";
349
413
  /** The MCP result of a tool call, as the AI app gets it. */
350
414
  export interface ToolCallResult {
351
415
  content: unknown[];
@@ -402,6 +466,6 @@ export interface TabMcpEventMap {
402
466
  reconnecting: CustomEvent<ReconnectingInfo | null>;
403
467
  /** An AI app called a tool (before any confirmation). */
404
468
  toolcall: CustomEvent<ToolCallStart>;
405
- /** That call ended; also when the user declined it or the AI app cancelled it. */
469
+ /** That call ended; also when the user declined it, did not answer, or the AI app cancelled it. */
406
470
  toolcallend: CustomEvent<ToolCallEnd>;
407
471
  }
@@ -195,6 +195,8 @@ var visible = escapeInvisible2;
195
195
  function clientLabel(client) {
196
196
  if ("kind" in client && client.kind === "webmcp")
197
197
  return "An agent in this browser";
198
+ if ("kind" in client && client.kind === "local")
199
+ return `${visible(client.name ?? client.id)} (this site's assistant)`;
198
200
  const host = visible(client.host || client.id);
199
201
  return client.name !== undefined && client.name !== "" ? `${visible(client.name)} (${host})` : host;
200
202
  }
@@ -777,5 +779,5 @@ export {
777
779
  showConnectDialog
778
780
  };
779
781
 
780
- //# debugId=95F32EBF4C4F2F7364756E2164756E21
781
- //# sourceMappingURL=ui-4qv8d1a3.js.map
782
+ //# debugId=BBCCC525D96FC97D64756E2164756E21
783
+ //# sourceMappingURL=ui-04mwfxm9.js.map