@ractive-ch/tab-mcp-client 0.14.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +538 -126
- package/always-allowed.d.ts +25 -6
- package/cdn/confirm-y30cx7e1.min.js +4 -0
- package/cdn/confirm-y30cx7e1.min.js.map +10 -0
- package/cdn/connect-bbhj2y7w.min.js +6 -0
- package/cdn/connect-bbhj2y7w.min.js.map +12 -0
- package/cdn/connection-0y7ngtq7.min.js +17 -0
- package/cdn/connection-0y7ngtq7.min.js.map +22 -0
- package/cdn/index-vt5zk9me.min.js +91 -0
- package/cdn/index-vt5zk9me.min.js.map +13 -0
- package/cdn/tab-mcp-client.min.js +3 -3
- package/cdn/tab-mcp-client.min.js.map +6 -6
- package/confirm-fgnjgd08.js +263 -0
- package/confirm-fgnjgd08.js.map +10 -0
- package/confirm.d.ts +54 -0
- package/connect-8jpb0k29.js +484 -0
- package/connect-8jpb0k29.js.map +10 -0
- package/connect.d.ts +40 -0
- package/{connection-eqsag07j.js → connection-1d8rxgbq.js} +515 -242
- package/connection-1d8rxgbq.js.map +16 -0
- package/connection.d.ts +9 -9
- package/dialog.d.ts +83 -0
- package/{index-nmn1j689.js → index-5jyqehpk.js} +14 -10
- package/index-5jyqehpk.js.map +11 -0
- package/index-jnz7w9xa.js +392 -0
- package/index-jnz7w9xa.js.map +12 -0
- package/index.d.ts +1 -1
- package/index.js +285 -244
- package/index.js.map +6 -6
- package/mapping.d.ts +37 -4
- package/mcp.d.ts +23 -8
- package/package.json +5 -1
- package/react.d.ts +13 -12
- package/react.js +20 -14
- package/react.js.map +3 -3
- package/registry.d.ts +12 -5
- package/secret.d.ts +5 -2
- package/serve.d.ts +68 -0
- package/setup.d.ts +15 -25
- package/setup.js +1 -1
- package/strings.d.ts +107 -0
- package/tab-mcp.d.ts +76 -36
- package/tunnel.d.ts +74 -0
- package/tunnel.js +263 -0
- package/tunnel.js.map +10 -0
- package/types.d.ts +206 -73
- package/webmcp.d.ts +13 -18
- package/cdn/connection-dweyrdbn.min.js +0 -12
- package/cdn/connection-dweyrdbn.min.js.map +0 -21
- package/cdn/ui-5zecjy7s.min.js +0 -86
- package/cdn/ui-5zecjy7s.min.js.map +0 -14
- package/connection-eqsag07j.js.map +0 -15
- package/index-nmn1j689.js.map +0 -11
- package/ui-4qv8d1a3.js +0 -781
- package/ui-4qv8d1a3.js.map +0 -11
- package/ui.d.ts +0 -83
|
@@ -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
|
|
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 (
|
|
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
|
-
|
|
127
|
-
|
|
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
|
|
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 (!
|
|
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 && !(
|
|
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
|
|
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
|
|
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 (!
|
|
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 (!
|
|
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 = (
|
|
520
|
+
const finish = (event) => {
|
|
438
521
|
if (signal.aborted)
|
|
439
522
|
return;
|
|
440
|
-
let event;
|
|
441
523
|
try {
|
|
442
|
-
event
|
|
443
|
-
} catch {
|
|
444
|
-
event = sseEvent(result(id, errorResult("The tool returned a result that is not JSON.")));
|
|
445
|
-
}
|
|
446
|
-
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(
|
|
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 (!
|
|
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 =
|
|
535
|
-
const meta =
|
|
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
|
|
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 (!
|
|
752
|
+
if (!isObject3(v) || !str(v["grantId"]) || !str(v["createdAt"]))
|
|
676
753
|
return false;
|
|
677
754
|
const c = v["client"];
|
|
678
|
-
return
|
|
755
|
+
return isObject3(c) && str(c["id"]) && str(c["name"]) && str(c["host"]);
|
|
679
756
|
}
|
|
680
757
|
function isLimits(v) {
|
|
681
|
-
if (!
|
|
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
|
|
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 (!
|
|
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"]) &&
|
|
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": {
|
|
@@ -743,6 +820,357 @@ function parseRelayMessage(text) {
|
|
|
743
820
|
}
|
|
744
821
|
}
|
|
745
822
|
|
|
823
|
+
// src/serve.ts
|
|
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) {
|
|
845
|
+
return {
|
|
846
|
+
tools: kind === "webmcp" ? host.registry : toolsFor(host.registry, kind),
|
|
847
|
+
confirm: (request) => host.confirm(request),
|
|
848
|
+
observe: {
|
|
849
|
+
start: (call) => host.toolCallStarted(call),
|
|
850
|
+
end: (call) => host.toolCallEnded(call)
|
|
851
|
+
}
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
var RESPONSE_HEADERS = ["content-type", "cache-control"];
|
|
855
|
+
function* pieces(text, max) {
|
|
856
|
+
let i = 0;
|
|
857
|
+
while (i < text.length) {
|
|
858
|
+
let end = Math.min(i + max, text.length);
|
|
859
|
+
const last = text.charCodeAt(end - 1);
|
|
860
|
+
if (end < text.length && last >= 55296 && last <= 56319) {
|
|
861
|
+
end += end - 1 > i ? -1 : 1;
|
|
862
|
+
}
|
|
863
|
+
yield text.slice(i, end);
|
|
864
|
+
i = end;
|
|
865
|
+
}
|
|
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
|
+
}
|
|
877
|
+
function createTunnel(options) {
|
|
878
|
+
const { handler, send, timeoutMs } = options;
|
|
879
|
+
const inflight = new Map;
|
|
880
|
+
let closed = false;
|
|
881
|
+
async function run(msg) {
|
|
882
|
+
const controller = new AbortController;
|
|
883
|
+
inflight.get(msg.id)?.abort();
|
|
884
|
+
inflight.set(msg.id, controller);
|
|
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);
|
|
921
|
+
try {
|
|
922
|
+
const request = new Request(`https://tab.invalid${msg.path}`, {
|
|
923
|
+
method: msg.method,
|
|
924
|
+
headers: msg.headers,
|
|
925
|
+
signal: controller.signal
|
|
926
|
+
});
|
|
927
|
+
const response = await handler.handle(request, {
|
|
928
|
+
grant: msg.grant,
|
|
929
|
+
body: msg.body
|
|
930
|
+
});
|
|
931
|
+
if (!live()) {
|
|
932
|
+
await response.body?.cancel().catch(() => {});
|
|
933
|
+
return;
|
|
934
|
+
}
|
|
935
|
+
const headers = {};
|
|
936
|
+
for (const name of RESPONSE_HEADERS) {
|
|
937
|
+
const value = response.headers.get(name);
|
|
938
|
+
if (value !== null)
|
|
939
|
+
headers[name] = value;
|
|
940
|
+
}
|
|
941
|
+
const streamed = (headers["content-type"] ?? "").startsWith("text/event-stream");
|
|
942
|
+
const maxChunk = options.maxChunk();
|
|
943
|
+
if (!streamed || response.body === null) {
|
|
944
|
+
const body = await response.text();
|
|
945
|
+
if (!live())
|
|
946
|
+
return;
|
|
947
|
+
if (body.length <= maxChunk) {
|
|
948
|
+
send({
|
|
949
|
+
type: "http.response",
|
|
950
|
+
id: msg.id,
|
|
951
|
+
status: response.status,
|
|
952
|
+
headers,
|
|
953
|
+
body
|
|
954
|
+
});
|
|
955
|
+
return;
|
|
956
|
+
}
|
|
957
|
+
send({
|
|
958
|
+
type: "http.response.start",
|
|
959
|
+
id: msg.id,
|
|
960
|
+
status: response.status,
|
|
961
|
+
headers
|
|
962
|
+
});
|
|
963
|
+
for (const data of pieces(body, maxChunk)) {
|
|
964
|
+
if (!live())
|
|
965
|
+
break;
|
|
966
|
+
send({ type: "http.response.chunk", id: msg.id, data });
|
|
967
|
+
}
|
|
968
|
+
if (live())
|
|
969
|
+
send({ type: "http.response.end", id: msg.id });
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
send({
|
|
973
|
+
type: "http.response.start",
|
|
974
|
+
id: msg.id,
|
|
975
|
+
status: response.status,
|
|
976
|
+
headers
|
|
977
|
+
});
|
|
978
|
+
started = true;
|
|
979
|
+
const reader = response.body.getReader();
|
|
980
|
+
const decoder = new TextDecoder;
|
|
981
|
+
controller.signal.addEventListener("abort", () => {
|
|
982
|
+
reader.cancel().catch(() => {});
|
|
983
|
+
});
|
|
984
|
+
for (;; ) {
|
|
985
|
+
const { done, value } = await reader.read();
|
|
986
|
+
if (done || !live())
|
|
987
|
+
break;
|
|
988
|
+
const text = decoder.decode(value, { stream: true });
|
|
989
|
+
if (text !== "")
|
|
990
|
+
tail = (tail + text).slice(-2);
|
|
991
|
+
for (const data of pieces(text, maxChunk)) {
|
|
992
|
+
send({ type: "http.response.chunk", id: msg.id, data });
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
if (live())
|
|
996
|
+
send({ type: "http.response.end", id: msg.id });
|
|
997
|
+
} catch (error) {
|
|
998
|
+
if (live()) {
|
|
999
|
+
options.error(error instanceof Error ? error : new Error(String(error)));
|
|
1000
|
+
send({
|
|
1001
|
+
type: "http.response",
|
|
1002
|
+
id: msg.id,
|
|
1003
|
+
status: 500,
|
|
1004
|
+
headers: { "content-type": "application/json" },
|
|
1005
|
+
body: JSON.stringify({
|
|
1006
|
+
jsonrpc: "2.0",
|
|
1007
|
+
id: null,
|
|
1008
|
+
error: { code: -32603, message: "Internal server error" }
|
|
1009
|
+
})
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
} finally {
|
|
1013
|
+
clearTimeout(timer);
|
|
1014
|
+
if (inflight.get(msg.id) === controller)
|
|
1015
|
+
inflight.delete(msg.id);
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
return {
|
|
1019
|
+
request(message) {
|
|
1020
|
+
if (!closed)
|
|
1021
|
+
run(message);
|
|
1022
|
+
},
|
|
1023
|
+
cancel(id) {
|
|
1024
|
+
inflight.get(id)?.abort();
|
|
1025
|
+
inflight.delete(id);
|
|
1026
|
+
},
|
|
1027
|
+
close() {
|
|
1028
|
+
if (closed)
|
|
1029
|
+
return;
|
|
1030
|
+
closed = true;
|
|
1031
|
+
for (const controller of inflight.values())
|
|
1032
|
+
controller.abort();
|
|
1033
|
+
inflight.clear();
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
}
|
|
1037
|
+
var MAX_CHUNK = 64 * 1024;
|
|
1038
|
+
var MIN_CHUNK = 64;
|
|
1039
|
+
var REQUEST_TIMEOUT_MS = 300000;
|
|
1040
|
+
var MAX_ID = 128;
|
|
1041
|
+
var served = new WeakSet;
|
|
1042
|
+
var lastPort = 0;
|
|
1043
|
+
var str2 = (v) => typeof v === "string";
|
|
1044
|
+
function isObject4(v) {
|
|
1045
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
1046
|
+
}
|
|
1047
|
+
function servePort(host, port, options) {
|
|
1048
|
+
const who = options?.client;
|
|
1049
|
+
if (!isObject4(who) || !str2(who.id) || who.id === "" || who.name !== undefined && !str2(who.name)) {
|
|
1050
|
+
throw new TypeError("serve: client needs an id (and may have a name)");
|
|
1051
|
+
}
|
|
1052
|
+
const maxChunk = options.maxChunk ?? MAX_CHUNK;
|
|
1053
|
+
if (!Number.isInteger(maxChunk) || maxChunk < MIN_CHUNK) {
|
|
1054
|
+
throw new TypeError(`serve: maxChunk must be a whole number of at least ${MIN_CHUNK}`);
|
|
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");
|
|
1062
|
+
if (typeof port?.postMessage !== "function" || !("onmessage" in port)) {
|
|
1063
|
+
throw new TypeError("serve: the port needs postMessage and onmessage");
|
|
1064
|
+
}
|
|
1065
|
+
if (served.has(port)) {
|
|
1066
|
+
throw new DOMException("serve: this port is served already; close that first", "InvalidStateError");
|
|
1067
|
+
}
|
|
1068
|
+
const client = { kind: "local", id: who.id };
|
|
1069
|
+
if (who.name !== undefined && who.name !== "")
|
|
1070
|
+
client.name = who.name;
|
|
1071
|
+
const grant = {
|
|
1072
|
+
grantId: `local:${++lastPort}`,
|
|
1073
|
+
clientId: who.id,
|
|
1074
|
+
scopes: ["tools"]
|
|
1075
|
+
};
|
|
1076
|
+
let closed = false;
|
|
1077
|
+
const send = (message) => {
|
|
1078
|
+
if (closed)
|
|
1079
|
+
return false;
|
|
1080
|
+
try {
|
|
1081
|
+
port.postMessage(message);
|
|
1082
|
+
return true;
|
|
1083
|
+
} catch {
|
|
1084
|
+
return false;
|
|
1085
|
+
}
|
|
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);
|
|
1090
|
+
const handler = createMcpHandler({
|
|
1091
|
+
...context,
|
|
1092
|
+
server: { ...host.server, icons: host.server.icons ?? pageIcons() },
|
|
1093
|
+
client: () => ({ ...client })
|
|
1094
|
+
});
|
|
1095
|
+
const stopWatching = watchTools(host.registry, context.tools, () => handler.toolsChanged());
|
|
1096
|
+
const tunnel = createTunnel({
|
|
1097
|
+
handler,
|
|
1098
|
+
send,
|
|
1099
|
+
maxChunk: () => maxChunk,
|
|
1100
|
+
error: (error) => host.error(error),
|
|
1101
|
+
timeoutMs
|
|
1102
|
+
});
|
|
1103
|
+
const bad = (message, id) => {
|
|
1104
|
+
const error = { type: "error", code: "bad_message", message };
|
|
1105
|
+
if (str2(id) && id.length <= MAX_ID)
|
|
1106
|
+
error.id = id;
|
|
1107
|
+
send(error);
|
|
1108
|
+
};
|
|
1109
|
+
const onMessage = (event) => {
|
|
1110
|
+
if (closed)
|
|
1111
|
+
return;
|
|
1112
|
+
const m = event?.data;
|
|
1113
|
+
if (!isObject4(m) || !str2(m["type"])) {
|
|
1114
|
+
bad("not a message");
|
|
1115
|
+
return;
|
|
1116
|
+
}
|
|
1117
|
+
const id = m["id"];
|
|
1118
|
+
switch (m["type"]) {
|
|
1119
|
+
case "http.request": {
|
|
1120
|
+
const { method, path, headers, body } = m;
|
|
1121
|
+
if (!str2(id) || id === "" || id.length > MAX_ID || !str2(method) || !str2(path) || !path.startsWith("/") || !isObject4(headers) || !Object.values(headers).every(str2) || !str2(body)) {
|
|
1122
|
+
bad("malformed http.request", id);
|
|
1123
|
+
return;
|
|
1124
|
+
}
|
|
1125
|
+
tunnel.request({
|
|
1126
|
+
type: "http.request",
|
|
1127
|
+
id,
|
|
1128
|
+
method,
|
|
1129
|
+
path,
|
|
1130
|
+
headers,
|
|
1131
|
+
body,
|
|
1132
|
+
grant
|
|
1133
|
+
});
|
|
1134
|
+
return;
|
|
1135
|
+
}
|
|
1136
|
+
case "http.cancel":
|
|
1137
|
+
if (str2(id))
|
|
1138
|
+
tunnel.cancel(id);
|
|
1139
|
+
else
|
|
1140
|
+
bad("malformed http.cancel");
|
|
1141
|
+
return;
|
|
1142
|
+
case "error":
|
|
1143
|
+
return;
|
|
1144
|
+
default:
|
|
1145
|
+
bad(`unexpected ${m["type"].slice(0, 64)}`, id);
|
|
1146
|
+
}
|
|
1147
|
+
};
|
|
1148
|
+
const events = port;
|
|
1149
|
+
const close = () => {
|
|
1150
|
+
if (closed)
|
|
1151
|
+
return;
|
|
1152
|
+
options.signal?.removeEventListener("abort", close);
|
|
1153
|
+
events.removeEventListener?.("close", close);
|
|
1154
|
+
stopWatching();
|
|
1155
|
+
tunnel.close();
|
|
1156
|
+
handler.close();
|
|
1157
|
+
if (served.delete(port))
|
|
1158
|
+
send({ type: "bye", reason: "closed" });
|
|
1159
|
+
closed = true;
|
|
1160
|
+
if (port.onmessage === onMessage)
|
|
1161
|
+
port.onmessage = null;
|
|
1162
|
+
};
|
|
1163
|
+
if (options.signal?.aborted === true) {
|
|
1164
|
+
close();
|
|
1165
|
+
return { close };
|
|
1166
|
+
}
|
|
1167
|
+
options.signal?.addEventListener("abort", close);
|
|
1168
|
+
events.addEventListener?.("close", close);
|
|
1169
|
+
served.add(port);
|
|
1170
|
+
port.onmessage = onMessage;
|
|
1171
|
+
return { close };
|
|
1172
|
+
}
|
|
1173
|
+
|
|
746
1174
|
// src/address.ts
|
|
747
1175
|
var BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
|
|
748
1176
|
function base32(bytes) {
|
|
@@ -781,24 +1209,18 @@ function withAddress(url, address) {
|
|
|
781
1209
|
}
|
|
782
1210
|
|
|
783
1211
|
// src/connection.ts
|
|
784
|
-
function callContext(host) {
|
|
785
|
-
return {
|
|
786
|
-
tools: host.registry,
|
|
787
|
-
confirm: (request) => host.confirm(request),
|
|
788
|
-
observe: {
|
|
789
|
-
start: (call) => host.toolCallStarted(call),
|
|
790
|
-
end: (call) => host.toolCallEnded(call)
|
|
791
|
-
}
|
|
792
|
-
};
|
|
793
|
-
}
|
|
794
1212
|
function callFromWebMcp(host, tool, input, signal) {
|
|
795
|
-
return webMcpCall(callContext(host), tool, input, signal);
|
|
1213
|
+
return webMcpCall(callContext(host, "webmcp"), tool, input, signal);
|
|
796
1214
|
}
|
|
797
1215
|
var CONNECT_TIMEOUT_MS = 15000;
|
|
798
1216
|
var CLOSE_REASONS = {
|
|
799
1217
|
1000: "closed",
|
|
1218
|
+
1001: "shutdown",
|
|
800
1219
|
1008: "policy",
|
|
801
1220
|
1009: "too_large",
|
|
1221
|
+
1011: "shutdown",
|
|
1222
|
+
1012: "shutdown",
|
|
1223
|
+
1013: "shutdown",
|
|
802
1224
|
4001: "expired",
|
|
803
1225
|
4002: "idle",
|
|
804
1226
|
4003: "heartbeat",
|
|
@@ -816,33 +1238,6 @@ var BYE_REASONS = {
|
|
|
816
1238
|
function refused(message, reason) {
|
|
817
1239
|
return Object.assign(new Error(message), { reason });
|
|
818
1240
|
}
|
|
819
|
-
var RESPONSE_HEADERS = ["content-type", "cache-control"];
|
|
820
|
-
function pageTitle() {
|
|
821
|
-
const title = globalThis.document?.title;
|
|
822
|
-
return typeof title === "string" ? title.slice(0, 300) : "";
|
|
823
|
-
}
|
|
824
|
-
function frameInfo(text) {
|
|
825
|
-
try {
|
|
826
|
-
const v = JSON.parse(text);
|
|
827
|
-
if (typeof v !== "object" || v === null || typeof v["type"] !== "string")
|
|
828
|
-
return;
|
|
829
|
-
return typeof v["id"] === "string" ? { type: v["type"], id: v["id"] } : { type: v["type"] };
|
|
830
|
-
} catch {
|
|
831
|
-
return;
|
|
832
|
-
}
|
|
833
|
-
}
|
|
834
|
-
var KNOWN_TYPES = new Set([
|
|
835
|
-
"session",
|
|
836
|
-
"ping",
|
|
837
|
-
"bye",
|
|
838
|
-
"http.request",
|
|
839
|
-
"http.cancel",
|
|
840
|
-
"pairing.code",
|
|
841
|
-
"grant.added",
|
|
842
|
-
"grant.removed",
|
|
843
|
-
"identity.bound",
|
|
844
|
-
"error"
|
|
845
|
-
]);
|
|
846
1241
|
var ENVELOPE_BYTES = 512;
|
|
847
1242
|
var WORST_BYTES_PER_UNIT = 6;
|
|
848
1243
|
var MIN_CHUNK_UNITS = 64;
|
|
@@ -851,29 +1246,19 @@ function chunkSize(maxMessageBytes) {
|
|
|
851
1246
|
const units = Math.floor((maxMessageBytes - ENVELOPE_BYTES) / WORST_BYTES_PER_UNIT);
|
|
852
1247
|
return units >= MIN_CHUNK_UNITS ? units : undefined;
|
|
853
1248
|
}
|
|
854
|
-
function* pieces(text, max) {
|
|
855
|
-
let i = 0;
|
|
856
|
-
while (i < text.length) {
|
|
857
|
-
let end = Math.min(i + max, text.length);
|
|
858
|
-
const last = text.charCodeAt(end - 1);
|
|
859
|
-
if (end < text.length && last >= 55296 && last <= 56319) {
|
|
860
|
-
end += end - 1 > i ? -1 : 1;
|
|
861
|
-
}
|
|
862
|
-
yield text.slice(i, end);
|
|
863
|
-
i = end;
|
|
864
|
-
}
|
|
865
|
-
}
|
|
866
1249
|
var SIBLING_WINDOW_MS = 1e4;
|
|
867
1250
|
var SIBLING_GRACE_MS = 1000;
|
|
868
|
-
function siblingTabs(name) {
|
|
1251
|
+
function siblingTabs(name, address) {
|
|
869
1252
|
let channel;
|
|
1253
|
+
let listening = false;
|
|
870
1254
|
let at = Number.NEGATIVE_INFINITY;
|
|
871
1255
|
let onClaim;
|
|
872
1256
|
try {
|
|
873
1257
|
if (name !== undefined && typeof BroadcastChannel === "function") {
|
|
874
1258
|
channel = new BroadcastChannel(name);
|
|
875
1259
|
channel.onmessage = (event) => {
|
|
876
|
-
|
|
1260
|
+
const data = event.data;
|
|
1261
|
+
if (!listening || data?.type !== "claimed" || data.address !== undefined && data.address !== address)
|
|
877
1262
|
return;
|
|
878
1263
|
at = Date.now();
|
|
879
1264
|
onClaim?.();
|
|
@@ -884,8 +1269,9 @@ function siblingTabs(name) {
|
|
|
884
1269
|
}
|
|
885
1270
|
return {
|
|
886
1271
|
claimed() {
|
|
1272
|
+
listening = true;
|
|
887
1273
|
try {
|
|
888
|
-
channel?.postMessage({ type: "claimed" });
|
|
1274
|
+
channel?.postMessage({ type: "claimed", address });
|
|
889
1275
|
} catch {}
|
|
890
1276
|
},
|
|
891
1277
|
heard() {
|
|
@@ -906,16 +1292,16 @@ function siblingTabs(name) {
|
|
|
906
1292
|
}
|
|
907
1293
|
};
|
|
908
1294
|
}
|
|
909
|
-
function openConnection(host, url, secret,
|
|
1295
|
+
function openConnection(host, url, secret, options = {}) {
|
|
1296
|
+
const revokeAll = options.revokeAll === true;
|
|
910
1297
|
const ws = new WebSocket(url, SUBPROTOCOL);
|
|
911
|
-
const inflight = new Map;
|
|
912
1298
|
let state = "opening";
|
|
913
1299
|
let byeReason;
|
|
914
1300
|
let maxChunk = 64 * 1024;
|
|
1301
|
+
let maxBodyBytes;
|
|
915
1302
|
let heartbeat;
|
|
916
1303
|
let heartbeatMs = 0;
|
|
917
|
-
const siblings = siblingTabs(host.tabs);
|
|
918
|
-
let revoking;
|
|
1304
|
+
const siblings = siblingTabs(host.tabs, options.address);
|
|
919
1305
|
let resolveReady;
|
|
920
1306
|
let rejectReady;
|
|
921
1307
|
const ready = new Promise((resolve, reject) => {
|
|
@@ -926,12 +1312,14 @@ function openConnection(host, url, secret, revokeAll = false) {
|
|
|
926
1312
|
const connectTimer = setTimeout(() => {
|
|
927
1313
|
fail(refused("The relay did not answer in time.", "network"));
|
|
928
1314
|
}, CONNECT_TIMEOUT_MS);
|
|
1315
|
+
const context = callContext(host, "relay");
|
|
929
1316
|
const handler = createMcpHandler({
|
|
930
|
-
...
|
|
1317
|
+
...context,
|
|
931
1318
|
server: { ...host.server, icons: host.server.icons ?? pageIcons() },
|
|
932
|
-
client: (grant) => host.clientFor(grant)
|
|
1319
|
+
client: (grant) => host.clientFor(grant),
|
|
1320
|
+
maxBodyBytes: () => maxBodyBytes
|
|
933
1321
|
});
|
|
934
|
-
const stopWatching = host.registry.
|
|
1322
|
+
const stopWatching = watchTools(host.registry, context.tools, () => handler.toolsChanged());
|
|
935
1323
|
function send(message) {
|
|
936
1324
|
if (ws.readyState !== WebSocket.OPEN)
|
|
937
1325
|
return false;
|
|
@@ -971,13 +1359,10 @@ function openConnection(host, url, secret, revokeAll = false) {
|
|
|
971
1359
|
clearTimeout(connectTimer);
|
|
972
1360
|
clearTimeout(heartbeat);
|
|
973
1361
|
stopWatching();
|
|
974
|
-
|
|
975
|
-
controller.abort();
|
|
976
|
-
inflight.clear();
|
|
1362
|
+
tunnel.close();
|
|
977
1363
|
handler.close();
|
|
978
1364
|
if (wasReady) {
|
|
979
1365
|
const reason = byeReason ?? CLOSE_REASONS[code] ?? (code === 1006 ? "network" : "closed");
|
|
980
|
-
rejectReady(refused("The address was taken over again before its AI apps were disconnected.", reason));
|
|
981
1366
|
host.closed(reason, code);
|
|
982
1367
|
if (reason === "replaced") {
|
|
983
1368
|
siblings.heard().then((sibling) => {
|
|
@@ -989,102 +1374,12 @@ function openConnection(host, url, secret, revokeAll = false) {
|
|
|
989
1374
|
}
|
|
990
1375
|
siblings.close();
|
|
991
1376
|
}
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
method: msg.method,
|
|
999
|
-
headers: msg.headers,
|
|
1000
|
-
signal: controller.signal
|
|
1001
|
-
});
|
|
1002
|
-
const response = await handler.handle(request, {
|
|
1003
|
-
grant: msg.grant,
|
|
1004
|
-
body: msg.body
|
|
1005
|
-
});
|
|
1006
|
-
if (!live()) {
|
|
1007
|
-
await response.body?.cancel().catch(() => {});
|
|
1008
|
-
return;
|
|
1009
|
-
}
|
|
1010
|
-
const headers = {};
|
|
1011
|
-
for (const name of RESPONSE_HEADERS) {
|
|
1012
|
-
const value = response.headers.get(name);
|
|
1013
|
-
if (value !== null)
|
|
1014
|
-
headers[name] = value;
|
|
1015
|
-
}
|
|
1016
|
-
const streamed = (headers["content-type"] ?? "").startsWith("text/event-stream");
|
|
1017
|
-
if (!streamed || response.body === null) {
|
|
1018
|
-
const body = await response.text();
|
|
1019
|
-
if (!live())
|
|
1020
|
-
return;
|
|
1021
|
-
if (body.length <= maxChunk) {
|
|
1022
|
-
send({
|
|
1023
|
-
type: "http.response",
|
|
1024
|
-
id: msg.id,
|
|
1025
|
-
status: response.status,
|
|
1026
|
-
headers,
|
|
1027
|
-
body
|
|
1028
|
-
});
|
|
1029
|
-
return;
|
|
1030
|
-
}
|
|
1031
|
-
send({
|
|
1032
|
-
type: "http.response.start",
|
|
1033
|
-
id: msg.id,
|
|
1034
|
-
status: response.status,
|
|
1035
|
-
headers
|
|
1036
|
-
});
|
|
1037
|
-
for (const data of pieces(body, maxChunk)) {
|
|
1038
|
-
if (!live())
|
|
1039
|
-
break;
|
|
1040
|
-
send({ type: "http.response.chunk", id: msg.id, data });
|
|
1041
|
-
}
|
|
1042
|
-
if (live())
|
|
1043
|
-
send({ type: "http.response.end", id: msg.id });
|
|
1044
|
-
return;
|
|
1045
|
-
}
|
|
1046
|
-
send({
|
|
1047
|
-
type: "http.response.start",
|
|
1048
|
-
id: msg.id,
|
|
1049
|
-
status: response.status,
|
|
1050
|
-
headers
|
|
1051
|
-
});
|
|
1052
|
-
const reader = response.body.getReader();
|
|
1053
|
-
const decoder = new TextDecoder;
|
|
1054
|
-
controller.signal.addEventListener("abort", () => {
|
|
1055
|
-
reader.cancel().catch(() => {});
|
|
1056
|
-
});
|
|
1057
|
-
for (;; ) {
|
|
1058
|
-
const { done, value } = await reader.read();
|
|
1059
|
-
if (done || !live())
|
|
1060
|
-
break;
|
|
1061
|
-
const text = decoder.decode(value, { stream: true });
|
|
1062
|
-
for (const data of pieces(text, maxChunk)) {
|
|
1063
|
-
send({ type: "http.response.chunk", id: msg.id, data });
|
|
1064
|
-
}
|
|
1065
|
-
}
|
|
1066
|
-
if (live())
|
|
1067
|
-
send({ type: "http.response.end", id: msg.id });
|
|
1068
|
-
} catch (error) {
|
|
1069
|
-
if (live()) {
|
|
1070
|
-
host.error(error instanceof Error ? error : new Error(String(error)));
|
|
1071
|
-
send({
|
|
1072
|
-
type: "http.response",
|
|
1073
|
-
id: msg.id,
|
|
1074
|
-
status: 500,
|
|
1075
|
-
headers: { "content-type": "application/json" },
|
|
1076
|
-
body: JSON.stringify({
|
|
1077
|
-
jsonrpc: "2.0",
|
|
1078
|
-
id: null,
|
|
1079
|
-
error: { code: -32603, message: "Internal server error" }
|
|
1080
|
-
})
|
|
1081
|
-
});
|
|
1082
|
-
}
|
|
1083
|
-
} finally {
|
|
1084
|
-
if (inflight.get(msg.id) === controller)
|
|
1085
|
-
inflight.delete(msg.id);
|
|
1086
|
-
}
|
|
1087
|
-
}
|
|
1377
|
+
const tunnel = createTunnel({
|
|
1378
|
+
handler,
|
|
1379
|
+
send,
|
|
1380
|
+
maxChunk: () => maxChunk,
|
|
1381
|
+
error: (error) => host.error(error)
|
|
1382
|
+
});
|
|
1088
1383
|
function onMessage(message) {
|
|
1089
1384
|
if (state === "opening") {
|
|
1090
1385
|
if (message.type === "session") {
|
|
@@ -1093,22 +1388,18 @@ function openConnection(host, url, secret, revokeAll = false) {
|
|
|
1093
1388
|
fail(refused(`The relay's message limit (${message.limits.maxMessageBytes} bytes) is too small; tab-mcp needs at least ${MIN_MESSAGE_BYTES}.`, "policy"));
|
|
1094
1389
|
return;
|
|
1095
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
|
+
}
|
|
1096
1395
|
maxChunk = chunk;
|
|
1396
|
+
maxBodyBytes = message.limits.maxBodyBytes;
|
|
1097
1397
|
state = "ready";
|
|
1098
1398
|
clearTimeout(connectTimer);
|
|
1099
1399
|
heartbeatMs = message.limits.heartbeatMs;
|
|
1100
1400
|
armHeartbeat();
|
|
1101
1401
|
siblings.claimed();
|
|
1102
|
-
|
|
1103
|
-
if (revokeAll && message.grants.length > 0) {
|
|
1104
|
-
revoking = {
|
|
1105
|
-
left: new Set(message.grants.map((g) => g.grantId)),
|
|
1106
|
-
session
|
|
1107
|
-
};
|
|
1108
|
-
send({ type: "grants.revokeAll" });
|
|
1109
|
-
return;
|
|
1110
|
-
}
|
|
1111
|
-
resolveReady(session);
|
|
1402
|
+
resolveReady(host.sessionStarted(message));
|
|
1112
1403
|
} else if (message.type === "error") {
|
|
1113
1404
|
fail(refused(`The relay refused the connection: ${message.message || message.code}`, message.code === "rate_limited" ? "rate_limited" : "policy"));
|
|
1114
1405
|
} else if (message.type === "bye") {
|
|
@@ -1124,11 +1415,10 @@ function openConnection(host, url, secret, revokeAll = false) {
|
|
|
1124
1415
|
send({ type: "pong", t: message.t });
|
|
1125
1416
|
return;
|
|
1126
1417
|
case "http.request":
|
|
1127
|
-
tunnel(message);
|
|
1418
|
+
tunnel.request(message);
|
|
1128
1419
|
return;
|
|
1129
1420
|
case "http.cancel":
|
|
1130
|
-
|
|
1131
|
-
inflight.delete(message.id);
|
|
1421
|
+
tunnel.cancel(message.id);
|
|
1132
1422
|
return;
|
|
1133
1423
|
case "pairing.code":
|
|
1134
1424
|
host.pairingCode(message.reason === undefined ? { code: message.code, expiresAt: message.expiresAt } : {
|
|
@@ -1142,9 +1432,6 @@ function openConnection(host, url, secret, revokeAll = false) {
|
|
|
1142
1432
|
return;
|
|
1143
1433
|
case "grant.removed":
|
|
1144
1434
|
host.grantRemoved(message.grantId);
|
|
1145
|
-
revoking?.left.delete(message.grantId);
|
|
1146
|
-
if (revoking?.left.size === 0)
|
|
1147
|
-
resolveReady(revoking.session);
|
|
1148
1435
|
return;
|
|
1149
1436
|
case "identity.bound":
|
|
1150
1437
|
host.identityResult(true, message.round);
|
|
@@ -1159,7 +1446,7 @@ function openConnection(host, url, secret, revokeAll = false) {
|
|
|
1159
1446
|
host.identityResult(false, typeof message.round === "number" ? message.round : undefined, message.message);
|
|
1160
1447
|
return;
|
|
1161
1448
|
}
|
|
1162
|
-
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 }));
|
|
1163
1450
|
return;
|
|
1164
1451
|
case "session":
|
|
1165
1452
|
return;
|
|
@@ -1173,7 +1460,7 @@ function openConnection(host, url, secret, revokeAll = false) {
|
|
|
1173
1460
|
const hello = {
|
|
1174
1461
|
type: "hello",
|
|
1175
1462
|
library: host.library,
|
|
1176
|
-
page: { title:
|
|
1463
|
+
page: { title: "" },
|
|
1177
1464
|
secret
|
|
1178
1465
|
};
|
|
1179
1466
|
if (host.appName !== undefined)
|
|
@@ -1186,26 +1473,11 @@ function openConnection(host, url, secret, revokeAll = false) {
|
|
|
1186
1473
|
if (typeof event.data !== "string")
|
|
1187
1474
|
return;
|
|
1188
1475
|
const message = parseRelayMessage(event.data);
|
|
1189
|
-
if (message
|
|
1190
|
-
if (state === "ready")
|
|
1191
|
-
armHeartbeat();
|
|
1192
|
-
onMessage(message);
|
|
1476
|
+
if (message === undefined)
|
|
1193
1477
|
return;
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
send(KNOWN_TYPES.has(info.type) ? {
|
|
1198
|
-
type: "error",
|
|
1199
|
-
code: "bad_message",
|
|
1200
|
-
message: `malformed ${info.type}`,
|
|
1201
|
-
id: info.id
|
|
1202
|
-
} : {
|
|
1203
|
-
type: "error",
|
|
1204
|
-
code: "unknown_type",
|
|
1205
|
-
message: `unknown type ${info.type}`,
|
|
1206
|
-
id: info.id
|
|
1207
|
-
});
|
|
1208
|
-
}
|
|
1478
|
+
if (state === "ready")
|
|
1479
|
+
armHeartbeat();
|
|
1480
|
+
onMessage(message);
|
|
1209
1481
|
});
|
|
1210
1482
|
ws.addEventListener("close", (event) => {
|
|
1211
1483
|
if (state === "opening") {
|
|
@@ -1245,8 +1517,9 @@ export {
|
|
|
1245
1517
|
compileRegistry,
|
|
1246
1518
|
openConnection,
|
|
1247
1519
|
pieces,
|
|
1520
|
+
servePort,
|
|
1248
1521
|
withAddress
|
|
1249
1522
|
};
|
|
1250
1523
|
|
|
1251
|
-
//# debugId=
|
|
1252
|
-
//# sourceMappingURL=connection-
|
|
1524
|
+
//# debugId=9E3DFFAD7EB6930C64756E2164756E21
|
|
1525
|
+
//# sourceMappingURL=connection-1d8rxgbq.js.map
|