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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +481 -148
  2. package/always-allowed.d.ts +25 -6
  3. package/cdn/confirm-y30cx7e1.min.js +4 -0
  4. package/cdn/confirm-y30cx7e1.min.js.map +10 -0
  5. package/cdn/connect-bbhj2y7w.min.js +6 -0
  6. package/cdn/connect-bbhj2y7w.min.js.map +12 -0
  7. package/cdn/connection-w97tf22a.min.js +17 -0
  8. package/cdn/connection-w97tf22a.min.js.map +22 -0
  9. package/cdn/index-vt5zk9me.min.js +91 -0
  10. package/cdn/index-vt5zk9me.min.js.map +13 -0
  11. package/cdn/tab-mcp-client.min.js +3 -3
  12. package/cdn/tab-mcp-client.min.js.map +6 -7
  13. package/cdn/webmcp-khy4f5rj.min.js +4 -0
  14. package/cdn/webmcp-khy4f5rj.min.js.map +10 -0
  15. package/confirm-fgnjgd08.js +263 -0
  16. package/confirm-fgnjgd08.js.map +10 -0
  17. package/confirm.d.ts +54 -0
  18. package/connect-8jpb0k29.js +484 -0
  19. package/connect-8jpb0k29.js.map +10 -0
  20. package/connect.d.ts +40 -0
  21. package/{connection-g6wk37yd.js → connection-g91xjjgm.js} +252 -126
  22. package/connection-g91xjjgm.js.map +16 -0
  23. package/connection.d.ts +7 -4
  24. package/dialog.d.ts +83 -0
  25. package/{index-nmn1j689.js → index-5jyqehpk.js} +14 -10
  26. package/index-5jyqehpk.js.map +11 -0
  27. package/index-jnz7w9xa.js +392 -0
  28. package/index-jnz7w9xa.js.map +12 -0
  29. package/index.d.ts +1 -1
  30. package/index.js +234 -263
  31. package/index.js.map +6 -7
  32. package/internal.d.ts +2 -0
  33. package/mapping.d.ts +37 -4
  34. package/mcp.d.ts +28 -8
  35. package/package.json +1 -1
  36. package/protocol.d.ts +8 -0
  37. package/react.d.ts +8 -10
  38. package/react.js +18 -14
  39. package/react.js.map +3 -3
  40. package/registry.d.ts +12 -5
  41. package/secret.d.ts +5 -2
  42. package/serve.d.ts +26 -4
  43. package/setup.d.ts +15 -25
  44. package/setup.js +1 -1
  45. package/strings.d.ts +107 -0
  46. package/tab-mcp.d.ts +63 -35
  47. package/types.d.ts +146 -68
  48. package/webmcp-zq1enyz0.js +57 -0
  49. package/webmcp-zq1enyz0.js.map +10 -0
  50. package/webmcp.d.ts +13 -24
  51. package/cdn/connection-hgt931xk.min.js +0 -12
  52. package/cdn/connection-hgt931xk.min.js.map +0 -22
  53. package/cdn/ui-2nv84ry7.min.js +0 -86
  54. package/cdn/ui-2nv84ry7.min.js.map +0 -14
  55. package/connection-g6wk37yd.js.map +0 -16
  56. package/index-nmn1j689.js.map +0 -11
  57. package/ui-04mwfxm9.js +0 -783
  58. package/ui-04mwfxm9.js.map +0 -11
  59. package/ui.d.ts +0 -83
