@ractive-ch/tab-mcp-client 0.15.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.
Files changed (53) hide show
  1. package/README.md +454 -147
  2. package/always-allowed.d.ts +25 -6
  3. package/cdn/confirm-y30cx7e1.min.js +4 -0
  4. package/cdn/confirm-y30cx7e1.min.js.map +10 -0
  5. package/cdn/connect-bbhj2y7w.min.js +6 -0
  6. package/cdn/connect-bbhj2y7w.min.js.map +12 -0
  7. package/cdn/connection-0y7ngtq7.min.js +17 -0
  8. package/cdn/connection-0y7ngtq7.min.js.map +22 -0
  9. package/cdn/index-vt5zk9me.min.js +91 -0
  10. package/cdn/index-vt5zk9me.min.js.map +13 -0
  11. package/cdn/tab-mcp-client.min.js +3 -3
  12. package/cdn/tab-mcp-client.min.js.map +6 -6
  13. package/confirm-fgnjgd08.js +263 -0
  14. package/confirm-fgnjgd08.js.map +10 -0
  15. package/confirm.d.ts +54 -0
  16. package/connect-8jpb0k29.js +484 -0
  17. package/connect-8jpb0k29.js.map +10 -0
  18. package/connect.d.ts +40 -0
  19. package/{connection-g6wk37yd.js → connection-1d8rxgbq.js} +247 -126
  20. package/connection-1d8rxgbq.js.map +16 -0
  21. package/connection.d.ts +7 -4
  22. package/dialog.d.ts +83 -0
  23. package/{index-nmn1j689.js → index-5jyqehpk.js} +14 -10
  24. package/index-5jyqehpk.js.map +11 -0
  25. package/index-jnz7w9xa.js +392 -0
  26. package/index-jnz7w9xa.js.map +12 -0
  27. package/index.d.ts +1 -1
  28. package/index.js +257 -240
  29. package/index.js.map +6 -6
  30. package/mapping.d.ts +37 -4
  31. package/mcp.d.ts +23 -8
  32. package/package.json +1 -1
  33. package/react.d.ts +8 -10
  34. package/react.js +18 -14
  35. package/react.js.map +3 -3
  36. package/registry.d.ts +12 -5
  37. package/secret.d.ts +5 -2
  38. package/serve.d.ts +26 -4
  39. package/setup.d.ts +15 -25
  40. package/setup.js +1 -1
  41. package/strings.d.ts +107 -0
  42. package/tab-mcp.d.ts +60 -35
  43. package/types.d.ts +146 -68
  44. package/webmcp.d.ts +13 -18
  45. package/cdn/connection-hgt931xk.min.js +0 -12
  46. package/cdn/connection-hgt931xk.min.js.map +0 -22
  47. package/cdn/ui-2nv84ry7.min.js +0 -86
  48. package/cdn/ui-2nv84ry7.min.js.map +0 -14
  49. package/connection-g6wk37yd.js.map +0 -16
  50. package/index-nmn1j689.js.map +0 -11
  51. package/ui-04mwfxm9.js +0 -783
  52. package/ui-04mwfxm9.js.map +0 -11
  53. package/ui.d.ts +0 -83
@@ -102,20 +102,64 @@ function mapAnnotations(hints) {
102
102
  out.meta = meta;
103
103
  return out;
104
104
  }
105
+ function markUntrusted(result) {
106
+ const meta = result._meta ?? {};
107
+ const own = meta[ANNOTATIONS_META_KEY];
108
+ return {
109
+ ...result,
110
+ _meta: {
111
+ ...meta,
112
+ [ANNOTATIONS_META_KEY]: {
113
+ ...isObject(own) ? own : {},
114
+ untrustedContentHint: true
115
+ }
116
+ }
117
+ };
118
+ }
105
119
  function errorResult(message) {
106
120
  return { content: [{ type: "text", text: message }], isError: true };
107
121
  }
