-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcontent.js
More file actions
584 lines (510 loc) · 15.2 KB
/
Copy pathcontent.js
File metadata and controls
584 lines (510 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
(() => {
/**
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*
* Content Script
* Detects available WebMCP APIs, lists tools, and executes tools on request.
*/
if (window.__webmcpInspectorInjected) {
console.debug('[WebMCP Inspector] Content script already active in this frame');
return;
}
window.__webmcpInspectorInjected = true;
console.debug('[WebMCP Inspector] Content script injected');
let toolsChangedCallback = null;
function toPlainSerializable(value, depth = 0, seen = new WeakSet()) {
if (value === null) return null;
const valueType = typeof value;
if (valueType === 'string' || valueType === 'number' || valueType === 'boolean') {
return value;
}
if (valueType === 'bigint') {
return String(value);
}
if (valueType === 'undefined' || valueType === 'function' || valueType === 'symbol') {
return undefined;
}
if (depth > 8) {
return '[MaxDepth]';
}
if (value instanceof Date) {
return value.toISOString();
}
if (Array.isArray(value)) {
const arr = [];
for (const item of value) {
const normalized = toPlainSerializable(item, depth + 1, seen);
if (normalized !== undefined) {
arr.push(normalized);
}
}
return arr;
}
if (valueType === 'object') {
if (seen.has(value)) {
return '[Circular]';
}
seen.add(value);
const out = {};
for (const [key, nested] of Object.entries(value)) {
const normalized = toPlainSerializable(nested, depth + 1, seen);
if (normalized !== undefined) {
out[key] = normalized;
}
}
seen.delete(value);
return out;
}
return undefined;
}
function cssEscape(value) {
if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') {
return CSS.escape(String(value));
}
return String(value).replace(/["\\]/g, '\\$&');
}
function getWebMCPAPI() {
// Prefer testing API because it includes discovery + execution methods used by inspector.
try {
return navigator.modelContextTesting || navigator.modelContext || null;
} catch {
return null;
}
}
function detectApiFlavor(api) {
try {
if (!api) return null;
if (api === navigator.modelContextTesting) return 'testing';
if (api === navigator.modelContext) return 'stable';
return 'unknown';
} catch {
return null;
}
}
function getCapabilities(api) {
if (!api) return [];
const names = [
'listTools',
'executeTool',
'registerToolsChangedCallback',
'getCrossDocumentScriptToolResult',
'registerTool',
'unregisterTool',
'provideContext',
'clearContext'
];
return names.filter((name) => {
try {
return typeof api[name] === 'function';
} catch {
return false;
}
});
}
function sendStatus(message, type = 'info') {
sendRuntimeMessage({
type: 'STATUS',
message,
messageType: type,
url: location.href
});
}
function isExtensionContextInvalidatedError(error) {
return /extension context invalidated/i.test(String(error?.message || error));
}
function isDomExceptionError(error) {
if (typeof DOMException !== 'undefined' && error instanceof DOMException) {
return true;
}
return /\bDOMException\b/i.test(String(error?.message || error));
}
function getRuntime() {
try {
return globalThis.chrome?.runtime || null;
} catch (error) {
if (!isExtensionContextInvalidatedError(error)) {
console.debug('[WebMCP Inspector] Unable to access chrome.runtime:', error);
}
return null;
}
}
function sendRuntimeMessage(payload) {
const runtime = getRuntime();
if (!runtime || typeof runtime.sendMessage !== 'function') {
return;
}
try {
const maybePromise = runtime.sendMessage(payload);
if (maybePromise && typeof maybePromise.catch === 'function') {
maybePromise.catch(() => {});
}
} catch (error) {
if (!isExtensionContextInvalidatedError(error)) {
console.debug('[WebMCP Inspector] Failed to send runtime message:', error);
}
}
}
function safeReply(reply, payload) {
if (typeof reply !== 'function') return;
try {
reply(payload);
} catch (error) {
if (!isExtensionContextInvalidatedError(error)) {
console.debug('[WebMCP Inspector] Failed to reply to runtime message:', error);
}
}
}
function errorToString(error) {
if (!error) return 'Unknown error';
if (typeof error === 'string') return error;
const name = typeof error.name === 'string' ? error.name : '';
const message = typeof error.message === 'string' ? error.message : '';
if (name && message) return `${name}: ${message}`;
if (message) return message;
const plain = toPlainSerializable(error);
if (plain !== undefined) {
try {
return JSON.stringify(plain);
} catch {
// fall through
}
}
return String(error);
}
function shouldRetryExecuteWithStringArgs(error) {
const message = String(error?.message || error || '').toLowerCase();
const errorName = String(error?.name || '').toLowerCase();
const hasJsonSignal =
message.includes('json') ||
message.includes('parse') ||
message.includes('input');
return (
message.includes('parse input arguments') ||
message.includes('parse input string as json') ||
message.includes('failed to parse input string as json') ||
message.includes('invalid input arguments') ||
message.includes('expected string') ||
(errorName === 'unknownerror' && hasJsonSignal)
);
}
function hasDeclarativeFormWithToolName(toolName) {
if (!toolName || toolName === '(unnamed_tool)') return false;
try {
return Boolean(document.querySelector(`form[toolname="${cssEscape(toolName)}"]`));
} catch {
return false;
}
}
function hasDeclarativeMetadata(tool) {
const type = String(tool?.type || '').toLowerCase();
const kind = String(tool?.kind || '').toLowerCase();
const source = String(tool?.source || '').toLowerCase();
if (type.includes('declarative') || kind === 'form' || source.includes('form')) {
return true;
}
const annotations = tool?.annotations;
if (annotations && typeof annotations === 'object') {
const annotationValues = Object.values(annotations)
.map((value) => String(value).toLowerCase());
if (annotationValues.some((value) => value.includes('declarative') || value.includes('form'))) {
return true;
}
}
return false;
}
function normalizeTools(rawTools) {
if (!Array.isArray(rawTools)) return [];
return rawTools
.filter((tool) => tool && typeof tool === 'object')
.map((tool) => {
const toolName = tool.name || '(unnamed_tool)';
const looksDeclarative = hasDeclarativeMetadata(tool) || hasDeclarativeFormWithToolName(toolName);
const normalized = {
name: toolName,
description: tool.description || '',
inputSchema: parseToolInputSchema(tool.inputSchema)
};
if (looksDeclarative) {
normalized.type = 'declarative';
normalized.kind = 'form';
normalized.source = 'form';
} else {
if (typeof tool.type === 'string') normalized.type = tool.type;
if (typeof tool.kind === 'string') normalized.kind = tool.kind;
if (typeof tool.source === 'string') normalized.source = tool.source;
}
if (tool.annotations && typeof tool.annotations === 'object') {
normalized.annotations = toPlainSerializable(tool.annotations) || {};
}
return normalized;
});
}
function toPlainSchemaObject(value) {
const normalized = toPlainSerializable(value);
if (normalized && typeof normalized === 'object' && !Array.isArray(normalized)) {
return normalized;
}
return { type: 'object', properties: {} };
}
function parseToolInputSchema(schema) {
if (!schema) return { type: 'object', properties: {} };
if (typeof schema === 'string') {
try {
const parsed = JSON.parse(schema);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
return toPlainSchemaObject(parsed);
}
} catch {
// fall through
}
return { type: 'object', properties: {} };
}
if (typeof schema === 'object' && !Array.isArray(schema)) {
return toPlainSchemaObject(schema);
}
return { type: 'object', properties: {} };
}
function listTools() {
try {
const api = getWebMCPAPI();
if (!api) {
return {
success: false,
error: 'WebMCP API is not available on this page',
tools: [],
api: null,
capabilities: []
};
}
if (typeof api.listTools !== 'function') {
sendStatus('WebMCP detected, but listTools() is unavailable in this API surface.', 'warning');
return {
success: true,
tools: [],
api: detectApiFlavor(api),
capabilities: getCapabilities(api),
warning: 'Current API surface does not expose listTools().'
};
}
const tools = normalizeTools(api.listTools());
const payload = {
success: true,
tools,
api: detectApiFlavor(api),
capabilities: getCapabilities(api),
url: location.href
};
sendRuntimeMessage({
type: 'TOOLS_LIST',
tools,
url: location.href
});
return payload;
} catch (error) {
const payload = {
success: false,
error: `Error listing tools: ${errorToString(error)}`,
tools: [],
api: detectApiFlavor(getWebMCPAPI()),
capabilities: getCapabilities(getWebMCPAPI())
};
sendStatus(payload.error, 'error');
return payload;
}
}
function setupToolsChangedListener() {
const api = getWebMCPAPI();
if (!api || typeof api.registerToolsChangedCallback !== 'function') return;
if (toolsChangedCallback && typeof api.unregisterToolsChangedCallback === 'function') {
try {
api.unregisterToolsChangedCallback(toolsChangedCallback);
} catch {
// best effort
}
}
toolsChangedCallback = () => {
console.debug('[WebMCP Inspector] Tools changed callback received');
listTools();
};
try {
api.registerToolsChangedCallback(toolsChangedCallback);
} catch (error) {
console.debug('[WebMCP Inspector] Failed to register tools changed callback:', error.message);
}
}
async function executeTool(name, inputArgs) {
const api = getWebMCPAPI();
if (!api) {
throw new Error('WebMCP API not available');
}
if (typeof api.executeTool !== 'function') {
throw new Error('executeTool() is not available on this page API surface');
}
const safeName = String(name || '');
console.debug(`[WebMCP Inspector] Executing tool "${safeName}"`, inputArgs);
let formElement = null;
try {
formElement = document.querySelector(`form[toolname="${cssEscape(safeName)}"]`);
} catch {
formElement = null;
}
const formTarget = formElement?.target;
let loadPromise = null;
if (formTarget) {
let targetFrame = null;
try {
targetFrame = document.querySelector(`[name="${cssEscape(formTarget)}"]`);
} catch {
targetFrame = null;
}
if (targetFrame) {
loadPromise = new Promise((resolve) => {
const handler = () => {
targetFrame.removeEventListener('load', handler);
resolve();
};
targetFrame.addEventListener('load', handler, { once: true });
});
}
}
let result;
try {
result = await api.executeTool(safeName, inputArgs);
} catch (error) {
if (typeof inputArgs === 'string') {
throw error;
}
// Some experimental API variants expect JSON string arguments.
if (!shouldRetryExecuteWithStringArgs(error)) {
throw error;
}
const stringArgs = JSON.stringify(inputArgs);
try {
result = await api.executeTool(safeName, stringArgs);
} catch (stringModeError) {
if (!shouldRetryExecuteWithStringArgs(stringModeError)) {
throw stringModeError;
}
// Some builds accept a single invocation envelope argument.
try {
result = await api.executeTool({
name: safeName,
inputArgs: stringArgs
});
} catch {
throw stringModeError;
}
}
}
if (result === null) {
if (loadPromise) {
try {
await Promise.race([
loadPromise,
new Promise((resolve) => setTimeout(resolve, 2000))
]);
} catch {
// best effort
}
}
if (typeof api.getCrossDocumentScriptToolResult === 'function') {
try {
return await api.getCrossDocumentScriptToolResult();
} catch (error) {
// Some implementations may not expose cross-document result in all contexts.
if (!isDomExceptionError(error)) {
throw error;
}
}
}
}
return result;
}
async function getCrossDocumentScriptToolResult() {
const api = getWebMCPAPI();
if (!api || typeof api.getCrossDocumentScriptToolResult !== 'function') {
throw new Error('getCrossDocumentScriptToolResult() is not available');
}
return api.getCrossDocumentScriptToolResult();
}
function handleRuntimeMessage(request, sender, reply) {
(async () => {
try {
const { action, name, inputArgs } = request;
switch (action) {
case 'LIST_TOOLS': {
const result = listTools();
setupToolsChangedListener();
safeReply(reply, toPlainSerializable(result));
return;
}
case 'EXECUTE_TOOL': {
const result = await executeTool(name, inputArgs);
safeReply(reply, { success: true, result: toPlainSerializable(result) });
return;
}
case 'GET_CROSS_DOCUMENT_SCRIPT_TOOL_RESULT': {
const result = await getCrossDocumentScriptToolResult();
safeReply(reply, { success: true, result: toPlainSerializable(result) });
return;
}
case 'CHECK_AVAILABILITY': {
const api = getWebMCPAPI();
safeReply(reply, {
available: !!api,
api: detectApiFlavor(api),
capabilities: getCapabilities(api)
});
return;
}
default:
safeReply(reply, { error: `Unknown action: ${action}` });
}
} catch (error) {
if (isExtensionContextInvalidatedError(error)) {
// Noisy during extension reloads; ignore.
} else if (isDomExceptionError(error)) {
console.debug('[WebMCP Inspector] Message handler DOMException:', error);
} else {
console.error('[WebMCP Inspector] Message handler error:', error);
}
safeReply(reply, { success: false, error: errorToString(error) });
}
})();
return true;
}
function setupRuntimeListener() {
const runtime = getRuntime();
const onMessage = runtime?.onMessage;
if (!onMessage || typeof onMessage.addListener !== 'function') {
console.debug('[WebMCP Inspector] chrome.runtime.onMessage unavailable in this context');
return;
}
try {
onMessage.addListener(handleRuntimeMessage);
} catch (error) {
if (!isExtensionContextInvalidatedError(error)) {
console.debug('[WebMCP Inspector] Failed to register runtime message listener:', error);
}
}
}
window.addEventListener('toolactivated', (event) => {
sendRuntimeMessage({
type: 'TOOL_EVENT',
event: 'activated',
toolName: event.toolName
});
});
window.addEventListener('toolcancel', (event) => {
sendRuntimeMessage({
type: 'TOOL_EVENT',
event: 'cancelled',
toolName: event.toolName
});
});
// Initial warm-up
setupRuntimeListener();
listTools();
setupToolsChangedListener();
})();