@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.
@@ -307,6 +307,7 @@ async function runCall(context, tool, raw, signal, client) {
307
307
  }
308
308
  return run;
309
309
  }
310
+ var UNANSWERED = "The user was asked and did not answer.";
310
311
  async function decideAndRun(context, tool, raw, signal, client) {
311
312
  const stopped = (outcome, message, stop) => ({ outcome, result: errorResult(message), stop });
312
313
  const invalid = validate(tool, raw);
@@ -321,14 +322,17 @@ async function decideAndRun(context, tool, raw, signal, client) {
321
322
  };
322
323
  if (tool.title !== undefined)
323
324
  question.tool.title = tool.title;
324
- let allowed = false;
325
+ let answer = false;
325
326
  try {
326
- allowed = await context.confirm(question);
327
+ answer = await context.confirm(question);
327
328
  } catch {
328
- allowed = false;
329
+ answer = false;
330
+ }
331
+ if (answer !== true) {
332
+ if (signal.aborted)
333
+ return stopped("cancelled", "The user declined", "cancelled");
334
+ return answer === "unanswered" ? stopped("unanswered", UNANSWERED, "unanswered") : stopped("declined", "The user declined", "declined");
329
335
  }
330
- if (!allowed)
331
- return signal.aborted ? stopped("cancelled", "The user declined", "cancelled") : stopped("declined", "The user declined", "declined");
332
336
  }
333
337
  if (signal.aborted)
334
338
  return stopped("cancelled", "Cancelled", "cancelled");
@@ -363,6 +367,8 @@ async function webMcpCall(context, tool, input, signal) {
363
367
  throw new DOMException("Cancelled", "AbortError");
364
368
  if (run.stop === "declined")
365
369
  return failed(`The user did not allow ${tool.name} to run.`);
370
+ if (run.stop === "unanswered")
371
+ return failed(`The user did not answer whether ${tool.name} may run.`);
366
372
  if (run.stop === "gone")
367
373
  return failed(gone);
368
374
  if (run.result.isError === true)
@@ -737,6 +743,274 @@ function parseRelayMessage(text) {
737
743
  }
738
744
  }
739
745
 
