@ractive-ch/tab-mcp-client 0.9.0 → 0.10.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.9.0.** Until 1.0, a new minor version can still change the API. Which AI apps
9
+ **Status: 0.10.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
@@ -22,7 +22,7 @@ docker run --rm -p 8080:8080 \
22
22
  -e TAB_MCP_PUBLIC_URL=http://localhost:8080 \
23
23
  -e TAB_MCP_ALLOWED_ORIGINS=http://localhost:3000 \
24
24
  -e TAB_MCP_STORE=memory \
25
- ractive/tab-mcp:0.5.1
25
+ ractive/tab-mcp:0.6.1
26
26
  ```
27
27
 
28
28
  For production, see
@@ -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.9.0/cdn/tab-mcp-client.min.js";
41
+ import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.10.0/cdn/tab-mcp-client.min.js";
42
42
  </script>
43
43
  ```
44
44
 
@@ -99,6 +99,12 @@ PNG, JPEG, GIF, WebP or ICO `data:` URIs up to 16 KiB (no inline SVG). They go o
99
99
  - `annotations`: `readOnlyHint`, `consequentialHint`, `untrustedContentHint`, and the
100
100
  MCP hints `destructiveHint`, `idempotentHint`, `openWorldHint`.
101
101
 
102
+ In TypeScript, `Tool<Input>` types the `input` of `execute`, and `registerTool` and
103
+ `useTool` infer it from the tool or take it explicitly
104
+ (`registerTool<{ a: number; b: number }>(…)`); without it, `input` is a
105
+ `Record<string, unknown>`. The library checks the arguments against `inputSchema`, not
106
+ against the type, so keep the two in step.
107
+
102
108
  Abort the `signal` to remove the tool. AI apps that listen for changes learn about
103
109
  added and removed tools.
104
110
 
@@ -146,7 +152,10 @@ handles only some calls itself.
146
152
 
147
153
  1. The user clicks your button. `showConnectDialog()` connects (call it from the click
148
154
  handler: browsers that report user activation refuse `connect()` without one) and
149
- opens the "Connect your AI app" dialog.
155
+ opens the "Connect your AI app" dialog. A script's `element.click()` has no user
156
+ activation, so tests and browser automation see "connect() must be called from a
157
+ user action"; a click through Playwright or the DevTools protocol has one, and
158
+ `connect({ resume: true })` skips the check.
150
159
  2. The dialog shows the address and short instructions for Claude, ChatGPT, Claude Code
151
160
  and Codex. The commands for Claude Code and Codex each have a Copy. They name the
152
161
  server by a label made from `server.name` that every shell reads as one plain word:
@@ -260,8 +269,31 @@ refusal by the relay, and an attempt the relay refuses stops it (an unreachable
260
269
  tried again); the event `error` then says why, just before `reconnecting` turns `null`. `reconnect: false` turns it off, `reconnect: { delaysMs: [...] }`
261
270
  sets the waits (the last one repeats).
262
271
 
263
- The library does not connect on page load by itself. A page that offers something like
264
- "Keep AI access on" can call `connect({ resume: true })` on load.
272
+ ### Keeping AI access on after a reload
273
+
274
+ The library does not connect on page load by itself, so after a reload the page is off
275
+ until the user clicks Connect again; its AI apps stay paired but cannot reach it. To keep
276
+ AI access on, remember the user's choice and connect on load:
277
+
278
+ ```ts
279
+ const key = "my-page:ai-on";
280
+ mcp.addEventListener("statechange", () => {
281
+ if (mcp.state === "connected") localStorage.setItem(key, "1");
282
+ });
283
+ // Turned off by the user (`disconnect()`): stay off after the next reload.
284
+ mcp.addEventListener("disconnected", (e) => {
285
+ if (e.detail.reason === "user") localStorage.removeItem(key);
286
+ });
287
+ turnOffButton.onclick = () => mcp.disconnect();
288
+ // On load: connect without a click if the user turned it on before.
289
+ if (localStorage.getItem(key) === "1") {
290
+ mcp.connect({ resume: true }).catch((error) => showNote(`AI access is off: ${error.message}`));
291
+ }
292
+ ```
293
+
294
+ `resume: true` lets `connect()` run without a click. Offer a way to turn it off. With
295
+ two tabs of the page open, the newer one takes the address over: listen for `replaced`
296
+ (above) to tell the older tab why it went off.
265
297
 
266
298
  ### Identity binding (no code)
267
299
 
