// ==UserScript== // @name WebMCP — page tools for the local CLI // @namespace https://github.com/FallDownTheSystem/WebMCP // @version 0.5.1 // @description Automatically connect published page and embedded app tools to the local CLI and MCP server. // @match https://*/* // @match http://localhost/* // @match http://127.0.0.1/* // @run-at document-start // @sandbox DOM // @inject-into content // @grant GM_addElement // @grant GM_getResourceText // @grant GM_getValue // @grant GM_setValue // @grant GM_xmlhttpRequest // @connect 127.0.0.1 // @resource polyfill https://cdn.jsdelivr.net/npm/@w3c/webmcp-polyfill@0.2.0/dist/polyfill.js#sha256=93b4db481cf395e39f9eb15797f98dc4eba6344ae7b216a1628aa08a54db6dea // ==/UserScript== (() => { 'use strict'; if (!isSecureContext || self.origin === 'null' || self.origin !== location.origin) return; const origin = location.origin, endpoint = 'http://127.0.0.1:4797/userscript/channel'; const valid = name => typeof name === 'string' && /^[\w.-]{1,128}$/.test(name); const MAX = 1024 * 1024; let lifetime = new AbortController(); window.addEventListener('pagehide', () => lifetime.abort()); window.addEventListener('pageshow', e => { if (e.persisted && lifetime.signal.aborted) { lifetime = new AbortController(); start(); } }); function start() { if (lifetime.signal.aborted) return; if (!document.documentElement) { const observer = new MutationObserver(() => { if (document.documentElement) { observer.disconnect(); start(); } }); observer.observe(document, {childList:true}); return; } const topLevel = self === top; const ticket = crypto.randomUUID(); let attach; if (topLevel) attach = host(); // Page-side code has no local session credential or manager request function. try { const polyfill = GM_getResourceText('polyfill'); const element = GM_addElement(document.documentElement, 'script', {textContent: `(() => {\nconst native = 'modelContext' in document || 'modelContext' in navigator || 'ModelContext' in window || 'Tool' in window || 'ToolActivatedEvent' in window || 'ToolCancelEvent' in window;\n` + `const whenReady = (${lazyPolyfill.toString()})(native ? null : function () {\n${polyfill}\n});\n` + (topLevel ? `(${pageTools.toString()})(${JSON.stringify(ticket)}, whenReady);\n` : '') + '})();'}); element?.remove(); if (topLevel) { const channel = new MessageChannel(); attach(channel.port1, '', origin); window.postMessage(ticket, origin, [channel.port2]); } } catch { /* Cooperating embeds can still publish their own tools without a page API. */ } } // Runs in the page world. The polyfill announces itself to every frame in the tab as soon as it installs, // and some sites treat any cross-frame string message as their own (a forum editor pasted each one as an // embed). So it installs only when the page itself first reads document.modelContext. function lazyPolyfill(install) { const waiting = []; let ready = !install; if (install) { const activate = () => { if (ready) return; ready = true; delete document.modelContext; install(); for (const callback of waiting.splice(0)) try { callback(); } catch {} }; Object.defineProperty(document, 'modelContext', {configurable:true, enumerable:true, get() { activate(); return document.modelContext; }}); } return callback => { if (ready) callback(); else waiting.push(callback); }; } // Runs in the page world. Keep the actual WebMCP handle so each call reaches its registration. function pageTools(ticket, whenReady) { function receive(e) { if (e.source !== window || e.origin !== location.origin || e.data !== ticket || e.ports.length !== 1) return; window.removeEventListener('message', receive); const port = e.ports[0]; whenReady(() => serve(port)); } function serve(port) { const ctx = document.modelContext; if (!ctx?.getTools || !ctx?.executeTool) { port.close(); return; } let handles = new Map(), revision = 0, serial = 0; const sources = new WeakMap(), life = new AbortController(); async function refresh() { const version = ++revision; try { const origins = new Set(); for (const frame of document.querySelectorAll('iframe[src]')) { try { const url = new URL(frame.src); if (url.origin !== 'null' && url.origin !== location.origin) origins.add(url.origin); } catch {} } const tools = await ctx.getTools(origins.size ? {fromOrigins:[...origins]} : {}); if (revision !== version || life.signal.aborted) return; const next = new Map(), catalog = []; for (const tool of tools) { if (!tool.source || typeof tool.name !== 'string' || tool.origin === 'null') continue; let name = tool.name; if (tool.source !== window) { if (!sources.has(tool.source)) sources.set(tool.source, ++serial); name = `nativeframe${sources.get(tool.source)}.${name}`; } else if (/^(?:frame|nativeframe)\d+\./.test(name)) continue; if (next.has(name) || !/^[\w.-]{1,128}$/.test(name)) continue; next.set(name, tool); catalog.push({name,description:tool.description,inputSchema:tool.inputSchema}); if (catalog.length === 256) break; } handles=next; port.postMessage({type:'catalog',tools:catalog}); } catch { if (revision===version) { handles.clear(); port.postMessage({type:'catalog',tools:[]}); } } } ctx.addEventListener('toolchange', refresh, {signal:life.signal}); window.addEventListener('pagehide', () => { life.abort(); port.close(); }, {once:true}); const proxies = new Map(), requests = new Map(); function syncProxies(tools) { if (typeof ctx.registerTool !== 'function') return; const wanted = new Set(tools.map(t => t.name)); for (const [name, controller] of proxies) if (!wanted.has(name)) {controller.abort();proxies.delete(name);} for (const t of tools) { if (proxies.has(t.name) || !/^frame\d+\.[\w.-]+$/.test(t.name)) continue; const controller = new AbortController(); proxies.set(t.name, controller); const signal = AbortSignal.any([controller.signal,life.signal]); const execute = args => new Promise((resolve,reject)=>{ if (requests.size>=32 || signal.aborted) return reject(Error('Frame unavailable')); const id=crypto.randomUUID(),timer=setTimeout(()=>{requests.delete(id);reject(Error('Frame timed out'));},55000); requests.set(id,{resolve,reject,timer});port.postMessage({type:'proxy-call',id,name:t.name,arguments:args}); }); Promise.resolve().then(()=>ctx.registerTool({...t,execute},{signal})).catch(()=>{if(proxies.get(t.name)===controller)proxies.delete(t.name);}); } } port.onmessage = async ({data}) => { if(data?.type==='proxies' && Array.isArray(data.tools)) {syncProxies(data.tools);return;} if(data?.type==='proxy-result') {const job=requests.get(data.id);if(job){requests.delete(data.id);clearTimeout(job.timer);if(data.error)job.reject(Error('Frame unavailable'));else job.resolve(data.text);}return;} if (data?.type !== 'call' || !handles.has(data.name)) return; try { const text = await ctx.executeTool(handles.get(data.name), data.arguments, {signal:AbortSignal.any([life.signal,AbortSignal.timeout(55000)])}); port.postMessage({type:'result',id:data.id,text}); } catch { port.postMessage({type:'result',id:data.id,error:'Tool failed or is no longer available'}); } }; refresh(); } window.addEventListener('message',receive); setTimeout(()=>window.removeEventListener('message',receive),5000); } class ApprovalError extends Error {} // The page and its frames cannot reach the bridge, so the userscript is the one place a gate can hold. // Approval covers a tab or a frame origin, not a single call, so a task runs without a prompt per step. function approvals() { const allowed = new Map(), denied = new Set(), asking = new Map(), WAIT = 50000, ARM = 600; const hostOf = name => { try { return new URL(name).host; } catch { return name; } }; const saved = () => { try { const list = GM_getValue('approved', []); return Array.isArray(list) ? list : []; } catch { return []; } }; const store = list => { try { GM_setValue('approved', [...new Set(list)]); } catch {} }; // Design canvases give each board its own subdomain, so a lasting frame approval covers its siblings too. function family(frameOrigin) { try { const url = new URL(frameOrigin), labels = url.hostname.split('.'); return labels.length > 2 && !/^[\d.]+$/.test(url.hostname) ? `${url.protocol}//*.${labels.slice(1).join('.')}${url.port ? ':' + url.port : ''}` : frameOrigin; } catch { return frameOrigin; } } const tab = {key:origin, lasting:origin, title:'Let your agent use this page?', what:hostOf(origin), always:'Always allow remembers this site.'}; function frame(frameOrigin) { const lasting = `${origin} ${family(frameOrigin)}`; return {key:`${origin} ${frameOrigin}`, lasting, title:'Let your agent use a frame on this page?', what:`${hostOf(frameOrigin)} in ${hostOf(origin)}`, always:`Always allow remembers ${family(frameOrigin) === frameOrigin ? 'this frame' : family(frameOrigin).replace(/^[a-z]+:\/\//, '')} on this site.`}; } let chip; function connected() { if (chip?.isConnected) return; chip = surface('status'); chip.body.innerHTML = 'Agent access'; const toggle = chip.body.querySelector('.toggle'); // The folded state is a preference about the notice, so it carries over to every tab and site. const fold = folded => { chip.body.toggleAttribute('data-folded', folded); toggle.setAttribute('aria-expanded', String(!folded)); toggle.setAttribute('aria-label', folded ? 'Agent access: show details' : 'Hide details'); }; try { fold(GM_getValue('chipFolded', false) === true); } catch { fold(false); } toggle.addEventListener('click', () => { const folded = !chip.body.hasAttribute('data-folded'); fold(folded); try { GM_setValue('chipFolded', folded); } catch {} }); chip.body.querySelector('.revoke').addEventListener('click', () => { const revoked = new Set(allowed.values()); allowed.clear(); store(saved().filter(key => !revoked.has(key))); chip.close(); }); chip.open({top:'auto', bottom:'16px'}); } function check(scope, tool) { if (allowed.has(scope.key) || saved().includes(scope.lasting)) { allowed.set(scope.key, scope.lasting); connected(); return Promise.resolve(); } if (denied.has(scope.key)) return Promise.reject(new ApprovalError(`The user denied your agent access to ${scope.what}. Reloading the tab asks again.`)); if (!asking.has(scope.key)) asking.set(scope.key, ask(scope, tool).finally(() => asking.delete(scope.key))); return asking.get(scope.key); } function ask(scope, tool) { return new Promise((resolve, reject) => { const prompt = surface('alertdialog'); let settled = false, shownAt = Infinity; const titleMark = 'Approve agent access · '; const marked = document.hidden && !document.title.startsWith(titleMark); if (marked) document.title = titleMark + document.title; function finish(error) { if (settled) return; settled = true; clearTimeout(timer); prompt.close(); if (marked && document.title.startsWith(titleMark)) document.title = document.title.slice(titleMark.length); if (error) reject(error); else { connected(); resolve(); } } const timer = setTimeout(() => finish(new ApprovalError(`No answer yet to the approval prompt in the tab titled "${document.title.replace(titleMark, '')}". Ask the user to answer it there, then call the tool again.`)), WAIT); prompt.body.innerHTML = `