108
- function isPlainObject(v) {
122
+ function isObject(v) {
109
123
  return typeof v === "object" && v !== null && !Array.isArray(v);
110
124
  }
125
+ var isString = (v) => typeof v === "string";
126
+ function isContentBlock(block) {
127
+ if (!isObject(block))
128
+ return false;
129
+ switch (block["type"]) {
130
+ case "text":
131
+ return isString(block["text"]);
132
+ case "image":
133
+ case "audio":
134
+ return isString(block["data"]) && isString(block["mimeType"]);
135
+ case "resource_link":
136
+ return isString(block["uri"]) && isString(block["name"]);
137
+ case "resource":
138
+ return isObject(block["resource"]) && isString(block["resource"]["uri"]);
139
+ default:
140
+ return false;
141
+ }
142
+ }
143
+ var RESULT_KEYS = new Set([
144
+ "content",
145
+ "structuredContent",
146
+ "isError",
147
+ "_meta",
148
+ "resultType"
149
+ ]);
150
+ function isCallToolResult(value) {
151
+ if (!isObject(value) || !Array.isArray(value["content"]))
152
+ return false;
153
+ const { content, isError, structuredContent, _meta } = value;
154
+ return (content.length > 0 ? content.every(isContentBlock) : Object.keys(value).every((key) => RESULT_KEYS.has(key))) && (isError === undefined || typeof isError === "boolean") && (structuredContent === undefined || isObject(structuredContent)) && (_meta === undefined || isObject(_meta));
155
+ }
111
156
  function toCallToolResult(value) {
112
157
  if (typeof value === "string")
113
158
  return { content: [{ type: "text", text: value }] };
114
159
  if (value === undefined)
115
160
  return { content: [] };
116
- if (isPlainObject(value) && Array.isArray(value["content"])) {
161
+ if (isCallToolResult(value))
117
162
  return value;
118
- }
119
163
  let text;
120
164
  try {
121
165
  text = JSON.stringify(value);
@@ -123,10 +167,20 @@ function toCallToolResult(value) {
123
167
  if (text === undefined)
124
168
  return errorResult("The tool returned a value that is not JSON.");
125
169
  const result = { content: [{ type: "text", text }] };
126
- if (isPlainObject(value))
127
- result.structuredContent = value;
170
+ const parsed = JSON.parse(text);
171
+ if (isObject(parsed))
172
+ result.structuredContent = parsed;
128
173
  return result;
129
174
  }
175
+ function resultText(result, noted = false) {
176
+ return result.content.map((block) => isObject(block) && block["type"] === "text" && typeof block["text"] === "string" ? block["text"] : noted ? `[${isObject(block) ? String(block["type"]) : "A"} content left out: WebMCP results are text.]` : "").filter((text) => text !== "").join(`
177
+ `);
178
+ }
179
+ function webMcpValue(value) {
180
+ if (isCallToolResult(value))
181
+ return value.structuredContent ?? (resultText(value, true) || "Done.");
182
+ return value === undefined ? "Done." : value;
183
+ }
130
184
  function thrownResult(error) {
131
185
  const message = error instanceof Error ? error.message : String(error);
132
186
  return errorResult(message || "The tool failed.");
@@ -141,6 +195,7 @@ var META_SERVER_INFO = "io.modelcontextprotocol/serverInfo";
141
195
  var META_SUBSCRIPTION = "io.modelcontextprotocol/subscriptionId";
142
196
  var HEADER_MISMATCH = -32020;
143
197
  var UNSUPPORTED_VERSION = -32022;
198
+ var CONFIRMED_IN_TAB = "The page may ask the user to allow each call, usually in the page's browser tab.";
144
199
  var lastCallId = 0;
145
200
  var compiled = new WeakMap;
146
201
  function compileTool(tool) {
@@ -198,7 +253,7 @@ function copy(value) {
198
253
  }
199
254
  }
200
255
  var encoder = new TextEncoder;
201
- function isObject(v) {
256
+ function isObject2(v) {
202
257
  return typeof v === "object" && v !== null && !Array.isArray(v);
203
258
  }
204
259
  function json(status, value) {
@@ -253,17 +308,17 @@ function envelopeIssue(meta) {
253
308
  if (typeof meta[META_VERSION] !== "string") {
254
309
  return { key: META_VERSION, problem: "expected a protocol version string" };
255
310
  }
256
- if (!isObject(meta[META_CAPABILITIES]))
311
+ if (!isObject2(meta[META_CAPABILITIES]))
257
312
  return { key: META_CAPABILITIES, problem: "expected an object" };
258
313
  const info = meta[META_CLIENT_INFO];
259
- if (info !== undefined && !(isObject(info) && typeof info["name"] === "string" && typeof info["version"] === "string")) {
314
+ if (info !== undefined && !(isObject2(info) && typeof info["name"] === "string" && typeof info["version"] === "string")) {
260
315
  return { key: META_CLIENT_INFO, problem: "expected {name, version}" };
261
316
  }
262
317
  return;
263
318
  }
264
319
  function honoured(params) {
265
320
  const requested = params["notifications"];
266
- return isObject(requested) && requested["toolsListChanged"] === true ? { toolsListChanged: true } : {};
321
+ return isObject2(requested) && requested["toolsListChanged"] === true ? { toolsListChanged: true } : {};
267
322
  }
268
323
  function validate(tool, args) {
269
324
  let outcome;
@@ -278,7 +333,7 @@ function validate(tool, args) {
278
333
  const detail = outcome.errors.filter((e) => e.keyword !== "properties" && e.keyword !== "$ref").map((e) => `${e.instanceLocation} ${e.error}`).slice(0, 5).join("; ");
279
334
  return `Input validation error: Invalid arguments for tool ${tool.name}: ${detail || "the arguments do not match the schema"}`;
280
335
  }
281
- async function runCall(context, tool, raw, signal, client) {
336
+ async function runCall(context, tool, raw, signal, client, deliverable) {
282
337
  const call = {
283
338
  id: ++lastCallId,
284
339
  tool: tool.name,
@@ -295,6 +350,11 @@ async function runCall(context, tool, raw, signal, client) {
295
350
  };
296
351
  try {
297
352
  run = await decideAndRun(context, tool, raw, signal, client);
353
+ if (tool.annotations.untrustedContentHint === true)
354
+ run.result = markUntrusted(run.result);
355
+ const instead = signal.aborted ? undefined : deliverable?.(run.result);
356
+ if (instead !== undefined)
357
+ run = { outcome: "error", result: instead };
298
358
  } finally {
299
359
  context.observe?.end({
300
360
  id: call.id,
@@ -313,6 +373,12 @@ async function decideAndRun(context, tool, raw, signal, client) {
313
373
  const invalid = validate(tool, raw);
314
374
  if (invalid !== undefined)
315
375
  return stopped("error", invalid, "invalid");
376
+ const cancelled = new Promise((_, reject) => {
377
+ if (signal.aborted)
378
+ reject(signal.reason);
379
+ signal.addEventListener("abort", () => reject(signal.reason));
380
+ });
381
+ cancelled.catch(() => {});
316
382
  if (tool.annotations.consequentialHint === true) {
317
383
  const question = {
318
384
  tool: { name: tool.name, description: tool.description },
@@ -324,7 +390,7 @@ async function decideAndRun(context, tool, raw, signal, client) {
324
390
  question.tool.title = tool.title;
325
391
  let answer = false;
326
392
  try {
327
- answer = await context.confirm(question);
393
+ answer = await Promise.race([context.confirm(question), cancelled]);
328
394
  } catch {
329
395
  answer = false;
330
396
  }
@@ -340,7 +406,10 @@ async function decideAndRun(context, tool, raw, signal, client) {
340
406
  return stopped("error", "The tool is no longer available", "gone");
341
407
  let run;
342
408
  try {
343
- const value = await tool.execute(raw, { signal, client });
409
+ const value = await Promise.race([
410
+ tool.execute(raw, { signal, client }),
411
+ cancelled
412
+ ]);
344
413
  run = {
345
414
  outcome: "ok",
346
415
  result: toCallToolResult(value),
@@ -360,7 +429,7 @@ async function webMcpCall(context, tool, input, signal) {
360
429
  const gone = `The tool ${tool.name} is no longer available.`;
361
430
  if (context.tools.get(tool.name) !== tool)
362
431
  return failed(gone);
363
- if (!isObject(input))
432
+ if (!isObject2(input))
364
433
  return failed("The input must be an object.");
365
434
  const run = await runCall(context, tool, input, signal instanceof AbortSignal ? signal : new AbortController().signal, { kind: "webmcp" });
366
435
  if (run.stop === "cancelled")
@@ -373,11 +442,7 @@ async function webMcpCall(context, tool, input, signal) {
373
442
  return failed(gone);
374
443
  if (run.result.isError === true)
375
444
  return failed(resultText(run.result) || "The tool failed.");
376
- return run.returned?.value;
377
- }
378
- function resultText(result) {
379
- return result.content.map((block) => isObject(block) && block["type"] === "text" && typeof block["text"] === "string" ? block["text"] : "").filter((text) => text !== "").join(`
380
- `);
445
+ return webMcpValue(run.returned?.value);
381
446
  }
382
447
  function createMcpHandler(options) {
383
448
  const { tools, server } = options;
@@ -404,8 +469,10 @@ function createMcpHandler(options) {
404
469
  const entry = { name: tool.name };
405
470
  if (tool.title !== undefined)
406
471
  entry["title"] = tool.title;
407
- entry["description"] = tool.description;
472
+ entry["description"] = tool.annotations.consequentialHint === true ? `${tool.description} ${CONFIRMED_IN_TAB}` : tool.description;
408
473
  entry["inputSchema"] = tool.inputSchema;
474
+ if (tool.outputSchema !== undefined)
475
+ entry["outputSchema"] = tool.outputSchema;
409
476
  const { annotations, meta } = mapAnnotations(tool.annotations);
410
477
  if (annotations !== undefined)
411
478
  entry["annotations"] = annotations;
@@ -418,7 +485,7 @@ function createMcpHandler(options) {
418
485
  kind: "invalid",
419
486
  message
420
487
  });
421
- async function runTool(params, signal, grant) {
488
+ async function runTool(params, signal, grant, deliverable) {
422
489
  const name = params["name"];
423
490
  if (typeof name !== "string")
424
491
  return invalidParams("Invalid params: name must be a string");
@@ -426,37 +493,47 @@ function createMcpHandler(options) {
426
493
  if (tool === undefined)
427
494
  return invalidParams(`Tool ${name} not found`);
428
495
  const raw = params["arguments"] ?? {};
429
- if (!isObject(raw))
496
+ if (!isObject2(raw))
430
497
  return invalidParams("Invalid params: arguments must be an object");
431
- const run = await runCall(options, tool, raw, signal, options.client(grant));
498
+ const run = await runCall(options, tool, raw, signal, options.client(grant), deliverable);
432
499
  return { kind: "result", result: run.result };
433
500
  }
434
501
  function callTool(id, params, signal, grant) {
502
+ const answer = (value) => sseEvent(result(id, value, resultMeta(value._meta)));
503
+ let checked;
504
+ const deliverable = (value) => {
505
+ let event;
506
+ try {
507
+ event = answer(value);
508
+ } catch {
509
+ return errorResult("The tool returned a result that is not JSON.");
510
+ }
511
+ const max = options.maxBodyBytes?.();
512
+ if (max !== undefined && event.byteLength > max) {
513
+ return errorResult(`The result is ${event.byteLength} bytes; the relay passes on at most ${max}.`);
514
+ }
515
+ checked = { result: value, event };
516
+ return;
517
+ };
435
518
  const stream = new ReadableStream({
436
519
  start: (controller) => {
437
- const finish = (message) => {
520
+ const finish = (event) => {
438
521
  if (signal.aborted)
439
522
  return;
440
- let event;
441
- try {
442
- event = sseEvent(message);
443
- } catch {
444
- event = sseEvent(result(id, errorResult("The tool returned a result that is not JSON.")));
445
- }
446
523
  try {
447
- controller.enqueue(event);
524
+ controller.enqueue(event());
448
525
  controller.close();
449
526
  } catch {}
450
527
  };
451
- runTool(params, signal, grant).then((outcome) => finish(outcome.kind === "invalid" ? {
528
+ runTool(params, signal, grant, deliverable).then((outcome) => finish(() => outcome.kind === "invalid" ? sseEvent({
452
529
  jsonrpc: "2.0",
453
530
  id,
454
531
  error: { code: -32602, message: outcome.message }
455
- } : result(id, outcome.result)), () => finish({
532
+ }) : outcome.result === checked?.result ? checked.event : answer(outcome.result)), () => finish(() => sseEvent({
456
533
  jsonrpc: "2.0",
457
534
  id,
458
535
  error: { code: -32603, message: "Internal error" }
459
- }));
536
+ })));
460
537
  }
461
538
  });
462
539
  return new Response(stream, { status: 200, headers: SSE_HEADERS });
@@ -521,7 +598,7 @@ function createMcpHandler(options) {
521
598
  if (Array.isArray(body)) {
522
599
  return rpcError(400, null, -32600, "Bad Request: JSON-RPC batches are not supported by this endpoint");
523
600
  }
524
- if (!isObject(body) || body["jsonrpc"] !== "2.0") {
601
+ if (!isObject2(body) || body["jsonrpc"] !== "2.0") {
525
602
  return rpcError(400, null, -32600, "Bad Request: the request body is not a valid JSON-RPC message");
526
603
  }
527
604
  const method = body["method"];
@@ -531,8 +608,8 @@ function createMcpHandler(options) {
531
608
  }
532
609
  const headerVersion = request.headers.get("mcp-protocol-version");
533
610
  const headerMethod = request.headers.get("mcp-method");
534
- const params = isObject(body["params"]) ? body["params"] : {};
535
- const meta = isObject(params["_meta"]) ? params["_meta"] : undefined;
611
+ const params = isObject2(body["params"]) ? body["params"] : {};
612
+ const meta = isObject2(params["_meta"]) ? params["_meta"] : undefined;
536
613
  const claim = meta !== undefined && META_VERSION in meta;
537
614
  const claimed = typeof meta?.[META_VERSION] === "string" ? meta[META_VERSION] : undefined;
538
615
  const headerModern = headerVersion !== null && headerVersion >= MCP_PROTOCOL_VERSION;
@@ -667,18 +744,18 @@ function createMcpHandler(options) {
667
744
  // src/protocol.ts
668
745
  var SUBPROTOCOL = "tab-mcp.v1";
669
746
  var CODE_REASONS = new Set(["start", "used", "locked", "expired"]);
670
- function isObject2(v) {
747
+ function isObject3(v) {
671
748
  return typeof v === "object" && v !== null && !Array.isArray(v);
672
749
  }
673
750
  var str = (v) => typeof v === "string";
674
751
  function isGrant(v) {
675
- if (!isObject2(v) || !str(v["grantId"]) || !str(v["createdAt"]))
752
+ if (!isObject3(v) || !str(v["grantId"]) || !str(v["createdAt"]))
676
753
  return false;
677
754
  const c = v["client"];
678
- return isObject2(c) && str(c["id"]) && str(c["name"]) && str(c["host"]);
755
+ return isObject3(c) && str(c["id"]) && str(c["name"]) && str(c["host"]);
679
756
  }
680
757
  function isLimits(v) {
681
- if (!isObject2(v))
758
+ if (!isObject3(v))
682
759
  return false;
683
760
  return [
684
761
  "maxMessageBytes",
@@ -691,7 +768,7 @@ function isLimits(v) {
691
768
  ].every((k) => typeof v[k] === "number");
692
769
  }
693
770
  function isStringRecord(v) {
694
- return isObject2(v) && Object.values(v).every(str);
771
+ return isObject3(v) && Object.values(v).every(str);
695
772
  }
696
773
  function parseRelayMessage(text) {
697
774
  let v;
@@ -700,7 +777,7 @@ function parseRelayMessage(text) {
700
777
  } catch {
701
778
  return;
702
779
  }
703
- if (!isObject2(v))
780
+ if (!isObject3(v))
704
781
  return;
705
782
  switch (v["type"]) {
706
783
  case "session":
@@ -710,7 +787,7 @@ function parseRelayMessage(text) {
710
787
  case "bye":
711
788
  return { type: "bye", reason: str(v["reason"]) ? v["reason"] : "" };
712
789
  case "http.request":
713
- return str(v["id"]) && str(v["method"]) && str(v["path"]) && isStringRecord(v["headers"]) && str(v["body"]) && isObject2(v["grant"]) && str(v["grant"]["grantId"]) && str(v["grant"]["clientId"]) ? v : undefined;
790
+ return str(v["id"]) && str(v["method"]) && str(v["path"]) && isStringRecord(v["headers"]) && str(v["body"]) && isObject3(v["grant"]) && str(v["grant"]["grantId"]) && str(v["grant"]["clientId"]) ? v : undefined;
714
791
  case "http.cancel":
715
792
  return str(v["id"]) ? v : undefined;
716
793
  case "pairing.code": {
@@ -744,9 +821,29 @@ function parseRelayMessage(text) {
744
821
  }
745
822
 
746
823
  // src/serve.ts
747
- function callContext(host) {
824
+ function toolsFor(registry, kind) {
825
+ const sees = (tool) => tool && (tool.callers?.includes(kind) ?? true);
826
+ return {
827
+ list: () => registry.list().filter(sees),
828
+ get: (name) => {
829
+ const tool = registry.get(name);
830
+ return sees(tool) ? tool : undefined;
831
+ }
832
+ };
833
+ }
834
+ function watchTools(registry, tools, changed) {
835
+ let last = tools.list();
836
+ return registry.onChange(() => {
837
+ const now = tools.list();
838
+ if (now.length === last.length && now.every((t, i) => t === last[i]))
839
+ return;
840
+ last = now;
841
+ changed();
842
+ });
843
+ }
844
+ function callContext(host, kind) {
748
845
  return {
749
- tools: host.registry,
846
+ tools: kind === "webmcp" ? host.registry : toolsFor(host.registry, kind),
750
847
  confirm: (request) => host.confirm(request),
751
848
  observe: {
752
849
  start: (call) => host.toolCallStarted(call),
@@ -767,8 +864,18 @@ function* pieces(text, max) {
767
864
  i = end;
768
865
  }
769
866
  }
867
+ var TIMEOUT = -31002;
868
+ var TIMED_OUT = "The page did not answer in time.";
869
+ function rpcId(body) {
870
+ try {
871
+ const id = JSON.parse(body)?.id;
872
+ return typeof id === "string" || typeof id === "number" ? id : null;
873
+ } catch {
874
+ return null;
875
+ }
876
+ }
770
877
  function createTunnel(options) {
771
- const { handler, send } = options;
878
+ const { handler, send, timeoutMs } = options;
772
879
  const inflight = new Map;
773
880
  let closed = false;
774
881
  async function run(msg) {
@@ -776,6 +883,41 @@ function createTunnel(options) {
776
883
  inflight.get(msg.id)?.abort();
777
884
  inflight.set(msg.id, controller);
778
885
  const live = () => !closed && inflight.get(msg.id) === controller && !controller.signal.aborted;
886
+ let started = false;
887
+ let tail = "";
888
+ const listen = Object.entries(msg.headers).some(([name, value]) => name.toLowerCase() === "mcp-method" && value === "subscriptions/listen");
889
+ const timer = timeoutMs === undefined || listen ? undefined : setTimeout(() => {
890
+ if (!live())
891
+ return;
892
+ controller.abort();
893
+ const error = JSON.stringify({
894
+ jsonrpc: "2.0",
895
+ id: rpcId(msg.body),
896
+ error: { code: TIMEOUT, message: TIMED_OUT }
897
+ });
898
+ if (!started) {
899
+ send({
900
+ type: "http.response",
901
+ id: msg.id,
902
+ status: 200,
903
+ headers: { "content-type": "application/json" },
904
+ body: error
905
+ });
906
+ return;
907
+ }
908
+ if (tail === "" || tail === `
909
+
910
+ `)
911
+ send({
912
+ type: "http.response.chunk",
913
+ id: msg.id,
914
+ data: `event: message
915
+ data: ${error}
916
+
917
+ `
918
+ });
919
+ send({ type: "http.response.end", id: msg.id });
920
+ }, timeoutMs);
779
921
  try {
780
922
  const request = new Request(`https://tab.invalid${msg.path}`, {
781
923
  method: msg.method,
@@ -833,6 +975,7 @@ function createTunnel(options) {
833
975
  status: response.status,
834
976
  headers
835
977
  });
978
+ started = true;
836
979
  const reader = response.body.getReader();
837
980
  const decoder = new TextDecoder;
838
981
  controller.signal.addEventListener("abort", () => {
@@ -843,6 +986,8 @@ function createTunnel(options) {
843
986
  if (done || !live())
844
987
  break;
845
988
  const text = decoder.decode(value, { stream: true });
989
+ if (text !== "")
990
+ tail = (tail + text).slice(-2);
846
991
  for (const data of pieces(text, maxChunk)) {
847
992
  send({ type: "http.response.chunk", id: msg.id, data });
848
993
  }
@@ -865,6 +1010,7 @@ function createTunnel(options) {
865
1010
  });
866
1011
  }
867
1012
  } finally {
1013
+ clearTimeout(timer);
868
1014
  if (inflight.get(msg.id) === controller)
869
1015
  inflight.delete(msg.id);
870
1016
  }
@@ -890,22 +1036,29 @@ function createTunnel(options) {
890
1036
  }
891
1037
  var MAX_CHUNK = 64 * 1024;
892
1038
  var MIN_CHUNK = 64;
1039
+ var REQUEST_TIMEOUT_MS = 300000;
893
1040
  var MAX_ID = 128;
894
1041
  var served = new WeakSet;
895
1042
  var lastPort = 0;
896
1043
  var str2 = (v) => typeof v === "string";
897
- function isObject3(v) {
1044
+ function isObject4(v) {
898
1045
  return typeof v === "object" && v !== null && !Array.isArray(v);
899
1046
  }
900
1047
  function servePort(host, port, options) {
901
1048
  const who = options?.client;
902
- if (!isObject3(who) || !str2(who.id) || who.id === "" || who.name !== undefined && !str2(who.name)) {
1049
+ if (!isObject4(who) || !str2(who.id) || who.id === "" || who.name !== undefined && !str2(who.name)) {
903
1050
  throw new TypeError("serve: client needs an id (and may have a name)");
904
1051
  }
905
1052
  const maxChunk = options.maxChunk ?? MAX_CHUNK;
906
1053
  if (!Number.isInteger(maxChunk) || maxChunk < MIN_CHUNK) {
907
1054
  throw new TypeError(`serve: maxChunk must be a whole number of at least ${MIN_CHUNK}`);
908
1055
  }
1056
+ const timeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS;
1057
+ if (typeof timeoutMs !== "number" || !(timeoutMs > 0) || timeoutMs >= 2 ** 31)
1058
+ throw new TypeError("serve: requestTimeoutMs must be milliseconds above 0 and below 2^31");
1059
+ const ask = options.onConfirm;
1060
+ if (ask !== undefined && typeof ask !== "function")
1061
+ throw new TypeError("serve: onConfirm must be a function");
909
1062
  if (typeof port?.postMessage !== "function" || !("onmessage" in port)) {
910
1063
  throw new TypeError("serve: the port needs postMessage and onmessage");
911
1064
  }
@@ -931,17 +1084,21 @@ function servePort(host, port, options) {
931
1084
  return false;
932
1085
  }
933
1086
  };
1087
+ const context = callContext(host, "local");
1088
+ if (ask !== undefined)
1089
+ context.confirm = (request) => Promise.resolve().then(() => ask(request)).then((answer) => answer === "unanswered" ? answer : answer === true);
934
1090
  const handler = createMcpHandler({
935
- ...callContext(host),
1091
+ ...context,
936
1092
  server: { ...host.server, icons: host.server.icons ?? pageIcons() },
937
1093
  client: () => ({ ...client })
938
1094
  });
939
- const stopWatching = host.registry.onChange(() => handler.toolsChanged());
1095
+ const stopWatching = watchTools(host.registry, context.tools, () => handler.toolsChanged());
940
1096
  const tunnel = createTunnel({
941
1097
  handler,
942
1098
  send,
943
1099
  maxChunk: () => maxChunk,
944
- error: (error) => host.error(error)
1100
+ error: (error) => host.error(error),
1101
+ timeoutMs
945
1102
  });
946
1103
  const bad = (message, id) => {
947
1104
  const error = { type: "error", code: "bad_message", message };
@@ -953,7 +1110,7 @@ function servePort(host, port, options) {
953
1110
  if (closed)
954
1111
  return;
955
1112
  const m = event?.data;
956
- if (!isObject3(m) || !str2(m["type"])) {
1113
+ if (!isObject4(m) || !str2(m["type"])) {
957
1114
  bad("not a message");
958
1115
  return;
959
1116
  }
@@ -961,7 +1118,7 @@ function servePort(host, port, options) {
961
1118
  switch (m["type"]) {
962
1119
  case "http.request": {
963
1120
  const { method, path, headers, body } = m;
964
- if (!str2(id) || id === "" || id.length > MAX_ID || !str2(method) || !str2(path) || !path.startsWith("/") || !isObject3(headers) || !Object.values(headers).every(str2) || !str2(body)) {
1121
+ if (!str2(id) || id === "" || id.length > MAX_ID || !str2(method) || !str2(path) || !path.startsWith("/") || !isObject4(headers) || !Object.values(headers).every(str2) || !str2(body)) {
965
1122
  bad("malformed http.request", id);
966
1123
  return;
967
1124
  }
@@ -988,10 +1145,12 @@ function servePort(host, port, options) {
988
1145
  bad(`unexpected ${m["type"].slice(0, 64)}`, id);
989
1146
  }
990
1147
  };
1148
+ const events = port;
991
1149
  const close = () => {
992
1150
  if (closed)
993
1151
  return;
994
1152
  options.signal?.removeEventListener("abort", close);
1153
+ events.removeEventListener?.("close", close);
995
1154
  stopWatching();
996
1155
  tunnel.close();
997
1156
  handler.close();
@@ -1006,6 +1165,7 @@ function servePort(host, port, options) {
1006
1165
  return { close };
1007
1166
  }
1008
1167
  options.signal?.addEventListener("abort", close);
1168
+ events.addEventListener?.("close", close);
1009
1169
  served.add(port);
1010
1170
  port.onmessage = onMessage;
1011
1171
  return { close };
@@ -1050,13 +1210,17 @@ function withAddress(url, address) {
1050
1210
 
1051
1211
  // src/connection.ts
1052
1212
  function callFromWebMcp(host, tool, input, signal) {
1053
- return webMcpCall(callContext(host), tool, input, signal);
1213
+ return webMcpCall(callContext(host, "webmcp"), tool, input, signal);
1054
1214
  }
1055
1215
  var CONNECT_TIMEOUT_MS = 15000;
1056
1216
  var CLOSE_REASONS = {
1057
1217
  1000: "closed",
1218
+ 1001: "shutdown",
1058
1219
  1008: "policy",
1059
1220
  1009: "too_large",
1221
+ 1011: "shutdown",
1222
+ 1012: "shutdown",
1223
+ 1013: "shutdown",
1060
1224
  4001: "expired",
1061
1225
  4002: "idle",
1062
1226
  4003: "heartbeat",
@@ -1074,32 +1238,6 @@ var BYE_REASONS = {
1074
1238
  function refused(message, reason) {
1075
1239
  return Object.assign(new Error(message), { reason });
1076
1240
  }
1077
- function pageTitle() {
1078
- const title = globalThis.document?.title;
1079
- return typeof title === "string" ? title.slice(0, 300) : "";
1080
- }
1081
- function frameInfo(text) {
1082
- try {
1083
- const v = JSON.parse(text);
1084
- if (typeof v !== "object" || v === null || typeof v["type"] !== "string")
1085
- return;
1086
- return typeof v["id"] === "string" ? { type: v["type"], id: v["id"] } : { type: v["type"] };
1087
- } catch {
1088
- return;
1089
- }
1090
- }
1091
- var KNOWN_TYPES = new Set([
1092
- "session",
1093
- "ping",
1094
- "bye",
1095
- "http.request",
1096
- "http.cancel",
1097
- "pairing.code",
1098
- "grant.added",
1099
- "grant.removed",
1100
- "identity.bound",
1101
- "error"
1102
- ]);
1103
1241
  var ENVELOPE_BYTES = 512;
1104
1242
  var WORST_BYTES_PER_UNIT = 6;
1105
1243
  var MIN_CHUNK_UNITS = 64;
@@ -1110,15 +1248,17 @@ function chunkSize(maxMessageBytes) {
1110
1248
  }
1111
1249
  var SIBLING_WINDOW_MS = 1e4;
1112
1250
  var SIBLING_GRACE_MS = 1000;
1113
- function siblingTabs(name) {
1251
+ function siblingTabs(name, address) {
1114
1252
  let channel;
1253
+ let listening = false;
1115
1254
  let at = Number.NEGATIVE_INFINITY;
1116
1255
  let onClaim;
1117
1256
  try {
1118
1257
  if (name !== undefined && typeof BroadcastChannel === "function") {
1119
1258
  channel = new BroadcastChannel(name);
1120
1259
  channel.onmessage = (event) => {
1121
- if (event.data?.type !== "claimed")
1260
+ const data = event.data;
1261
+ if (!listening || data?.type !== "claimed" || data.address !== undefined && data.address !== address)
1122
1262
  return;
1123
1263
  at = Date.now();
1124
1264
  onClaim?.();
@@ -1129,8 +1269,9 @@ function siblingTabs(name) {
1129
1269
  }
1130
1270
  return {
1131
1271
  claimed() {
1272
+ listening = true;
1132
1273
  try {
1133
- channel?.postMessage({ type: "claimed" });
1274
+ channel?.postMessage({ type: "claimed", address });
1134
1275
  } catch {}
1135
1276
  },
1136
1277
  heard() {
@@ -1151,15 +1292,16 @@ function siblingTabs(name) {
1151
1292
  }
1152
1293
  };
1153
1294
  }
1154
- function openConnection(host, url, secret, revokeAll = false) {
1295
+ function openConnection(host, url, secret, options = {}) {
1296
+ const revokeAll = options.revokeAll === true;
1155
1297
  const ws = new WebSocket(url, SUBPROTOCOL);
1156
1298
  let state = "opening";
1157
1299
  let byeReason;
1158
1300
  let maxChunk = 64 * 1024;
1301
+ let maxBodyBytes;
1159
1302
  let heartbeat;
1160
1303
  let heartbeatMs = 0;
1161
- const siblings = siblingTabs(host.tabs);
1162
- let revoking;
1304
+ const siblings = siblingTabs(host.tabs, options.address);
1163
1305
  let resolveReady;
1164
1306
  let rejectReady;
1165
1307
  const ready = new Promise((resolve, reject) => {
@@ -1170,12 +1312,14 @@ function openConnection(host, url, secret, revokeAll = false) {
1170
1312
  const connectTimer = setTimeout(() => {
1171
1313
  fail(refused("The relay did not answer in time.", "network"));
1172
1314
  }, CONNECT_TIMEOUT_MS);
1315
+ const context = callContext(host, "relay");
1173
1316
  const handler = createMcpHandler({
1174
- ...callContext(host),
1317
+ ...context,
1175
1318
  server: { ...host.server, icons: host.server.icons ?? pageIcons() },
1176
- client: (grant) => host.clientFor(grant)
1319
+ client: (grant) => host.clientFor(grant),
1320
+ maxBodyBytes: () => maxBodyBytes
1177
1321
  });
1178
- const stopWatching = host.registry.onChange(() => handler.toolsChanged());
1322
+ const stopWatching = watchTools(host.registry, context.tools, () => handler.toolsChanged());
1179
1323
  function send(message) {
1180
1324
  if (ws.readyState !== WebSocket.OPEN)
1181
1325
  return false;
@@ -1219,7 +1363,6 @@ function openConnection(host, url, secret, revokeAll = false) {
1219
1363
  handler.close();
1220
1364
  if (wasReady) {
1221
1365
  const reason = byeReason ?? CLOSE_REASONS[code] ?? (code === 1006 ? "network" : "closed");
1222
- rejectReady(refused("The address was taken over again before its AI apps were disconnected.", reason));
1223
1366
  host.closed(reason, code);
1224
1367
  if (reason === "replaced") {
1225
1368
  siblings.heard().then((sibling) => {
@@ -1245,22 +1388,18 @@ function openConnection(host, url, secret, revokeAll = false) {
1245
1388
  fail(refused(`The relay's message limit (${message.limits.maxMessageBytes} bytes) is too small; tab-mcp needs at least ${MIN_MESSAGE_BYTES}.`, "policy"));
1246
1389
  return;
1247
1390
  }
1391
+ if (revokeAll && message.grants.length > 0) {
1392
+ fail(refused("The relay did not revoke the address's grants (it needs tab-mcp 0.5 or later).", "policy"));
1393
+ return;
1394
+ }
1248
1395
  maxChunk = chunk;
1396
+ maxBodyBytes = message.limits.maxBodyBytes;
1249
1397
  state = "ready";
1250
1398
  clearTimeout(connectTimer);
1251
1399
  heartbeatMs = message.limits.heartbeatMs;
1252
1400
  armHeartbeat();
1253
1401
  siblings.claimed();
1254
- const session = host.sessionStarted(message);
1255
- if (revokeAll && message.grants.length > 0) {
1256
- revoking = {
1257
- left: new Set(message.grants.map((g) => g.grantId)),
1258
- session
1259
- };
1260
- send({ type: "grants.revokeAll" });
1261
- return;
1262
- }
1263
- resolveReady(session);
1402
+ resolveReady(host.sessionStarted(message));
1264
1403
  } else if (message.type === "error") {
1265
1404
  fail(refused(`The relay refused the connection: ${message.message || message.code}`, message.code === "rate_limited" ? "rate_limited" : "policy"));
1266
1405
  } else if (message.type === "bye") {
@@ -1293,9 +1432,6 @@ function openConnection(host, url, secret, revokeAll = false) {
1293
1432
  return;
1294
1433
  case "grant.removed":
1295
1434
  host.grantRemoved(message.grantId);
1296
- revoking?.left.delete(message.grantId);
1297
- if (revoking?.left.size === 0)
1298
- resolveReady(revoking.session);
1299
1435
  return;
1300
1436
  case "identity.bound":
1301
1437
  host.identityResult(true, message.round);
@@ -1310,7 +1446,7 @@ function openConnection(host, url, secret, revokeAll = false) {
1310
1446
  host.identityResult(false, typeof message.round === "number" ? message.round : undefined, message.message);
1311
1447
  return;
1312
1448
  }
1313
- host.error(new Error(`Relay error ${message.code}: ${message.message}`));
1449
+ host.error(Object.assign(new Error(`Relay error ${message.code}: ${message.message}`), { code: message.code }));
1314
1450
  return;
1315
1451
  case "session":
1316
1452
  return;
@@ -1324,7 +1460,7 @@ function openConnection(host, url, secret, revokeAll = false) {
1324
1460
  const hello = {
1325
1461
  type: "hello",
1326
1462
  library: host.library,
1327
- page: { title: pageTitle() },
1463
+ page: { title: "" },
1328
1464
  secret
1329
1465
  };
1330
1466
  if (host.appName !== undefined)
@@ -1337,26 +1473,11 @@ function openConnection(host, url, secret, revokeAll = false) {
1337
1473
  if (typeof event.data !== "string")
1338
1474
  return;
1339
1475
  const message = parseRelayMessage(event.data);
1340
- if (message !== undefined) {
1341
- if (state === "ready")
1342
- armHeartbeat();
1343
- onMessage(message);
1476
+ if (message === undefined)
1344
1477
  return;
1345
- }
1346
- const info = frameInfo(event.data);
1347
- if (info?.id !== undefined) {
1348
- send(KNOWN_TYPES.has(info.type) ? {
1349
- type: "error",
1350
- code: "bad_message",
1351
- message: `malformed ${info.type}`,
1352
- id: info.id
1353
- } : {
1354
- type: "error",
1355
- code: "unknown_type",
1356
- message: `unknown type ${info.type}`,
1357
- id: info.id
1358
- });
1359
- }
1478
+ if (state === "ready")
1479
+ armHeartbeat();
1480
+ onMessage(message);
1360
1481
  });
1361
1482
  ws.addEventListener("close", (event) => {
1362
1483
  if (state === "opening") {
@@ -1400,5 +1521,5 @@ export {
1400
1521
  withAddress
1401
1522
  };
1402
1523
 
1403
- //# debugId=EBEC5A72AFF3C4C664756E2164756E21
1404
- //# sourceMappingURL=connection-g6wk37yd.js.map
1524
+ //# debugId=9E3DFFAD7EB6930C64756E2164756E21
1525
+ //# sourceMappingURL=connection-1d8rxgbq.js.map