@@ -428,14 +460,51 @@ function TodoList() {
428
460
  `deps`. StrictMode's double mount registers it once at a time. A duplicate name or an
429
461
  invalid tool is thrown from the component's render, for an error boundary. Tools that
430
462
  read state right after another tool changed it should read it from a store (as the
431
- example does), not from a render's props.
463
+ example does) or a ref ([Tools in a `useState` app](#tools-in-a-usestate-app)), not
464
+ from a render's props.
432
465
  - `useToolCalls({ limit })` lists the AI app's tool calls since the component mounted,
433
466
  newest first (default 20), each with its `end` (outcome, result, duration) once over.
434
- - `<ConnectButton>` calls `showConnectDialog()`. Its label follows the state ("Connect
435
- your AI app", "Connecting…", "Reconnecting…", "AI app connected"); `children` (a node,
436
- or a function of the state) and the usual button props replace or style it, and
437
- `data-state` (`disconnected`, `connecting`, `connected`, `reconnecting`) is there for
438
- CSS. An `onClick` that calls `preventDefault()` keeps the dialog closed.
467
+ - `<ConnectButton>` calls `showConnectDialog()`, so it needs a real click (see
468
+ [Connecting and pairing](#connecting-and-pairing)). Its label follows the state
469
+ ("Connect your AI app", "Connecting…", "Reconnecting…", "AI app connected"), and
470
+ "Connection lost, retrying…" once three reconnect attempts have failed; a click then
471
+ tries again at once. `children` replaces the label: a node, or a function of the state
472
+ from `useTabMcpState()`, such as
473
+ `{(s) => (s.grants.length > 0 ? "Claude is playing" : "Let Claude play")}`. The usual
474
+ button props style it, and `data-state` (`disconnected`, `connecting`, `connected`,
475
+ `reconnecting`) is there for CSS. An `onClick` that calls `preventDefault()` keeps the
476
+ dialog closed.
477
+
478
+ ### Tools in a `useState` app
479
+
480
+ A tool that changes the page's state and returns the result needs the state as it is
481
+ after the change, but `setState` only schedules the next render. Keep the current value
482
+ in a ref next to the state, and change both through one function that the page's own UI
483
+ uses too:
484
+
485
+ ```tsx
486
+ function Game() {
487
+ const [game, setGame] = useState(newGame);
488
+ const current = useRef(game);
489
+ const update = (change: (g: GameState) => GameState) => {
490
+ current.current = change(current.current);
491
+ setGame(current.current);
492
+ return current.current;
493
+ };
494
+ useTool<{ card: string }>({
495
+ name: "play_card",
496
+ description: "Play a card from the hand",
497
+ inputSchema: { type: "object", properties: { card: { type: "string" } }, required: ["card"] },
498
+ // play() throws for a move that is not allowed: the AI app gets the message.
499
+ execute: ({ card }) => summary(update((g) => play(g, card))),
500
+ });
501
+ return <Board game={game} onPlay={(card) => update((g) => play(g, card))} />;
502
+ }
503
+ ```
504
+
505
+ Two calls in a row then each see the other's change, before React renders. Wrap the
506
+ `setGame` in `flushSync` (from `react-dom`) only if the tool has to read the rendered DOM.
507
+ A store outside React (as in the todo example) works as well.
439
508
 
440
509
  The module starts with `"use client"`, so React Server Components frameworks (Next.js's
441
510
  app router) render the provider on the client; it never connects or touches storage on
@@ -443,6 +512,10 @@ the server. The CDN build does not include the React bindings: a page that loads
443
512
  from a CDN uses the core API. [examples/react-todo](https://github.com/ractive/tab-mcp/tree/main/examples/react-todo)
444
513
  is a complete todo app.
445
514
 
515
+ For end-to-end tests of a page's tools, `@ractive-ch/tab-mcp/testing` (the relay's
516
+ package) starts a relay in the test process and issues a token for the page's address
517
+ without pairing; see the relay's [README](https://github.com/ractive/tab-mcp/tree/main/packages/tab-mcp#testing-a-pages-tools).
518
+
446
519
  ## Security
447
520
 
448
521
  Connecting an AI app to a page means trusting that page, as with any MCP server. Keep
@@ -5,7 +5,7 @@ bundler build (index.js and its chunks) does not include it; it is installed
5
5
  as a dependency instead.
6
6
 
7
7
  ------------------------------------------------------------------------------
8
- @cfworker/json-schema 4.1.1
8
+ @cfworker/json-schema 4.1.4
9
9
  https://github.com/cfworker/cfworker
10
10
  ------------------------------------------------------------------------------
11
11
 
@@ -0,0 +1,11 @@
1
+ var lt=/^(?:\d{1,4}x\d{1,4}|any)$/;function ft(e){let{src:t,mimeType:n,sizes:s,theme:i}=e;if(typeof t!=="string")return;let d=/^https?:/i.test(t)&&t.length<=2048,r=/^data:image\/(?:png|jpeg|gif|webp|x-icon|vnd\.microsoft\.icon)[;,]/i.test(t)&&t.length<=16384;if(!d&&!r)return;let a={src:t};if(typeof n==="string"&&/^image\/[\w.+-]+$/i.test(n))a.mimeType=n.toLowerCase();let b=Array.isArray(s)?s.map((E)=>String(E).toLowerCase()).filter((E)=>lt.test(E)):[];if(b.length>0)a.sizes=b;if(i==="light"||i==="dark")a.theme=i;return a}function Te(e){let t=[];for(let n of e){let s=typeof n==="object"&&n!==null?ft(n):void 0;if(s!==void 0)t.push(s);if(t.length===8)break}return t}function je(e=globalThis.document){try{let t=e?.querySelectorAll('link[rel~="icon" i], link[rel~="apple-touch-icon" i]');return Te([...t??[]].filter((n)=>n.getAttribute("href")?.trim()).map((n)=>{let s={src:n.href};if(n.type)s.mimeType=n.type;let i=n.getAttribute("sizes");if(i)s.sizes=i.trim().split(/\s+/);let d=/prefers-color-scheme:\s*(light|dark)/i.exec(n.media);if(d)s.theme=d[1]?.toLowerCase();return s}))}catch{return[]}}function ue(e,t){let n=typeof e;if(n!==typeof t)return!1;let s=Array.isArray(e),i=Array.isArray(t);if(s!==i)return!1;if(s){let d=e.length;if(d!==t.length)return!1;for(let r=0;r<d;r++)if(!ue(e[r],t[r]))return!1;return!0}if(n==="object"){if(!e||!t)return e===t;let d=Object.keys(e),r=Object.keys(t);if(d.length!==r.length)return!1;for(let b of d){if(!Object.prototype.hasOwnProperty.call(t,b))return!1;if(!ue(e[b],t[b]))return!1}return!0}return e===t}function B(e){return encodeURI(ct(e))}function ct(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var pt={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},mt={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},yt={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},gt=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),n=gt,s=""){if(e&&typeof e==="object"&&!Array.isArray(e)){let d=e.$id||e.id;if(d){let r=new URL(d,n.href);if(r.hash.length>1)t[r.href]=e;else if(r.hash="",s==="")n=r;else ee(e,t,n)}}else if(e!==!0&&e!==!1)return t;let i=n.href+(s?"#"+s:"");if(t[i]!==void 0&&t[i]!==e)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0)Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i});if(e.$ref&&e.__absolute_ref__===void 0){let d=new URL(e.$ref,n.href);d.hash=d.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:d.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let d=new URL(e.$recursiveRef,n.href);d.hash=d.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:d.href})}if(e.$anchor){let d=new URL("#"+e.$anchor,n.href);t[d.href]=e}for(let d in e){if(yt[d])continue;let r=`${s}/${B(d)}`,a=e[d];if(Array.isArray(a)){if(pt[d]){let b=a.length;for(let E=0;E<b;E++)ee(a[E],t,n,`${r}/${E}`)}}else if(mt[d])for(let b in a)ee(a[b],t,n,`${r}/${B(b)}`);else ee(a,t,n,r)}return t}var ht=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,$t=[0,31,28,31,30,31,30,31,31,30,31,30,31],bt=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,wt=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"')return!1;let[t,n,...s]=e.split("@");if(!t||!n||s.length!==0||t.length>64||n.length>253)return!1;if(t[0]==="."||t.endsWith(".")||t.includes(".."))return!1;if(!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t))return!1;return n.split(".").every((i)=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},Mt=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Ot=/^((([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,Et=(e)=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function Y(e){return e.test.bind(e)}var _e={date:qe,time:ze.bind(void 0,!1),"date-time":Ct,duration:Et,uri:qt,"uri-reference":Y(kt),"uri-template":Y(Rt),url:Y(It),email:St,hostname:Y(wt),ipv4:Y(Mt),ipv6:Y(Ot),regex:Ht,uuid:Y(xt),"json-pointer":Y(Tt),"json-pointer-uri-fragment":Y(_t),"relative-json-pointer":Y(vt)};function At(e){return e%4===0&&(e%100!==0||e%400===0)}function qe(e){let t=e.match(ht);if(!t)return!1;let n=t[1],s=t[2],i=t[3];if(!n||!s||!i)return!1;let d=+n,r=+s,a=+i,b=r==2&&At(d)?29:$t[r];return r>=1&&r<=12&&a>=1&&b!==void 0&&a<=b}function ze(e,t){let n=t.match(bt);if(!n)return!1;let s=n[1],i=n[2],d=n[3];if(!s||!i||!d)return!1;let r=+s,a=+i,b=+d,E=!!n[5];return(r<=23&&a<=59&&b<=59||r==23&&a==59&&b==60)&&(!e||E)}var Pt=/t|\s/i;function Ct(e){let[t,n,s]=e.split(Pt);return t!==void 0&&n!==void 0&&s===void 0&&qe(t)&&ze(!0,n)}var Nt=/\/|:/,jt=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-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/;function Ht(e){if(zt.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}}function He(e){let t=0,n=e.length,s=0,i;while(s<n)if(t++,i=e.charCodeAt(s++),i>=55296&&i<=56319&&s<n){if(i=e.charCodeAt(s),(i&64512)==56320)s++}return t}function se(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Je(e){let t=Math.abs(e).toString().split("e"),n=t[0],s=t[1]??"0",i=n.indexOf("."),d=i===-1?0:n.length-i-1;return[BigInt(n.replace(".","")),Number(s)-d]}function Jt(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return!1;let[n,s]=Je(e),[i,d]=Je(t),r=s-d;if(r>=0)return n*10n**BigInt(r)%i===0n;return n%(i*10n**BigInt(-r))===0n}function O(e,t,n="2019-09",s=ee(t),i=!0,d=null,r="#",a="#",b=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:r,keyword:"false",keywordLocation:r,error:"False boolean schema."}]};let E=typeof e,v;switch(E){case"boolean":case"number":case"string":v=E;break;case"object":if(e===null)v="null";else if(Array.isArray(e))v="array";else v="object";break;default:throw Error(`Instances of "${E}" type are not supported.`)}let{$ref:U,$recursiveRef:D,$recursiveAnchor:V,type:C,const:G,enum:W,required:Q,not:L,anyOf:A,allOf:l,oneOf:g,if:R,then:T,else:y,format:o,properties:w,patternProperties:c,additionalProperties:S,unevaluatedProperties:_,minProperties:N,maxProperties:P,propertyNames:K,dependentRequired:H,dependentSchemas:q,dependencies:J,prefixItems:ce,items:ne,additionalItems:Oe,unevaluatedItems:Ee,contains:Ae,minContains:X,maxContains:ke,minItems:Re,maxItems:Ie,uniqueItems:at,minimum:re,maximum:oe,exclusiveMinimum:pe,exclusiveMaximum:me,multipleOf:xe,minLength:ye,maxLength:ge,pattern:Pe,__absolute_ref__:he,__absolute_recursive_ref__:ut}=t,f=[];if(V===!0&&d===null)d=t;if(D==="#"){let x=d===null?s[ut]:d,m=`${a}/$recursiveRef`,I=O(e,d===null?t:d,n,s,i,x,r,m,b);if(!I.valid)f.push({instanceLocation:r,keyword:"$recursiveRef",keywordLocation:m,error:"A subschema had errors."},...I.errors)}if(U!==void 0){let m=s[he||U];if(m===void 0){let u=`Unresolved $ref "${U}".`;if(he&&he!==U)u+=` Absolute URI "${he}".`;throw u+=`
2
+ Known schemas:
3
+ - ${Object.keys(s).join(`
4
+ - `)}`,Error(u)}let I=`${a}/$ref`,p=O(e,m,n,s,i,d,r,I,b);if(!p.valid)f.push({instanceLocation:r,keyword:"$ref",keywordLocation:I,error:"A subschema had errors."},...p.errors);if(n==="4"||n==="7")return{valid:f.length===0,errors:f}}if(Array.isArray(C)){let x=C.length,m=!1;for(let I=0;I<x;I++)if(v===C[I]||C[I]==="integer"&&v==="number"&&e%1===0&&e===e){m=!0;break}if(!m)f.push({instanceLocation:r,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${v}" is invalid. Expected "${C.join('", "')}".`})}else if(C==="integer"){if(v!=="number"||e%1||e!==e)f.push({instanceLocation:r,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${v}" is invalid. Expected "${C}".`})}else if(C!==void 0&&v!==C)f.push({instanceLocation:r,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${v}" is invalid. Expected "${C}".`});if(G!==void 0){if(v==="object"||v==="array"){if(!ue(e,G))f.push({instanceLocation:r,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(G)}.`})}else if(e!==G)f.push({instanceLocation:r,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(G)}.`})}if(W!==void 0){if(v==="object"||v==="array"){if(!W.some((x)=>ue(e,x)))f.push({instanceLocation:r,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(W)}.`})}else if(!W.some((x)=>e===x))f.push({instanceLocation:r,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(W)}.`})}if(L!==void 0){let x=`${a}/not`;if(O(e,L,n,s,i,d,r,x).valid)f.push({instanceLocation:r,keyword:"not",keywordLocation:x,error:'Instance matched "not" schema.'})}let $e=[];if(A!==void 0){let x=`${a}/anyOf`,m=f.length,I=!1;for(let[p,u]of A.entries()){let k=Object.create(b),h=O(e,u,n,s,i,V===!0?d:null,r,`${x}/${p}`,k);if(f.push(...h.errors),I=I||h.valid,h.valid)$e.push(k)}if(I)f.length=m;else f.splice(m,0,{instanceLocation:r,keyword:"anyOf",keywordLocation:x,error:"Instance does not match any subschemas."})}if(l!==void 0){let x=`${a}/allOf`,m=f.length,I=!0;for(let[p,u]of l.entries()){let k=Object.create(b),h=O(e,u,n,s,i,V===!0?d:null,r,`${x}/${p}`,k);if(f.push(...h.errors),I=I&&h.valid,h.valid)$e.push(k)}if(I)f.length=m;else f.splice(m,0,{instanceLocation:r,keyword:"allOf",keywordLocation:x,error:"Instance does not match every subschema."})}if(g!==void 0){let x=`${a}/oneOf`,m=f.length,I=g.filter((p,u)=>{let k=Object.create(b),h=O(e,p,n,s,i,V===!0?d:null,r,`${x}/${u}`,k);if(f.push(...h.errors),h.valid)$e.push(k);return h.valid}).length;if(I===1)f.length=m;else f.splice(m,0,{instanceLocation:r,keyword:"oneOf",keywordLocation:x,error:`Instance does not match exactly one subschema (${I} matches).`})}if(v==="object"||v==="array")Object.assign(b,...$e);if(R!==void 0){let x=`${a}/if`;if(O(e,R,n,s,i,d,r,x,b).valid){if(T!==void 0){let I=O(e,T,n,s,i,d,r,`${a}/then`,b);if(!I.valid)f.push({instanceLocation:r,keyword:"if",keywordLocation:x,error:'Instance does not match "then" schema.'},...I.errors)}}else if(y!==void 0){let I=O(e,y,n,s,i,d,r,`${a}/else`,b);if(!I.valid)f.push({instanceLocation:r,keyword:"if",keywordLocation:x,error:'Instance does not match "else" schema.'},...I.errors)}}if(v==="object"){if(Q!==void 0){for(let p of Q)if(!se(e,p))f.push({instanceLocation:r,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${p}".`})}let x=Object.keys(e);if(N!==void 0&&x.length<N)f.push({instanceLocation:r,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${N} properties.`});if(P!==void 0&&x.length>P)f.push({instanceLocation:r,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${P} properties.`});if(K!==void 0){let p=`${a}/propertyNames`;for(let u in e){let k=`${r}/${B(u)}`,h=O(u,K,n,s,i,d,k,p);if(!h.valid)f.push({instanceLocation:r,keyword:"propertyNames",keywordLocation:p,error:`Property name "${u}" does not match schema.`},...h.errors)}}if(H!==void 0){let p=`${a}/dependantRequired`;for(let u in H)if(se(e,u)){let k=H[u];for(let h of k)if(!se(e,h))f.push({instanceLocation:r,keyword:"dependentRequired",keywordLocation:p,error:`Instance has "${u}" but does not have "${h}".`})}}if(q!==void 0)for(let[p,u]of Object.entries(q)){let k=`${a}/dependentSchemas`;if(se(e,p)){let h=O(e,u,n,s,i,d,r,`${k}/${B(p)}`,b);if(!h.valid)f.push({instanceLocation:r,keyword:"dependentSchemas",keywordLocation:k,error:`Instance has "${p}" but does not match dependant schema.`},...h.errors)}}if(J!==void 0){let p=`${a}/dependencies`;for(let u in J)if(se(e,u)){let k=J[u];if(Array.isArray(k)){for(let h of k)if(!se(e,h))f.push({instanceLocation:r,keyword:"dependencies",keywordLocation:p,error:`Instance has "${u}" but does not have "${h}".`})}else{let h=O(e,k,n,s,i,d,r,`${p}/${B(u)}`);if(!h.valid)f.push({instanceLocation:r,keyword:"dependencies",keywordLocation:p,error:`Instance has "${u}" but does not match dependant schema.`},...h.errors)}}}let m=Object.create(null),I=!1;if(w!==void 0){let p=`${a}/properties`;for(let[u,k]of Object.entries(w)){if(!se(e,u))continue;let h=`${r}/${B(u)}`,j=O(e[u],k,n,s,i,d,h,`${p}/${B(u)}`);if(m[u]=!0,j.valid)b[u]=!0;else if(I=i,f.push({instanceLocation:r,keyword:"properties",keywordLocation:p,error:`Property "${u}" does not match schema.`},...j.errors),I)break}}if(!I&&c!==void 0){let p=`${a}/patternProperties`;for(let[u,k]of Object.entries(c)){let h=new RegExp(u,"u");for(let j in e){if(!h.test(j))continue;let Ce=`${r}/${B(j)}`,Ne=O(e[j],k,n,s,i,d,Ce,`${p}/${B(u)}`);if(m[j]=!0,Ne.valid)b[j]=!0;else I=i,f.push({instanceLocation:r,keyword:"patternProperties",keywordLocation:p,error:`Property "${j}" matches pattern "${u}" but does not match associated schema.`},...Ne.errors)}}}if(!I&&S!==void 0){let p=`${a}/additionalProperties`;for(let u in e){if(m[u])continue;let k=`${r}/${B(u)}`,h=O(e[u],S,n,s,i,d,k,p);if(h.valid)b[u]=!0;else I=i,f.push({instanceLocation:r,keyword:"additionalProperties",keywordLocation:p,error:`Property "${u}" does not match additional properties schema.`},...h.errors)}}else if(!I&&_!==void 0){let p=`${a}/unevaluatedProperties`;for(let u in e)if(!b[u]){let k=`${r}/${B(u)}`,h=O(e[u],_,n,s,i,d,k,p);if(h.valid)b[u]=!0;else f.push({instanceLocation:r,keyword:"unevaluatedProperties",keywordLocation:p,error:`Property "${u}" does not match unevaluated properties schema.`},...h.errors)}}}else if(v==="array"){if(Ie!==void 0&&e.length>Ie)f.push({instanceLocation:r,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${Ie}).`});if(Re!==void 0&&e.length<Re)f.push({instanceLocation:r,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${Re}).`});let x=e.length,m=0,I=!1;if(ce!==void 0){let p=`${a}/prefixItems`,u=Math.min(ce.length,x);for(;m<u;m++){let k=O(e[m],ce[m],n,s,i,d,`${r}/${m}`,`${p}/${m}`);if(b[m]=!0,!k.valid){if(I=i,f.push({instanceLocation:r,keyword:"prefixItems",keywordLocation:p,error:"Items did not match schema."},...k.errors),I)break}}}if(ne!==void 0){let p=`${a}/items`;if(Array.isArray(ne)){let u=Math.min(ne.length,x);for(;m<u;m++){let k=O(e[m],ne[m],n,s,i,d,`${r}/${m}`,`${p}/${m}`);if(b[m]=!0,!k.valid){if(I=i,f.push({instanceLocation:r,keyword:"items",keywordLocation:p,error:"Items did not match schema."},...k.errors),I)break}}}else for(;m<x;m++){let u=O(e[m],ne,n,s,i,d,`${r}/${m}`,p);if(b[m]=!0,!u.valid){if(I=i,f.push({instanceLocation:r,keyword:"items",keywordLocation:p,error:"Items did not match schema."},...u.errors),I)break}}if(!I&&Oe!==void 0){let u=`${a}/additionalItems`;for(;m<x;m++){let k=O(e[m],Oe,n,s,i,d,`${r}/${m}`,u);if(b[m]=!0,!k.valid)I=i,f.push({instanceLocation:r,keyword:"additionalItems",keywordLocation:u,error:"Items did not match additional items schema."},...k.errors)}}}if(Ae!==void 0)if(x===0&&X===void 0)f.push({instanceLocation:r,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(X!==void 0&&x<X)f.push({instanceLocation:r,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${x}) than minContains (${X}).`});else{let p=`${a}/contains`,u=f.length,k=0;for(let h=0;h<x;h++){let j=O(e[h],Ae,n,s,i,d,`${r}/${h}`,p);if(j.valid)b[h]=!0,k++;else f.push(...j.errors)}if(k>=(X||0))f.length=u;if(X===void 0&&k===0)f.splice(u,0,{instanceLocation:r,keyword:"contains",keywordLocation:p,error:"Array does not contain item matching schema."});else if(X!==void 0&&k<X)f.push({instanceLocation:r,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${X} items matching schema. Only ${k} items were found.`});else if(ke!==void 0&&k>ke)f.push({instanceLocation:r,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${ke} items matching schema. ${k} items were found.`})}if(!I&&Ee!==void 0){let p=`${a}/unevaluatedItems`;for(m;m<x;m++){if(b[m])continue;let u=O(e[m],Ee,n,s,i,d,`${r}/${m}`,p);if(b[m]=!0,!u.valid)f.push({instanceLocation:r,keyword:"unevaluatedItems",keywordLocation:p,error:"Items did not match unevaluated items schema."},...u.errors)}}if(at)for(let p=0;p<x;p++){let u=e[p],k=typeof u==="object"&&u!==null;for(let h=0;h<x;h++){if(p===h)continue;let j=e[h];if(u===j||k&&(typeof j==="object"&&j!==null)&&ue(u,j))f.push({instanceLocation:r,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${p} and ${h}.`}),p=Number.MAX_SAFE_INTEGER,h=Number.MAX_SAFE_INTEGER}}}else if(v==="number"){if(n==="4"){if(re!==void 0&&(pe===!0&&e<=re||e<re))f.push({instanceLocation:r,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${pe?"or equal to ":""} ${re}.`});if(oe!==void 0&&(me===!0&&e>=oe||e>oe))f.push({instanceLocation:r,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${me?"or equal to ":""} ${oe}.`})}else{if(re!==void 0&&e<re)f.push({instanceLocation:r,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${re}.`});if(oe!==void 0&&e>oe)f.push({instanceLocation:r,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${oe}.`});if(pe!==void 0&&e<=pe)f.push({instanceLocation:r,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${pe}.`});if(me!==void 0&&e>=me)f.push({instanceLocation:r,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${me}.`})}if(xe!==void 0){if(!Jt(e,xe))f.push({instanceLocation:r,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${xe}.`})}}else if(v==="string"){let x=ye===void 0&&ge===void 0?0:He(e);if(ye!==void 0&&x<ye)f.push({instanceLocation:r,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${x} < ${ye}).`});if(ge!==void 0&&x>ge)f.push({instanceLocation:r,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${x} > ${ge}).`});if(Pe!==void 0&&!new RegExp(Pe,"u").test(e))f.push({instanceLocation:r,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."});if(o!==void 0&&_e[o]&&!_e[o](e))f.push({instanceLocation:r,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${o}".`})}return{valid:f.length===0,errors:f}}var Ue="ch.ractive.tab-mcp/annotations",Bt=["readOnlyHint","untrustedContentHint","consequentialHint","debugging"],Ut=["destructiveHint","idempotentHint","openWorldHint"];function De(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 i of Ut){let d=e[i];if(d!==void 0)t[i]=d}let n={};for(let i of Bt){let d=e[i];if(d!==void 0)n[i]=d}let s={};if(Object.keys(t).length>0)s.annotations=t;if(Object.keys(n).length>0)s.meta=n;return s}function Z(e){return{content:[{type:"text",text:e}],isError:!0}}function Be(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Ve(e){if(typeof e==="string")return{content:[{type:"text",text:e}]};if(e===void 0)return{content:[]};if(Be(e)&&Array.isArray(e.content))return e;let t;try{t=JSON.stringify(e)}catch{}if(t===void 0)return Z("The tool returned a value that is not JSON.");let n={content:[{type:"text",text:t}]};if(Be(e))n.structuredContent=e;return n}function Ge(e){let t=e instanceof Error?e.message:String(e);return Z(t||"The tool failed.")}var ie="2026-07-28",te="io.modelcontextprotocol/protocolVersion",be="io.modelcontextprotocol/clientCapabilities",We="io.modelcontextprotocol/clientInfo",Ke="io.modelcontextprotocol/serverInfo",ve="io.modelcontextprotocol/subscriptionId",Dt=-32020,Ye=-32022,Vt=0,Fe=new WeakMap;function Se(e){let t=Fe.get(e);if(t!==void 0)return t;let n=e.inputSchema,s;try{s=ee(n)}catch(d){let r=d instanceof Error?d.message:String(d);throw Error(r.split(`
5
+ `)[0])}for(let d of Object.values(s)){if(typeof d!=="object"||d.$ref===void 0)continue;let r=d.__absolute_ref__;if(s[r??d.$ref]===void 0)throw Error(`$ref ${JSON.stringify(d.$ref)} does not resolve`)}let i=(d)=>O(d,n,"2020-12",s,!1);return Fe.set(e,i),i}function Xe(e,t,n=""){let s=t instanceof Error?t.message:String(t);return TypeError(`registerTool: the inputSchema of ${e}: ${s}${n}`)}function Gt(e){let t=[];for(let n of e.list())try{Se(n)}catch(s){e.remove(n),t.push(Xe(n.name,s,"; the tool was unregistered"))}return e.setCompiler((n)=>{try{Se(n)}catch(s){throw Xe(n.name,s)}}),t}function Ze(e){try{return structuredClone(e)}catch{return e}}var Wt=new TextEncoder;function de(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 z(e,t,n,s,i){let d={code:n,message:s};if(i!==void 0)d.data=i;return Me(e,{jsonrpc:"2.0",id:t,error:d})}function F(e,t,n){return z(400,e,Dt,`Bad Request: the request headers and body disagree: ${n}`,{mismatch:{header:t,body:n}})}function le(e){return Wt.encode(`event: message
6
+ data: ${JSON.stringify(e)}
7
+
8
+ `)}var Qe={"content-type":"text/event-stream","cache-control":"no-cache"};function Kt(e){return(e??"").split(";")[0]?.trim().toLowerCase()==="application/json"}function Yt(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 n=atob(t),s=Uint8Array.from(n,(i)=>i.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(s)}catch{return}}function Ft(e){if(!(te in e))return{key:te,problem:"missing"};if(!(be in e))return{key:be,problem:"missing"};if(typeof e[te]!=="string")return{key:te,problem:"expected a protocol version string"};if(!de(e[be]))return{key:be,problem:"expected an object"};let t=e[We];if(t!==void 0&&!(de(t)&&typeof t.name==="string"&&typeof t.version==="string"))return{key:We,problem:"expected {name, version}"};return}function Xt(e){let t=e.notifications;return de(t)&&t.toolsListChanged===!0?{toolsListChanged:!0}:{}}function Le(e){let{tools:t,server:n}=e,s={name:n.name,version:n.version};if(n.title!==void 0)s.title=n.title;let i=Te(n.icons??[]),d=i.length>0?{...s,icons:i}:s,r=new Set,a=!1,b=(l={})=>({...l,[Ke]:s});function E(l,g,R=b()){return{jsonrpc:"2.0",id:l,result:{...g,resultType:"complete",_meta:R}}}function v(l,g){let R;try{R=Se(l)(g)}catch(y){let o=y instanceof Error?y.message:String(y);return`The input schema of tool ${l.name} cannot be used: ${o}`}if(R.valid)return;let T=R.errors.filter((y)=>y.keyword!=="properties"&&y.keyword!=="$ref").map((y)=>`${y.instanceLocation} ${y.error}`).slice(0,5).join("; ");return`Input validation error: Invalid arguments for tool ${l.name}: ${T||"the arguments do not match the schema"}`}function U(){return t.list().map((l)=>{let g={name:l.name};if(l.title!==void 0)g.title=l.title;g.description=l.description,g.inputSchema=l.inputSchema;let{annotations:R,meta:T}=De(l.annotations);if(R!==void 0)g.annotations=R;if(T!==void 0)g._meta={[Ue]:T};return g})}let D=(l)=>({kind:"invalid",message:l});async function V(l,g,R){let T=l.name;if(typeof T!=="string")return D("Invalid params: name must be a string");let y=t.get(T);if(y===void 0)return D(`Tool ${T} not found`);let o=l.arguments??{};if(!de(o))return D("Invalid params: arguments must be an object");let w=e.client(R),c={id:++Vt,tool:y.name,arguments:Ze(o),client:{...w}};if(y.title!==void 0)c.title=y.title;let S=Date.now();e.observe?.start(c);let _="error",N=Z("Internal error");try{[_,N]=await C(y,o,g,w)}finally{e.observe?.end({id:c.id,tool:y.name,client:{...w},outcome:_,result:Ze(N),durationMs:Date.now()-S})}return{kind:"result",result:N}}async function C(l,g,R,T){let y=v(l,g);if(y!==void 0)return["error",Z(y)];if(l.annotations.consequentialHint===!0){let w={tool:{name:l.name,description:l.description},arguments:g,client:T,signal:R};if(l.title!==void 0)w.tool.title=l.title;let c=!1;try{c=await e.confirm(w)}catch{c=!1}if(!c)return[R.aborted?"cancelled":"declined",Z("The user declined")]}if(R.aborted)return["cancelled",Z("Cancelled")];if(t.get(l.name)!==l)return["error",Z("The tool is no longer available")];let o;try{o=Ve(await l.execute(g,{signal:R,client:T}))}catch(w){o=Ge(w)}if(R.aborted)return["cancelled",o];return[o.isError===!0?"error":"ok",o]}function G(l,g,R,T){let y=new ReadableStream({start:(o)=>{let w=(c)=>{if(R.aborted)return;let S;try{S=le(c)}catch{S=le(E(l,Z("The tool returned a result that is not JSON.")))}try{o.enqueue(S),o.close()}catch{}};V(g,R,T).then((c)=>w(c.kind==="invalid"?{jsonrpc:"2.0",id:l,error:{code:-32602,message:c.message}}:E(l,c.result)),()=>w({jsonrpc:"2.0",id:l,error:{code:-32603,message:"Internal error"}}))}});return new Response(y,{status:200,headers:Qe})}function W(l,g,R){let T=Xt(g),y={jsonrpc:"2.0",id:l,result:{resultType:"complete",_meta:b({[ve]:l})}},o,w=new ReadableStream({start:(c)=>{if(c.enqueue(le({jsonrpc:"2.0",method:"notifications/subscriptions/acknowledged",params:{notifications:T,_meta:{[ve]:l}}})),Object.keys(T).length===0){c.enqueue(le(y)),c.close();return}let S={id:l,send:(_)=>{try{c.enqueue(le(_))}catch{r.delete(S)}},end:()=>{r.delete(S);try{c.enqueue(le(y)),c.close()}catch{}}};o=S,r.add(S),R.addEventListener("abort",()=>{r.delete(S);try{c.close()}catch{}})},cancel:()=>{if(o!==void 0)r.delete(o)}});return new Response(w,{status:200,headers:Qe})}function Q(l,g){if(Array.isArray(g))return z(400,null,-32600,"Bad Request: JSON-RPC batches are not supported by this endpoint");if(!de(g)||g.jsonrpc!=="2.0")return z(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let{method:R,id:T}=g;if(typeof R!=="string")return"result"in g||"error"in g?z(400,null,-32600,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"):z(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let y=l.headers.get("mcp-protocol-version"),o=l.headers.get("mcp-method"),w=de(g.params)?g.params:{},c=de(w._meta)?w._meta:void 0,S=c!==void 0&&te in c,_=typeof c?.[te]==="string"?c[te]:void 0,N=y!==null&&y>=ie;if(T===void 0){if(_!==void 0&&y!==null&&y!==_)return F(null,y,`the notification envelope names protocol version ${_} but the MCP-Protocol-Version header names ${y}`);if((S||N)&&o!==null&&o!==R)return F(null,o,`the notification body names method ${R} but the Mcp-Method header names ${o}`);return"notification"}if(typeof T!=="string"&&typeof T!=="number")return z(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let P=T;if(!S||R==="initialize"&&(_===void 0||_<ie)){if(R==="initialize"){if(N)return F(P,y,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let H=typeof w.protocolVersion==="string"?w.protocolVersion:void 0;return L(P,H)}if(N){let H=c===void 0?["_meta"]:[te];return z(400,P,-32602,`Invalid params: the MCP-Protocol-Version header names protocol revision ${y}, but the request is missing the required per-request envelope key(s): ${H.join(", ")}`,{envelope:{missing:H}})}return L(P,y??void 0)}let K=Ft(c);if(K!==void 0)return z(400,P,-32602,`Invalid _meta envelope for protocol revision ${ie}: ${K.key}: ${K.problem}`,{envelope:K});if(y!==null&&_!==void 0&&y!==_)return F(P,y,`the body envelope names protocol version ${_} but the MCP-Protocol-Version header names ${y}`);if(o!==null&&o!==R)return F(P,o,`the body names method ${R} but the Mcp-Method header names ${o}`);if(_!==ie)return L(P,_);if(y===null)return F(P,"(missing)",`the body envelope names protocol version ${_} but the required MCP-Protocol-Version header is absent`);if(o===null)return F(P,"(missing)",`the body names method ${R} but the required Mcp-Method header is absent`);if(R==="tools/call"&&typeof w.name==="string"){let H=w.name,q=l.headers.get("mcp-name");if(q===null)return F(P,"(missing)",`the body carries params.name="${H}" but the required Mcp-Name header is absent`);let J=Yt(q);if(J===void 0)return F(P,q,"the Mcp-Name header carries an invalid Base64 sentinel value");if(J!==H)return F(P,q,`the body carries params.name="${H}" but the Mcp-Name header names "${J}"`)}return{id:P,method:R,params:w}}function L(l,g){return g===void 0?z(400,l,Ye,"Unsupported protocol version: the request did not name a protocol version",{supported:[ie]}):z(400,l,Ye,`Unsupported protocol version: ${g}`,{supported:[ie],requested:g})}async function A(l,g){if(l.method.toUpperCase()!=="POST")return z(405,null,-32000,"Method not allowed.");if(!Kt(l.headers.get("content-type")))return z(415,null,-32000,"Unsupported Media Type: Content-Type must be application/json");let R;try{R=JSON.parse(g.body??await l.text())}catch{return z(400,null,-32700,"Parse error: the request body is not valid JSON")}let T=Q(l,R);if(T instanceof Response)return T;if(T==="notification")return new Response(null,{status:202});let{id:y,method:o,params:w}=T;switch(o){case"server/discover":{let c={supportedVersions:[ie],capabilities:{tools:{listChanged:!0}}};if(n.instructions!==void 0)c.instructions=n.instructions;return c.ttlMs=0,c.cacheScope="private",Me(200,E(y,c,{[Ke]:d}))}case"tools/list":return Me(200,E(y,{tools:U(),ttlMs:0,cacheScope:"private"}));case"tools/call":return G(y,w,l.signal,g.grant);case"subscriptions/listen":return W(y,w,l.signal);default:return z(404,y,-32601,"Method not found")}}return{handle:(l,g)=>A(l,g).catch(()=>z(500,null,-32603,"Internal server error")),toolsChanged(){if(a)return;a=!0,queueMicrotask(()=>{a=!1;for(let l of[...r])l.send({jsonrpc:"2.0",method:"notifications/tools/list_changed",params:{_meta:{[ve]:l.id}}})})},close(){for(let l of[...r])l.end()}}}var we="tab-mcp.v1";function fe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var M=(e)=>typeof e==="string";function et(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 Zt(e){if(!fe(e))return!1;return["maxMessageBytes","maxBodyBytes","requestTimeoutMs","idleTimeoutMs","heartbeatMs","keepAliveMs","maxConcurrentRequests"].every((t)=>typeof e[t]==="number")}function Qt(e){return fe(e)&&Object.values(e).every(M)}function tt(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)&&Zt(t.limits)&&Array.isArray(t.grants)&&t.grants.every(et)&&(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)&&Qt(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":return M(t.code)&&M(t.expiresAt)?t:void 0;case"grant.added":return et(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 Lt(e){let t="",n=0,s=0;for(let i of e){n=n<<8|i,s+=8;while(s>=5)s-=5,t+="abcdefghijklmnopqrstuvwxyz234567"[n>>>s&31];n&=(1<<s)-1}if(s>0)t+="abcdefghijklmnopqrstuvwxyz234567"[n<<5-s&31];return t}async function en(e,t=globalThis.crypto?.subtle??null){if(t===null)return;try{let n=await t.digest("SHA-256",new TextEncoder().encode(e));return Lt(new Uint8Array(n))}catch{return}}function tn(e,t){if(t===void 0)return e;let n=new URL(e);return n.searchParams.set("a",t),n.href}var nn=15000,nt={1000:"closed",1008:"policy",1009:"too_large",4001:"expired",4002:"idle",4003:"heartbeat",4004:"shutdown",4005:"replaced",4008:"rate_limited",4009:"policy"},rt={replaced:"replaced",expired:"expired",idle:"idle",shutdown:"shutdown"};function ae(e,t){return Object.assign(Error(e),{reason:t})}var rn=["content-type","cache-control"];function on(){let e=globalThis.document?.title;return typeof e==="string"?e.slice(0,300):""}function sn(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 dn=new Set(["session","ping","bye","http.request","http.cancel","pairing.code","grant.added","grant.removed","identity.bound","error"]),st=512,it=6,dt=64,an=st+it*dt;function un(e){let t=Math.floor((e-st)/it);return t>=dt?t:void 0}function*ot(e,t){let n=0;while(n<e.length){let s=Math.min(n+t,e.length),i=e.charCodeAt(s-1);if(s<e.length&&i>=55296&&i<=56319)s+=s-1>n?-1:1;yield e.slice(n,s),n=s}}var ln=1e4,fn=1000;function cn(e){let t,n=Number.NEGATIVE_INFINITY,s;try{if(e!==void 0&&typeof BroadcastChannel==="function")t=new BroadcastChannel(e),t.onmessage=(i)=>{if(i.data?.type!=="claimed")return;n=Date.now(),s?.()}}catch{t=void 0}return{claimed(){try{t?.postMessage({type:"claimed"})}catch{}},heard(){if(Date.now()-n<=ln)return Promise.resolve(!0);if(t===void 0)return Promise.resolve(!1);return new Promise((i)=>{let d=setTimeout(()=>i(!1),fn);s=()=>{clearTimeout(d),i(!0)}})},close(){t?.close()}}}function jn(e,t,n,s=!1){let i=new WebSocket(t,we),d=new Map,r="opening",a,b=65536,E,v=0,U=cn(e.tabs),D,V,C,G=new Promise((o,w)=>{V=o,C=w});G.catch(()=>{});let W=setTimeout(()=>{g(ae("The relay did not answer in time.","network"))},nn),Q=Le({tools:e.registry,server:{...e.server,icons:e.server.icons??je()},confirm:(o)=>e.confirm(o),client:(o)=>e.clientFor(o),observe:{start:(o)=>e.toolCallStarted(o),end:(o)=>e.toolCallEnded(o)}}),L=e.registry.onChange(()=>Q.toolsChanged());function A(o){if(i.readyState!==WebSocket.OPEN)return!1;try{return i.send(JSON.stringify(o)),!0}catch{return!1}}function l(){if(v<=0)return;clearTimeout(E),E=setTimeout(()=>{a??="heartbeat",R(4003);try{i.close()}catch{}},v*2.5)}function g(o){if(r!=="opening")return;R(0),C(o);try{i.close()}catch{}}function R(o){if(r==="closed")return;let w=r==="ready";r="closed",clearTimeout(W),clearTimeout(E),L();for(let c of d.values())c.abort();if(d.clear(),Q.close(),w){let c=a??nt[o]??(o===1006?"network":"closed");if(C(ae("The address was taken over again before its AI apps were disconnected.",c)),e.closed(c,o),c==="replaced"){U.heard().then((S)=>{U.close(),e.replaced({sibling:S})});return}}U.close()}async function T(o){let w=new AbortController;d.set(o.id,w);let c=()=>r==="ready"&&d.get(o.id)===w&&!w.signal.aborted;try{let S=new Request(`https://tab.invalid${o.path}`,{method:o.method,headers:o.headers,signal:w.signal}),_=await Q.handle(S,{grant:o.grant,body:o.body});if(!c()){await _.body?.cancel().catch(()=>{});return}let N={};for(let q of rn){let J=_.headers.get(q);if(J!==null)N[q]=J}if(!(N["content-type"]??"").startsWith("text/event-stream")||_.body===null){let q=await _.text();if(!c())return;if(q.length<=b){A({type:"http.response",id:o.id,status:_.status,headers:N,body:q});return}A({type:"http.response.start",id:o.id,status:_.status,headers:N});for(let J of ot(q,b)){if(!c())break;A({type:"http.response.chunk",id:o.id,data:J})}if(c())A({type:"http.response.end",id:o.id});return}A({type:"http.response.start",id:o.id,status:_.status,headers:N});let K=_.body.getReader(),H=new TextDecoder;w.signal.addEventListener("abort",()=>{K.cancel().catch(()=>{})});for(;;){let{done:q,value:J}=await K.read();if(q||!c())break;let ce=H.decode(J,{stream:!0});for(let ne of ot(ce,b))A({type:"http.response.chunk",id:o.id,data:ne})}if(c())A({type:"http.response.end",id:o.id})}catch(S){if(c())e.error(S instanceof Error?S:Error(String(S))),A({type:"http.response",id:o.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(d.get(o.id)===w)d.delete(o.id)}}function y(o){if(r==="opening"){if(o.type==="session"){let w=un(o.limits.maxMessageBytes);if(w===void 0){g(ae(`The relay's message limit (${o.limits.maxMessageBytes} bytes) is too small; tab-mcp needs at least ${an}.`,"policy"));return}b=w,r="ready",clearTimeout(W),v=o.limits.heartbeatMs,l(),U.claimed();let c=e.sessionStarted(o);if(s&&o.grants.length>0){D={left:new Set(o.grants.map((S)=>S.grantId)),session:c},A({type:"grants.revokeAll"});return}V(c)}else if(o.type==="error")g(ae(`The relay refused the connection: ${o.message||o.code}`,o.code==="rate_limited"?"rate_limited":"policy"));else if(o.type==="bye")g(ae(`The relay ended the connection: ${o.reason}`,rt[o.reason]??"closed"));return}if(r!=="ready")return;switch(o.type){case"ping":l(),A({type:"pong",t:o.t});return;case"http.request":T(o);return;case"http.cancel":d.get(o.id)?.abort(),d.delete(o.id);return;case"pairing.code":e.pairingCode({code:o.code,expiresAt:o.expiresAt});return;case"grant.added":e.grantAdded(o.grant);return;case"grant.removed":if(e.grantRemoved(o.grantId),D?.left.delete(o.grantId),D?.left.size===0)V(D.session);return;case"identity.bound":e.identityResult(!0,o.round);return;case"bye":if(a=rt[o.reason]??"closed",a==="replaced")R(4005);return;case"error":if(o.code==="identity_refused"){e.identityResult(!1,typeof o.round==="number"?o.round:void 0,o.message);return}e.error(Error(`Relay error ${o.code}: ${o.message}`));return;case"session":return}}return i.addEventListener("open",()=>{if(i.protocol!==""&&i.protocol!==we){g(ae(`The relay speaks ${i.protocol}, not ${we}.`,"policy"));return}let o={type:"hello",library:e.library,page:{title:on()},secret:n};if(e.appName!==void 0)o.app={name:e.appName};if(s)o.revokeAll=!0;A(o)}),i.addEventListener("message",(o)=>{if(typeof o.data!=="string")return;let w=tt(o.data);if(w!==void 0){if(r==="ready")l();y(w);return}let c=sn(o.data);if(c?.id!==void 0)A(dn.has(c.type)?{type:"error",code:"bad_message",message:`malformed ${c.type}`,id:c.id}:{type:"error",code:"unknown_type",message:`unknown type ${c.type}`,id:c.id})}),i.addEventListener("close",(o)=>{if(r==="opening"){R(o.code);let w=o.code===1006||o.code===1002;C(ae(w?"Could not connect to the relay (refused, unreachable, or this page's origin is not allowed).":`The relay closed the connection (${o.code}${o.reason?`: ${o.reason}`:""}).`,nt[o.code]??(w?"network":"closed")));return}R(o.code)}),{ready:G,send:A,close(o){if(r==="closed")return;if(r==="opening"){g(new DOMException("The connection was cancelled","AbortError"));return}a=o,A({type:"bye",reason:"user"}),R(1000);try{i.close(1000,"bye")}catch{}}}}export{en as addressIdOf,Gt as compileRegistry,jn as openConnection,tn as withAddress};
9
+
10
+ //# debugId=32B409545CAF306A64756E2164756E21
11
+ //# sourceMappingURL=connection-9w0rx0vf.min.js.map