746
+ // src/serve.ts
747
+ function callContext(host) {
748
+ return {
749
+ tools: host.registry,
750
+ confirm: (request) => host.confirm(request),
751
+ observe: {
752
+ start: (call) => host.toolCallStarted(call),
753
+ end: (call) => host.toolCallEnded(call)
754
+ }
755
+ };
756
+ }
757
+ var RESPONSE_HEADERS = ["content-type", "cache-control"];
758
+ function* pieces(text, max) {
759
+ let i = 0;
760
+ while (i < text.length) {
761
+ let end = Math.min(i + max, text.length);
762
+ const last = text.charCodeAt(end - 1);
763
+ if (end < text.length && last >= 55296 && last <= 56319) {
764
+ end += end - 1 > i ? -1 : 1;
765
+ }
766
+ yield text.slice(i, end);
767
+ i = end;
768
+ }
769
+ }
770
+ function createTunnel(options) {
771
+ const { handler, send } = options;
772
+ const inflight = new Map;
773
+ let closed = false;
774
+ async function run(msg) {
775
+ const controller = new AbortController;
776
+ inflight.get(msg.id)?.abort();
777
+ inflight.set(msg.id, controller);
778
+ const live = () => !closed && inflight.get(msg.id) === controller && !controller.signal.aborted;
779
+ try {
780
+ const request = new Request(`https://tab.invalid${msg.path}`, {
781
+ method: msg.method,
782
+ headers: msg.headers,
783
+ signal: controller.signal
784
+ });
785
+ const response = await handler.handle(request, {
786
+ grant: msg.grant,
787
+ body: msg.body
788
+ });
789
+ if (!live()) {
790
+ await response.body?.cancel().catch(() => {});
791
+ return;
792
+ }
793
+ const headers = {};
794
+ for (const name of RESPONSE_HEADERS) {
795
+ const value = response.headers.get(name);
796
+ if (value !== null)
797
+ headers[name] = value;
798
+ }
799
+ const streamed = (headers["content-type"] ?? "").startsWith("text/event-stream");
800
+ const maxChunk = options.maxChunk();
801
+ if (!streamed || response.body === null) {
802
+ const body = await response.text();
803
+ if (!live())
804
+ return;
805
+ if (body.length <= maxChunk) {
806
+ send({
807
+ type: "http.response",
808
+ id: msg.id,
809
+ status: response.status,
810
+ headers,
811
+ body
812
+ });
813
+ return;
814
+ }
815
+ send({
816
+ type: "http.response.start",
817
+ id: msg.id,
818
+ status: response.status,
819
+ headers
820
+ });
821
+ for (const data of pieces(body, maxChunk)) {
822
+ if (!live())
823
+ break;
824
+ send({ type: "http.response.chunk", id: msg.id, data });
825
+ }
826
+ if (live())
827
+ send({ type: "http.response.end", id: msg.id });
828
+ return;
829
+ }
830
+ send({
831
+ type: "http.response.start",
832
+ id: msg.id,
833
+ status: response.status,
834
+ headers
835
+ });
836
+ const reader = response.body.getReader();
837
+ const decoder = new TextDecoder;
838
+ controller.signal.addEventListener("abort", () => {
839
+ reader.cancel().catch(() => {});
840
+ });
841
+ for (;; ) {
842
+ const { done, value } = await reader.read();
843
+ if (done || !live())
844
+ break;
845
+ const text = decoder.decode(value, { stream: true });
846
+ for (const data of pieces(text, maxChunk)) {
847
+ send({ type: "http.response.chunk", id: msg.id, data });
848
+ }
849
+ }
850
+ if (live())
851
+ send({ type: "http.response.end", id: msg.id });
852
+ } catch (error) {
853
+ if (live()) {
854
+ options.error(error instanceof Error ? error : new Error(String(error)));
855
+ send({
856
+ type: "http.response",
857
+ id: msg.id,
858
+ status: 500,
859
+ headers: { "content-type": "application/json" },
860
+ body: JSON.stringify({
861
+ jsonrpc: "2.0",
862
+ id: null,
863
+ error: { code: -32603, message: "Internal server error" }
864
+ })
865
+ });
866
+ }
867
+ } finally {
868
+ if (inflight.get(msg.id) === controller)
869
+ inflight.delete(msg.id);
870
+ }
871
+ }
872
+ return {
873
+ request(message) {
874
+ if (!closed)
875
+ run(message);
876
+ },
877
+ cancel(id) {
878
+ inflight.get(id)?.abort();
879
+ inflight.delete(id);
880
+ },
881
+ close() {
882
+ if (closed)
883
+ return;
884
+ closed = true;
885
+ for (const controller of inflight.values())
886
+ controller.abort();
887
+ inflight.clear();
888
+ }
889
+ };
890
+ }
891
+ var MAX_CHUNK = 64 * 1024;
892
+ var MIN_CHUNK = 64;
893
+ var MAX_ID = 128;
894
+ var served = new WeakSet;
895
+ var lastPort = 0;
896
+ var str2 = (v) => typeof v === "string";
897
+ function isObject3(v) {
898
+ return typeof v === "object" && v !== null && !Array.isArray(v);
899
+ }
900
+ function servePort(host, port, options) {
901
+ const who = options?.client;
902
+ if (!isObject3(who) || !str2(who.id) || who.id === "" || who.name !== undefined && !str2(who.name)) {
903
+ throw new TypeError("serve: client needs an id (and may have a name)");
904
+ }
905
+ const maxChunk = options.maxChunk ?? MAX_CHUNK;
906
+ if (!Number.isInteger(maxChunk) || maxChunk < MIN_CHUNK) {
907
+ throw new TypeError(`serve: maxChunk must be a whole number of at least ${MIN_CHUNK}`);
908
+ }
909
+ if (typeof port?.postMessage !== "function" || !("onmessage" in port)) {
910
+ throw new TypeError("serve: the port needs postMessage and onmessage");
911
+ }
912
+ if (served.has(port)) {
913
+ throw new DOMException("serve: this port is served already; close that first", "InvalidStateError");
914
+ }
915
+ const client = { kind: "local", id: who.id };
916
+ if (who.name !== undefined && who.name !== "")
917
+ client.name = who.name;
918
+ const grant = {
919
+ grantId: `local:${++lastPort}`,
920
+ clientId: who.id,
921
+ scopes: ["tools"]
922
+ };
923
+ let closed = false;
924
+ const send = (message) => {
925
+ if (closed)
926
+ return false;
927
+ try {
928
+ port.postMessage(message);
929
+ return true;
930
+ } catch {
931
+ return false;
932
+ }
933
+ };
934
+ const handler = createMcpHandler({
935
+ ...callContext(host),
936
+ server: { ...host.server, icons: host.server.icons ?? pageIcons() },
937
+ client: () => ({ ...client })
938
+ });
939
+ const stopWatching = host.registry.onChange(() => handler.toolsChanged());
940
+ const tunnel = createTunnel({
941
+ handler,
942
+ send,
943
+ maxChunk: () => maxChunk,
944
+ error: (error) => host.error(error)
945
+ });
946
+ const bad = (message, id) => {
947
+ const error = { type: "error", code: "bad_message", message };
948
+ if (str2(id) && id.length <= MAX_ID)
949
+ error.id = id;
950
+ send(error);
951
+ };
952
+ const onMessage = (event) => {
953
+ if (closed)
954
+ return;
955
+ const m = event?.data;
956
+ if (!isObject3(m) || !str2(m["type"])) {
957
+ bad("not a message");
958
+ return;
959
+ }
960
+ const id = m["id"];
961
+ switch (m["type"]) {
962
+ case "http.request": {
963
+ 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)) {
965
+ bad("malformed http.request", id);
966
+ return;
967
+ }
968
+ tunnel.request({
969
+ type: "http.request",
970
+ id,
971
+ method,
972
+ path,
973
+ headers,
974
+ body,
975
+ grant
976
+ });
977
+ return;
978
+ }
979
+ case "http.cancel":
980
+ if (str2(id))
981
+ tunnel.cancel(id);
982
+ else
983
+ bad("malformed http.cancel");
984
+ return;
985
+ case "error":
986
+ return;
987
+ default:
988
+ bad(`unexpected ${m["type"].slice(0, 64)}`, id);
989
+ }
990
+ };
991
+ const close = () => {
992
+ if (closed)
993
+ return;
994
+ options.signal?.removeEventListener("abort", close);
995
+ stopWatching();
996
+ tunnel.close();
997
+ handler.close();
998
+ if (served.delete(port))
999
+ send({ type: "bye", reason: "closed" });
1000
+ closed = true;
1001
+ if (port.onmessage === onMessage)
1002
+ port.onmessage = null;
1003
+ };
1004
+ if (options.signal?.aborted === true) {
1005
+ close();
1006
+ return { close };
1007
+ }
1008
+ options.signal?.addEventListener("abort", close);
1009
+ served.add(port);
1010
+ port.onmessage = onMessage;
1011
+ return { close };
1012
+ }
1013
+
740
1014
  // src/address.ts