@@ -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 && !options.ownConfirm ? `${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,10 +821,31 @@ 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),
848
+ ownConfirm: host.ownConfirm(),
751
849
  observe: {
752
850
  start: (call) => host.toolCallStarted(call),
753
851
  end: (call) => host.toolCallEnded(call)
@@ -767,8 +865,18 @@ function* pieces(text, max) {
767
865
  i = end;
768
866
  }
769
867
  }
868
+ var TIMEOUT = -31002;
869
+ var TIMED_OUT = "The page did not answer in time.";
870
+ function rpcId(body) {
871
+ try {
872
+ const id = JSON.parse(body)?.id;
873
+ return typeof id === "string" || typeof id === "number" ? id : null;
874
+ } catch {
875
+ return null;
876
+ }
877
+ }
770
878
  function createTunnel(options) {
771
- const { handler, send } = options;
879
+ const { handler, send, timeoutMs } = options;
772
880
  const inflight = new Map;
773
881
  let closed = false;
774
882
  async function run(msg) {
@@ -776,6 +884,41 @@ function createTunnel(options) {
776
884
  inflight.get(msg.id)?.abort();
777
885
  inflight.set(msg.id, controller);
778
886
  const live = () => !closed && inflight.get(msg.id) === controller && !controller.signal.aborted;
887
+ let started = false;
888
+ let tail = "";
889
+ const listen = Object.entries(msg.headers).some(([name, value]) => name.toLowerCase() === "mcp-method" && value === "subscriptions/listen");
890
+ const timer = timeoutMs === undefined || listen ? undefined : setTimeout(() => {
891
+ if (!live())
892
+ return;
893
+ controller.abort();
894
+ const error = JSON.stringify({
895
+ jsonrpc: "2.0",
896
+ id: rpcId(msg.body),
897
+ error: { code: TIMEOUT, message: TIMED_OUT }
898
+ });
899
+ if (!started) {
900
+ send({
901
+ type: "http.response",
902
+ id: msg.id,
903
+ status: 200,
904
+ headers: { "content-type": "application/json" },
905
+ body: error
906
+ });
907
+ return;
908
+ }
909
+ if (tail === "" || tail === `
910
+
911
+ `)
912
+ send({
913
+ type: "http.response.chunk",
914
+ id: msg.id,
915
+ data: `event: message
916
+ data: ${error}
917
+
918
+ `
919
+ });
920
+ send({ type: "http.response.end", id: msg.id });
921
+ }, timeoutMs);
779
922
  try {
780
923
  const request = new Request(`https://tab.invalid${msg.path}`, {
781
924
  method: msg.method,
@@ -833,6 +976,7 @@ function createTunnel(options) {
833
976
  status: response.status,
834
977
  headers
835
978
  });
979
+ started = true;
836
980
  const reader = response.body.getReader();
837
981
  const decoder = new TextDecoder;
838
982
  controller.signal.addEventListener("abort", () => {
@@ -843,6 +987,8 @@ function createTunnel(options) {
843
987
  if (done || !live())
844
988
  break;
845
989
  const text = decoder.decode(value, { stream: true });
990
+ if (text !== "")
991
+ tail = (tail + text).slice(-2);
846
992
  for (const data of pieces(text, maxChunk)) {
847
993
  send({ type: "http.response.chunk", id: msg.id, data });
848
994
  }
@@ -865,6 +1011,7 @@ function createTunnel(options) {
865
1011
  });
866
1012
  }
867
1013
  } finally {
1014
+ clearTimeout(timer);
868
1015
  if (inflight.get(msg.id) === controller)
869
1016
  inflight.delete(msg.id);
870
1017
  }
@@ -890,22 +1037,29 @@ function createTunnel(options) {
890
1037
  }
891
1038
  var MAX_CHUNK = 64 * 1024;
892
1039
  var MIN_CHUNK = 64;
1040
+ var REQUEST_TIMEOUT_MS = 300000;
893
1041
  var MAX_ID = 128;
894
1042
  var served = new WeakSet;
895
1043
  var lastPort = 0;
896
1044
  var str2 = (v) => typeof v === "string";