It asked to run .

`; prompt.body.querySelector('h2').textContent = scope.title; prompt.body.querySelector('.what').textContent = scope.what; prompt.body.querySelector('code').textContent = tool; prompt.body.querySelector('[data-choice=always]').textContent = 'Always allow'; prompt.body.querySelector('.note').textContent = scope.always; const buttons = [...prompt.body.querySelectorAll('button')]; for (const button of buttons) { button.disabled = true; button.addEventListener('click', e => { // A page script cannot make a trusted click, and the checks below catch a prompt hidden under a lure. if (!e.isTrusted || performance.now() - shownAt < ARM || !prompt.visible(e)) return; const choice = button.dataset.choice; if (choice === 'deny') { denied.add(scope.key); return finish(new ApprovalError(`The user denied your agent access to ${scope.what}. Reloading the tab asks again.`)); } allowed.set(scope.key, scope.lasting); if (choice === 'always') store([...saved(), scope.lasting]); finish(); }); } prompt.onlost = () => finish(new ApprovalError(`The approval prompt in ${scope.what} was closed by the page, so the call was refused.`)); prompt.open({top:'16px', bottom:'auto'}); shownAt = performance.now(); setTimeout(() => { for (const button of buttons) button.disabled = false; }, ARM); }); } // The host element sits in the page, so its inline !important styles outrank the page's stylesheets, // and any change the page makes to it closes the prompt instead of leaving it half visible. function surface(role) { const element = document.createElement('webmcp-approval'); const root = element.attachShadow({mode:'closed'}); // Sites with a strict style-src policy block a