@ractive-ch/tab-mcp-client 0.12.0 → 0.13.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 CHANGED
@@ -6,7 +6,7 @@ relay. The page connects to the relay and gets an address. The user adds that ad
6
6
  their AI app and types a pairing code from the page; the AI app then calls the page's
7
7
  tools while the tab stays open. Nothing is installed on the user's computer.
8
8
 
9
- **Status: 0.12.0.** Until 1.0, a new minor version can still change the API. Which AI apps
9
+ **Status: 0.13.0.** Until 1.0, a new minor version can still change the API. Which AI apps
10
10
  work is listed in [compatibility](https://github.com/ractive/tab-mcp/blob/main/docs/compatibility.md).
11
11
 
12
12
  ## You need a relay
@@ -38,7 +38,7 @@ Or without a bundler, from a CDN as an ES module:
38
38
 
39
39
  ```html
40
40
  <script type="module">
41
- import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.12.0/cdn/tab-mcp-client.min.js";
41
+ import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.13.0/cdn/tab-mcp-client.min.js";
42
42
  </script>
43
43
  ```
44
44
 
@@ -91,8 +91,11 @@ PNG, JPEG, GIF, WebP or ICO `data:` URIs up to 16 KiB (no inline SVG). They go o
91
91
  validator itself is loaded by `connect()`: from then on it checks each schema at
92
92
  registration too, and a tool registered earlier whose schema it refuses (for example a
93
93
  `$ref` next to a nested `$id`) is unregistered, with the reason in the event `error`;
94
- - `execute(input, { signal, client })`: runs the tool. `signal` aborts when the AI app
95
- gives up; `client` names the caller (`id`, verified `host`, declared `name`). Return a
94
+ - `execute(input, { signal, client })`: runs the tool. `signal` aborts when the caller
95
+ gives up. `client` names the caller: `{ kind: "relay", grantId, id, host, name? }` for
96
+ an AI app through the relay (`id`, verified `host`, declared `name`), or
97
+ `{ kind: "webmcp" }` for an agent in the browser ([WebMCP](#webmcp)), of which nothing
98
+ more is known. Check `client.kind` before you read `host`. Return a
96
99
  string (one text block), an MCP result with a `content` array (passed through), or any
97
100
  other JSON value (sent as JSON text, and as `structuredContent` for an object). A thrown
98
101
  error becomes an error result with its message;
@@ -108,6 +111,48 @@ against the type, so keep the two in step.
108
111
  Abort the `signal` to remove the tool. AI apps that listen for changes learn about
109
112
  added and removed tools.
110
113
 
114
+ ### WebMCP
115
+
116
+ `new TabMcp({ ..., webmcp: true })` also registers the tools with the browser's own
117
+ WebMCP (`document.modelContext.registerTool()`, the
118
+ [WebMCP draft](https://webmachinelearning.github.io/webmcp/)), where the browser has it,
119
+ so that agents in the browser can call them: an agent built into the browser, or an
120
+ extension. Off by default. Turning it on is a change in what the page exposes: any
121
+ agent in the browser can then call the mirrored tools without pairing.
122
+
123
+ - Tools marked `consequentialHint` are left out unless their registration says
124
+ `{ webmcp: true }`: an agent in the browser often drives the very tab it calls into,
125
+ so it can click Allow in the page's confirmation itself. `{ webmcp: false }` keeps any
126
+ tool out of WebMCP.
127
+ - A WebMCP call takes the same path as an AI app's: the arguments are checked against
128
+ `inputSchema` (Chrome does not check them), a consequential tool asks (`onConfirm`, or
129
+ the library's dialog, which names the caller "An agent in this browser"), and
130
+ `toolcall` and `toolcallend` fire with `client: { kind: "webmcp" }`. "Always allow" is
131
+ never offered or applied for these calls: there is no identity to remember it for.
132
+ - The call resolves with what `execute` returned. It rejects with what `execute` threw,
133
+ an `Error` with the text of an MCP result with `isError: true`, a `TypeError` for
134
+ invalid arguments, a `NotAllowedError` when the user declined, an `AbortError` when the
135
+ browser cancelled it, and an `InvalidStateError` when the tool is gone. Chrome 156
136
+ passes the agent neither the name nor the message of a rejection
137
+ (`UnknownError`).
138
+ - Only the native object is used, read through `Document.prototype`'s getter: an own
139
+ `document.modelContext` (a polyfill such as `@mcp-b/global`, or a page script) is
140
+ passed by, and with native WebMCP and the polyfill both present the tools go to the
141
+ native object.
142
+ - A tool leaves WebMCP whenever it leaves the page's registry: its `signal`, or the
143
+ validator, which the first WebMCP call loads (as `connect()` does), refusing its
144
+ schema.
145
+ - A failed native registration only warns in the console, once per tool, and the tool
146
+ stays offered through the relay; it is tried again only when the tool is registered
147
+ again: a name the page or another script already registered
148
+ natively keeps its owner, and a frame without `allow="tools"` refuses all. The other
149
+ way round, once a name is mirrored, the page's own native `registerTool()` of that name
150
+ fails: a page that registers tools natively itself leaves `webmcp` off or uses other
151
+ names.
152
+ - `<html data-tab-mcp-webmcp="…">` lists the mirrored names, so that tab-mcp for Chrome
153
+ does not offer them a second time to an AI app that is connected to the page and to
154
+ the extension.
155
+
111
156
  ### Consequential tools
112
157
 
113
158
  Mark tools that change or delete something with `consequentialHint: true`. The page then
@@ -143,7 +188,10 @@ import { escapeInvisible } from "@ractive-ch/tab-mcp-client/visible";
143
188
  const mcp = new TabMcp({
144
189
  relay: "https://relay.example",
145
190
  server: { name: "calculator", version: "1.0.0" },
146
- onConfirm: ({ tool, arguments: args, client, signal }) => {
191
+ onConfirm: (request) => {
192
+ const { tool, arguments: args, client, signal } = request;
193
+ // An agent in the browser (`webmcp`): the library's own dialog.
194
+ if (client.kind !== "relay") return mcp.confirmInPage(request);
147
195
  const name = client.name ? escapeInvisible(client.name) : undefined;
148
196
  const app = name ? `${name} (${client.host})` : client.host;
149
197
  const shown = escapeInvisible(JSON.stringify(args, null, 2));
@@ -354,13 +402,16 @@ Instead of `showConnectDialog()`, use `connect()`, `disconnect()`, `newAddress()
354
402
  `reconnecting` and `tools`, and the events `statechange`, `connected`, `disconnected`,
355
403
  `pairingcode`, `grantschange`, `reconnecting`, `toolschange`, `replaced` (with
356
404
  `detail.sibling`, see above) and `error`. For an activity log, `toolcall`
357
- and `toolcallend` report every call by an AI app: its id, tool, arguments and AI app as it
358
- starts, then its outcome (`ok`, `error`, `declined` or `cancelled`), result and duration.
405
+ and `toolcallend` report every call by an AI app (or, with `webmcp`, an agent in the
406
+ browser): its id, tool, arguments and caller as it starts, then its outcome (`ok`,
407
+ `error`, `declined` or `cancelled`), result and duration.
359
408
 
360
409
  ```ts
361
410
  mcp.addEventListener("toolcallend", (e) => {
362
411
  const { tool, client, outcome, durationMs } = e.detail;
363
- log(`${client.name ?? client.host}: ${tool} ${outcome} in ${durationMs} ms`);
412
+ const who =
413
+ client.kind === "relay" ? (client.name ?? client.host) : "An agent in this browser";
414
+ log(`${who}: ${tool} ${outcome} in ${durationMs} ms`);
364
415
  });
365
416
  ```
366
417
 
@@ -506,10 +557,11 @@ function TodoList() {
506
557
  identityMessage, reconnecting, tools }` through `useSyncExternalStore`: the component
507
558
  renders again only when one of them changed. On the server and during hydration it is
508
559
  `disconnected`.
509
- - `useTool(tool, deps?)` registers the tool while the component is mounted and removes it
510
- on unmount. `execute` is always the latest closure, so it may use the component's
511
- current props and state without registering again; the tool is registered again only
512
- when its name, title, description, input schema or annotations change, or one of
560
+ - `useTool(tool, deps?, options?)` registers the tool while the component is mounted and
561
+ removes it on unmount. `execute` is always the latest closure, so it may use the
562
+ component's current props and state without registering again; the tool is registered
563
+ again only when its name, title, description, input schema or annotations change, or
564
+ `options.webmcp` ([WebMCP](#webmcp); `webmcp` on the provider turns it on), or one of
513
565
  `deps`. StrictMode's double mount registers it once at a time. A duplicate name or an
514
566
  invalid tool is thrown from the component's render, for an error boundary. Tools that
515
567
  read state right after another tool changed it should read it from a store (as the
@@ -0,0 +1,12 @@
1
+ var $t=/^(?:\d{1,4}x\d{1,4}|any)$/;function bt(e){let{src:t,mimeType:r,sizes:o,theme:s}=e;if(typeof t!=="string")return;let i=/^https?:/i.test(t)&&t.length<=2048,n=/^data:image\/(?:png|jpeg|gif|webp|x-icon|vnd\.microsoft\.icon)[;,]/i.test(t)&&t.length<=16384;if(!i&&!n)return;let a={src:t};if(typeof r==="string"&&/^image\/[\w.+-]+$/i.test(r))a.mimeType=r.toLowerCase();let c=Array.isArray(o)?o.map((S)=>String(S).toLowerCase()).filter((S)=>$t.test(S)):[];if(c.length>0)a.sizes=c;if(s==="light"||s==="dark")a.theme=s;return a}function ve(e){let t=[];for(let r of e){let o=typeof r==="object"&&r!==null?bt(r):void 0;if(o!==void 0)t.push(o);if(t.length===8)break}return t}function qe(e=globalThis.document){try{let t=e?.querySelectorAll('link[rel~="icon" i], link[rel~="apple-touch-icon" i]');return ve([...t??[]].filter((r)=>r.getAttribute("href")?.trim()).map((r)=>{let o={src:r.href};if(r.type)o.mimeType=r.type;let s=r.getAttribute("sizes");if(s)o.sizes=s.trim().split(/\s+/);let i=/prefers-color-scheme:\s*(light|dark)/i.exec(r.media);if(i)o.theme=i[1]?.toLowerCase();return o}))}catch{return[]}}function ae(e,t){let r=typeof e;if(r!==typeof t)return!1;let o=Array.isArray(e),s=Array.isArray(t);if(o!==s)return!1;if(o){let i=e.length;if(i!==t.length)return!1;for(let n=0;n<i;n++)if(!ae(e[n],t[n]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(let c of i){if(!Object.prototype.hasOwnProperty.call(t,c))return!1;if(!ae(e[c],t[c]))return!1}return!0}return e===t}function J(e){return encodeURI(wt(e)).replace(/#/g,"%23")}function wt(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var xt=/^[A-Za-z0-9._~!$&'()*+,;=:@/?-]$/,Rt=/^%[0-9A-Fa-f]{2}$/,kt=/^[A-Za-z0-9._~-]$/;function It(e){let t="";for(let r=0;r<e.length;){let o=e[r],s=e.slice(r,r+3);if(o==="%"&&Rt.test(s)){let n=String.fromCharCode(parseInt(s.slice(1),16));t+=kt.test(n)?n:s.toUpperCase(),r+=3;continue}let i=String.fromCodePoint(e.codePointAt(r));t+=xt.test(i)?i:encodeURIComponent(i),r+=i.length}return t}function be(e,t){let r=new URL(e,t.href);return r.hash=r.hash?It(r.hash.slice(1)):"",r}var Tt={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},vt={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},St={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,dependentRequired:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},_t=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function ee(e,t=Object.create(null),r=_t,o=""){if(e&&typeof e==="object"&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let n=be(i,r);if(n.hash.length>1)t[n.href]=e;else if(n.hash="",o==="")r=n;else ee(e,t,r)}}else if(e!==!0&&e!==!1)return t;let s=r.href+(o?"#"+o:"");if(t[s]!==void 0&&t[s]!==e)throw Error(`Duplicate schema URI "${s}".`);if(t[s]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0)Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:s});if(e.$ref&&e.__absolute_ref__===void 0){let i=be(e.$ref,r);Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let i=be(e.$recursiveRef,r);Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){let i=be("#"+e.$anchor,r);t[i.href]=e}for(let i in e){if(St[i])continue;let n=`${o}/${J(i)}`,a=e[i];if(Array.isArray(a)){if(Tt[i]){let c=a.length;for(let S=0;S<c;S++)ee(a[S],t,r,`${n}/${S}`)}}else if(vt[i])for(let c in a)ee(a[c],t,r,`${n}/${J(c)}`);else ee(a,t,r,n)}return t}var Et=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Mt=[0,31,28,31,30,31,30,31,31,30,31,30,31],At=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|([+-])(\d\d):(\d\d))?$/i,ze=/^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.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20-\x21\x23-\x5b\x5d-\x7e]|\\[\x20-\x7e])*"|[a-z0-9.!#$%&'*+/=?^_`{|}~-]+)@(.+)$/i,Jt=(e)=>{let t=e.match(Ht);if(!t)return!1;let r=t[1],o=t[2];if(!r||!o||r.length>64||o.length>253)return!1;if(r[0]!=='"'&&(r[0]==="."||r.endsWith(".")||r.includes("..")))return!1;if(o.startsWith("[")&&o.endsWith("]")){let s=o.slice(1,-1);if(/^ipv6:/i.test(s))return Je.test(s.slice(5));return He.test(s)}return ze.test(o)},He=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Je=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Ut=(e)=>/^P(?:\d+W|(?:(?:\d+Y(?:\d+M(?:\d+D)?)?|\d+M(?:\d+D)?|\d+D)(?:T(?:\d+H(?:\d+M(?:\d+S)?)?|\d+M(?:\d+S)?|\d+S))?|T(?:\d+H(?:\d+M(?:\d+S)?)?|\d+M(?:\d+S)?|\d+S)))$/.test(e);function K(e){return e.test.bind(e)}var Se={date:Ue,time:Be.bind(void 0,!0),"date-time":Vt,duration:Ut,uri:Ft,"uri-reference":K(Ot),"uri-template":K(Ct),url:K(Pt),email:Jt,hostname:K(ze),ipv4:K(He),ipv6:K(Je),regex:Yt,uuid:K(Nt),"json-pointer":K(jt),"json-pointer-uri-fragment":K(qt),"relative-json-pointer":K(zt)};function Bt(e){return e%4===0&&(e%100!==0||e%400===0)}function Ue(e){let t=e.match(Et);if(!t)return!1;let r=t[1],o=t[2],s=t[3];if(!r||!o||!s)return!1;let i=+r,n=+o,a=+s,c=n==2&&Bt(i)?29:Mt[n];return n>=1&&n<=12&&a>=1&&c!==void 0&&a<=c}function Be(e,t){let r=t.match(At);if(!r)return!1;let o=r[1],s=r[2],i=r[3];if(!o||!s||!i)return!1;let n=+o,a=+s,c=+i,S=r[5],I=r[6],N=+(r[7]??0),D=+(r[8]??0);if(n>23||a>59||c>60||N>23||D>59||e&&S===void 0)return!1;if(c<60)return!0;let U=I==="+"?1:I==="-"?-1:0;return(n*60+a-U*(N*60+D)+1440)%1440===1439}var Dt=/t|\s/i;function Vt(e){let[t,r,o]=e.split(Dt);return t!==void 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{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Ft(e){return Gt.test(e)&&Wt.test(e)}var Kt=/[^\\]\\Z/;function Yt(e){if(Kt.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}}function De(e){let t=0,r=e.length,o=0,s;while(o<r)if(t++,s=e.charCodeAt(o++),s>=55296&&s<=56319&&o<r){if(s=e.charCodeAt(o),(s&64512)==56320)o++}return t}function se(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ve(e){let t=Math.abs(e).toString().split("e"),r=t[0],o=t[1]??"0",s=r.indexOf("."),i=s===-1?0:r.length-s-1;return[BigInt(r.replace(".","")),Number(o)-i]}function Zt(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return!1;let[r,o]=Ve(e),[s,i]=Ve(t),n=o-i;if(n>=0)return r*10n**BigInt(n)%s===0n;return r%(s*10n**BigInt(-n))===0n}function A(e,t,r="2019-09",o=ee(t),s=!0,i=null,n="#",a="#",c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:n,keyword:"false",keywordLocation:n,error:"False boolean schema."}]};let S=typeof e,I;switch(S){case"boolean":case"number":case"string":I=S;break;case"object":if(e===null)I="null";else if(Array.isArray(e))I="array";else I="object";break;default:throw Error(`Instances of "${S}" type are not supported.`)}let{$ref:N,$recursiveRef:D,$recursiveAnchor:U,type:C,const:G,enum:B,required:L,not:m,anyOf:y,allOf:T,oneOf:v,if:R,then:_,else:O,format:d,properties:k,patternProperties:w,additionalProperties:j,unevaluatedProperties:E,minProperties:z,maxProperties:H,propertyNames:W,dependentRequired:Z,dependentSchemas:V,dependencies:F,prefixItems:ce,items:re,additionalItems:Ae,unevaluatedItems:Oe,contains:Ce,minContains:X,maxContains:Re,minItems:ke,maxItems:Ie,uniqueItems:gt,minimum:ne,maximum:oe,exclusiveMinimum:pe,exclusiveMaximum:me,multipleOf:Te,minLength:ye,maxLength:ge,pattern:Pe,__absolute_ref__:he,__absolute_recursive_ref__:ht}=t,l=[];if(U===!0&&i===null)i=t;if(D==="#"){let b=i===null?o[ht]:i,p=`${a}/$recursiveRef`,x=A(e,i===null?t:i,r,o,s,b,n,p,c);if(!x.valid)l.push({instanceLocation:n,keyword:"$recursiveRef",keywordLocation:p,error:"A subschema had errors."},...x.errors)}if(N!==void 0){let p=o[he||N];if(p===void 0){let u=`Unresolved $ref "${N}".`;if(he&&he!==N)u+=` Absolute URI "${he}".`;throw u+=`
2
+ Known schemas:
3
+ - ${Object.keys(o).join(`
4
+ - `)}`,Error(u)}let x=`${a}/$ref`,f=A(e,p,r,o,s,i,n,x,c);if(!f.valid)l.push({instanceLocation:n,keyword:"$ref",keywordLocation:x,error:"A subschema had errors."},...f.errors);if(r==="4"||r==="7")return{valid:l.length===0,errors:l}}if(Array.isArray(C)){let b=C.length,p=!1;for(let x=0;x<b;x++)if(I===C[x]||C[x]==="integer"&&I==="number"&&e%1===0&&e===e){p=!0;break}if(!p)l.push({instanceLocation:n,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${I}" is invalid. Expected "${C.join('", "')}".`})}else if(C==="integer"){if(I!=="number"||e%1||e!==e)l.push({instanceLocation:n,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${I}" is invalid. Expected "${C}".`})}else if(C!==void 0&&I!==C)l.push({instanceLocation:n,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${I}" is invalid. Expected "${C}".`});if(G!==void 0){if(I==="object"||I==="array"){if(!ae(e,G))l.push({instanceLocation:n,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(G)}.`})}else if(e!==G)l.push({instanceLocation:n,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(G)}.`})}if(B!==void 0){if(I==="object"||I==="array"){if(!B.some((b)=>ae(e,b)))l.push({instanceLocation:n,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(B)}.`})}else if(!B.some((b)=>e===b))l.push({instanceLocation:n,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(B)}.`})}if(m!==void 0){let b=`${a}/not`;if(A(e,m,r,o,s,i,n,b).valid)l.push({instanceLocation:n,keyword:"not",keywordLocation:b,error:'Instance matched "not" schema.'})}let $e=[];if(y!==void 0){let b=`${a}/anyOf`,p=l.length,x=!1;for(let[f,u]of y.entries()){let h=Object.create(c),g=A(e,u,r,o,s,U===!0?i:null,n,`${b}/${f}`,h);if(l.push(...g.errors),x=x||g.valid,g.valid)$e.push(h)}if(x)l.length=p;else l.splice(p,0,{instanceLocation:n,keyword:"anyOf",keywordLocation:b,error:"Instance does not match any subschemas."})}if(T!==void 0){let b=`${a}/allOf`,p=l.length,x=!0;for(let[f,u]of T.entries()){let h=Object.create(c),g=A(e,u,r,o,s,U===!0?i:null,n,`${b}/${f}`,h);if(l.push(...g.errors),x=x&&g.valid,g.valid)$e.push(h)}if(x)l.length=p;else l.splice(p,0,{instanceLocation:n,keyword:"allOf",keywordLocation:b,error:"Instance does not match every subschema."})}if(v!==void 0){let b=`${a}/oneOf`,p=l.length,x=v.filter((f,u)=>{let h=Object.create(c),g=A(e,f,r,o,s,U===!0?i:null,n,`${b}/${u}`,h);if(l.push(...g.errors),g.valid)$e.push(h);return g.valid}).length;if(x===1)l.length=p;else l.splice(p,0,{instanceLocation:n,keyword:"oneOf",keywordLocation:b,error:`Instance does not match exactly one subschema (${x} matches).`})}if(I==="object"||I==="array")Object.assign(c,...$e);if(R!==void 0){let b=`${a}/if`,p=Object.create(null);if(A(e,R,r,o,s,i,n,b,p).valid){if(Object.assign(c,p),_!==void 0){let f=A(e,_,r,o,s,i,n,`${a}/then`,c);if(!f.valid)l.push({instanceLocation:n,keyword:"if",keywordLocation:b,error:'Instance does not match "then" schema.'},...f.errors)}}else if(O!==void 0){let f=A(e,O,r,o,s,i,n,`${a}/else`,c);if(!f.valid)l.push({instanceLocation:n,keyword:"if",keywordLocation:b,error:'Instance does not match "else" schema.'},...f.errors)}}if(I==="object"){if(L!==void 0){for(let f of L)if(!se(e,f))l.push({instanceLocation:n,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${f}".`})}let b=Object.keys(e);if(z!==void 0&&b.length<z)l.push({instanceLocation:n,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${z} properties.`});if(H!==void 0&&b.length>H)l.push({instanceLocation:n,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${H} properties.`});if(W!==void 0){let f=`${a}/propertyNames`;for(let u in e){let h=`${n}/${J(u)}`,g=A(u,W,r,o,s,i,h,f);if(!g.valid)l.push({instanceLocation:n,keyword:"propertyNames",keywordLocation:f,error:`Property name "${u}" does not match schema.`},...g.errors)}}if(Z!==void 0){let f=`${a}/dependantRequired`;for(let u in Z)if(se(e,u)){let h=Z[u];for(let g of h)if(!se(e,g))l.push({instanceLocation:n,keyword:"dependentRequired",keywordLocation:f,error:`Instance has "${u}" but does not have "${g}".`})}}if(V!==void 0)for(let[f,u]of Object.entries(V)){let h=`${a}/dependentSchemas`;if(se(e,f)){let g=A(e,u,r,o,s,i,n,`${h}/${J(f)}`,c);if(!g.valid)l.push({instanceLocation:n,keyword:"dependentSchemas",keywordLocation:h,error:`Instance has "${f}" but does not match dependant schema.`},...g.errors)}}if(F!==void 0){let f=`${a}/dependencies`;for(let u in F)if(se(e,u)){let h=F[u];if(Array.isArray(h)){for(let g of h)if(!se(e,g))l.push({instanceLocation:n,keyword:"dependencies",keywordLocation:f,error:`Instance has "${u}" but does not have "${g}".`})}else{let g=A(e,h,r,o,s,i,n,`${f}/${J(u)}`);if(!g.valid)l.push({instanceLocation:n,keyword:"dependencies",keywordLocation:f,error:`Instance has "${u}" but does not match dependant schema.`},...g.errors)}}}let p=Object.create(null),x=!1;if(k!==void 0){let f=`${a}/properties`;for(let[u,h]of Object.entries(k)){if(!se(e,u))continue;let g=`${n}/${J(u)}`,P=A(e[u],h,r,o,s,i,g,`${f}/${J(u)}`);if(p[u]=!0,P.valid)c[u]=!0;else if(x=s,l.push({instanceLocation:n,keyword:"properties",keywordLocation:f,error:`Property "${u}" does not match schema.`},...P.errors),x)break}}if(!x&&w!==void 0){let f=`${a}/patternProperties`;for(let[u,h]of Object.entries(w)){let g=new RegExp(u,"u");for(let P in e){if(!g.test(P))continue;let Ne=`${n}/${J(P)}`,je=A(e[P],h,r,o,s,i,Ne,`${f}/${J(u)}`);if(p[P]=!0,je.valid)c[P]=!0;else x=s,l.push({instanceLocation:n,keyword:"patternProperties",keywordLocation:f,error:`Property "${P}" matches pattern "${u}" but does not match associated schema.`},...je.errors)}}}if(!x&&j!==void 0){let f=`${a}/additionalProperties`;for(let u in e){if(p[u])continue;let h=`${n}/${J(u)}`,g=A(e[u],j,r,o,s,i,h,f);if(g.valid)c[u]=!0;else x=s,l.push({instanceLocation:n,keyword:"additionalProperties",keywordLocation:f,error:`Property "${u}" does not match additional properties schema.`},...g.errors)}}else if(!x&&E!==void 0){let f=`${a}/unevaluatedProperties`;for(let u in e)if(!c[u]){let h=`${n}/${J(u)}`,g=A(e[u],E,r,o,s,i,h,f);if(g.valid)c[u]=!0;else l.push({instanceLocation:n,keyword:"unevaluatedProperties",keywordLocation:f,error:`Property "${u}" does not match unevaluated properties schema.`},...g.errors)}}}else if(I==="array"){if(Ie!==void 0&&e.length>Ie)l.push({instanceLocation:n,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${Ie}).`});if(ke!==void 0&&e.length<ke)l.push({instanceLocation:n,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${ke}).`});let b=e.length,p=0,x=!1;if(ce!==void 0){let f=`${a}/prefixItems`,u=Math.min(ce.length,b);for(;p<u;p++){let h=A(e[p],ce[p],r,o,s,i,`${n}/${p}`,`${f}/${p}`);if(c[p]=!0,!h.valid){if(x=s,l.push({instanceLocation:n,keyword:"prefixItems",keywordLocation:f,error:"Items did not match schema."},...h.errors),x)break}}}if(re!==void 0){let f=`${a}/items`;if(Array.isArray(re)){let u=Math.min(re.length,b);for(;p<u;p++){let h=A(e[p],re[p],r,o,s,i,`${n}/${p}`,`${f}/${p}`);if(c[p]=!0,!h.valid){if(x=s,l.push({instanceLocation:n,keyword:"items",keywordLocation:f,error:"Items did not match schema."},...h.errors),x)break}}}else for(;p<b;p++){let u=A(e[p],re,r,o,s,i,`${n}/${p}`,f);if(c[p]=!0,!u.valid){if(x=s,l.push({instanceLocation:n,keyword:"items",keywordLocation:f,error:"Items did not match schema."},...u.errors),x)break}}if(!x&&Ae!==void 0){let u=`${a}/additionalItems`;for(;p<b;p++){let h=A(e[p],Ae,r,o,s,i,`${n}/${p}`,u);if(c[p]=!0,!h.valid)x=s,l.push({instanceLocation:n,keyword:"additionalItems",keywordLocation:u,error:"Items did not match additional items schema."},...h.errors)}}}if(Ce!==void 0)if(b===0&&X===void 0)l.push({instanceLocation:n,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(X!==void 0&&b<X)l.push({instanceLocation:n,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${b}) than minContains (${X}).`});else{let f=`${a}/contains`,u=l.length,h=0;for(let g=0;g<b;g++){let P=A(e[g],Ce,r,o,s,i,`${n}/${g}`,f);if(P.valid)c[g]=!0,h++;else l.push(...P.errors)}if(h>=(X||0))l.length=u;if(X===void 0&&h===0)l.splice(u,0,{instanceLocation:n,keyword:"contains",keywordLocation:f,error:"Array does not contain item matching schema."});else if(X!==void 0&&h<X)l.push({instanceLocation:n,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${X} items matching schema. Only ${h} items were found.`});else if(Re!==void 0&&h>Re)l.push({instanceLocation:n,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Re} items matching schema. ${h} items were found.`})}if(!x&&Oe!==void 0){let f=`${a}/unevaluatedItems`;for(p;p<b;p++){if(c[p])continue;let u=A(e[p],Oe,r,o,s,i,`${n}/${p}`,f);if(c[p]=!0,!u.valid)l.push({instanceLocation:n,keyword:"unevaluatedItems",keywordLocation:f,error:"Items did not match unevaluated items schema."},...u.errors)}}if(gt)for(let f=0;f<b;f++){let u=e[f],h=typeof u==="object"&&u!==null;for(let g=0;g<b;g++){if(f===g)continue;let P=e[g];if(u===P||h&&(typeof P==="object"&&P!==null)&&ae(u,P))l.push({instanceLocation:n,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${f} and ${g}.`}),f=Number.MAX_SAFE_INTEGER,g=Number.MAX_SAFE_INTEGER}}}else if(I==="number"){if(r==="4"){if(ne!==void 0&&(pe===!0&&e<=ne||e<ne))l.push({instanceLocation:n,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${pe?"or equal to ":""} ${ne}.`});if(oe!==void 0&&(me===!0&&e>=oe||e>oe))l.push({instanceLocation:n,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${me?"or equal to ":""} ${oe}.`})}else{if(ne!==void 0&&e<ne)l.push({instanceLocation:n,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${ne}.`});if(oe!==void 0&&e>oe)l.push({instanceLocation:n,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${oe}.`});if(pe!==void 0&&e<=pe)l.push({instanceLocation:n,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${pe}.`});if(me!==void 0&&e>=me)l.push({instanceLocation:n,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${me}.`})}if(Te!==void 0){if(!Zt(e,Te))l.push({instanceLocation:n,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Te}.`})}}else if(I==="string"){let b=ye===void 0&&ge===void 0?0:De(e);if(ye!==void 0&&b<ye)l.push({instanceLocation:n,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${b} < ${ye}).`});if(ge!==void 0&&b>ge)l.push({instanceLocation:n,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${b} > ${ge}).`});if(Pe!==void 0&&!new RegExp(Pe,"u").test(e))l.push({instanceLocation:n,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."});if(d!==void 0&&Se[d]&&!Se[d](e))l.push({instanceLocation:n,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${d}".`})}return{valid:l.length===0,errors:l}}var We="ch.ractive.tab-mcp/annotations",Xt=["readOnlyHint","untrustedContentHint","consequentialHint","debugging"],Qt=["destructiveHint","idempotentHint","openWorldHint"];function Fe(e){let t={};if(e.readOnlyHint===!0)t.readOnlyHint=!0,t.destructiveHint=!1;else if(e.readOnlyHint===!1)t.readOnlyHint=!1;if(e.consequentialHint===!0)t.destructiveHint=!0;if(e.untrustedContentHint===!0)t.openWorldHint=!0;for(let s of Qt){let i=e[s];if(i!==void 0)t[s]=i}let r={};for(let s of Xt){let i=e[s];if(i!==void 0)r[s]=i}let o={};if(Object.keys(t).length>0)o.annotations=t;if(Object.keys(r).length>0)o.meta=r;return o}function ue(e){return{content:[{type:"text",text:e}],isError:!0}}function Ge(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Ke(e){if(typeof e==="string")return{content:[{type:"text",text:e}]};if(e===void 0)return{content:[]};if(Ge(e)&&Array.isArray(e.content))return e;let t;try{t=JSON.stringify(e)}catch{}if(t===void 0)return ue("The tool returned a value that is not JSON.");let r={content:[{type:"text",text:t}]};if(Ge(e))r.structuredContent=e;return r}function Ye(e){let t=e instanceof Error?e.message:String(e);return ue(t||"The tool failed.")}var ie="2026-07-28",te="io.modelcontextprotocol/protocolVersion",we="io.modelcontextprotocol/clientCapabilities",Ze="io.modelcontextprotocol/clientInfo",Xe="io.modelcontextprotocol/serverInfo",_e="io.modelcontextprotocol/subscriptionId",Lt=-32020,Qe=-32022,er=0,Le=new WeakMap;function Ee(e){let t=Le.get(e);if(t!==void 0)return t;let r=e.inputSchema,o;try{o=ee(r)}catch(i){let n=i instanceof Error?i.message:String(i);throw Error(n.split(`
5
+ `)[0])}for(let i of Object.values(o)){if(typeof i!=="object"||i.$ref===void 0)continue;let n=i.__absolute_ref__;if(o[n??i.$ref]===void 0)throw Error(`$ref ${JSON.stringify(i.$ref)} does not resolve`)}let s=(i)=>A(i,r,"2020-12",o,!1);return Le.set(e,s),s}function et(e,t,r=""){let o=t instanceof Error?t.message:String(t);return TypeError(`registerTool: the inputSchema of ${e}: ${o}${r}`)}function tr(e){let t=[];for(let r of e.list())try{Ee(r)}catch(o){e.remove(r),t.push(et(r.name,o,"; the tool was unregistered"))}return e.setCompiler((r)=>{try{Ee(r)}catch(o){throw et(r.name,o)}}),t}function tt(e){try{return structuredClone(e)}catch{return e}}var rr=new TextEncoder;function Q(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Me(e,t){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}})}function q(e,t,r,o,s){let i={code:r,message:o};if(s!==void 0)i.data=s;return Me(e,{jsonrpc:"2.0",id:t,error:i})}function Y(e,t,r){return q(400,e,Lt,`Bad Request: the request headers and body disagree: ${r}`,{mismatch:{header:t,body:r}})}function le(e){return rr.encode(`event: message
6
+ data: ${JSON.stringify(e)}
7
+
8
+ `)}var rt={"content-type":"text/event-stream","cache-control":"no-cache"};function nr(e){return(e??"").split(";")[0]?.trim().toLowerCase()==="application/json"}function or(e){if(!(e.startsWith("=?base64?")&&e.endsWith("?=")))return e;let t=e.slice(9,-2);if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return;try{let r=atob(t),o=Uint8Array.from(r,(s)=>s.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{return}}function sr(e){if(!(te in e))return{key:te,problem:"missing"};if(!(we in e))return{key:we,problem:"missing"};if(typeof e[te]!=="string")return{key:te,problem:"expected a protocol version string"};if(!Q(e[we]))return{key:we,problem:"expected an object"};let t=e[Ze];if(t!==void 0&&!(Q(t)&&typeof t.name==="string"&&typeof t.version==="string"))return{key:Ze,problem:"expected {name, version}"};return}function ir(e){let t=e.notifications;return Q(t)&&t.toolsListChanged===!0?{toolsListChanged:!0}:{}}function dr(e,t){let r;try{r=Ee(e)(t)}catch(s){let i=s instanceof Error?s.message:String(s);return`The input schema of tool ${e.name} cannot be used: ${i}`}if(r.valid)return;let o=r.errors.filter((s)=>s.keyword!=="properties"&&s.keyword!=="$ref").map((s)=>`${s.instanceLocation} ${s.error}`).slice(0,5).join("; ");return`Input validation error: Invalid arguments for tool ${e.name}: ${o||"the arguments do not match the schema"}`}async function ot(e,t,r,o,s){let i={id:++er,tool:t.name,arguments:tt(r),client:{...s}};if(t.title!==void 0)i.title=t.title;let n=Date.now();e.observe?.start(i);let a={outcome:"error",result:ue("Internal error")};try{a=await ar(e,t,r,o,s)}finally{e.observe?.end({id:i.id,tool:t.name,client:{...s},outcome:a.outcome,result:tt(a.result),durationMs:Date.now()-n})}return a}async function ar(e,t,r,o,s){let i=(c,S,I)=>({outcome:c,result:ue(S),stop:I}),n=dr(t,r);if(n!==void 0)return i("error",n,"TypeError");if(t.annotations.consequentialHint===!0){let c={tool:{name:t.name,description:t.description},arguments:r,client:s,signal:o};if(t.title!==void 0)c.tool.title=t.title;let S=!1;try{S=await e.confirm(c)}catch{S=!1}if(!S)return o.aborted?i("cancelled","The user declined","AbortError"):i("declined","The user declined","NotAllowedError")}if(o.aborted)return i("cancelled","Cancelled","AbortError");if(e.tools.get(t.name)!==t)return i("error","The tool is no longer available","InvalidStateError");let a;try{let c=await t.execute(r,{signal:o,client:s});a={outcome:"ok",result:Ke(c),returned:{value:c}}}catch(c){a={outcome:"error",result:Ye(c),thrown:{error:c}}}if(o.aborted)return{...a,outcome:"cancelled",stop:"AbortError"};if(a.result.isError===!0)a.outcome="error";return a}async function st(e,t,r,o){let s=(n,a)=>n==="TypeError"?TypeError(a):new DOMException(a,n);if(e.tools.get(t.name)!==t)throw s("InvalidStateError",`The tool ${t.name} is no longer available`);if(!Q(r))throw s("TypeError","The input must be an object");let i=await ot(e,t,r,o instanceof AbortSignal?o:new AbortController().signal,{kind:"webmcp"});if(i.stop!==void 0)throw s(i.stop,i.stop==="AbortError"?"Cancelled":nt(i.result));if(i.thrown!==void 0)throw i.thrown.error;if(i.result.isError===!0)throw Error(nt(i.result)||"The tool failed.");return i.returned?.value}function nt(e){return e.content.map((t)=>Q(t)&&t.type==="text"&&typeof t.text==="string"?t.text:"").filter((t)=>t!=="").join(`
9
+ `)}function it(e){let{tools:t,server:r}=e,o={name:r.name,version:r.version};if(r.title!==void 0)o.title=r.title;let s=ve(r.icons??[]),i=s.length>0?{...o,icons:s}:o,n=new Set,a=!1,c=(m={})=>({...m,[Xe]:o});function S(m,y,T=c()){return{jsonrpc:"2.0",id:m,result:{...y,resultType:"complete",_meta:T}}}function I(){return t.list().map((m)=>{let y={name:m.name};if(m.title!==void 0)y.title=m.title;y.description=m.description,y.inputSchema=m.inputSchema;let{annotations:T,meta:v}=Fe(m.annotations);if(T!==void 0)y.annotations=T;if(v!==void 0)y._meta={[We]:v};return y})}let N=(m)=>({kind:"invalid",message:m});async function D(m,y,T){let v=m.name;if(typeof v!=="string")return N("Invalid params: name must be a string");let R=t.get(v);if(R===void 0)return N(`Tool ${v} not found`);let _=m.arguments??{};if(!Q(_))return N("Invalid params: arguments must be an object");return{kind:"result",result:(await ot(e,R,_,y,e.client(T))).result}}function U(m,y,T,v){let R=new ReadableStream({start:(_)=>{let O=(d)=>{if(T.aborted)return;let k;try{k=le(d)}catch{k=le(S(m,ue("The tool returned a result that is not JSON.")))}try{_.enqueue(k),_.close()}catch{}};D(y,T,v).then((d)=>O(d.kind==="invalid"?{jsonrpc:"2.0",id:m,error:{code:-32602,message:d.message}}:S(m,d.result)),()=>O({jsonrpc:"2.0",id:m,error:{code:-32603,message:"Internal error"}}))}});return new Response(R,{status:200,headers:rt})}function C(m,y,T){let v=ir(y),R={jsonrpc:"2.0",id:m,result:{resultType:"complete",_meta:c({[_e]:m})}},_,O=new ReadableStream({start:(d)=>{if(d.enqueue(le({jsonrpc:"2.0",method:"notifications/subscriptions/acknowledged",params:{notifications:v,_meta:{[_e]:m}}})),Object.keys(v).length===0){d.enqueue(le(R)),d.close();return}let k={id:m,send:(w)=>{try{d.enqueue(le(w))}catch{n.delete(k)}},end:()=>{n.delete(k);try{d.enqueue(le(R)),d.close()}catch{}}};_=k,n.add(k),T.addEventListener("abort",()=>{n.delete(k);try{d.close()}catch{}})},cancel:()=>{if(_!==void 0)n.delete(_)}});return new Response(O,{status:200,headers:rt})}function G(m,y){if(Array.isArray(y))return q(400,null,-32600,"Bad Request: JSON-RPC batches are not supported by this endpoint");if(!Q(y)||y.jsonrpc!=="2.0")return q(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let{method:T,id:v}=y;if(typeof T!=="string")return"result"in y||"error"in y?q(400,null,-32600,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"):q(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let R=m.headers.get("mcp-protocol-version"),_=m.headers.get("mcp-method"),O=Q(y.params)?y.params:{},d=Q(O._meta)?O._meta:void 0,k=d!==void 0&&te in d,w=typeof d?.[te]==="string"?d[te]:void 0,j=R!==null&&R>=ie;if(v===void 0){if(w!==void 0&&R!==null&&R!==w)return Y(null,R,`the notification envelope names protocol version ${w} but the MCP-Protocol-Version header names ${R}`);if((k||j)&&_!==null&&_!==T)return Y(null,_,`the notification body names method ${T} but the Mcp-Method header names ${_}`);return"notification"}if(typeof v!=="string"&&typeof v!=="number")return q(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let E=v;if(!k||T==="initialize"&&(w===void 0||w<ie)){if(T==="initialize"){if(j)return Y(E,R,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let H=typeof O.protocolVersion==="string"?O.protocolVersion:void 0;return B(E,H)}if(j){let H=d===void 0?["_meta"]:[te];return q(400,E,-32602,`Invalid params: the MCP-Protocol-Version header names protocol revision ${R}, but the request is missing the required per-request envelope key(s): ${H.join(", ")}`,{envelope:{missing:H}})}return B(E,R??void 0)}let z=sr(d);if(z!==void 0)return q(400,E,-32602,`Invalid _meta envelope for protocol revision ${ie}: ${z.key}: ${z.problem}`,{envelope:z});if(R!==null&&w!==void 0&&R!==w)return Y(E,R,`the body envelope names protocol version ${w} but the MCP-Protocol-Version header names ${R}`);if(_!==null&&_!==T)return Y(E,_,`the body names method ${T} but the Mcp-Method header names ${_}`);if(w!==ie)return B(E,w);if(R===null)return Y(E,"(missing)",`the body envelope names protocol version ${w} but the required MCP-Protocol-Version header is absent`);if(_===null)return Y(E,"(missing)",`the body names method ${T} but the required Mcp-Method header is absent`);if(T==="tools/call"&&typeof O.name==="string"){let H=O.name,W=m.headers.get("mcp-name");if(W===null)return Y(E,"(missing)",`the body carries params.name="${H}" but the required Mcp-Name header is absent`);let Z=or(W);if(Z===void 0)return Y(E,W,"the Mcp-Name header carries an invalid Base64 sentinel value");if(Z!==H)return Y(E,W,`the body carries params.name="${H}" but the Mcp-Name header names "${Z}"`)}return{id:E,method:T,params:O}}function B(m,y){return y===void 0?q(400,m,Qe,"Unsupported protocol version: the request did not name a protocol version",{supported:[ie]}):q(400,m,Qe,`Unsupported protocol version: ${y}`,{supported:[ie],requested:y})}async function L(m,y){if(m.method.toUpperCase()!=="POST")return q(405,null,-32000,"Method not allowed.");if(!nr(m.headers.get("content-type")))return q(415,null,-32000,"Unsupported Media Type: Content-Type must be application/json");let T;try{T=JSON.parse(y.body??await m.text())}catch{return q(400,null,-32700,"Parse error: the request body is not valid JSON")}let v=G(m,T);if(v instanceof Response)return v;if(v==="notification")return new Response(null,{status:202});let{id:R,method:_,params:O}=v;switch(_){case"server/discover":{let d={supportedVersions:[ie],capabilities:{tools:{listChanged:!0}}};if(r.instructions!==void 0)d.instructions=r.instructions;return d.ttlMs=0,d.cacheScope="private",Me(200,S(R,d,{[Xe]:i}))}case"tools/list":return Me(200,S(R,{tools:I(),ttlMs:0,cacheScope:"private"}));case"tools/call":return U(R,O,m.signal,y.grant);case"subscriptions/listen":return C(R,O,m.signal);default:return q(404,R,-32601,"Method not found")}}return{handle:(m,y)=>L(m,y).catch(()=>q(500,null,-32603,"Internal server error")),toolsChanged(){if(a)return;a=!0,queueMicrotask(()=>{a=!1;for(let m of[...n])m.send({jsonrpc:"2.0",method:"notifications/tools/list_changed",params:{_meta:{[_e]:m.id}}})})},close(){for(let m of[...n])m.end()}}}var xe="tab-mcp.v1",ur=new Set(["start","used","locked","expired"]);function fe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var M=(e)=>typeof e==="string";function dt(e){if(!fe(e)||!M(e.grantId)||!M(e.createdAt))return!1;let t=e.client;return fe(t)&&M(t.id)&&M(t.name)&&M(t.host)}function lr(e){if(!fe(e))return!1;return["maxMessageBytes","maxBodyBytes","requestTimeoutMs","idleTimeoutMs","heartbeatMs","keepAliveMs","maxConcurrentRequests"].every((t)=>typeof e[t]==="number")}function fr(e){return fe(e)&&Object.values(e).every(M)}function at(e){let t;try{t=JSON.parse(e)}catch{return}if(!fe(t))return;switch(t.type){case"session":return M(t.sessionId)&&M(t.address)&&M(t.origin)&&M(t.expiresAt)&&lr(t.limits)&&Array.isArray(t.grants)&&t.grants.every(dt)&&(t.appName===void 0||M(t.appName))&&(t.pairing===void 0||M(t.pairing))?t:void 0;case"ping":return typeof t.t==="number"?t:void 0;case"bye":return{type:"bye",reason:M(t.reason)?t.reason:""};case"http.request":return M(t.id)&&M(t.method)&&M(t.path)&&fr(t.headers)&&M(t.body)&&fe(t.grant)&&M(t.grant.grantId)&&M(t.grant.clientId)?t:void 0;case"http.cancel":return M(t.id)?t:void 0;case"pairing.code":{if(!M(t.code)||!M(t.expiresAt))return;let r={type:"pairing.code",code:t.code,expiresAt:t.expiresAt},o=t.reason;if(typeof o==="string"&&ur.has(o))r.reason=o;return r}case"grant.added":return dt(t.grant)?t:void 0;case"grant.removed":return M(t.grantId)?{type:"grant.removed",grantId:t.grantId,reason:M(t.reason)?t.reason:""}:void 0;case"identity.bound":return typeof t.round==="number"?{type:"identity.bound",round:t.round}:{type:"identity.bound"};case"error":return M(t.code)?t:void 0;default:return}}function cr(e){let t="",r=0,o=0;for(let s of e){r=r<<8|s,o+=8;while(o>=5)o-=5,t+="abcdefghijklmnopqrstuvwxyz234567"[r>>>o&31];r&=(1<<o)-1}if(o>0)t+="abcdefghijklmnopqrstuvwxyz234567"[r<<5-o&31];return t}async function pr(e,t=globalThis.crypto?.subtle??null){if(t===null)return;try{let r=await t.digest("SHA-256",new TextEncoder().encode(e));return cr(new Uint8Array(r))}catch{return}}function mr(e,t){if(t===void 0)return e;let r=new URL(e);return r.searchParams.set("a",t),r.href}function ct(e){return{tools:e.registry,confirm:(t)=>e.confirm(t),observe:{start:(t)=>e.toolCallStarted(t),end:(t)=>e.toolCallEnded(t)}}}function Kr(e,t,r,o){return st(ct(e),t,r,o)}var yr=15000,ut={1000:"closed",1008:"policy",1009:"too_large",4001:"expired",4002:"idle",4003:"heartbeat",4004:"shutdown",4005:"replaced",4008:"rate_limited",4009:"policy"},lt={replaced:"replaced",expired:"expired",idle:"idle",shutdown:"shutdown"};function de(e,t){return Object.assign(Error(e),{reason:t})}var gr=["content-type","cache-control"];function hr(){let e=globalThis.document?.title;return typeof e==="string"?e.slice(0,300):""}function $r(e){try{let t=JSON.parse(e);if(typeof t!=="object"||t===null||typeof t.type!=="string")return;return typeof t.id==="string"?{type:t.type,id:t.id}:{type:t.type}}catch{return}}var br=new Set(["session","ping","bye","http.request","http.cancel","pairing.code","grant.added","grant.removed","identity.bound","error"]),pt=512,mt=6,yt=64,wr=pt+mt*yt;function xr(e){let t=Math.floor((e-pt)/mt);return t>=yt?t:void 0}function*ft(e,t){let r=0;while(r<e.length){let o=Math.min(r+t,e.length),s=e.charCodeAt(o-1);if(o<e.length&&s>=55296&&s<=56319)o+=o-1>r?-1:1;yield e.slice(r,o),r=o}}var Rr=1e4,kr=1000;function Ir(e){let t,r=Number.NEGATIVE_INFINITY,o;try{if(e!==void 0&&typeof BroadcastChannel==="function")t=new BroadcastChannel(e),t.onmessage=(s)=>{if(s.data?.type!=="claimed")return;r=Date.now(),o?.()}}catch{t=void 0}return{claimed(){try{t?.postMessage({type:"claimed"})}catch{}},heard(){if(Date.now()-r<=Rr)return Promise.resolve(!0);if(t===void 0)return Promise.resolve(!1);return new Promise((s)=>{let i=setTimeout(()=>s(!1),kr);o=()=>{clearTimeout(i),s(!0)}})},close(){t?.close()}}}function Yr(e,t,r,o=!1){let s=new WebSocket(t,xe),i=new Map,n="opening",a,c=65536,S,I=0,N=Ir(e.tabs),D,U,C,G=new Promise((d,k)=>{U=d,C=k});G.catch(()=>{});let B=setTimeout(()=>{v(de("The relay did not answer in time.","network"))},yr),L=it({...ct(e),server:{...e.server,icons:e.server.icons??qe()},client:(d)=>e.clientFor(d)}),m=e.registry.onChange(()=>L.toolsChanged());function y(d){if(s.readyState!==WebSocket.OPEN)return!1;try{return s.send(JSON.stringify(d)),!0}catch{return!1}}function T(){if(I<=0)return;clearTimeout(S),S=setTimeout(()=>{a??="heartbeat",R(4003);try{s.close()}catch{}},I*2.5)}function v(d){if(n!=="opening")return;R(0),C(d);try{s.close()}catch{}}function R(d){if(n==="closed")return;let k=n==="ready";n="closed",clearTimeout(B),clearTimeout(S),m();for(let w of i.values())w.abort();if(i.clear(),L.close(),k){let w=a??ut[d]??(d===1006?"network":"closed");if(C(de("The address was taken over again before its AI apps were disconnected.",w)),e.closed(w,d),w==="replaced"){N.heard().then((j)=>{N.close(),e.replaced({sibling:j})});return}}N.close()}async function _(d){let k=new AbortController;i.set(d.id,k);let w=()=>n==="ready"&&i.get(d.id)===k&&!k.signal.aborted;try{let j=new Request(`https://tab.invalid${d.path}`,{method:d.method,headers:d.headers,signal:k.signal}),E=await L.handle(j,{grant:d.grant,body:d.body});if(!w()){await E.body?.cancel().catch(()=>{});return}let z={};for(let V of gr){let F=E.headers.get(V);if(F!==null)z[V]=F}if(!(z["content-type"]??"").startsWith("text/event-stream")||E.body===null){let V=await E.text();if(!w())return;if(V.length<=c){y({type:"http.response",id:d.id,status:E.status,headers:z,body:V});return}y({type:"http.response.start",id:d.id,status:E.status,headers:z});for(let F of ft(V,c)){if(!w())break;y({type:"http.response.chunk",id:d.id,data:F})}if(w())y({type:"http.response.end",id:d.id});return}y({type:"http.response.start",id:d.id,status:E.status,headers:z});let W=E.body.getReader(),Z=new TextDecoder;k.signal.addEventListener("abort",()=>{W.cancel().catch(()=>{})});for(;;){let{done:V,value:F}=await W.read();if(V||!w())break;let ce=Z.decode(F,{stream:!0});for(let re of ft(ce,c))y({type:"http.response.chunk",id:d.id,data:re})}if(w())y({type:"http.response.end",id:d.id})}catch(j){if(w())e.error(j instanceof Error?j:Error(String(j))),y({type:"http.response",id:d.id,status:500,headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32603,message:"Internal server error"}})})}finally{if(i.get(d.id)===k)i.delete(d.id)}}function O(d){if(n==="opening"){if(d.type==="session"){let k=xr(d.limits.maxMessageBytes);if(k===void 0){v(de(`The relay's message limit (${d.limits.maxMessageBytes} bytes) is too small; tab-mcp needs at least ${wr}.`,"policy"));return}c=k,n="ready",clearTimeout(B),I=d.limits.heartbeatMs,T(),N.claimed();let w=e.sessionStarted(d);if(o&&d.grants.length>0){D={left:new Set(d.grants.map((j)=>j.grantId)),session:w},y({type:"grants.revokeAll"});return}U(w)}else if(d.type==="error")v(de(`The relay refused the connection: ${d.message||d.code}`,d.code==="rate_limited"?"rate_limited":"policy"));else if(d.type==="bye")v(de(`The relay ended the connection: ${d.reason}`,lt[d.reason]??"closed"));return}if(n!=="ready")return;switch(d.type){case"ping":T(),y({type:"pong",t:d.t});return;case"http.request":_(d);return;case"http.cancel":i.get(d.id)?.abort(),i.delete(d.id);return;case"pairing.code":e.pairingCode(d.reason===void 0?{code:d.code,expiresAt:d.expiresAt}:{code:d.code,expiresAt:d.expiresAt,reason:d.reason});return;case"grant.added":e.grantAdded(d.grant);return;case"grant.removed":if(e.grantRemoved(d.grantId),D?.left.delete(d.grantId),D?.left.size===0)U(D.session);return;case"identity.bound":e.identityResult(!0,d.round);return;case"bye":if(a=lt[d.reason]??"closed",a==="replaced")R(4005);return;case"error":if(d.code==="identity_refused"){e.identityResult(!1,typeof d.round==="number"?d.round:void 0,d.message);return}e.error(Error(`Relay error ${d.code}: ${d.message}`));return;case"session":return}}return s.addEventListener("open",()=>{if(s.protocol!==""&&s.protocol!==xe){v(de(`The relay speaks ${s.protocol}, not ${xe}.`,"policy"));return}let d={type:"hello",library:e.library,page:{title:hr()},secret:r};if(e.appName!==void 0)d.app={name:e.appName};if(o)d.revokeAll=!0;y(d)}),s.addEventListener("message",(d)=>{if(typeof d.data!=="string")return;let k=at(d.data);if(k!==void 0){if(n==="ready")T();O(k);return}let w=$r(d.data);if(w?.id!==void 0)y(br.has(w.type)?{type:"error",code:"bad_message",message:`malformed ${w.type}`,id:w.id}:{type:"error",code:"unknown_type",message:`unknown type ${w.type}`,id:w.id})}),s.addEventListener("close",(d)=>{if(n==="opening"){R(d.code);let k=d.code===1006||d.code===1002;C(de(k?"Could not connect to the relay (refused, unreachable, or this page's origin is not allowed).":`The relay closed the connection (${d.code}${d.reason?`: ${d.reason}`:""}).`,ut[d.code]??(k?"network":"closed")));return}R(d.code)}),{ready:G,send:y,close(d){if(n==="closed")return;if(n==="opening"){v(new DOMException("The connection was cancelled","AbortError"));return}a=d,y({type:"bye",reason:"user"}),R(1000);try{s.close(1000,"bye")}catch{}}}}export{wr as MIN_MESSAGE_BYTES,kr as SIBLING_GRACE_MS,Rr as SIBLING_WINDOW_MS,pr as addressIdOf,Kr as callFromWebMcp,xr as chunkSize,tr as compileRegistry,Yr as openConnection,ft as pieces,mr as withAddress};
10
+
11
+ //# debugId=92C3A49EE24D628064756E2164756E21
12
+ //# sourceMappingURL=connection-bjvxzxer.min.js.map