741
1015
  var BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
742
1016
  function base32(bytes) {
@@ -775,16 +1049,6 @@ function withAddress(url, address) {
775
1049
  }
776
1050
 
777
1051
  // src/connection.ts
778
- function callContext(host) {
779
- return {
780
- tools: host.registry,
781
- confirm: (request) => host.confirm(request),
782
- observe: {
783
- start: (call) => host.toolCallStarted(call),
784
- end: (call) => host.toolCallEnded(call)
785
- }
786
- };
787
- }
788
1052
  function callFromWebMcp(host, tool, input, signal) {
789
1053
  return webMcpCall(callContext(host), tool, input, signal);
790
1054
  }
@@ -810,7 +1074,6 @@ var BYE_REASONS = {
810
1074
  function refused(message, reason) {
811
1075
  return Object.assign(new Error(message), { reason });
812
1076
  }
813
- var RESPONSE_HEADERS = ["content-type", "cache-control"];
814
1077
  function pageTitle() {
815
1078
  const title = globalThis.document?.title;
816
1079
  return typeof title === "string" ? title.slice(0, 300) : "";
@@ -845,18 +1108,6 @@ function chunkSize(maxMessageBytes) {
845
1108
  const units = Math.floor((maxMessageBytes - ENVELOPE_BYTES) / WORST_BYTES_PER_UNIT);
846
1109
  return units >= MIN_CHUNK_UNITS ? units : undefined;
847
1110
  }
848
- function* pieces(text, max) {
849
- let i = 0;
850
- while (i < text.length) {
851
- let end = Math.min(i + max, text.length);
852
- const last = text.charCodeAt(end - 1);
853
- if (end < text.length && last >= 55296 && last <= 56319) {
854
- end += end - 1 > i ? -1 : 1;
855
- }
856
- yield text.slice(i, end);
857
- i = end;
858
- }
859
- }
860
1111
  var SIBLING_WINDOW_MS = 1e4;
861
1112
  var SIBLING_GRACE_MS = 1000;
862
1113
  function siblingTabs(name) {
@@ -902,7 +1153,6 @@ function siblingTabs(name) {
902
1153
  }
903
1154
  function openConnection(host, url, secret, revokeAll = false) {
904
1155
  const ws = new WebSocket(url, SUBPROTOCOL);
905
- const inflight = new Map;
906
1156
  let state = "opening";
907
1157
  let byeReason;
908
1158
  let maxChunk = 64 * 1024;
@@ -965,9 +1215,7 @@ function openConnection(host, url, secret, revokeAll = false) {
965
1215
  clearTimeout(connectTimer);
966
1216
  clearTimeout(heartbeat);
967
1217
  stopWatching();
968
- for (const controller of inflight.values())
969
- controller.abort();
970
- inflight.clear();
1218
+ tunnel.close();
971
1219
  handler.close();
972
1220
  if (wasReady) {
973
1221
  const reason = byeReason ?? CLOSE_REASONS[code] ?? (code === 1006 ? "network" : "closed");
@@ -983,102 +1231,12 @@ function openConnection(host, url, secret, revokeAll = false) {
983
1231
  }
984
1232
  siblings.close();
985
1233
  }
986
- async function tunnel(msg) {
987
- const controller = new AbortController;
988
- inflight.set(msg.id, controller);
989
- const live = () => state === "ready" && inflight.get(msg.id) === controller && !controller.signal.aborted;
990
- try {
991
- const request = new Request(`https://tab.invalid${msg.path}`, {
992
- method: msg.method,
993
- headers: msg.headers,
994
- signal: controller.signal
995
- });
996
- const response = await handler.handle(request, {
997
- grant: msg.grant,
998
- body: msg.body
999
- });
1000
- if (!live()) {
1001
- await response.body?.cancel().catch(() => {});
1002
- return;
1003
- }
1004
- const headers = {};
1005
- for (const name of RESPONSE_HEADERS) {
1006
- const value = response.headers.get(name);
1007
- if (value !== null)
1008
- headers[name] = value;
1009
- }
1010
- const streamed = (headers["content-type"] ?? "").startsWith("text/event-stream");
1011
- if (!streamed || response.body === null) {
1012
- const body = await response.text();
1013
- if (!live())
1014
- return;
1015
- if (body.length <= maxChunk) {
1016
- send({
1017
- type: "http.response",
1018
- id: msg.id,
1019
- status: response.status,
1020
- headers,
1021
- body
1022
- });
1023
- return;
1024
- }
1025
- send({
1026
- type: "http.response.start",
1027
- id: msg.id,
1028
- status: response.status,
1029
- headers
1030
- });
1031
- for (const data of pieces(body, maxChunk)) {
1032
- if (!live())
1033
- break;
1034
- send({ type: "http.response.chunk", id: msg.id, data });
1035
- }
1036
- if (live())
1037
- send({ type: "http.response.end", id: msg.id });
1038
- return;
1039
- }
1040
- send({
1041
- type: "http.response.start",
1042
- id: msg.id,
1043
- status: response.status,
1044
- headers
1045
- });
1046
- const reader = response.body.getReader();
1047
- const decoder = new TextDecoder;
1048
- controller.signal.addEventListener("abort", () => {
1049
- reader.cancel().catch(() => {});
1050
- });
1051
- for (;; ) {
1052
- const { done, value } = await reader.read();
1053
- if (done || !live())
1054
- break;
1055
- const text = decoder.decode(value, { stream: true });
1056
- for (const data of pieces(text, maxChunk)) {
1057
- send({ type: "http.response.chunk", id: msg.id, data });
1058
- }
1059
- }
1060
- if (live())
1061
- send({ type: "http.response.end", id: msg.id });
1062
- } catch (error) {
1063
- if (live()) {
1064
- host.error(error instanceof Error ? error : new Error(String(error)));
1065
- send({
1066
- type: "http.response",
1067
- id: msg.id,
1068
- status: 500,
1069
- headers: { "content-type": "application/json" },
1070
- body: JSON.stringify({
1071
- jsonrpc: "2.0",
1072
- id: null,
1073
- error: { code: -32603, message: "Internal server error" }
1074
- })
1075
- });
1076
- }
1077
- } finally {
1078
- if (inflight.get(msg.id) === controller)
1079
- inflight.delete(msg.id);
1080
- }
1081
- }
1234
+ const tunnel = createTunnel({
1235
+ handler,
1236
+ send,
1237
+ maxChunk: () => maxChunk,
1238
+ error: (error) => host.error(error)
1239
+ });
1082
1240
  function onMessage(message) {
1083
1241
  if (state === "opening") {
1084
1242
  if (message.type === "session") {
@@ -1118,11 +1276,10 @@ function openConnection(host, url, secret, revokeAll = false) {
1118
1276
  send({ type: "pong", t: message.t });
1119
1277
  return;
1120
1278
  case "http.request":
1121
- tunnel(message);
1279
+ tunnel.request(message);
1122
1280
  return;
1123
1281
  case "http.cancel":
1124
- inflight.get(message.id)?.abort();
1125
- inflight.delete(message.id);
1282
+ tunnel.cancel(message.id);
1126
1283
  return;
1127
1284
  case "pairing.code":
1128
1285
  host.pairingCode(message.reason === undefined ? { code: message.code, expiresAt: message.expiresAt } : {
@@ -1239,8 +1396,9 @@ export {
1239
1396
  compileRegistry,
1240
1397
  openConnection,
1241
1398
  pieces,
1399
+ servePort,
1242
1400
  withAddress
1243
1401
  };
1244
1402
 
1245
- //# debugId=319FF6CC80A08E2C64756E2164756E21
1246
- //# sourceMappingURL=connection-h2ct4x47.js.map
1403
+ //# debugId=EBEC5A72AFF3C4C664756E2164756E21
1404
+ //# sourceMappingURL=connection-g6wk37yd.js.map