897
- function isObject3(v) {
1045
+ function isObject4(v) {
898
1046
  return typeof v === "object" && v !== null && !Array.isArray(v);
899
1047
  }
900
1048
  function servePort(host, port, options) {
901
1049
  const who = options?.client;
902
- if (!isObject3(who) || !str2(who.id) || who.id === "" || who.name !== undefined && !str2(who.name)) {
1050
+ if (!isObject4(who) || !str2(who.id) || who.id === "" || who.name !== undefined && !str2(who.name)) {
903
1051
  throw new TypeError("serve: client needs an id (and may have a name)");
904
1052
  }
905
1053
  const maxChunk = options.maxChunk ?? MAX_CHUNK;
906
1054
  if (!Number.isInteger(maxChunk) || maxChunk < MIN_CHUNK) {
907
1055
  throw new TypeError(`serve: maxChunk must be a whole number of at least ${MIN_CHUNK}`);
908
1056
  }
1057
+ const timeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS;
1058
+ if (typeof timeoutMs !== "number" || !(timeoutMs > 0) || timeoutMs >= 2 ** 31)
1059
+ throw new TypeError("serve: requestTimeoutMs must be milliseconds above 0 and below 2^31");
1060
+ const ask = options.onConfirm;
1061
+ if (ask !== undefined && typeof ask !== "function")
1062
+ throw new TypeError("serve: onConfirm must be a function");
909
1063
  if (typeof port?.postMessage !== "function" || !("onmessage" in port)) {
910
1064
  throw new TypeError("serve: the port needs postMessage and onmessage");
911
1065
  }
@@ -931,17 +1085,23 @@ function servePort(host, port, options) {
931
1085
  return false;
932
1086
  }
933
1087
  };
1088
+ const context = callContext(host, "local");
1089
+ if (ask !== undefined) {
1090
+ context.confirm = (request) => Promise.resolve().then(() => ask(request)).then((answer) => answer === "unanswered" ? answer : answer === true);
1091
+ context.ownConfirm = true;
1092
+ }
934
1093
  const handler = createMcpHandler({
935
- ...callContext(host),
1094
+ ...context,
936
1095
  server: { ...host.server, icons: host.server.icons ?? pageIcons() },
937
1096
  client: () => ({ ...client })
938
1097
  });
939
- const stopWatching = host.registry.onChange(() => handler.toolsChanged());
1098
+ const stopWatching = watchTools(host.registry, context.tools, () => handler.toolsChanged());
940
1099
  const tunnel = createTunnel({
941
1100
  handler,
942
1101
  send,
943
1102
  maxChunk: () => maxChunk,
944
- error: (error) => host.error(error)
1103
+ error: (error) => host.error(error),
1104
+ timeoutMs
945
1105
  });
946
1106
  const bad = (message, id) => {
947
1107
  const error = { type: "error", code: "bad_message", message };
@@ -953,7 +1113,7 @@ function servePort(host, port, options) {
953
1113
  if (closed)
954
1114
  return;
955
1115
  const m = event?.data;
956
- if (!isObject3(m) || !str2(m["type"])) {
1116
+ if (!isObject4(m) || !str2(m["type"])) {
957
1117
  bad("not a message");
958
1118
  return;
959
1119
  }
@@ -961,7 +1121,7 @@ function servePort(host, port, options) {
961
1121
  switch (m["type"]) {
962
1122
  case "http.request": {
963
1123
  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)) {
1124
+ if (!str2(id) || id === "" || id.length > MAX_ID || !str2(method) || !str2(path) || !path.startsWith("/") || !isObject4(headers) || !Object.values(headers).every(str2) || !str2(body)) {
965
1125
  bad("malformed http.request", id);
966
1126
  return;
967
1127
  }
@@ -988,10 +1148,12 @@ function servePort(host, port, options) {
988
1148
  bad(`unexpected ${m["type"].slice(0, 64)}`, id);
989
1149
  }
990
1150
  };
1151
+ const events = port;
991
1152
  const close = () => {
992
1153
  if (closed)
993
1154
  return;
994
1155
  options.signal?.removeEventListener("abort", close);
1156
+ events.removeEventListener?.("close", close);
995
1157
  stopWatching();
996
1158
  tunnel.close();
997
1159
  handler.close();
@@ -1006,6 +1168,7 @@ function servePort(host, port, options) {
1006
1168
  return { close };
1007
1169
  }
1008
1170
  options.signal?.addEventListener("abort", close);
1171
+ events.addEventListener?.("close", close);
1009
1172
  served.add(port);
1010
1173
  port.onmessage = onMessage;
1011
1174
  return { close };
@@ -1050,13 +1213,17 @@ function withAddress(url, address) {
1050
1213
 
1051
1214
  // src/connection.ts
1052
1215
  function callFromWebMcp(host, tool, input, signal) {
1053
- return webMcpCall(callContext(host), tool, input, signal);
1216
+ return webMcpCall(callContext(host, "webmcp"), tool, input, signal);
1054
1217
  }
1055
1218
  var CONNECT_TIMEOUT_MS = 15000;
1056
1219
  var CLOSE_REASONS = {
1057
1220
  1000: "closed",
1221
+ 1001: "shutdown",
1058
1222
  1008: "policy",
1059
1223
  1009: "too_large",
1224
+ 1011: "shutdown",
1225
+ 1012: "shutdown",
1226
+ 1013: "shutdown",
1060
1227
  4001: "expired",
1061
1228
  4002: "idle",
1062
1229
  4003: "heartbeat",
@@ -1074,32 +1241,6 @@ var BYE_REASONS = {
1074
1241
  function refused(message, reason) {
1075
1242
  return Object.assign(new Error(message), { reason });
1076
1243
  }
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
1244
  var ENVELOPE_BYTES = 512;
1104
1245
  var WORST_BYTES_PER_UNIT = 6;
1105
1246
  var MIN_CHUNK_UNITS = 64;
@@ -1110,15 +1251,17 @@ function chunkSize(maxMessageBytes) {
1110
1251
  }
1111
1252
  var SIBLING_WINDOW_MS = 1e4;
1112
1253
  var SIBLING_GRACE_MS = 1000;
1113
- function siblingTabs(name) {
1254
+ function siblingTabs(name, address) {
1114
1255
  let channel;
1256
+ let listening = false;
1115
1257
  let at = Number.NEGATIVE_INFINITY;
1116
1258
  let onClaim;
1117
1259
  try {
1118
1260
  if (name !== undefined && typeof BroadcastChannel === "function") {
1119
1261
  channel = new BroadcastChannel(name);
1120
1262
  channel.onmessage = (event) => {
1121
- if (event.data?.type !== "claimed")
1263
+ const data = event.data;
1264
+ if (!listening || data?.type !== "claimed" || data.address !== undefined && data.address !== address)
1122
1265
  return;
1123
1266
  at = Date.now();
1124
1267
  onClaim?.();
@@ -1129,8 +1272,9 @@ function siblingTabs(name) {
1129
1272
  }
1130
1273
  return {
1131
1274
  claimed() {
1275
+ listening = true;
1132
1276
  try {
1133
- channel?.postMessage({ type: "claimed" });
1277
+ channel?.postMessage({ type: "claimed", address });
1134
1278
  } catch {}
1135
1279
  },
1136
1280
  heard() {
@@ -1151,15 +1295,16 @@ function siblingTabs(name) {
1151
1295
  }
1152
1296
  };
1153
1297
  }
1154
- function openConnection(host, url, secret, revokeAll = false) {
1298
+ function openConnection(host, url, secret, options = {}) {
1299
+ const revokeAll = options.revokeAll === true;
1155
1300
  const ws = new WebSocket(url, SUBPROTOCOL);
1156
1301
  let state = "opening";
1157
1302
  let byeReason;
1158
1303
  let maxChunk = 64 * 1024;
1304
+ let maxBodyBytes;
1159
1305
  let heartbeat;
1160
1306
  let heartbeatMs = 0;
1161
- const siblings = siblingTabs(host.tabs);
1162
- let revoking;
1307
+ const siblings = siblingTabs(host.tabs, options.address);
1163
1308
  let resolveReady;
1164
1309
  let rejectReady;
1165
1310
  const ready = new Promise((resolve, reject) => {
@@ -1170,12 +1315,14 @@ function openConnection(host, url, secret, revokeAll = false) {
1170
1315
  const connectTimer = setTimeout(() => {
1171
1316
  fail(refused("The relay did not answer in time.", "network"));
1172
1317
  }, CONNECT_TIMEOUT_MS);
1318
+ const context = callContext(host, "relay");
1173
1319
  const handler = createMcpHandler({
1174
- ...callContext(host),
1320
+ ...context,
1175
1321
  server: { ...host.server, icons: host.server.icons ?? pageIcons() },
1176
- client: (grant) => host.clientFor(grant)
1322
+ client: (grant) => host.clientFor(grant),
1323
+ maxBodyBytes: () => maxBodyBytes
1177
1324
  });
1178
- const stopWatching = host.registry.onChange(() => handler.toolsChanged());
1325
+ const stopWatching = watchTools(host.registry, context.tools, () => handler.toolsChanged());
1179
1326
  function send(message) {
1180
1327
  if (ws.readyState !== WebSocket.OPEN)
1181
1328
  return false;
@@ -1219,7 +1366,6 @@ function openConnection(host, url, secret, revokeAll = false) {
1219
1366
  handler.close();
1220
1367
  if (wasReady) {
1221
1368
  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
1369
  host.closed(reason, code);
1224
1370
  if (reason === "replaced") {
1225
1371
  siblings.heard().then((sibling) => {
@@ -1245,22 +1391,18 @@ function openConnection(host, url, secret, revokeAll = false) {
1245
1391
  fail(refused(`The relay's message limit (${message.limits.maxMessageBytes} bytes) is too small; tab-mcp needs at least ${MIN_MESSAGE_BYTES}.`, "policy"));
1246
1392
  return;
1247
1393
  }
1394
+ if (revokeAll && message.grants.length > 0) {
1395
+ fail(refused("The relay did not revoke the address's grants (it needs tab-mcp 0.5 or later).", "policy"));
1396
+ return;
1397
+ }
1248
1398
  maxChunk = chunk;
1399
+ maxBodyBytes = message.limits.maxBodyBytes;
1249
1400
  state = "ready";
1250
1401
  clearTimeout(connectTimer);
1251
1402
  heartbeatMs = message.limits.heartbeatMs;
1252
1403
  armHeartbeat();
1253
1404
  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);
1405
+ resolveReady(host.sessionStarted(message));
1264
1406
  } else if (message.type === "error") {
1265
1407
  fail(refused(`The relay refused the connection: ${message.message || message.code}`, message.code === "rate_limited" ? "rate_limited" : "policy"));
1266
1408
  } else if (message.type === "bye") {
@@ -1293,9 +1435,6 @@ function openConnection(host, url, secret, revokeAll = false) {
1293
1435
  return;
1294
1436
  case "grant.removed":
1295
1437
  host.grantRemoved(message.grantId);
1296
- revoking?.left.delete(message.grantId);
1297
- if (revoking?.left.size === 0)
1298
- resolveReady(revoking.session);
1299
1438
  return;
1300
1439
  case "identity.bound":
1301
1440
  host.identityResult(true, message.round);
@@ -1310,7 +1449,9 @@ function openConnection(host, url, secret, revokeAll = false) {
1310
1449
  host.identityResult(false, typeof message.round === "number" ? message.round : undefined, message.message);
1311
1450
  return;
1312
1451
  }
1313
- host.error(new Error(`Relay error ${message.code}: ${message.message}`));
1452
+ if (message.code === "unknown_id" && message.for === "grant.revoke" && typeof message.grantId === "string")
1453
+ host.grantRemoved(message.grantId);
1454
+ host.error(Object.assign(new Error(`Relay error ${message.code}: ${message.message}`), { code: message.code }, typeof message.for === "string" ? { for: message.for } : {}, typeof message.grantId === "string" ? { grantId: message.grantId } : {}));
1314
1455
  return;
1315
1456
  case "session":
1316
1457
  return;
@@ -1324,7 +1465,7 @@ function openConnection(host, url, secret, revokeAll = false) {
1324
1465
  const hello = {
1325
1466
  type: "hello",
1326
1467
  library: host.library,
1327
- page: { title: pageTitle() },
1468
+ page: { title: "" },
1328
1469
  secret
1329
1470
  };
1330
1471
  if (host.appName !== undefined)
@@ -1337,26 +1478,11 @@ function openConnection(host, url, secret, revokeAll = false) {
1337
1478
  if (typeof event.data !== "string")
1338
1479
  return;
1339
1480
  const message = parseRelayMessage(event.data);
1340
- if (message !== undefined) {
1341
- if (state === "ready")
1342
- armHeartbeat();
1343
- onMessage(message);
1481
+ if (message === undefined)
1344
1482
  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
- }
1483
+ if (state === "ready")
1484
+ armHeartbeat();
1485
+ onMessage(message);
1360
1486
  });
1361
1487
  ws.addEventListener("close", (event) => {
1362
1488
  if (state === "opening") {
@@ -1400,5 +1526,5 @@ export {
1400
1526
  withAddress
1401
1527
  };
1402
1528
 
1403
- //# debugId=EBEC5A72AFF3C4C664756E2164756E21
1404
- //# sourceMappingURL=connection-g6wk37yd.js.map
1529
+ //# debugId=F72380915EFCE0FC64756E2164756E21
1530
+ //# sourceMappingURL=connection-g91xjjgm.js.map