@mcp-b/global 6.0.0-beta.20261001010549 → 6.0.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 +1 -1
- package/dist/index.iife.js +3 -3
- package/package.json +4 -4
package/dist/index.iife.js
CHANGED
|
@@ -61,16 +61,16 @@ var WebMCP=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Modul
|
|
|
61
61
|
|
|
62
62
|
`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,s=re,c=!o.jitless,l=c&&ie.value,d=t.catchall,f;e._zod.parse=(o,u)=>{f??=r.value;let p=o.value;return s(p)?c&&l&&u?.async===!1&&u.jitless!==!0?(a||=i(t.shape),o=a(o,u),d?bn([],p,o,u,f,e):o):n(o,u):(o.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),o)}});function Cn(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!ye(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>b(e,r,s())))}),t)}let wn=r(`$ZodUnion`,(e,t)=>{T.init(e,t),h(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),h(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),h(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),h(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>f(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Cn(t,r,e,i)):Cn(o,r,e,i)}}),Tn=r(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,wn.init(e,t);let n=e._zod.parse;h(e._zod,`propValues`,()=>{let e={};for(let n of t.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(let r of n)e[t].add(r)}}return e});let r=u(()=>{let e=t.options,n=new Map;for(let r of e){let e=r._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!re(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}}),En=r(`$ZodIntersection`,(e,t)=>{T.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>On(e,t,n)):On(e,i,a)}});function Dn(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(ae(e)&&ae(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Dn(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Dn(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function On(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),ye(e))return e;let o=Dn(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}let kn=r(`$ZodRecord`,(e,t)=>{T.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!ae(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let c=new Set;for(let l of o)if(typeof l==`string`||typeof l==`number`||typeof l==`symbol`){c.add(typeof l==`number`?l.toString():l);let o=t.keyType._zod.run({value:l,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>b(e,r,s())),input:l,path:[l],inst:e});continue}let u=o.value,d=t.valueType._zod.run({value:i[l],issues:[]},r);d instanceof Promise?a.push(d.then(e=>{e.issues.length&&n.issues.push(...xe(l,e.issues)),n.value[u]=e.value})):(d.issues.length&&n.issues.push(...xe(l,d.issues)),n.value[u]=d.value)}let l;for(let e in i)c.has(e)||(l??=[],l.push(e));l&&l.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:l})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let c=t.keyType._zod.run({value:o,issues:[]},r);if(c instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&ft.test(o)&&c.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(c=e)}if(c.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:c.issues.map(e=>b(e,r,s())),input:o,path:[o],inst:e});continue}let l=t.valueType._zod.run({value:i[o],issues:[]},r);l instanceof Promise?a.push(l.then(e=>{e.issues.length&&n.issues.push(...xe(o,e.issues)),n.value[c.value]=e.value})):(l.issues.length&&n.issues.push(...xe(o,l.issues)),n.value[c.value]=l.value)}}return a.length?Promise.all(a).then(()=>n):n}}),An=r(`$ZodEnum`,(e,t)=>{T.init(e,t);let n=c(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>se.has(typeof e)).map(e=>typeof e==`string`?ce(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),jn=r(`$ZodLiteral`,(e,t)=>{if(T.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?ce(e):e?ce(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),Mn=r(`$ZodTransform`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new a(e.constructor.name);let o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(e=>(n.value=e,n.fallback=!0,n));if(o instanceof Promise)throw new i;return n.value=o,n.fallback=!0,n}});function Nn(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}let Pn=r(`$ZodOptional`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,h(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),h(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${f(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>Nn(e,r)):Nn(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Fn=r(`$ZodExactOptional`,(e,t)=>{Pn.init(e,t),h(e._zod,`values`,()=>t.innerType._zod.values),h(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),In=r(`$ZodNullable`,(e,t)=>{T.init(e,t),h(e._zod,`optin`,()=>t.innerType._zod.optin),h(e._zod,`optout`,()=>t.innerType._zod.optout),h(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${f(e.source)}|null)$`):void 0}),h(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Ln=r(`$ZodDefault`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,h(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Rn(e,t)):Rn(r,t)}});function Rn(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}let zn=r(`$ZodPrefault`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,h(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Bn=r(`$ZodNonOptional`,(e,t)=>{T.init(e,t),h(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Vn(t,e)):Vn(i,e)}});function Vn(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}let Hn=r(`$ZodCatch`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,h(e._zod,`optout`,()=>t.innerType._zod.optout),h(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>b(e,n,s()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>b(e,n,s()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),Un=r(`$ZodPipe`,(e,t)=>{T.init(e,t),h(e._zod,`values`,()=>t.in._zod.values),h(e._zod,`optin`,()=>t.in._zod.optin),h(e._zod,`optout`,()=>t.out._zod.optout),h(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Wn(e,t.in,n)):Wn(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Wn(e,t.out,n)):Wn(r,t.out,n)}});function Wn(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}let Gn=r(`$ZodPreprocess`,(e,t)=>{Un.init(e,t)}),Kn=r(`$ZodReadonly`,(e,t)=>{T.init(e,t),h(e._zod,`propValues`,()=>t.innerType._zod.propValues),h(e._zod,`values`,()=>t.innerType._zod.values),h(e._zod,`optin`,()=>t.innerType?._zod?.optin),h(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(qn):qn(r)}});function qn(e){return e.value=Object.freeze(e.value),e}let Jn=r(`$ZodLazy`,(e,t)=>{T.init(e,t),h(e._zod,`innerType`,()=>{let e=t;return e._cachedInner||=t.getter(),e._cachedInner}),h(e._zod,`pattern`,()=>e._zod.innerType?._zod?.pattern),h(e._zod,`propValues`,()=>e._zod.innerType?._zod?.propValues),h(e._zod,`optin`,()=>e._zod.innerType?._zod?.optin??void 0),h(e._zod,`optout`,()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Yn=r(`$ZodCustom`,(e,t)=>{w.init(e,t),T.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Xn(t,n,r,e));Xn(i,n,r,e)}});function Xn(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Ce(e))}}var Zn,Qn=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function $n(){return new Qn}(Zn=globalThis).__zod_globalRegistry??(Zn.__zod_globalRegistry=$n());let er=globalThis.__zod_globalRegistry;function tr(e,t){return new e({type:`string`,...v(t)})}function nr(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...v(t)})}function rr(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...v(t)})}function ir(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...v(t)})}function ar(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...v(t)})}function or(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...v(t)})}function sr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...v(t)})}function cr(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...v(t)})}function lr(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...v(t)})}function ur(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...v(t)})}function dr(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...v(t)})}function fr(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...v(t)})}function pr(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...v(t)})}function mr(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...v(t)})}function hr(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...v(t)})}function gr(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...v(t)})}function _r(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...v(t)})}function vr(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...v(t)})}function yr(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...v(t)})}function br(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...v(t)})}function xr(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...v(t)})}function Sr(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...v(t)})}function Cr(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...v(t)})}function wr(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...v(t)})}function Tr(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...v(t)})}function Er(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...v(t)})}function Dr(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...v(t)})}function Or(e,t){return new e({type:`number`,checks:[],...v(t)})}function kr(e,t){return new e({type:`number`,coerce:!0,checks:[],...v(t)})}function Ar(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...v(t)})}function jr(e,t){return new e({type:`boolean`,...v(t)})}function Mr(e,t){return new e({type:`null`,...v(t)})}function Nr(e){return new e({type:`any`})}function Pr(e){return new e({type:`unknown`})}function Fr(e,t){return new e({type:`never`,...v(t)})}function Ir(e,t){return new vt({check:`less_than`,...v(t),value:e,inclusive:!1})}function Lr(e,t){return new vt({check:`less_than`,...v(t),value:e,inclusive:!0})}function Rr(e,t){return new yt({check:`greater_than`,...v(t),value:e,inclusive:!1})}function zr(e,t){return new yt({check:`greater_than`,...v(t),value:e,inclusive:!0})}function Br(e,t){return new bt({check:`multiple_of`,...v(t),value:e})}function Vr(e,t){return new St({check:`max_length`,...v(t),maximum:e})}function Hr(e,t){return new Ct({check:`min_length`,...v(t),minimum:e})}function Ur(e,t){return new wt({check:`length_equals`,...v(t),length:e})}function Wr(e,t){return new Et({check:`string_format`,format:`regex`,...v(t),pattern:e})}function Gr(e){return new Dt({check:`string_format`,format:`lowercase`,...v(e)})}function Kr(e){return new Ot({check:`string_format`,format:`uppercase`,...v(e)})}function qr(e,t){return new kt({check:`string_format`,format:`includes`,...v(t),includes:e})}function Jr(e,t){return new At({check:`string_format`,format:`starts_with`,...v(t),prefix:e})}function Yr(e,t){return new jt({check:`string_format`,format:`ends_with`,...v(t),suffix:e})}function Xr(e){return new Mt({check:`overwrite`,tx:e})}function Zr(e){return Xr(t=>t.normalize(e))}function Qr(){return Xr(e=>e.trim())}function $r(){return Xr(e=>e.toLowerCase())}function ei(){return Xr(e=>e.toUpperCase())}function ti(){return Xr(e=>te(e))}function ni(e,t,n){return new e({type:`array`,element:t,...v(n)})}function ri(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...v(n)})}function ii(e,t){let n=ai(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Ce(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Ce(r))}},e(t.value,t)),t);return n}function ai(e,t){let n=new w({check:`custom`,...v(t)});return n._zod.check=e,n}function oi(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??er,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function D(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,D(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&li(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function si(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
63
63
|
|
|
64
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function ci(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:di(t,`input`,e.processors),output:di(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function li(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return li(r.element,n);if(r.type===`set`)return li(r.valueType,n);if(r.type===`lazy`)return li(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return li(r.innerType,n);if(r.type===`intersection`)return li(r.left,n)||li(r.right,n);if(r.type===`record`||r.type===`map`)return li(r.keyType,n)||li(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:li(r.in,n)||li(r.out,n);if(r.type===`object`){for(let e in r.shape)if(li(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(li(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(li(e,n))return!0;return!!(r.rest&&li(r.rest,n))}return!1}let ui=(e,t={})=>n=>{let r=oi({...n,processors:t});return D(e,r),si(r,e),ci(r,e)},di=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=oi({...i??{},target:a,io:t,processors:n});return D(e,o),si(o,e),ci(o,e)},fi={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},pi=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=fi[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},mi=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},hi=(e,t,n,r)=>{n.type=`boolean`},gi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},_i=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},vi=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},yi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},bi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},xi=(e,t,n,r)=>{n.not={}},Si=(e,t,n,r)=>{},Ci=(e,t,n,r)=>{},wi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},Ti=(e,t,n,r)=>{let i=e._zod.def,a=c(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Ei=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0)if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a},Di=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},Oi=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},ki=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},Ai=(e,t,n,r)=>{n.type=`boolean`},ji=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Mi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},Ni=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Pi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},Fi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},Ii=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=D(a.element,t,{...r,path:[...r.path,`items`]})},Li=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=D(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=D(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Ri=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>D(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},zi=(e,t,n,r)=>{let i=e._zod.def,a=D(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=D(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},Bi=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>D(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?D(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},Vi=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=D(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=D(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=D(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},Hi=(e,t,n,r)=>{let i=e._zod.def,a=D(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Ui=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Wi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Gi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Ki=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},qi=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;D(o,t,r);let s=t.seen.get(e);s.ref=o},Ji=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Yi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Xi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Zi=(e,t,n,r)=>{let i=e._zod.innerType;D(i,t,r);let a=t.seen.get(e);a.ref=i},Qi={string:pi,number:mi,boolean:hi,bigint:gi,symbol:_i,null:vi,undefined:yi,void:bi,never:xi,any:Si,unknown:Ci,date:wi,enum:Ti,literal:Ei,nan:Di,template_literal:Oi,file:ki,success:Ai,custom:ji,function:Mi,transform:Ni,map:Pi,set:Fi,array:Ii,object:Li,union:Ri,intersection:zi,tuple:Bi,record:Vi,nullable:Hi,nonoptional:Ui,default:Wi,prefault:Gi,catch:Ki,pipe:qi,readonly:Ji,promise:Yi,optional:Xi,lazy:Zi};function $i(e,t){if(`_idmap`in e){let n=e,r=oi({...t,processors:Qi}),i={};for(let e of n._idmap.entries()){let[t,n]=e;D(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;si(r,n),a[t]=ci(r,n)}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=oi({...t,processors:Qi});return D(e,n),si(n,e),ci(n,e)}let ea=r(`ZodISODateTime`,(e,t)=>{qt.init(e,t),A.init(e,t)});function ta(e){return wr(ea,e)}let na=r(`ZodISODate`,(e,t)=>{Jt.init(e,t),A.init(e,t)});function ra(e){return Tr(na,e)}let ia=r(`ZodISOTime`,(e,t)=>{Yt.init(e,t),A.init(e,t)});function aa(e){return Er(ia,e)}let oa=r(`ZodISODuration`,(e,t)=>{Xt.init(e,t),A.init(e,t)});function sa(e){return Dr(oa,e)}let ca=r(`ZodError`,(e,t)=>{Te.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>De(e,t)},flatten:{value:t=>Ee(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,l,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,l,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),la=Oe(ca),ua=ke(ca),da=Ae(ca),fa=Me(ca),pa=S(ca),ma=Pe(ca),ha=Fe(ca),ga=Ie(ca),_a=Le(ca),va=Re(ca),ya=ze(ca),ba=Be(ca),xa=new WeakMap;function Sa(e,t,n){let r=Object.getPrototypeOf(e),i=xa.get(r);if(i||(i=new Set,xa.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}let O=r(`ZodType`,(e,t)=>(T.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:di(e,`input`),output:di(e,`output`)}}),e.toJSONSchema=ui(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>la(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>da(e,t,n),e.parseAsync=async(t,n)=>ua(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>fa(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>pa(e,t,n),e.decode=(t,n)=>ma(e,t,n),e.encodeAsync=async(t,n)=>ha(e,t,n),e.decodeAsync=async(t,n)=>ga(e,t,n),e.safeEncode=(t,n)=>_a(e,t,n),e.safeDecode=(t,n)=>va(e,t,n),e.safeEncodeAsync=async(t,n)=>ya(e,t,n),e.safeDecodeAsync=async(t,n)=>ba(e,t,n),Sa(e,`ZodType`,{check(...e){let t=this.def;return this.clone(_(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return le(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Lo(e,t))},superRefine(e,t){return this.check(Ro(e,t))},overwrite(e){return this.check(Xr(e))},optional(){return V(this)},exactOptional(){return vo(this)},nullable(){return bo(this)},nullish(){return V(bo(this))},nonoptional(e){return Eo(this,e)},array(){return P(this)},or(e){return L([this,e])},and(e){return lo(this,e)},transform(e){return Ao(this,ho(e))},default(e){return So(this,e)},prefault(e){return wo(this,e)},catch(e){return Oo(this,e)},pipe(e){return Ao(this,e)},readonly(){return No(this)},describe(e){let t=this.clone();return er.add(t,{description:e}),t},meta(...e){if(e.length===0)return er.get(this);let t=this.clone();return er.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return er.get(e)?.description},configurable:!0}),e)),Ca=r(`_ZodString`,(e,t)=>{Ft.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pi(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Sa(e,`_ZodString`,{regex(...e){return this.check(Wr(...e))},includes(...e){return this.check(qr(...e))},startsWith(...e){return this.check(Jr(...e))},endsWith(...e){return this.check(Yr(...e))},min(...e){return this.check(Hr(...e))},max(...e){return this.check(Vr(...e))},length(...e){return this.check(Ur(...e))},nonempty(...e){return this.check(Hr(1,...e))},lowercase(e){return this.check(Gr(e))},uppercase(e){return this.check(Kr(e))},trim(){return this.check(Qr())},normalize(...e){return this.check(Zr(...e))},toLowerCase(){return this.check($r())},toUpperCase(){return this.check(ei())},slugify(){return this.check(ti())}})}),wa=r(`ZodString`,(e,t)=>{Ft.init(e,t),Ca.init(e,t),e.email=t=>e.check(nr(Ta,t)),e.url=t=>e.check(cr(ka,t)),e.jwt=t=>e.check(Cr(Ga,t)),e.emoji=t=>e.check(lr(ja,t)),e.guid=t=>e.check(rr(Da,t)),e.uuid=t=>e.check(ir(Oa,t)),e.uuidv4=t=>e.check(ar(Oa,t)),e.uuidv6=t=>e.check(or(Oa,t)),e.uuidv7=t=>e.check(sr(Oa,t)),e.nanoid=t=>e.check(ur(Ma,t)),e.guid=t=>e.check(rr(Da,t)),e.cuid=t=>e.check(dr(Na,t)),e.cuid2=t=>e.check(fr(Pa,t)),e.ulid=t=>e.check(pr(Fa,t)),e.base64=t=>e.check(br(Ha,t)),e.base64url=t=>e.check(xr(Ua,t)),e.xid=t=>e.check(mr(Ia,t)),e.ksuid=t=>e.check(hr(La,t)),e.ipv4=t=>e.check(gr(Ra,t)),e.ipv6=t=>e.check(_r(za,t)),e.cidrv4=t=>e.check(vr(Ba,t)),e.cidrv6=t=>e.check(yr(Va,t)),e.e164=t=>e.check(Sr(Wa,t)),e.datetime=t=>e.check(ta(t)),e.date=t=>e.check(ra(t)),e.time=t=>e.check(aa(t)),e.duration=t=>e.check(sa(t))});function k(e){return tr(wa,e)}let A=r(`ZodStringFormat`,(e,t)=>{E.init(e,t),Ca.init(e,t)}),Ta=r(`ZodEmail`,(e,t)=>{Rt.init(e,t),A.init(e,t)});function Ea(e){return nr(Ta,e)}let Da=r(`ZodGUID`,(e,t)=>{It.init(e,t),A.init(e,t)}),Oa=r(`ZodUUID`,(e,t)=>{Lt.init(e,t),A.init(e,t)}),ka=r(`ZodURL`,(e,t)=>{zt.init(e,t),A.init(e,t)});function Aa(e){return cr(ka,e)}let ja=r(`ZodEmoji`,(e,t)=>{Bt.init(e,t),A.init(e,t)}),Ma=r(`ZodNanoID`,(e,t)=>{Vt.init(e,t),A.init(e,t)}),Na=r(`ZodCUID`,(e,t)=>{Ht.init(e,t),A.init(e,t)}),Pa=r(`ZodCUID2`,(e,t)=>{Ut.init(e,t),A.init(e,t)}),Fa=r(`ZodULID`,(e,t)=>{Wt.init(e,t),A.init(e,t)}),Ia=r(`ZodXID`,(e,t)=>{Gt.init(e,t),A.init(e,t)}),La=r(`ZodKSUID`,(e,t)=>{Kt.init(e,t),A.init(e,t)}),Ra=r(`ZodIPv4`,(e,t)=>{Zt.init(e,t),A.init(e,t)}),za=r(`ZodIPv6`,(e,t)=>{Qt.init(e,t),A.init(e,t)}),Ba=r(`ZodCIDRv4`,(e,t)=>{$t.init(e,t),A.init(e,t)}),Va=r(`ZodCIDRv6`,(e,t)=>{en.init(e,t),A.init(e,t)}),Ha=r(`ZodBase64`,(e,t)=>{nn.init(e,t),A.init(e,t)}),Ua=r(`ZodBase64URL`,(e,t)=>{an.init(e,t),A.init(e,t)}),Wa=r(`ZodE164`,(e,t)=>{on.init(e,t),A.init(e,t)}),Ga=r(`ZodJWT`,(e,t)=>{cn.init(e,t),A.init(e,t)}),Ka=r(`ZodNumber`,(e,t)=>{ln.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mi(e,t,n,r),Sa(e,`ZodNumber`,{gt(e,t){return this.check(Rr(e,t))},gte(e,t){return this.check(zr(e,t))},min(e,t){return this.check(zr(e,t))},lt(e,t){return this.check(Ir(e,t))},lte(e,t){return this.check(Lr(e,t))},max(e,t){return this.check(Lr(e,t))},int(e){return this.check(Ja(e))},safe(e){return this.check(Ja(e))},positive(e){return this.check(Rr(0,e))},nonnegative(e){return this.check(zr(0,e))},negative(e){return this.check(Ir(0,e))},nonpositive(e){return this.check(Lr(0,e))},multipleOf(e,t){return this.check(Br(e,t))},step(e,t){return this.check(Br(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function j(e){return Or(Ka,e)}let qa=r(`ZodNumberFormat`,(e,t)=>{un.init(e,t),Ka.init(e,t)});function Ja(e){return Ar(qa,e)}let Ya=r(`ZodBoolean`,(e,t)=>{dn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hi(e,t,n,r)});function M(e){return jr(Ya,e)}let Xa=r(`ZodNull`,(e,t)=>{fn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vi(e,t,n,r)});function Za(e){return Mr(Xa,e)}let Qa=r(`ZodAny`,(e,t)=>{pn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function $a(){return Nr(Qa)}let eo=r(`ZodUnknown`,(e,t)=>{mn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function N(){return Pr(eo)}let to=r(`ZodNever`,(e,t)=>{hn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xi(e,t,n,r)});function no(e){return Fr(to,e)}let ro=r(`ZodArray`,(e,t)=>{_n.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ii(e,t,n,r),e.element=t.element,Sa(e,`ZodArray`,{min(e,t){return this.check(Hr(e,t))},nonempty(e){return this.check(Hr(1,e))},max(e,t){return this.check(Vr(e,t))},length(e,t){return this.check(Ur(e,t))},unwrap(){return this.element}})});function P(e,t){return ni(ro,e,t)}let io=r(`ZodObject`,(e,t)=>{Sn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Li(e,t,n,r),h(e,`shape`,()=>t.shape),Sa(e,`ZodObject`,{keyof(){return z(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:N()})},loose(){return this.clone({...this._zod.def,catchall:N()})},strict(){return this.clone({...this._zod.def,catchall:no()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return me(this,e)},safeExtend(e){return he(this,e)},merge(e){return ge(this,e)},pick(e){return fe(this,e)},omit(e){return pe(this,e)},partial(...e){return _e(go,this,e[0])},required(...e){return ve(To,this,e[0])}})});function F(e,t){return new io({type:`object`,shape:e??{},...v(t)})}function I(e,t){return new io({type:`object`,shape:e,catchall:N(),...v(t)})}let ao=r(`ZodUnion`,(e,t)=>{wn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ri(e,t,n,r),e.options=t.options});function L(e,t){return new ao({type:`union`,options:e,...v(t)})}let oo=r(`ZodDiscriminatedUnion`,(e,t)=>{ao.init(e,t),Tn.init(e,t)});function so(e,t,n){return new oo({type:`union`,options:t,discriminator:e,...v(n)})}let co=r(`ZodIntersection`,(e,t)=>{En.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zi(e,t,n,r)});function lo(e,t){return new co({type:`intersection`,left:e,right:t})}let uo=r(`ZodRecord`,(e,t)=>{kn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vi(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function R(e,t,n){return!t||!t._zod?new uo({type:`record`,keyType:k(),valueType:e,...v(t)}):new uo({type:`record`,keyType:e,valueType:t,...v(n)})}let fo=r(`ZodEnum`,(e,t)=>{An.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ti(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new fo({...t,checks:[],...v(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new fo({...t,checks:[],...v(r),entries:i})}});function z(e,t){return new fo({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...v(t)})}let po=r(`ZodLiteral`,(e,t)=>{jn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ei(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function B(e,t){return new po({type:`literal`,values:Array.isArray(e)?e:[e],...v(t)})}let mo=r(`ZodTransform`,(e,t)=>{Mn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ni(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new a(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Ce(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(Ce(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function ho(e){return new mo({type:`transform`,transform:e})}let go=r(`ZodOptional`,(e,t)=>{Pn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function V(e){return new go({type:`optional`,innerType:e})}let _o=r(`ZodExactOptional`,(e,t)=>{Fn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function vo(e){return new _o({type:`optional`,innerType:e})}let yo=r(`ZodNullable`,(e,t)=>{In.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function bo(e){return new yo({type:`nullable`,innerType:e})}let xo=r(`ZodDefault`,(e,t)=>{Ln.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function So(e,t){return new xo({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():oe(t)}})}let Co=r(`ZodPrefault`,(e,t)=>{zn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wo(e,t){return new Co({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():oe(t)}})}let To=r(`ZodNonOptional`,(e,t)=>{Bn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ui(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Eo(e,t){return new To({type:`nonoptional`,innerType:e,...v(t)})}let Do=r(`ZodCatch`,(e,t)=>{Hn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ki(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Oo(e,t){return new Do({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}let ko=r(`ZodPipe`,(e,t)=>{Un.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qi(e,t,n,r),e.in=t.in,e.out=t.out});function Ao(e,t){return new ko({type:`pipe`,in:e,out:t})}let jo=r(`ZodPreprocess`,(e,t)=>{ko.init(e,t),Gn.init(e,t)}),Mo=r(`ZodReadonly`,(e,t)=>{Kn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ji(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function No(e){return new Mo({type:`readonly`,innerType:e})}let Po=r(`ZodLazy`,(e,t)=>{Jn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zi(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Fo(e){return new Po({type:`lazy`,getter:e})}let Io=r(`ZodCustom`,(e,t)=>{Yn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ji(e,t,n,r)});function Lo(e,t={}){return ri(Io,e,t)}function Ro(e,t){return ii(e,t)}function zo(e,t){return new jo({type:`pipe`,in:ho(e),out:t})}let Bo={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var Vo;Vo||={};function Ho(e){return kr(Ka,e)}let Uo=[`2025-11-25`,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Wo=`io.modelcontextprotocol/protocolVersion`,Go=`io.modelcontextprotocol/clientInfo`,Ko=`io.modelcontextprotocol/serverInfo`,qo=`io.modelcontextprotocol/clientCapabilities`,Jo=`io.modelcontextprotocol/logLevel`,Yo=Fo(()=>L([k(),j(),M(),Za(),R(k(),Yo),P(Yo)])),H=R(k(),Yo),Xo=P(Yo),Zo=L([k(),j().int()]),Qo=k(),$o=F({ttl:j().optional()}),es=F({taskId:k()}),ts=I({progressToken:Zo.optional(),"io.modelcontextprotocol/related-task":es.optional()}),U=F({_meta:ts.optional()}),ns=U.extend({task:$o.optional()}),W=F({method:k(),params:U.loose().optional()}),rs=F({_meta:ts.optional()}),is=F({method:k(),params:rs.loose().optional()}),as=I({get[Ko](){return ys.optional().catch(void 0)}}),G=I({_meta:as.optional()}),os=L([k(),j().int()]),ss=F({jsonrpc:B(`2.0`),id:os,...W.shape}).strict(),cs=F({jsonrpc:B(`2.0`),...is.shape}).strict(),ls=F({jsonrpc:B(`2.0`),id:os,result:G}).strict(),us=F({jsonrpc:B(`2.0`),id:os.optional(),error:F({code:j().int(),message:k(),data:N().optional()})}).strict(),ds=L([ss,cs,ls,us]),fs=L([ls,us]),ps=G.strict(),ms=rs.extend({requestId:os.optional(),reason:k().optional()}),hs=is.extend({method:B(`notifications/cancelled`),params:ms}),gs=F({src:k(),mimeType:k().optional(),sizes:P(k()).optional(),theme:z([`light`,`dark`]).optional()}),_s=F({icons:P(gs).optional()}),vs=F({name:k(),title:k().optional()}),ys=vs.extend({...vs.shape,..._s.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),bs=zo(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,lo(F({form:lo(F({applyDefaults:M().optional()}),H).optional(),url:H.optional()}),H.optional())),xs=I({list:H.optional(),cancel:H.optional(),requests:I({sampling:I({createMessage:H.optional()}).optional(),elicitation:I({create:H.optional()}).optional()}).optional()}),Ss=I({list:H.optional(),cancel:H.optional(),requests:I({tools:I({call:H.optional()}).optional()}).optional()}),Cs=F({experimental:R(k(),H).optional(),sampling:F({context:H.optional(),tools:H.optional()}).optional(),elicitation:bs.optional(),roots:F({listChanged:M().optional()}).optional(),tasks:xs.optional(),extensions:R(k(),H).optional()}),ws=U.extend({protocolVersion:k(),capabilities:Cs,clientInfo:ys}),Ts=W.extend({method:B(`initialize`),params:ws}),Es=F({experimental:R(k(),H).optional(),logging:H.optional(),completions:H.optional(),prompts:F({listChanged:M().optional()}).optional(),resources:F({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:F({listChanged:M().optional()}).optional(),tasks:Ss.optional(),extensions:R(k(),H).optional()}),Ds=G.extend({protocolVersion:k(),capabilities:Es,serverInfo:ys,instructions:k().optional()}),Os=is.extend({method:B(`notifications/initialized`),params:rs.optional()}),ks=W.extend({method:B(`server/discover`),params:U.optional()}),As=G.extend({supportedVersions:P(k()),capabilities:Es,instructions:k().optional()}),js=W.extend({method:B(`ping`),params:U.optional()}),Ms=F({progress:j(),total:V(j()),message:V(k())}),Ns=F({...rs.shape,...Ms.shape,progressToken:Zo}),Ps=is.extend({method:B(`notifications/progress`),params:Ns}),Fs=U.extend({cursor:Qo.optional()}),Is=W.extend({params:Fs.optional()}),Ls=G.extend({nextCursor:Qo.optional()}),Rs=F({uri:k(),mimeType:V(k()),_meta:R(k(),N()).optional()}),zs=Rs.extend({text:k()}),Bs=k().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Vs=Rs.extend({blob:Bs}),Hs=z([`user`,`assistant`]),Us=F({audience:P(Hs).optional(),priority:j().min(0).max(1).optional(),lastModified:ta({offset:!0}).optional()}),Ws=F({...vs.shape,..._s.shape,uri:k(),description:V(k()),mimeType:V(k()),size:V(j()),annotations:Us.optional(),_meta:V(I({}))}),Gs=F({...vs.shape,..._s.shape,uriTemplate:k(),description:V(k()),mimeType:V(k()),annotations:Us.optional(),_meta:V(I({}))}),Ks=Is.extend({method:B(`resources/list`)}),qs=Ls.extend({resources:P(Ws)}),Js=Is.extend({method:B(`resources/templates/list`)}),Ys=Ls.extend({resourceTemplates:P(Gs)}),Xs=U.extend({uri:k()}),Zs=Xs,Qs=W.extend({method:B(`resources/read`),params:Zs}),$s=G.extend({contents:P(L([zs,Vs]))}),ec=is.extend({method:B(`notifications/resources/list_changed`),params:rs.optional()}),tc=Xs,nc=W.extend({method:B(`resources/subscribe`),params:tc}),rc=Xs,ic=W.extend({method:B(`resources/unsubscribe`),params:rc}),ac=F({toolsListChanged:M().optional(),promptsListChanged:M().optional(),resourcesListChanged:M().optional(),resourceSubscriptions:P(k()).optional()}),oc=U.extend({notifications:ac}),sc=W.extend({method:B(`subscriptions/listen`),params:oc}),cc=rs.extend({notifications:ac}),lc=is.extend({method:B(`notifications/subscriptions/acknowledged`),params:cc}),uc=as.extend({"io.modelcontextprotocol/subscriptionId":os}),dc=G.extend({_meta:uc}),fc=rs.extend({uri:k()}),pc=is.extend({method:B(`notifications/resources/updated`),params:fc}),mc=F({name:k(),description:V(k()),required:V(M())}),hc=F({...vs.shape,..._s.shape,description:V(k()),arguments:V(P(mc)),_meta:V(I({}))}),gc=Is.extend({method:B(`prompts/list`)}),_c=Ls.extend({prompts:P(hc)}),vc=U.extend({name:k(),arguments:R(k(),k()).optional()}),yc=W.extend({method:B(`prompts/get`),params:vc}),bc=F({type:B(`text`),text:k(),annotations:Us.optional(),_meta:R(k(),N()).optional()}),xc=F({type:B(`image`),data:Bs,mimeType:k(),annotations:Us.optional(),_meta:R(k(),N()).optional()}),Sc=F({type:B(`audio`),data:Bs,mimeType:k(),annotations:Us.optional(),_meta:R(k(),N()).optional()}),Cc=F({type:B(`tool_use`),name:k(),id:k(),input:R(k(),N()),_meta:R(k(),N()).optional()}),wc=F({type:B(`resource`),resource:L([zs,Vs]),annotations:Us.optional(),_meta:R(k(),N()).optional()}),Tc=Ws.extend({type:B(`resource_link`)}),Ec=L([bc,xc,Sc,Tc,wc]),Dc=F({role:Hs,content:Ec}),Oc=G.extend({description:k().optional(),messages:P(Dc)}),kc=is.extend({method:B(`notifications/prompts/list_changed`),params:rs.optional()}),Ac=F({title:k().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),jc=F({taskSupport:z([`required`,`optional`,`forbidden`]).optional()}),Mc=F({...vs.shape,..._s.shape,description:k().optional(),inputSchema:F({type:B(`object`),properties:R(k(),Yo).optional(),required:P(k()).optional()}).catchall(N()),outputSchema:I({$schema:k().optional()}).optional(),annotations:Ac.optional(),execution:jc.optional(),_meta:R(k(),N()).optional()}),Nc=Is.extend({method:B(`tools/list`)}),Pc=Ls.extend({tools:P(Mc)}),Fc=G.extend({content:P(Ec).default([]),structuredContent:N().optional(),isError:M().optional()}),Ic=Fc.or(G.extend({toolResult:N()})),Lc=ns.extend({name:k(),arguments:R(k(),N()).optional()}),Rc=W.extend({method:B(`tools/call`),params:Lc}),zc=is.extend({method:B(`notifications/tools/list_changed`),params:rs.optional()}),Bc=F({autoRefresh:M().default(!0),debounceMs:j().int().nonnegative().default(300)}),Vc=z([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Hc=U.extend({level:Vc}),Uc=W.extend({method:B(`logging/setLevel`),params:Hc}),Wc=rs.extend({level:Vc,logger:k().optional(),data:N()}),Gc=is.extend({method:B(`notifications/message`),params:Wc}),Kc=F({name:k().optional()}),qc=F({hints:P(Kc).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),Jc=F({mode:z([`auto`,`required`,`none`]).optional()}),Yc=F({type:B(`tool_result`),toolUseId:k().describe(`The unique identifier for the corresponding tool call.`),content:P(Ec),structuredContent:N().optional(),isError:M().optional(),_meta:R(k(),N()).optional()}),Xc=so(`type`,[bc,xc,Sc]),Zc=so(`type`,[bc,xc,Sc,Cc,Yc]),Qc=F({role:Hs,content:L([Zc,P(Zc)]),_meta:R(k(),N()).optional()}),$c=ns.extend({messages:P(Qc),modelPreferences:qc.optional(),systemPrompt:k().optional(),includeContext:z([`none`,`thisServer`,`allServers`]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:P(k()).optional(),metadata:H.optional(),tools:P(Mc).optional(),toolChoice:Jc.optional()}),el=W.extend({method:B(`sampling/createMessage`),params:$c}),tl=G.extend({model:k(),stopReason:V(z([`endTurn`,`stopSequence`,`maxTokens`]).or(k())),role:Hs,content:Xc}),nl=G.extend({model:k(),stopReason:V(z([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(k())),role:Hs,content:L([Zc,P(Zc)])}),rl=F({type:B(`boolean`),title:k().optional(),description:k().optional(),default:M().optional()}),il=F({type:B(`string`),title:k().optional(),description:k().optional(),minLength:j().optional(),maxLength:j().optional(),format:z([`email`,`uri`,`date`,`date-time`]).optional(),default:k().optional()}),al=F({type:z([`number`,`integer`]),title:k().optional(),description:k().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),ol=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),default:k().optional()}),sl=F({type:B(`string`),title:k().optional(),description:k().optional(),oneOf:P(F({const:k(),title:k()})),default:k().optional()}),cl=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),enumNames:P(k()).optional(),default:k().optional()}),ll=L([ol,sl]),ul=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({type:B(`string`),enum:P(k())}),default:P(k()).optional()}),dl=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({anyOf:P(F({const:k(),title:k()}))}),default:P(k()).optional()}),fl=L([ul,dl]),pl=L([cl,ll,fl]),ml=L([pl,rl,il,al]),hl=ns.extend({mode:B(`form`).optional(),message:k(),requestedSchema:F({type:B(`object`),properties:R(k(),ml),required:P(k()).optional()}).catchall(N())}),gl=ns.extend({mode:B(`url`),message:k(),elicitationId:k(),url:k().url()}),_l=L([hl,gl]),vl=W.extend({method:B(`elicitation/create`),params:_l}),yl=rs.extend({elicitationId:k()}),bl=is.extend({method:B(`notifications/elicitation/complete`),params:yl}),xl=G.extend({action:z([`accept`,`decline`,`cancel`]),content:zo(e=>e===null?void 0:e,R(k(),L([k(),j(),M(),P(k())])).optional())}),Sl=F({type:B(`ref/resource`),uri:k()}),Cl=F({type:B(`ref/prompt`),name:k()}),wl=U.extend({ref:L([Cl,Sl]),argument:F({name:k(),value:k()}),context:F({arguments:R(k(),k()).optional()}).optional()}),Tl=W.extend({method:B(`completion/complete`),params:wl}),El=G.extend({completion:I({values:P(k()).max(100),total:V(j().int()),hasMore:V(M())})}),Dl=F({uri:k().startsWith(`file://`),name:k().optional(),_meta:R(k(),N()).optional()}),Ol=W.extend({method:B(`roots/list`),params:U.optional()}),kl=G.extend({roots:P(Dl)}),Al=is.extend({method:B(`notifications/roots/list_changed`),params:rs.optional()}),jl=I({ttl:j().optional(),pollInterval:j().optional()}),Ml=z([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Nl=F({taskId:k(),status:Ml,ttl:L([j(),Za()]),createdAt:k(),lastUpdatedAt:k(),pollInterval:V(j()),statusMessage:V(k())}),Pl=G.extend({task:Nl}),Fl=rs.merge(Nl),Il=is.extend({method:B(`notifications/tasks/status`),params:Fl}),Ll=W.extend({method:B(`tasks/get`),params:U.extend({taskId:k()})}),Rl=G.merge(Nl),zl=W.extend({method:B(`tasks/result`),params:U.extend({taskId:k()})}),Bl=G.loose(),Vl=Is.extend({method:B(`tasks/list`)}),Hl=Ls.extend({tasks:P(Nl)}),Ul=W.extend({method:B(`tasks/cancel`),params:U.extend({taskId:k()})}),Wl=G.merge(Nl),Gl=L([js,Ts,ks,Tl,Uc,yc,gc,Ks,Js,Qs,nc,ic,sc,Rc,Nc]),Kl=L([hs,Ps,Os,Al]),ql=L([ps,tl,nl,xl,kl]),Jl=L([js,el,vl,Ol]),Yl=L([hs,Ps,Gc,pc,ec,zc,kc,lc,bl]),Xl=L([ps,Ds,As,El,Oc,_c,qs,Ys,$s,Fc,Pc,dc]),K=Aa().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Bo.custom,message:`URL must be parseable`,fatal:!0}),n}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),Zl=I({resource:k().url(),authorization_servers:P(K).optional(),jwks_uri:k().url().optional(),scopes_supported:P(k()).optional(),bearer_methods_supported:P(k()).optional(),resource_signing_alg_values_supported:P(k()).optional(),resource_name:k().optional(),resource_documentation:k().optional(),resource_policy_uri:k().url().optional(),resource_tos_uri:k().url().optional(),tls_client_certificate_bound_access_tokens:M().optional(),authorization_details_types_supported:P(k()).optional(),dpop_signing_alg_values_supported:P(k()).optional(),dpop_bound_access_tokens_required:M().optional()}),Ql=I({issuer:k(),authorization_endpoint:K,token_endpoint:K,registration_endpoint:K.optional(),scopes_supported:P(k()).optional(),response_types_supported:P(k()),response_modes_supported:P(k()).optional(),grant_types_supported:P(k()).optional(),token_endpoint_auth_methods_supported:P(k()).optional(),token_endpoint_auth_signing_alg_values_supported:P(k()).optional(),service_documentation:K.optional(),revocation_endpoint:K.optional(),revocation_endpoint_auth_methods_supported:P(k()).optional(),revocation_endpoint_auth_signing_alg_values_supported:P(k()).optional(),introspection_endpoint:k().optional(),introspection_endpoint_auth_methods_supported:P(k()).optional(),introspection_endpoint_auth_signing_alg_values_supported:P(k()).optional(),code_challenge_methods_supported:P(k()).optional(),client_id_metadata_document_supported:M().optional(),authorization_response_iss_parameter_supported:M().optional().catch(void 0)}),$l=I({issuer:k(),authorization_endpoint:K,token_endpoint:K,userinfo_endpoint:K.optional(),jwks_uri:K,registration_endpoint:K.optional(),scopes_supported:P(k()).optional(),response_types_supported:P(k()),response_modes_supported:P(k()).optional(),grant_types_supported:P(k()).optional(),acr_values_supported:P(k()).optional(),subject_types_supported:P(k()),id_token_signing_alg_values_supported:P(k()),id_token_encryption_alg_values_supported:P(k()).optional(),id_token_encryption_enc_values_supported:P(k()).optional(),userinfo_signing_alg_values_supported:P(k()).optional(),userinfo_encryption_alg_values_supported:P(k()).optional(),userinfo_encryption_enc_values_supported:P(k()).optional(),request_object_signing_alg_values_supported:P(k()).optional(),request_object_encryption_alg_values_supported:P(k()).optional(),request_object_encryption_enc_values_supported:P(k()).optional(),token_endpoint_auth_methods_supported:P(k()).optional(),token_endpoint_auth_signing_alg_values_supported:P(k()).optional(),display_values_supported:P(k()).optional(),claim_types_supported:P(k()).optional(),claims_supported:P(k()).optional(),service_documentation:k().optional(),claims_locales_supported:P(k()).optional(),ui_locales_supported:P(k()).optional(),claims_parameter_supported:M().optional(),request_parameter_supported:M().optional(),request_uri_parameter_supported:M().optional(),require_request_uri_registration:M().optional(),op_policy_uri:K.optional(),op_tos_uri:K.optional(),client_id_metadata_document_supported:M().optional(),authorization_response_iss_parameter_supported:M().optional().catch(void 0)}),eu=F({...$l.shape,...Ql.pick({code_challenge_methods_supported:!0}).shape}),tu=F({access_token:k(),id_token:k().optional(),token_type:k(),expires_in:Ho().optional(),scope:k().optional(),refresh_token:k().optional()}).strip(),nu=F({issued_token_type:B(`urn:ietf:params:oauth:token-type:id-jag`),access_token:k(),token_type:k().optional(),expires_in:j().optional(),scope:k().optional()}).strip(),ru=F({error:k(),error_description:k().optional(),error_uri:k().optional()}),iu=K.optional().or(B(``).transform(()=>void 0)),au=F({redirect_uris:P(K),token_endpoint_auth_method:k().optional(),grant_types:P(k()).optional(),response_types:P(k()).optional(),application_type:k().optional(),client_name:k().optional(),client_uri:K.optional(),logo_uri:iu,scope:k().optional(),contacts:P(k()).optional(),tos_uri:iu,policy_uri:k().optional(),jwks_uri:K.optional(),jwks:$a().optional(),software_id:k().optional(),software_version:k().optional(),software_statement:k().optional()}).strip(),ou=F({client_id:k(),client_secret:k().optional(),client_id_issued_at:j().optional(),client_secret_expires_at:j().optional()}).strip(),su=au.merge(ou),cu=F({error:k(),error_description:k().optional()}).strip(),lu=F({token:k(),token_type_hint:k().optional()}).strip();function uu(e,t,n){return typeof e==`object`&&!!e&&`channel`in e&&e.channel===t&&`type`in e&&e.type===`mcp`&&`direction`in e&&e.direction===n&&`payload`in e}function du(e,t,n,r,i){e.postMessage({channel:n,type:`mcp`,direction:r,payload:i},t)}var fu=class{_started=!1;_closed=!1;_allowedOrigins;_channelId;_messageHandler;_clientOrigin;onclientorigin;onclose;onerror;onmessage;constructor(e){if(!e.allowedOrigins?.length)throw Error(`At least one allowed origin must be specified`);this._allowedOrigins=new Set(e.allowedOrigins),this._channelId=e.channelId??`mcp-iframe`}get clientOrigin(){return this._clientOrigin}async start(){if(this._closed)throw Error(`IframeChildTransport cannot be restarted after it closes`);if(this._started)throw Error(`Transport already started`);this._messageHandler=e=>{if(e.source!==window.parent||!this._allowedOrigins.has(`*`)&&!this._allowedOrigins.has(e.origin)||!uu(e.data,this._channelId,`client-to-server`))return;this._clientOrigin!==e.origin&&(this._clientOrigin=e.origin,this.onclientorigin?.(e.origin));let{payload:t}=e.data;if(t===`mcp-check-ready`){this._broadcastServerReady();return}try{let e=ds.parse(t);this.onmessage?.(e)}catch(e){this.onerror?.(Error(`Invalid message: ${e instanceof Error?e.message:String(e)}`))}},window.addEventListener(`message`,this._messageHandler),this._started=!0,this._broadcastServerReady()}async send(e,t){if(this._closed)throw Error(`Transport is closed`);if(!this._started)throw Error(`Transport not started`);if(!this._clientOrigin){console.debug(`[IframeChildTransport] No client connected, message not sent`);return}if(window.parent===window){console.debug(`[IframeChildTransport] Not running in an iframe, message not sent`);return}du(window.parent,this._clientOrigin,this._channelId,`server-to-client`,e)}async close(){this._closed||(this._closed=!0,this._started=!1,this._messageHandler&&=(window.removeEventListener(`message`,this._messageHandler),void 0),this._clientOrigin&&window.parent!==window&&du(window.parent,this._clientOrigin,this._channelId,`server-to-client`,`mcp-server-stopped`),this.onclose?.())}_broadcastServerReady(){window.parent!==window&&du(window.parent,`*`,this._channelId,`server-to-client`,`mcp-server-ready`)}},pu=class{_started=!1;_closed=!1;_allowedOrigins;_channelId;_messageHandler;onclose;onerror;onmessage;constructor(e){if(!e.allowedOrigins?.length)throw Error(`At least one allowed origin must be specified`);this._allowedOrigins=new Set(e.allowedOrigins),this._channelId=e.channelId??`mcp-default`}async start(){if(this._closed)throw Error(`TabServerTransport cannot be restarted after it closes`);if(this._started)throw Error(`Transport already started`);this._messageHandler=e=>{if(e.source!==window||!this._allowedOrigins.has(`*`)&&!this._allowedOrigins.has(e.origin)||!uu(e.data,this._channelId,`client-to-server`))return;let{payload:t}=e.data;if(t===`mcp-check-ready`){du(window,`*`,this._channelId,`server-to-client`,`mcp-server-ready`);return}try{let e=ds.parse(t);this.onmessage?.(e)}catch(e){this.onerror?.(Error(`Invalid message: ${e instanceof Error?e.message:String(e)}`))}},window.addEventListener(`message`,this._messageHandler),this._started=!0,du(window,`*`,this._channelId,`server-to-client`,`mcp-server-ready`)}async send(e,t){if(this._closed)throw Error(`Transport is closed`);if(!this._started)throw Error(`Transport not started`);du(window,`*`,this._channelId,`server-to-client`,e)}async close(){this._closed||(this._closed=!0,this._messageHandler&&=(window.removeEventListener(`message`,this._messageHandler),void 0),this._started&&du(window,`*`,this._channelId,`server-to-client`,`mcp-server-stopped`),this._started=!1,this.onclose?.())}};let mu=[`consequentialHint`,`debugging`,`readOnlyHint`,`untrustedContentHint`],hu=`webmcp-polyfill`,gu=globalThis.DOMException;var _u=class{#e;#t;#n;#r=new Set;#i=new Set;#a=Promise.withResolvers();#o=new Map;#s=new Set;#c;#l=!1;constructor(e,t){this.#t=e,this.#e=e.document,this.#n=t,this.#t.addEventListener(`message`,e=>this.#d(e),!0),this.#t.addEventListener(`pagehide`,()=>{this.#l=!0;for(let e of this.#s)e.end()}),this.#t.addEventListener(`pageshow`,e=>{e.persisted&&(this.#l=!1,this.#x())});for(let e of this.#x())this.#i.add(e);this.#i.size===0?this.#a.resolve():setTimeout(()=>{this.#i.clear(),this.#a.resolve()},500)}async allowed(){return this.#l?!1:this.#h(this.#e)}async getTools(e){await this.#a.promise;let t=this.#t.origin,n=[t,...e];return(await Promise.all(this.#b().map(async e=>{if(e===this.#t)return this.#n.getTools(t).map(e=>wu(e,this.#t,t));try{let t=await this.#u(e,n,{kind:`getTools`});if(!Array.isArray(t.value))throw TypeError(`Expected a tool list from the frame`);return t.value.map(n=>wu(Tu(n),e,t.origin))}catch(e){return e instanceof gu&&e.name===`UnknownError`||console.warn(`WebMCP: could not read tools from a frame.`,e),[]}}))).flat()}async execute(e,t,n,r,i){let a=await this.#u(e,[t],{kind:`execute`,name:n,input:r},i);if(typeof a.value!=`string`)throw q();return a.value}async notify(e){await this.#a.promise;let t=[this.#t.origin,...e];for(let e of this.#b()){if(e===this.#t){await this.#n.changed();continue}try{await this.#u(e,t,{kind:`changed`})}catch{}}}#u(e,t,n,r){return new Promise((i,a)=>{if(r?.throwIfAborted(),this.#l||!this.#v(e)){a(q());return}let o=crypto.randomUUID(),{port1:s,port2:c}=new MessageChannel,l,u=()=>{clearTimeout(h),g(),r?.removeEventListener(`abort`,f),this.#o.delete(o),s.close()},d=(e=q())=>{s.postMessage({kind:`cancel`}),u(),a(e)},f=()=>d(r?.reason),p=()=>{l===void 0&&this.#C(e),d()},m=r=>{if(r.source===e){if(this.#o.delete(o),t&&!t.includes(r.origin)){d();return}l=r.origin,clearTimeout(h),n.kind!==`execute`&&n.kind!==`changed`&&(h=setTimeout(p,500)),s.postMessage(n)}},h=setTimeout(p,500),g=this.#w(e,d);s.onmessage=e=>{let t=Du(e.data);if(t?.kind===`error`){d();return}t?.kind!==`result`||l===void 0||(u(),i({value:t.value,origin:l}))},s.onmessageerror=()=>d(),r?.addEventListener(`abort`,f,{once:!0}),this.#o.set(o,m);try{e.postMessage(`${hu}:connect:${o}`,`*`,[c])}catch{c.close(),d()}})}#d(e){let t=Eu(e.data);if(!t)return;e.stopImmediatePropagation();let n=e.source;if(!e.isTrusted||!n||!Ou(n)||!this.#v(n)||e.origin===`null`||this.#l)return;if(t.kind===`announce`){let t=!this.#r.has(n);if(this.#S(n),n.postMessage(`${hu}:present`,e.origin),!t||this.#t!==this.#t.top)return;for(let e of this.#r)e!==n&&e.postMessage(`${hu}:refresh`,`*`);return}if(t.kind===`present`){this.#S(n);return}if(t.kind===`refresh`){n===this.#t.top&&this.#x();return}if(t.kind===`ready`){this.#o.get(t.id)?.(e);return}let[r]=e.ports;t.kind!==`connect`||!t.id||!r||e.ports.length!==1||(this.#S(n),this.#f(n,e.origin,t.id,r))}#f(e,t,n,r){let i=new AbortController,a=!1,o=()=>{clearTimeout(l),u(),r.close()},s=()=>{i.abort(),o()},c=()=>{r.postMessage({kind:`error`}),s()},l=setTimeout(c,500),u=this.#w(e,c);r.onmessageerror=c,r.onmessage=async n=>{let u=Du(n.data);if(u?.kind===`cancel`){s();return}if(!a){a=!0,clearTimeout(l);try{let n=await this.#p(e,t,u,i.signal);r.postMessage({kind:`result`,value:n}),o()}catch{c()}}},e.postMessage(`${hu}:ready:${n}`,t)}async#p(e,t,n,r){if(!n||!this.#v(e))throw q();if(n.kind===`permission`){let{childIndex:e,childOrigin:t}=n;if(typeof e!=`number`||!Number.isInteger(e)||e<0||typeof t!=`string`)throw q();return this.#m(e,t)}if(!await this.allowed()||!await this.#g(e,t)||!this.#v(e))throw q();if(r.throwIfAborted(),n.kind===`getTools`)return this.#n.getTools(t);if(n.kind===`execute`&&typeof n.name==`string`&&typeof n.input==`string`)return this.#n.execute(t,n.name,n.input,r);if(n.kind===`changed`){await this.#n.changed();return}throw q()}async#m(e,t){let n=this.#t[e];return n!==void 0&&await this.allowed()&&vu(this.#e,n,t)}async#h(e){let t=Su(e);if(!t)return!1;let n=Cu(e);if(n!==void 0)return n;if(t===t.parent)return!0;let r=t.location.ancestorOrigins?.[0],i=yu(t.parent,r===void 0||r===t.origin);return i?vu(i,t,t.origin)&&await this.#h(i):this.#_(t,t.origin)}async#g(e,t){let n=yu(e,t===this.#t.origin);return n?this.#h(n):this.#_(e,t)}async#_(e,t){let n=e.parent;if(n===e)return!0;let r=-1;for(let t=0;t<n.length;t++)if(n[t]===e){r=t;break}if(r<0)return!1;if(n===this.#t)return await this.allowed()&&vu(this.#e,e,t);if(await this.#a.promise,!this.#r.has(n))return!1;try{let e=await this.#u(n,void 0,{kind:`permission`,childIndex:r,childOrigin:t});return e.value===!0&&await this.#g(n,e.origin)}catch{return!1}}#v(e){try{return!e.closed&&e!==this.#t&&e.top===this.#t.top}catch{return!1}}#y(){if(this.#t.closed)return[];for(let e of this.#r)this.#v(e)||this.#r.delete(e);let e=[this.#t,...this.#r];for(let t=this.#t.parent;t!==t.parent;t=t.parent)e.push(t);let t=new Set,n=[this.#t.top];for(;n.length;){let r=n.pop();if(t.has(r))continue;t.add(r);let i=[];for(let e=0;e<r.length;e++){let t=r[e];t&&i.push(t)}for(let t of e)t!==r&&t.parent===r&&!i.includes(t)&&i.push(t);n.push(...i.reverse())}return Array.from(t).filter(e=>e===this.#t||this.#v(e))}#b(){return this.#y().filter(e=>e===this.#t||this.#r.has(e))}#x(){let e=this.#y().filter(e=>e!==this.#t);for(let t of e)t.postMessage(`${hu}:announce`,`*`);return e}#S(e){this.#r.add(e),this.#i.delete(e),this.#i.size===0&&this.#a.resolve()}#C(e){this.#r.delete(e),this.#v(e)&&e.postMessage(`${hu}:announce`,`*`)}#w(e,t){let n={peer:e,end:t};return this.#s.add(n),this.#c===void 0&&(this.#c=this.#t.setInterval(()=>{for(let e of this.#s)this.#v(e.peer)||e.end()},100)),()=>{this.#s.delete(n),this.#s.size===0&&(this.#t.clearInterval(this.#c),this.#c=void 0)}}};function vu(e,t,n){let r=e.defaultView?.origin,i=bu(e,t,n===r);if(!i)return!1;let a=(i.getAttribute(`allow`)??``).split(`;`).map(e=>e.trim().split(/\s+/u)).find(([e])=>e===`tools`);if(!a)return n===r;let o=a.length===1?[`'src'`]:a.slice(1);if(o.includes(`'none'`))return!1;let s=i.hasAttribute(`srcdoc`)?null:i.getAttribute(`src`),c=s?URL.parse(s,e.baseURI):null,l=!s||c?.protocol===`about:`?r:c?.origin;return o.some(e=>e===`*`||e===`'self'`&&n===r||e===`'src'`&&n===l||e===n)}function yu(e,t){if(t)try{return e.document}catch{return}}function bu(e,t,n){if(n)try{let n=t.frameElement;if(n?.ownerDocument===e)return n}catch{}return xu(e,t)}function xu(e,t){let n=e.querySelectorAll(`iframe, frame`);for(let e of n)if(e.contentWindow===t)return e;for(let n of e.querySelectorAll(`*`)){if(!n.shadowRoot)continue;let e=xu(n.shadowRoot,t);if(e)return e}}function Su(e){let t=e.defaultView;return t&&!t.closed&&t.document===e?t:void 0}function Cu(e){let t=e,n=Du(t.permissionsPolicy??t.featurePolicy);if(typeof n?.features!=`function`||typeof n.allowsFeature!=`function`)return;let r=n.features();return Array.isArray(r)&&r.includes(`tools`)?!!n.allowsFeature(`tools`):void 0}function wu(e,t,n){let r=e.serializedSchema===void 0?void 0:JSON.parse(e.serializedSchema);return{...e.annotations!==void 0&&{annotations:{...e.annotations}},description:e.description,...r!==void 0&&{inputSchema:r},name:e.name,origin:n,title:e.title,window:t}}function Tu(e){let t=Du(e);if(!t||typeof t.name!=`string`||typeof t.title!=`string`||typeof t.description!=`string`||t.serializedSchema!==void 0&&typeof t.serializedSchema!=`string`)throw TypeError(`Invalid tool metadata from the frame`);let n={name:t.name,title:t.title,description:t.description,annotations:void 0,serializedSchema:t.serializedSchema};if(t.annotations===void 0)return n;let r=Du(t.annotations);if(!r)throw TypeError(`Invalid tool annotations from the frame`);let i={};for(let e of mu){let t=r[e];if(t!==void 0){if(typeof t!=`boolean`)throw TypeError(`Invalid ${e} annotation from the frame`);i[e]=t}}return n.annotations=i,n}function Eu(e){if(typeof e!=`string`)return;let[t,n=``,r=``,i]=e.split(`:`);return t===hu&&i===void 0?{kind:n,id:r}:void 0}function Du(e){if(!(typeof e!=`object`||!e||Array.isArray(e)))return e}function Ou(e){try{return`postMessage`in e&&`window`in e}catch{return!1}}function q(){return new gu(`Tool execution failed`,`UnknownError`)}let ku=new WeakSet,Au=new WeakMap,ju=new WeakMap;function Mu(e){return e.isTrusted&&(ku.has(e)||e.eventPhase!==Event.NONE&&e.target instanceof HTMLFormElement&&ju.has(e.target))}function Nu(e,t){if(!Mu(e))throw new DOMException(`respondWith() is only available during an agent-invoked submit event`,`InvalidStateError`);if(!e.defaultPrevented)throw new DOMException(`respondWith() requires preventDefault() during an agent-invoked submit event`,`InvalidStateError`);if(e.eventPhase===Event.NONE)throw new DOMException(`respondWith() is only available while the submit event is being dispatched`,`InvalidStateError`);ku.add(e);let n=Promise.resolve(t);Au.set(e,n),e.target instanceof HTMLFormElement&&ju.get(e.target)?.respond(e)}let Pu=new Set([`email`,`password`,`search`,`tel`,`text`,`url`]),Fu=new Set([...Pu,`date`,`datetime-local`,`month`,`number`,`time`,`week`]);function Iu(e){return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement}function Lu(e){return Object.getOwnPropertyDescriptor(HTMLFormElement.prototype,`elements`)?.get?.call(e)}function Ru(e,t){return Element.prototype.getAttribute.call(e,t)}function zu(e,t){return Element.prototype.hasAttribute.call(e,t)}function Bu(e){return Object.getOwnPropertyDescriptor(Node.prototype,`isConnected`)?.get?.call(e)}function Vu(e){return Object.getOwnPropertyDescriptor(Element.prototype,`shadowRoot`)?.get?.call(e)}function Hu(e){return HTMLFormElement.prototype.checkValidity.call(e)}function Uu(e,t){HTMLFormElement.prototype.requestSubmit.call(e,t)}function Wu(e){return[...Lu(e)].filter(e=>Iu(e)&&!e.matches(`:disabled`)&&!(`readOnly`in e&&e.readOnly&&(e instanceof HTMLTextAreaElement||Fu.has(e.type))))}function Gu(e){let t=new Map;for(let n of Wu(e)){let e=n.name.trim(),r=t.get(e);r?r.push(n):t.set(e,[n])}return t}function Ku(e){return[...e.labels??[]].map(e=>{let t=e.cloneNode(!0);return t instanceof HTMLElement?(t.querySelectorAll(`button, input, meter, output, progress, select, textarea`).forEach(e=>e.remove()),t.textContent?.trim()??``):``}).filter(Boolean).join(`; `)}function qu(e,t){for(let n=t[0]?.parentElement;n&&n!==e;n=n.parentElement)if(n instanceof HTMLFieldSetElement&&t.every(e=>n.contains(e)))return n}function Ju(e,t){if(t.length===1){let e=t[0];return e&&(e.getAttribute(`toolparamdescription`)||Ku(e)||e.getAttribute(`aria-description`))||void 0}return qu(e,t)?.getAttribute(`toolparamdescription`)||void 0}function Yu(e,t,n,r){let i=Ju(t,n),a=i&&r?`${i} (${r})`:i||r;return a?{...e,description:a}:e}function Xu(e,t){let n=e.getAttribute(t);if(n===null||n.trim()===``)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function Zu(e,t){let n=Number(e.getAttribute(`step`));return Number.isFinite(n)&&n>0?n:t}function Qu(e,t){let n=e/t;return Math.abs(n-Math.round(n))<2**-52*16}function $u(e,t){let n=t.getAttribute(`pattern`);if(n===null)return e;try{new RegExp(n,`v`)}catch{return e}return{...e,pattern:n}}function ed(e){let t={type:`number`},n=Xu(e,`min`),r=Xu(e,`max`);if(n!==void 0&&(t.minimum=n),r!==void 0&&(t.maximum=r),e.getAttribute(`step`)!==`any`){let r=Zu(e,1),i=Number(e.getAttribute(`value`));Qu(n??(Number.isFinite(i)?i:0),r)&&(t.multipleOf=r)}return t}function td(e,t){let n=Zu(e,60);return n<1?`${t}(:[0-5][0-9](\\.[0-9]{1,3})?)?$`:n<60?`${t}(:[0-5][0-9])?$`:`${t}$`}function nd(e){return{anyOf:e.map(e=>({type:`string`,const:e.value,title:e.textContent??``})),enum:e.map(e=>e.value)}}function rd(e){return{anyOf:e.map(e=>{let t=Ku(e),n={type:`string`,const:e.value};return t&&(n.title=t),n}),enum:e.map(e=>e.value)}}function id(e,t){return e instanceof HTMLInputElement&&e.type===t}function ad(e){if(Pu.has(e.type))return $u({type:`string`},e);switch(e.type){case`hidden`:return e.getAttribute(`toolparamdescription`)?{type:`string`}:void 0;case`number`:return $u(ed(e),e);case`range`:{let t=ed(e);return t.minimum??=0,t.maximum??=100,t}case`checkbox`:return{type:`boolean`};case`date`:return{type:`string`,format:`date`};case`month`:return{type:`string`,format:`^[0-9]{4}-(0[1-9]|1[0-2])$`};case`week`:return{type:`string`,format:`^[0-9]{4}-W(0[1-9]|[1-4][0-9]|5[0-3])$`};case`time`:return{type:`string`,format:td(e,`^([01][0-9]|2[0-3]):[0-5][0-9]`)};case`datetime-local`:return{type:`string`,format:td(e,`^[0-9]{4}-(0[1-9]|1[0-2])-[0-9]{2}T([01][0-9]|2[0-3]):[0-5][0-9]`)};case`color`:return{type:`string`,format:`^#[0-9a-zA-Z]{6}$`};default:return}}function od(e,t){let[n]=t;if(!n)return;let r;if(t.every(e=>id(e,`radio`)))r={type:`string`,...rd(t)};else if(t.length>1)t.every(e=>id(e,`checkbox`))&&(r={type:`array`,items:{type:`string`,...rd(t)},uniqueItems:!0});else if(n instanceof HTMLTextAreaElement)r={type:`string`};else if(n instanceof HTMLSelectElement){let e=nd([...n.options]);r=n.multiple?{type:`array`,items:{type:`string`,...e},uniqueItems:!0}:{type:`string`,...e}}else r=ad(n);let i=n.type===`date`?`Dates MUST be provided in 'YYYY-MM-DD' format.`:void 0;return r&&Yu(r,e,t,i)}function sd(e){let t={},n=[];for(let[r,i]of Gu(e)){if(!r)continue;let a=od(e,i);a&&(Object.defineProperty(t,r,{configurable:!0,enumerable:!0,value:a,writable:!0}),i.some(e=>e.required)&&n.push(r))}return{type:`object`,properties:t,required:n}}function cd(e){return{name:Ru(e,`toolname`)??``,title:Ru(e,`tooltitle`)??``,description:Ru(e,`tooldescription`)??``,inputSchema:sd(e),autosubmit:zu(e,`toolautosubmit`)}}function ld(e){if(typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return String(e)}function ud(e){if(typeof e==`boolean`)return e;if(typeof e==`number`&&Number.isInteger(e))return e!==0;if(typeof e==`string`){if(e===`1`||e.toLowerCase()===`true`)return!0;if(e===`0`||e.toLowerCase()===`false`)return!1}}function dd(e,t){if(!Array.isArray(e))return!1;let n=new Set(t);for(let t of e){let e=ld(t);if(e===void 0||!n.delete(e))return!1}return!0}function fd(e,t){if(t===``)return e.type!==`number`&&e.type!==`range`;let n=e.ownerDocument.createElement(`input`);return n.type=e.type,n.value=t,n.value!==``}function pd(e,t,n){let[r]=t;if(!r||!od(e,t))return!1;let i=ld(n);if(t.every(e=>id(e,`radio`)))return t.some(e=>e.value===i);if(t.length>1)return dd(n,new Set(t.map(e=>e.value)));if(r instanceof HTMLSelectElement){let e=new Set([...r.options].map(e=>e.value));return r.multiple?dd(n,e):i!==void 0&&e.has(i)}return r instanceof HTMLTextAreaElement?i!==void 0:r.type===`checkbox`?ud(n)!==void 0:i!==void 0&&fd(r,i)}function md(e){e.dispatchEvent(new Event(`input`,{bubbles:!0,composed:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0}))}function hd(e,t){if(e.value===t)return;let n=e instanceof HTMLInputElement?HTMLInputElement.prototype:HTMLTextAreaElement.prototype;Object.getOwnPropertyDescriptor(n,`value`)?.set?.call(e,t),md(e)}function gd(e,t){e.checked!==t&&(Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,`checked`)?.set?.call(e,t),md(e))}function _d(e,t){let[n]=e,r=ld(t),i=new Set(Array.isArray(t)?t.map(ld):[]);if(e.every(e=>id(e,`radio`))){let t=e.find(e=>e.value===r);t&&gd(t,!0)}else if(e.length>1)for(let t of e)t instanceof HTMLInputElement&&gd(t,i.has(t.value));else if(n instanceof HTMLSelectElement)if(n.multiple){let e=!1;for(let t of n.options){let n=i.has(t.value);t.selected!==n&&(t.selected=n,e=!0)}e&&md(n)}else r!==void 0&&n.value!==r&&(n.value=r,md(n));else if(n&&id(n,`checkbox`)){let e=ud(t);e!==void 0&&gd(n,e)}else n&&r!==void 0&&hd(n,r)}function vd(e,t){if(Array.isArray(t))throw q();let n=Gu(e),r=[];for(let[i,a]of Object.entries(t)){let t=n.get(i);if(!t||!pd(e,t,a))throw q();r.push({controls:t,value:a})}for(let{controls:e,value:t}of r)_d(e,t)}function yd(e){return[...Lu(e)].find(e=>!e.matches(`:disabled`)&&(e instanceof HTMLButtonElement&&e.type===`submit`||e instanceof HTMLInputElement&&[`image`,`submit`].includes(e.type)))}function bd(e,t){let n=new Event(e);return Object.defineProperty(n,"toolName",{enumerable:!0,value:t}),n}function xd(e,t,n,r,i){let{form:a}=t;return t.cancelPending?.(q()),new Promise((o,s)=>{let c=!1,l=()=>{EventTarget.prototype.removeEventListener.call(a,`invalid`,p,!0),i.removeEventListener(`abort`,m),ju.delete(a),t.cancelPending===d&&delete t.cancelPending},u=e=>{c||(c=!0,l(),e())},d=e=>u(()=>s(e)),f=e=>{e.then(e=>u(()=>o(e??null)),e=>u(()=>s(e)))},p=e=>{e.isTrusted&&queueMicrotask(()=>{Hu(a)||d(q())})},m=()=>{u(()=>{e.dispatchEvent(bd(`toolcancel`,n.name)),s(i.reason)})};if(ju.set(a,{complete(e){queueMicrotask(()=>{let t=Au.get(e);t?f(t):e.defaultPrevented?d(q()):u(()=>o(null))})},direct(){u(()=>o(null))},respond(e){queueMicrotask(()=>{let t=Au.get(e);t&&f(t)})}}),t.cancelPending=d,EventTarget.prototype.addEventListener.call(a,`invalid`,p,!0),i.addEventListener(`abort`,m,{once:!0}),!n.autosubmit){r?.focus(),e.dispatchEvent(bd(`toolactivated`,n.name));return}try{Uu(a,r),e.dispatchEvent(bd(`toolactivated`,n.name))}catch(e){d(e)}})}function Sd(e){let t=SubmitEvent.prototype;if(`agentInvoked`in t&&`respondWith`in t)return;`agentInvoked`in t||Object.defineProperty(t,"agentInvoked",{configurable:!0,enumerable:!0,get(){return Mu(this)}}),`respondWith`in t||Object.defineProperty(t,"respondWith",{configurable:!0,enumerable:!0,writable:!0,value(e){Nu(this,e)}});let n=new Map,r=new Map,i=new Map,a=e=>{if(!(e instanceof SubmitEvent)||!e.isTrusted||!(e.target instanceof HTMLFormElement))return;let t=ju.get(e.target);t&&(ku.add(e),t.complete(e))},o=e=>{if(!e.isTrusted||!(e.target instanceof HTMLFormElement))return;let t=e.target;queueMicrotask(()=>{e.defaultPrevented||n.get(t)?.cancelPending?.(q())})};function s(e){i.get(e)?.disconnect(),i.delete(e),e.removeEventListener(`reset`,o,!0),e.removeEventListener(`submit`,a,!0)}function c(e){if(i.has(e))return;let t=new MutationObserver(l);i.set(e,t),t.observe(e,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),e.addEventListener(`reset`,o,!0),e.addEventListener(`submit`,a,!0)}function l(){c(document);for(let e of i.keys())e instanceof ShadowRoot&&!e.host.isConnected&&s(e);let t=new Set,a=new Map,o=new Map;for(let e of i.keys())for(let n of e.querySelectorAll(`*`)){let e=Vu(n);if(e&&c(e),!(n instanceof HTMLFormElement)||!zu(n,`toolname`)||!zu(n,`tooldescription`)||!Bu(n))continue;let i=n;t.add(i);let s=cd(i),l=JSON.stringify(s),u=r.get(i);if(u===l)continue;r.delete(i);let d=o.get(s.name);if(d){if(u===void 0){r.set(i,l);continue}let e=a.get(d);e&&r.set(d,e.fingerprint),a.delete(d)}o.set(s.name,i),a.set(i,{definition:s,fingerprint:l})}for(let e of r.keys())t.has(e)||r.delete(e);for(let[e,t]of n)a.get(e)?.fingerprint!==t.fingerprint&&(t.cancelPending?.(q()),t.controller.abort(),n.delete(e));for(let[t,{definition:r,fingerprint:i}]of a){if(n.has(t))continue;let a=new AbortController,o={controller:a,fingerprint:i,form:t};n.set(t,o),e.registerTool({name:r.name,title:r.title,description:r.description,inputSchema:r.inputSchema,execute(n,i){let a=yd(t);if(!r.autosubmit&&!a)throw q();return vd(t,n),xd(e,o,r,a,i.signal)}},{signal:a.signal}).catch(e=>{a.abort(),!(e instanceof DOMException&&e.name===`AbortError`)&&console.error(`[webmcp] declarative form tool "${r.name}" was not registered:`,e)})}}let u=Object.getOwnPropertyDescriptor(Element.prototype,`attachShadow`);if(u?.configurable){let e=Element.prototype.attachShadow,t=function(t){let n=e.call(this,t);return n.mode===`open`&&Object.getOwnPropertyDescriptor(Node.prototype,`ownerDocument`)?.get?.call(this)===document&&Bu(this)&&c(n),n};Object.defineProperty(Element.prototype,"attachShadow",{...u,value:t})}let d=Object.getOwnPropertyDescriptor(HTMLFormElement.prototype,`submit`);if(d?.configurable){let e=HTMLFormElement.prototype.submit,t=function(){e.call(this),ju.get(this)?.direct()};Object.defineProperty(HTMLFormElement.prototype,"submit",{...d,value:t})}l()}
|
|
64
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function ci(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:di(t,`input`,e.processors),output:di(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function li(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return li(r.element,n);if(r.type===`set`)return li(r.valueType,n);if(r.type===`lazy`)return li(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return li(r.innerType,n);if(r.type===`intersection`)return li(r.left,n)||li(r.right,n);if(r.type===`record`||r.type===`map`)return li(r.keyType,n)||li(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:li(r.in,n)||li(r.out,n);if(r.type===`object`){for(let e in r.shape)if(li(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(li(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(li(e,n))return!0;return!!(r.rest&&li(r.rest,n))}return!1}let ui=(e,t={})=>n=>{let r=oi({...n,processors:t});return D(e,r),si(r,e),ci(r,e)},di=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=oi({...i??{},target:a,io:t,processors:n});return D(e,o),si(o,e),ci(o,e)},fi={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},pi=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=fi[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},mi=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},hi=(e,t,n,r)=>{n.type=`boolean`},gi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},_i=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},vi=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},yi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},bi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},xi=(e,t,n,r)=>{n.not={}},Si=(e,t,n,r)=>{},Ci=(e,t,n,r)=>{},wi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},Ti=(e,t,n,r)=>{let i=e._zod.def,a=c(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Ei=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0)if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a},Di=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},Oi=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},ki=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},Ai=(e,t,n,r)=>{n.type=`boolean`},ji=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Mi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},Ni=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Pi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},Fi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},Ii=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=D(a.element,t,{...r,path:[...r.path,`items`]})},Li=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=D(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=D(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Ri=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>D(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},zi=(e,t,n,r)=>{let i=e._zod.def,a=D(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=D(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},Bi=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>D(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?D(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},Vi=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=D(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=D(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=D(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},Hi=(e,t,n,r)=>{let i=e._zod.def,a=D(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Ui=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Wi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Gi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Ki=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},qi=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;D(o,t,r);let s=t.seen.get(e);s.ref=o},Ji=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Yi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Xi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Zi=(e,t,n,r)=>{let i=e._zod.innerType;D(i,t,r);let a=t.seen.get(e);a.ref=i},Qi={string:pi,number:mi,boolean:hi,bigint:gi,symbol:_i,null:vi,undefined:yi,void:bi,never:xi,any:Si,unknown:Ci,date:wi,enum:Ti,literal:Ei,nan:Di,template_literal:Oi,file:ki,success:Ai,custom:ji,function:Mi,transform:Ni,map:Pi,set:Fi,array:Ii,object:Li,union:Ri,intersection:zi,tuple:Bi,record:Vi,nullable:Hi,nonoptional:Ui,default:Wi,prefault:Gi,catch:Ki,pipe:qi,readonly:Ji,promise:Yi,optional:Xi,lazy:Zi};function $i(e,t){if(`_idmap`in e){let n=e,r=oi({...t,processors:Qi}),i={};for(let e of n._idmap.entries()){let[t,n]=e;D(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;si(r,n),a[t]=ci(r,n)}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=oi({...t,processors:Qi});return D(e,n),si(n,e),ci(n,e)}let ea=r(`ZodISODateTime`,(e,t)=>{qt.init(e,t),A.init(e,t)});function ta(e){return wr(ea,e)}let na=r(`ZodISODate`,(e,t)=>{Jt.init(e,t),A.init(e,t)});function ra(e){return Tr(na,e)}let ia=r(`ZodISOTime`,(e,t)=>{Yt.init(e,t),A.init(e,t)});function aa(e){return Er(ia,e)}let oa=r(`ZodISODuration`,(e,t)=>{Xt.init(e,t),A.init(e,t)});function sa(e){return Dr(oa,e)}let ca=r(`ZodError`,(e,t)=>{Te.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>De(e,t)},flatten:{value:t=>Ee(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,l,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,l,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),la=Oe(ca),ua=ke(ca),da=Ae(ca),fa=Me(ca),pa=S(ca),ma=Pe(ca),ha=Fe(ca),ga=Ie(ca),_a=Le(ca),va=Re(ca),ya=ze(ca),ba=Be(ca),xa=new WeakMap;function Sa(e,t,n){let r=Object.getPrototypeOf(e),i=xa.get(r);if(i||(i=new Set,xa.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}let O=r(`ZodType`,(e,t)=>(T.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:di(e,`input`),output:di(e,`output`)}}),e.toJSONSchema=ui(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>la(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>da(e,t,n),e.parseAsync=async(t,n)=>ua(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>fa(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>pa(e,t,n),e.decode=(t,n)=>ma(e,t,n),e.encodeAsync=async(t,n)=>ha(e,t,n),e.decodeAsync=async(t,n)=>ga(e,t,n),e.safeEncode=(t,n)=>_a(e,t,n),e.safeDecode=(t,n)=>va(e,t,n),e.safeEncodeAsync=async(t,n)=>ya(e,t,n),e.safeDecodeAsync=async(t,n)=>ba(e,t,n),Sa(e,`ZodType`,{check(...e){let t=this.def;return this.clone(_(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return le(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Lo(e,t))},superRefine(e,t){return this.check(Ro(e,t))},overwrite(e){return this.check(Xr(e))},optional(){return V(this)},exactOptional(){return vo(this)},nullable(){return bo(this)},nullish(){return V(bo(this))},nonoptional(e){return Eo(this,e)},array(){return P(this)},or(e){return L([this,e])},and(e){return lo(this,e)},transform(e){return Ao(this,ho(e))},default(e){return So(this,e)},prefault(e){return wo(this,e)},catch(e){return Oo(this,e)},pipe(e){return Ao(this,e)},readonly(){return No(this)},describe(e){let t=this.clone();return er.add(t,{description:e}),t},meta(...e){if(e.length===0)return er.get(this);let t=this.clone();return er.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return er.get(e)?.description},configurable:!0}),e)),Ca=r(`_ZodString`,(e,t)=>{Ft.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pi(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Sa(e,`_ZodString`,{regex(...e){return this.check(Wr(...e))},includes(...e){return this.check(qr(...e))},startsWith(...e){return this.check(Jr(...e))},endsWith(...e){return this.check(Yr(...e))},min(...e){return this.check(Hr(...e))},max(...e){return this.check(Vr(...e))},length(...e){return this.check(Ur(...e))},nonempty(...e){return this.check(Hr(1,...e))},lowercase(e){return this.check(Gr(e))},uppercase(e){return this.check(Kr(e))},trim(){return this.check(Qr())},normalize(...e){return this.check(Zr(...e))},toLowerCase(){return this.check($r())},toUpperCase(){return this.check(ei())},slugify(){return this.check(ti())}})}),wa=r(`ZodString`,(e,t)=>{Ft.init(e,t),Ca.init(e,t),e.email=t=>e.check(nr(Ta,t)),e.url=t=>e.check(cr(ka,t)),e.jwt=t=>e.check(Cr(Ga,t)),e.emoji=t=>e.check(lr(ja,t)),e.guid=t=>e.check(rr(Da,t)),e.uuid=t=>e.check(ir(Oa,t)),e.uuidv4=t=>e.check(ar(Oa,t)),e.uuidv6=t=>e.check(or(Oa,t)),e.uuidv7=t=>e.check(sr(Oa,t)),e.nanoid=t=>e.check(ur(Ma,t)),e.guid=t=>e.check(rr(Da,t)),e.cuid=t=>e.check(dr(Na,t)),e.cuid2=t=>e.check(fr(Pa,t)),e.ulid=t=>e.check(pr(Fa,t)),e.base64=t=>e.check(br(Ha,t)),e.base64url=t=>e.check(xr(Ua,t)),e.xid=t=>e.check(mr(Ia,t)),e.ksuid=t=>e.check(hr(La,t)),e.ipv4=t=>e.check(gr(Ra,t)),e.ipv6=t=>e.check(_r(za,t)),e.cidrv4=t=>e.check(vr(Ba,t)),e.cidrv6=t=>e.check(yr(Va,t)),e.e164=t=>e.check(Sr(Wa,t)),e.datetime=t=>e.check(ta(t)),e.date=t=>e.check(ra(t)),e.time=t=>e.check(aa(t)),e.duration=t=>e.check(sa(t))});function k(e){return tr(wa,e)}let A=r(`ZodStringFormat`,(e,t)=>{E.init(e,t),Ca.init(e,t)}),Ta=r(`ZodEmail`,(e,t)=>{Rt.init(e,t),A.init(e,t)});function Ea(e){return nr(Ta,e)}let Da=r(`ZodGUID`,(e,t)=>{It.init(e,t),A.init(e,t)}),Oa=r(`ZodUUID`,(e,t)=>{Lt.init(e,t),A.init(e,t)}),ka=r(`ZodURL`,(e,t)=>{zt.init(e,t),A.init(e,t)});function Aa(e){return cr(ka,e)}let ja=r(`ZodEmoji`,(e,t)=>{Bt.init(e,t),A.init(e,t)}),Ma=r(`ZodNanoID`,(e,t)=>{Vt.init(e,t),A.init(e,t)}),Na=r(`ZodCUID`,(e,t)=>{Ht.init(e,t),A.init(e,t)}),Pa=r(`ZodCUID2`,(e,t)=>{Ut.init(e,t),A.init(e,t)}),Fa=r(`ZodULID`,(e,t)=>{Wt.init(e,t),A.init(e,t)}),Ia=r(`ZodXID`,(e,t)=>{Gt.init(e,t),A.init(e,t)}),La=r(`ZodKSUID`,(e,t)=>{Kt.init(e,t),A.init(e,t)}),Ra=r(`ZodIPv4`,(e,t)=>{Zt.init(e,t),A.init(e,t)}),za=r(`ZodIPv6`,(e,t)=>{Qt.init(e,t),A.init(e,t)}),Ba=r(`ZodCIDRv4`,(e,t)=>{$t.init(e,t),A.init(e,t)}),Va=r(`ZodCIDRv6`,(e,t)=>{en.init(e,t),A.init(e,t)}),Ha=r(`ZodBase64`,(e,t)=>{nn.init(e,t),A.init(e,t)}),Ua=r(`ZodBase64URL`,(e,t)=>{an.init(e,t),A.init(e,t)}),Wa=r(`ZodE164`,(e,t)=>{on.init(e,t),A.init(e,t)}),Ga=r(`ZodJWT`,(e,t)=>{cn.init(e,t),A.init(e,t)}),Ka=r(`ZodNumber`,(e,t)=>{ln.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mi(e,t,n,r),Sa(e,`ZodNumber`,{gt(e,t){return this.check(Rr(e,t))},gte(e,t){return this.check(zr(e,t))},min(e,t){return this.check(zr(e,t))},lt(e,t){return this.check(Ir(e,t))},lte(e,t){return this.check(Lr(e,t))},max(e,t){return this.check(Lr(e,t))},int(e){return this.check(Ja(e))},safe(e){return this.check(Ja(e))},positive(e){return this.check(Rr(0,e))},nonnegative(e){return this.check(zr(0,e))},negative(e){return this.check(Ir(0,e))},nonpositive(e){return this.check(Lr(0,e))},multipleOf(e,t){return this.check(Br(e,t))},step(e,t){return this.check(Br(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function j(e){return Or(Ka,e)}let qa=r(`ZodNumberFormat`,(e,t)=>{un.init(e,t),Ka.init(e,t)});function Ja(e){return Ar(qa,e)}let Ya=r(`ZodBoolean`,(e,t)=>{dn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hi(e,t,n,r)});function M(e){return jr(Ya,e)}let Xa=r(`ZodNull`,(e,t)=>{fn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vi(e,t,n,r)});function Za(e){return Mr(Xa,e)}let Qa=r(`ZodAny`,(e,t)=>{pn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function $a(){return Nr(Qa)}let eo=r(`ZodUnknown`,(e,t)=>{mn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function N(){return Pr(eo)}let to=r(`ZodNever`,(e,t)=>{hn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xi(e,t,n,r)});function no(e){return Fr(to,e)}let ro=r(`ZodArray`,(e,t)=>{_n.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ii(e,t,n,r),e.element=t.element,Sa(e,`ZodArray`,{min(e,t){return this.check(Hr(e,t))},nonempty(e){return this.check(Hr(1,e))},max(e,t){return this.check(Vr(e,t))},length(e,t){return this.check(Ur(e,t))},unwrap(){return this.element}})});function P(e,t){return ni(ro,e,t)}let io=r(`ZodObject`,(e,t)=>{Sn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Li(e,t,n,r),h(e,`shape`,()=>t.shape),Sa(e,`ZodObject`,{keyof(){return z(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:N()})},loose(){return this.clone({...this._zod.def,catchall:N()})},strict(){return this.clone({...this._zod.def,catchall:no()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return me(this,e)},safeExtend(e){return he(this,e)},merge(e){return ge(this,e)},pick(e){return fe(this,e)},omit(e){return pe(this,e)},partial(...e){return _e(go,this,e[0])},required(...e){return ve(To,this,e[0])}})});function F(e,t){return new io({type:`object`,shape:e??{},...v(t)})}function I(e,t){return new io({type:`object`,shape:e,catchall:N(),...v(t)})}let ao=r(`ZodUnion`,(e,t)=>{wn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ri(e,t,n,r),e.options=t.options});function L(e,t){return new ao({type:`union`,options:e,...v(t)})}let oo=r(`ZodDiscriminatedUnion`,(e,t)=>{ao.init(e,t),Tn.init(e,t)});function so(e,t,n){return new oo({type:`union`,options:t,discriminator:e,...v(n)})}let co=r(`ZodIntersection`,(e,t)=>{En.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zi(e,t,n,r)});function lo(e,t){return new co({type:`intersection`,left:e,right:t})}let uo=r(`ZodRecord`,(e,t)=>{kn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vi(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function R(e,t,n){return!t||!t._zod?new uo({type:`record`,keyType:k(),valueType:e,...v(t)}):new uo({type:`record`,keyType:e,valueType:t,...v(n)})}let fo=r(`ZodEnum`,(e,t)=>{An.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ti(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new fo({...t,checks:[],...v(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new fo({...t,checks:[],...v(r),entries:i})}});function z(e,t){return new fo({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...v(t)})}let po=r(`ZodLiteral`,(e,t)=>{jn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ei(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function B(e,t){return new po({type:`literal`,values:Array.isArray(e)?e:[e],...v(t)})}let mo=r(`ZodTransform`,(e,t)=>{Mn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ni(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new a(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Ce(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(Ce(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function ho(e){return new mo({type:`transform`,transform:e})}let go=r(`ZodOptional`,(e,t)=>{Pn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function V(e){return new go({type:`optional`,innerType:e})}let _o=r(`ZodExactOptional`,(e,t)=>{Fn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function vo(e){return new _o({type:`optional`,innerType:e})}let yo=r(`ZodNullable`,(e,t)=>{In.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function bo(e){return new yo({type:`nullable`,innerType:e})}let xo=r(`ZodDefault`,(e,t)=>{Ln.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function So(e,t){return new xo({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():oe(t)}})}let Co=r(`ZodPrefault`,(e,t)=>{zn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wo(e,t){return new Co({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():oe(t)}})}let To=r(`ZodNonOptional`,(e,t)=>{Bn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ui(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Eo(e,t){return new To({type:`nonoptional`,innerType:e,...v(t)})}let Do=r(`ZodCatch`,(e,t)=>{Hn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ki(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Oo(e,t){return new Do({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}let ko=r(`ZodPipe`,(e,t)=>{Un.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qi(e,t,n,r),e.in=t.in,e.out=t.out});function Ao(e,t){return new ko({type:`pipe`,in:e,out:t})}let jo=r(`ZodPreprocess`,(e,t)=>{ko.init(e,t),Gn.init(e,t)}),Mo=r(`ZodReadonly`,(e,t)=>{Kn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ji(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function No(e){return new Mo({type:`readonly`,innerType:e})}let Po=r(`ZodLazy`,(e,t)=>{Jn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zi(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Fo(e){return new Po({type:`lazy`,getter:e})}let Io=r(`ZodCustom`,(e,t)=>{Yn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ji(e,t,n,r)});function Lo(e,t={}){return ri(Io,e,t)}function Ro(e,t){return ii(e,t)}function zo(e,t){return new jo({type:`pipe`,in:ho(e),out:t})}let Bo={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var Vo;Vo||={};function Ho(e){return kr(Ka,e)}let Uo=[`2025-11-25`,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Wo=`io.modelcontextprotocol/protocolVersion`,Go=`io.modelcontextprotocol/clientInfo`,Ko=`io.modelcontextprotocol/serverInfo`,qo=`io.modelcontextprotocol/clientCapabilities`,Jo=`io.modelcontextprotocol/logLevel`,Yo=Fo(()=>L([k(),j(),M(),Za(),R(k(),Yo),P(Yo)])),H=R(k(),Yo),Xo=P(Yo),Zo=L([k(),j().int()]),Qo=k(),$o=F({ttl:j().optional()}),es=F({taskId:k()}),ts=I({progressToken:Zo.optional(),"io.modelcontextprotocol/related-task":es.optional()}),U=F({_meta:ts.optional()}),ns=U.extend({task:$o.optional()}),W=F({method:k(),params:U.loose().optional()}),rs=F({_meta:ts.optional()}),is=F({method:k(),params:rs.loose().optional()}),as=I({get[Ko](){return ys.optional().catch(void 0)}}),G=I({_meta:as.optional()}),os=L([k(),j().int()]),ss=F({jsonrpc:B(`2.0`),id:os,...W.shape}).strict(),cs=F({jsonrpc:B(`2.0`),...is.shape}).strict(),ls=F({jsonrpc:B(`2.0`),id:os,result:G}).strict(),us=F({jsonrpc:B(`2.0`),id:os.optional(),error:F({code:j().int(),message:k(),data:N().optional()})}).strict(),ds=L([ss,cs,ls,us]),fs=L([ls,us]),ps=G.strict(),ms=rs.extend({requestId:os.optional(),reason:k().optional()}),hs=is.extend({method:B(`notifications/cancelled`),params:ms}),gs=F({src:k(),mimeType:k().optional(),sizes:P(k()).optional(),theme:z([`light`,`dark`]).optional()}),_s=F({icons:P(gs).optional()}),vs=F({name:k(),title:k().optional()}),ys=vs.extend({...vs.shape,..._s.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),bs=zo(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,lo(F({form:lo(F({applyDefaults:M().optional()}),H).optional(),url:H.optional()}),H.optional())),xs=I({list:H.optional(),cancel:H.optional(),requests:I({sampling:I({createMessage:H.optional()}).optional(),elicitation:I({create:H.optional()}).optional()}).optional()}),Ss=I({list:H.optional(),cancel:H.optional(),requests:I({tools:I({call:H.optional()}).optional()}).optional()}),Cs=F({experimental:R(k(),H).optional(),sampling:F({context:H.optional(),tools:H.optional()}).optional(),elicitation:bs.optional(),roots:F({listChanged:M().optional()}).optional(),tasks:xs.optional(),extensions:R(k(),H).optional()}),ws=U.extend({protocolVersion:k(),capabilities:Cs,clientInfo:ys}),Ts=W.extend({method:B(`initialize`),params:ws}),Es=F({experimental:R(k(),H).optional(),logging:H.optional(),completions:H.optional(),prompts:F({listChanged:M().optional()}).optional(),resources:F({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:F({listChanged:M().optional()}).optional(),tasks:Ss.optional(),extensions:R(k(),H).optional()}),Ds=G.extend({protocolVersion:k(),capabilities:Es,serverInfo:ys,instructions:k().optional()}),Os=is.extend({method:B(`notifications/initialized`),params:rs.optional()}),ks=W.extend({method:B(`server/discover`),params:U.optional()}),As=G.extend({supportedVersions:P(k()),capabilities:Es,instructions:k().optional()}),js=W.extend({method:B(`ping`),params:U.optional()}),Ms=F({progress:j(),total:V(j()),message:V(k())}),Ns=F({...rs.shape,...Ms.shape,progressToken:Zo}),Ps=is.extend({method:B(`notifications/progress`),params:Ns}),Fs=U.extend({cursor:Qo.optional()}),Is=W.extend({params:Fs.optional()}),Ls=G.extend({nextCursor:Qo.optional()}),Rs=F({uri:k(),mimeType:V(k()),_meta:R(k(),N()).optional()}),zs=Rs.extend({text:k()}),Bs=k().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Vs=Rs.extend({blob:Bs}),Hs=z([`user`,`assistant`]),Us=F({audience:P(Hs).optional(),priority:j().min(0).max(1).optional(),lastModified:ta({offset:!0}).optional()}),Ws=F({...vs.shape,..._s.shape,uri:k(),description:V(k()),mimeType:V(k()),size:V(j()),annotations:Us.optional(),_meta:V(I({}))}),Gs=F({...vs.shape,..._s.shape,uriTemplate:k(),description:V(k()),mimeType:V(k()),annotations:Us.optional(),_meta:V(I({}))}),Ks=Is.extend({method:B(`resources/list`)}),qs=Ls.extend({resources:P(Ws)}),Js=Is.extend({method:B(`resources/templates/list`)}),Ys=Ls.extend({resourceTemplates:P(Gs)}),Xs=U.extend({uri:k()}),Zs=Xs,Qs=W.extend({method:B(`resources/read`),params:Zs}),$s=G.extend({contents:P(L([zs,Vs]))}),ec=is.extend({method:B(`notifications/resources/list_changed`),params:rs.optional()}),tc=Xs,nc=W.extend({method:B(`resources/subscribe`),params:tc}),rc=Xs,ic=W.extend({method:B(`resources/unsubscribe`),params:rc}),ac=F({toolsListChanged:M().optional(),promptsListChanged:M().optional(),resourcesListChanged:M().optional(),resourceSubscriptions:P(k()).optional()}),oc=U.extend({notifications:ac}),sc=W.extend({method:B(`subscriptions/listen`),params:oc}),cc=rs.extend({notifications:ac}),lc=is.extend({method:B(`notifications/subscriptions/acknowledged`),params:cc}),uc=as.extend({"io.modelcontextprotocol/subscriptionId":os}),dc=G.extend({_meta:uc}),fc=rs.extend({uri:k()}),pc=is.extend({method:B(`notifications/resources/updated`),params:fc}),mc=F({name:k(),description:V(k()),required:V(M())}),hc=F({...vs.shape,..._s.shape,description:V(k()),arguments:V(P(mc)),_meta:V(I({}))}),gc=Is.extend({method:B(`prompts/list`)}),_c=Ls.extend({prompts:P(hc)}),vc=U.extend({name:k(),arguments:R(k(),k()).optional()}),yc=W.extend({method:B(`prompts/get`),params:vc}),bc=F({type:B(`text`),text:k(),annotations:Us.optional(),_meta:R(k(),N()).optional()}),xc=F({type:B(`image`),data:Bs,mimeType:k(),annotations:Us.optional(),_meta:R(k(),N()).optional()}),Sc=F({type:B(`audio`),data:Bs,mimeType:k(),annotations:Us.optional(),_meta:R(k(),N()).optional()}),Cc=F({type:B(`tool_use`),name:k(),id:k(),input:R(k(),N()),_meta:R(k(),N()).optional()}),wc=F({type:B(`resource`),resource:L([zs,Vs]),annotations:Us.optional(),_meta:R(k(),N()).optional()}),Tc=Ws.extend({type:B(`resource_link`)}),Ec=L([bc,xc,Sc,Tc,wc]),Dc=F({role:Hs,content:Ec}),Oc=G.extend({description:k().optional(),messages:P(Dc)}),kc=is.extend({method:B(`notifications/prompts/list_changed`),params:rs.optional()}),Ac=F({title:k().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),jc=F({taskSupport:z([`required`,`optional`,`forbidden`]).optional()}),Mc=F({...vs.shape,..._s.shape,description:k().optional(),inputSchema:F({type:B(`object`),properties:R(k(),Yo).optional(),required:P(k()).optional()}).catchall(N()),outputSchema:I({$schema:k().optional()}).optional(),annotations:Ac.optional(),execution:jc.optional(),_meta:R(k(),N()).optional()}),Nc=Is.extend({method:B(`tools/list`)}),Pc=Ls.extend({tools:P(Mc)}),Fc=G.extend({content:P(Ec).default([]),structuredContent:N().optional(),isError:M().optional()}),Ic=Fc.or(G.extend({toolResult:N()})),Lc=ns.extend({name:k(),arguments:R(k(),N()).optional()}),Rc=W.extend({method:B(`tools/call`),params:Lc}),zc=is.extend({method:B(`notifications/tools/list_changed`),params:rs.optional()}),Bc=F({autoRefresh:M().default(!0),debounceMs:j().int().nonnegative().default(300)}),Vc=z([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Hc=U.extend({level:Vc}),Uc=W.extend({method:B(`logging/setLevel`),params:Hc}),Wc=rs.extend({level:Vc,logger:k().optional(),data:N()}),Gc=is.extend({method:B(`notifications/message`),params:Wc}),Kc=F({name:k().optional()}),qc=F({hints:P(Kc).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),Jc=F({mode:z([`auto`,`required`,`none`]).optional()}),Yc=F({type:B(`tool_result`),toolUseId:k().describe(`The unique identifier for the corresponding tool call.`),content:P(Ec),structuredContent:N().optional(),isError:M().optional(),_meta:R(k(),N()).optional()}),Xc=so(`type`,[bc,xc,Sc]),Zc=so(`type`,[bc,xc,Sc,Cc,Yc]),Qc=F({role:Hs,content:L([Zc,P(Zc)]),_meta:R(k(),N()).optional()}),$c=ns.extend({messages:P(Qc),modelPreferences:qc.optional(),systemPrompt:k().optional(),includeContext:z([`none`,`thisServer`,`allServers`]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:P(k()).optional(),metadata:H.optional(),tools:P(Mc).optional(),toolChoice:Jc.optional()}),el=W.extend({method:B(`sampling/createMessage`),params:$c}),tl=G.extend({model:k(),stopReason:V(z([`endTurn`,`stopSequence`,`maxTokens`]).or(k())),role:Hs,content:Xc}),nl=G.extend({model:k(),stopReason:V(z([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(k())),role:Hs,content:L([Zc,P(Zc)])}),rl=F({type:B(`boolean`),title:k().optional(),description:k().optional(),default:M().optional()}),il=F({type:B(`string`),title:k().optional(),description:k().optional(),minLength:j().optional(),maxLength:j().optional(),format:z([`email`,`uri`,`date`,`date-time`]).optional(),default:k().optional()}),al=F({type:z([`number`,`integer`]),title:k().optional(),description:k().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),ol=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),default:k().optional()}),sl=F({type:B(`string`),title:k().optional(),description:k().optional(),oneOf:P(F({const:k(),title:k()})),default:k().optional()}),cl=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),enumNames:P(k()).optional(),default:k().optional()}),ll=L([ol,sl]),ul=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({type:B(`string`),enum:P(k())}),default:P(k()).optional()}),dl=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({anyOf:P(F({const:k(),title:k()}))}),default:P(k()).optional()}),fl=L([ul,dl]),pl=L([cl,ll,fl]),ml=L([pl,rl,il,al]),hl=ns.extend({mode:B(`form`).optional(),message:k(),requestedSchema:F({type:B(`object`),properties:R(k(),ml),required:P(k()).optional()}).catchall(N())}),gl=ns.extend({mode:B(`url`),message:k(),elicitationId:k(),url:k().url()}),_l=L([hl,gl]),vl=W.extend({method:B(`elicitation/create`),params:_l}),yl=rs.extend({elicitationId:k()}),bl=is.extend({method:B(`notifications/elicitation/complete`),params:yl}),xl=G.extend({action:z([`accept`,`decline`,`cancel`]),content:zo(e=>e===null?void 0:e,R(k(),L([k(),j(),M(),P(k())])).optional())}),Sl=F({type:B(`ref/resource`),uri:k()}),Cl=F({type:B(`ref/prompt`),name:k()}),wl=U.extend({ref:L([Cl,Sl]),argument:F({name:k(),value:k()}),context:F({arguments:R(k(),k()).optional()}).optional()}),Tl=W.extend({method:B(`completion/complete`),params:wl}),El=G.extend({completion:I({values:P(k()).max(100),total:V(j().int()),hasMore:V(M())})}),Dl=F({uri:k().startsWith(`file://`),name:k().optional(),_meta:R(k(),N()).optional()}),Ol=W.extend({method:B(`roots/list`),params:U.optional()}),kl=G.extend({roots:P(Dl)}),Al=is.extend({method:B(`notifications/roots/list_changed`),params:rs.optional()}),jl=I({ttl:j().optional(),pollInterval:j().optional()}),Ml=z([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Nl=F({taskId:k(),status:Ml,ttl:L([j(),Za()]),createdAt:k(),lastUpdatedAt:k(),pollInterval:V(j()),statusMessage:V(k())}),Pl=G.extend({task:Nl}),Fl=rs.merge(Nl),Il=is.extend({method:B(`notifications/tasks/status`),params:Fl}),Ll=W.extend({method:B(`tasks/get`),params:U.extend({taskId:k()})}),Rl=G.merge(Nl),zl=W.extend({method:B(`tasks/result`),params:U.extend({taskId:k()})}),Bl=G.loose(),Vl=Is.extend({method:B(`tasks/list`)}),Hl=Ls.extend({tasks:P(Nl)}),Ul=W.extend({method:B(`tasks/cancel`),params:U.extend({taskId:k()})}),Wl=G.merge(Nl),Gl=L([js,Ts,ks,Tl,Uc,yc,gc,Ks,Js,Qs,nc,ic,sc,Rc,Nc]),Kl=L([hs,Ps,Os,Al]),ql=L([ps,tl,nl,xl,kl]),Jl=L([js,el,vl,Ol]),Yl=L([hs,Ps,Gc,pc,ec,zc,kc,lc,bl]),Xl=L([ps,Ds,As,El,Oc,_c,qs,Ys,$s,Fc,Pc,dc]),K=Aa().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Bo.custom,message:`URL must be parseable`,fatal:!0}),n}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),Zl=I({resource:k().url(),authorization_servers:P(K).optional(),jwks_uri:k().url().optional(),scopes_supported:P(k()).optional(),bearer_methods_supported:P(k()).optional(),resource_signing_alg_values_supported:P(k()).optional(),resource_name:k().optional(),resource_documentation:k().optional(),resource_policy_uri:k().url().optional(),resource_tos_uri:k().url().optional(),tls_client_certificate_bound_access_tokens:M().optional(),authorization_details_types_supported:P(k()).optional(),dpop_signing_alg_values_supported:P(k()).optional(),dpop_bound_access_tokens_required:M().optional()}),Ql=I({issuer:k(),authorization_endpoint:K,token_endpoint:K,registration_endpoint:K.optional(),scopes_supported:P(k()).optional(),response_types_supported:P(k()),response_modes_supported:P(k()).optional(),grant_types_supported:P(k()).optional(),token_endpoint_auth_methods_supported:P(k()).optional(),token_endpoint_auth_signing_alg_values_supported:P(k()).optional(),service_documentation:K.optional(),revocation_endpoint:K.optional(),revocation_endpoint_auth_methods_supported:P(k()).optional(),revocation_endpoint_auth_signing_alg_values_supported:P(k()).optional(),introspection_endpoint:k().optional(),introspection_endpoint_auth_methods_supported:P(k()).optional(),introspection_endpoint_auth_signing_alg_values_supported:P(k()).optional(),code_challenge_methods_supported:P(k()).optional(),client_id_metadata_document_supported:M().optional(),authorization_response_iss_parameter_supported:M().optional().catch(void 0)}),$l=I({issuer:k(),authorization_endpoint:K,token_endpoint:K,userinfo_endpoint:K.optional(),jwks_uri:K,registration_endpoint:K.optional(),scopes_supported:P(k()).optional(),response_types_supported:P(k()),response_modes_supported:P(k()).optional(),grant_types_supported:P(k()).optional(),acr_values_supported:P(k()).optional(),subject_types_supported:P(k()),id_token_signing_alg_values_supported:P(k()),id_token_encryption_alg_values_supported:P(k()).optional(),id_token_encryption_enc_values_supported:P(k()).optional(),userinfo_signing_alg_values_supported:P(k()).optional(),userinfo_encryption_alg_values_supported:P(k()).optional(),userinfo_encryption_enc_values_supported:P(k()).optional(),request_object_signing_alg_values_supported:P(k()).optional(),request_object_encryption_alg_values_supported:P(k()).optional(),request_object_encryption_enc_values_supported:P(k()).optional(),token_endpoint_auth_methods_supported:P(k()).optional(),token_endpoint_auth_signing_alg_values_supported:P(k()).optional(),display_values_supported:P(k()).optional(),claim_types_supported:P(k()).optional(),claims_supported:P(k()).optional(),service_documentation:k().optional(),claims_locales_supported:P(k()).optional(),ui_locales_supported:P(k()).optional(),claims_parameter_supported:M().optional(),request_parameter_supported:M().optional(),request_uri_parameter_supported:M().optional(),require_request_uri_registration:M().optional(),op_policy_uri:K.optional(),op_tos_uri:K.optional(),client_id_metadata_document_supported:M().optional(),authorization_response_iss_parameter_supported:M().optional().catch(void 0)}),eu=F({...$l.shape,...Ql.pick({code_challenge_methods_supported:!0}).shape}),tu=F({access_token:k(),id_token:k().optional(),token_type:k(),expires_in:Ho().optional(),scope:k().optional(),refresh_token:k().optional()}).strip(),nu=F({issued_token_type:B(`urn:ietf:params:oauth:token-type:id-jag`),access_token:k(),token_type:k().optional(),expires_in:j().optional(),scope:k().optional()}).strip(),ru=F({error:k(),error_description:k().optional(),error_uri:k().optional()}),iu=K.optional().or(B(``).transform(()=>void 0)),au=F({redirect_uris:P(K),token_endpoint_auth_method:k().optional(),grant_types:P(k()).optional(),response_types:P(k()).optional(),application_type:k().optional(),client_name:k().optional(),client_uri:K.optional(),logo_uri:iu,scope:k().optional(),contacts:P(k()).optional(),tos_uri:iu,policy_uri:k().optional(),jwks_uri:K.optional(),jwks:$a().optional(),software_id:k().optional(),software_version:k().optional(),software_statement:k().optional()}).strip(),ou=F({client_id:k(),client_secret:k().optional(),client_id_issued_at:j().optional(),client_secret_expires_at:j().optional()}).strip(),su=au.merge(ou),cu=F({error:k(),error_description:k().optional()}).strip(),lu=F({token:k(),token_type_hint:k().optional()}).strip();function uu(e,t,n){return typeof e==`object`&&!!e&&`channel`in e&&e.channel===t&&`type`in e&&e.type===`mcp`&&`direction`in e&&e.direction===n&&`payload`in e}function du(e,t,n,r,i){e.postMessage({channel:n,type:`mcp`,direction:r,payload:i},t)}var fu=class{_started=!1;_closed=!1;_allowedOrigins;_channelId;_messageHandler;_clientOrigin;onclientorigin;onclose;onerror;onmessage;constructor(e){if(!e.allowedOrigins?.length)throw Error(`At least one allowed origin must be specified`);this._allowedOrigins=new Set(e.allowedOrigins),this._channelId=e.channelId??`mcp-iframe`}get clientOrigin(){return this._clientOrigin}async start(){if(this._closed)throw Error(`IframeChildTransport cannot be restarted after it closes`);if(this._started)throw Error(`Transport already started`);this._messageHandler=e=>{if(e.source!==window.parent||!this._allowedOrigins.has(`*`)&&!this._allowedOrigins.has(e.origin)||!uu(e.data,this._channelId,`client-to-server`))return;this._clientOrigin!==e.origin&&(this._clientOrigin=e.origin,this.onclientorigin?.(e.origin));let{payload:t}=e.data;if(t===`mcp-check-ready`){this._broadcastServerReady();return}try{let e=ds.parse(t);this.onmessage?.(e)}catch(e){this.onerror?.(Error(`Invalid message: ${e instanceof Error?e.message:String(e)}`))}},window.addEventListener(`message`,this._messageHandler),this._started=!0,this._broadcastServerReady()}async send(e,t){if(this._closed)throw Error(`Transport is closed`);if(!this._started)throw Error(`Transport not started`);if(!this._clientOrigin){console.debug(`[IframeChildTransport] No client connected, message not sent`);return}if(window.parent===window){console.debug(`[IframeChildTransport] Not running in an iframe, message not sent`);return}du(window.parent,this._clientOrigin,this._channelId,`server-to-client`,e)}async close(){this._closed||(this._closed=!0,this._started=!1,this._messageHandler&&=(window.removeEventListener(`message`,this._messageHandler),void 0),this._clientOrigin&&window.parent!==window&&du(window.parent,this._clientOrigin,this._channelId,`server-to-client`,`mcp-server-stopped`),this.onclose?.())}_broadcastServerReady(){window.parent!==window&&du(window.parent,`*`,this._channelId,`server-to-client`,`mcp-server-ready`)}},pu=class{_started=!1;_closed=!1;_allowedOrigins;_channelId;_messageHandler;onclose;onerror;onmessage;constructor(e){if(!e.allowedOrigins?.length)throw Error(`At least one allowed origin must be specified`);this._allowedOrigins=new Set(e.allowedOrigins),this._channelId=e.channelId??`mcp-default`}async start(){if(this._closed)throw Error(`TabServerTransport cannot be restarted after it closes`);if(this._started)throw Error(`Transport already started`);this._messageHandler=e=>{if(e.source!==window||!this._allowedOrigins.has(`*`)&&!this._allowedOrigins.has(e.origin)||!uu(e.data,this._channelId,`client-to-server`))return;let{payload:t}=e.data;if(t===`mcp-check-ready`){du(window,`*`,this._channelId,`server-to-client`,`mcp-server-ready`);return}try{let e=ds.parse(t);this.onmessage?.(e)}catch(e){this.onerror?.(Error(`Invalid message: ${e instanceof Error?e.message:String(e)}`))}},window.addEventListener(`message`,this._messageHandler),this._started=!0,du(window,`*`,this._channelId,`server-to-client`,`mcp-server-ready`)}async send(e,t){if(this._closed)throw Error(`Transport is closed`);if(!this._started)throw Error(`Transport not started`);du(window,`*`,this._channelId,`server-to-client`,e)}async close(){this._closed||(this._closed=!0,this._messageHandler&&=(window.removeEventListener(`message`,this._messageHandler),void 0),this._started&&du(window,`*`,this._channelId,`server-to-client`,`mcp-server-stopped`),this._started=!1,this.onclose?.())}};let mu=[`consequentialHint`,`debugging`,`readOnlyHint`,`untrustedContentHint`],hu=`webmcp-polyfill`,gu=globalThis.DOMException;var _u=class{#e;#t;#n;#r=new Set;#i=new Set;#a=Promise.withResolvers();#o=new Map;#s=new Set;#c;#l=!1;constructor(e,t){this.#t=e,this.#e=e.document,this.#n=t,this.#t.addEventListener(`message`,e=>this.#d(e),!0),this.#t.addEventListener(`pagehide`,()=>{this.#l=!0;for(let e of this.#s)e.end()}),this.#t.addEventListener(`pageshow`,e=>{e.persisted&&(this.#l=!1,this.#x())});for(let e of this.#x())this.#i.add(e);this.#i.size===0?this.#a.resolve():setTimeout(()=>{this.#i.clear(),this.#a.resolve()},500)}async allowed(){return this.#l?!1:this.#h(this.#e)}async getTools(e){await this.#a.promise;let t=this.#t.origin,n=[t,...e];return(await Promise.all(this.#b().map(async e=>{if(e===this.#t)return this.#n.getTools(t).map(e=>wu(e,this.#t,t));try{let t=await this.#u(e,n,{kind:`getTools`});if(!Array.isArray(t.value))throw TypeError(`Expected a tool list from the frame`);return t.value.map(n=>wu(Tu(n),e,t.origin))}catch(e){return e instanceof gu&&e.name===`UnknownError`||console.warn(`WebMCP: could not read tools from a frame.`,e),[]}}))).flat()}async execute(e,t,n,r,i){let a=await this.#u(e,[t],{kind:`execute`,name:n,input:r},i);if(typeof a.value!=`string`)throw q();return a.value}async notify(e){await this.#a.promise;let t=[this.#t.origin,...e];for(let e of this.#b()){if(e===this.#t){await this.#n.changed();continue}try{await this.#u(e,t,{kind:`changed`})}catch{}}}#u(e,t,n,r){return new Promise((i,a)=>{if(r?.throwIfAborted(),this.#l||!this.#v(e)){a(q());return}let o=crypto.randomUUID(),{port1:s,port2:c}=new MessageChannel,l,u=()=>{clearTimeout(h),g(),r?.removeEventListener(`abort`,f),this.#o.delete(o),s.close()},d=(e=q())=>{s.postMessage({kind:`cancel`}),u(),a(e)},f=()=>d(r?.reason),p=()=>{l===void 0&&this.#C(e),d()},m=r=>{if(r.source===e){if(this.#o.delete(o),t&&!t.includes(r.origin)){d();return}l=r.origin,clearTimeout(h),n.kind!==`execute`&&n.kind!==`changed`&&(h=setTimeout(p,500)),s.postMessage(n)}},h=setTimeout(p,500),g=this.#w(e,d);s.onmessage=e=>{let t=Du(e.data);if(t?.kind===`error`){d();return}t?.kind!==`result`||l===void 0||(u(),i({value:t.value,origin:l}))},s.onmessageerror=()=>d(),r?.addEventListener(`abort`,f,{once:!0}),this.#o.set(o,m);try{e.postMessage(`${hu}:connect:${o}`,`*`,[c])}catch{c.close(),d()}})}#d(e){let t=Eu(e.data);if(!t)return;e.stopImmediatePropagation();let n=e.source;if(!e.isTrusted||!n||!Ou(n)||!this.#v(n)||e.origin===`null`||this.#l)return;if(t.kind===`announce`){let t=!this.#r.has(n);if(this.#S(n),n.postMessage(`${hu}:present`,e.origin),!t||this.#t!==this.#t.top)return;for(let e of this.#r)e!==n&&e.postMessage(`${hu}:refresh`,`*`);return}if(t.kind===`present`){this.#S(n);return}if(t.kind===`refresh`){n===this.#t.top&&this.#x();return}if(t.kind===`ready`){this.#o.get(t.id)?.(e);return}let[r]=e.ports;t.kind!==`connect`||!t.id||!r||e.ports.length!==1||(this.#S(n),this.#f(n,e.origin,t.id,r))}#f(e,t,n,r){let i=new AbortController,a=!1,o=()=>{clearTimeout(l),u(),r.close()},s=()=>{i.abort(),o()},c=()=>{r.postMessage({kind:`error`}),s()},l=setTimeout(c,500),u=this.#w(e,c);r.onmessageerror=c,r.onmessage=async n=>{let u=Du(n.data);if(u?.kind===`cancel`){s();return}if(!a){a=!0,clearTimeout(l);try{let n=await this.#p(e,t,u,i.signal);r.postMessage({kind:`result`,value:n}),o()}catch{c()}}},e.postMessage(`${hu}:ready:${n}`,t)}async#p(e,t,n,r){if(!n||!this.#v(e))throw q();if(n.kind===`permission`){let{childIndex:e,childOrigin:t}=n;if(typeof e!=`number`||!Number.isInteger(e)||e<0||typeof t!=`string`)throw q();return this.#m(e,t)}if(!await this.allowed()||!await this.#g(e,t)||!this.#v(e))throw q();if(r.throwIfAborted(),n.kind===`getTools`)return this.#n.getTools(t);if(n.kind===`execute`&&typeof n.name==`string`&&typeof n.input==`string`)return this.#n.execute(t,n.name,n.input,r);if(n.kind===`changed`){await this.#n.changed();return}throw q()}async#m(e,t){let n=this.#t[e];return n!==void 0&&await this.allowed()&&vu(this.#e,n,t)}async#h(e){let t=Su(e);if(!t)return!1;let n=Cu(e);if(n!==void 0)return n;if(t===t.parent)return!0;let r=t.location.ancestorOrigins?.[0],i=yu(t.parent,r===void 0||r===t.origin);return i?vu(i,t,t.origin)&&await this.#h(i):this.#_(t,t.origin)}async#g(e,t){let n=yu(e,t===this.#t.origin);return n?this.#h(n):this.#_(e,t)}async#_(e,t){let n=e.parent;if(n===e)return!0;let r=-1;for(let t=0;t<n.length;t++)if(n[t]===e){r=t;break}if(r<0)return!1;if(n===this.#t)return await this.allowed()&&vu(this.#e,e,t);if(await this.#a.promise,!this.#r.has(n))return!1;try{let e=await this.#u(n,void 0,{kind:`permission`,childIndex:r,childOrigin:t});return e.value===!0&&await this.#g(n,e.origin)}catch{return!1}}#v(e){try{return!e.closed&&e!==this.#t&&e.top===this.#t.top}catch{return!1}}#y(){if(this.#t.closed)return[];for(let e of this.#r)this.#v(e)||this.#r.delete(e);let e=[this.#t,...this.#r];for(let t=this.#t.parent;t!==t.parent;t=t.parent)e.push(t);let t=new Set,n=[this.#t.top];for(;n.length;){let r=n.pop();if(t.has(r))continue;t.add(r);let i=[];for(let e=0;e<r.length;e++){let t=r[e];t&&i.push(t)}for(let t of e)t!==r&&t.parent===r&&!i.includes(t)&&i.push(t);n.push(...i.reverse())}return Array.from(t).filter(e=>e===this.#t||this.#v(e))}#b(){return this.#y().filter(e=>e===this.#t||this.#r.has(e))}#x(){let e=this.#y().filter(e=>e!==this.#t);for(let t of e)t.postMessage(`${hu}:announce`,`*`);return e}#S(e){this.#r.add(e),this.#i.delete(e),this.#i.size===0&&this.#a.resolve()}#C(e){this.#r.delete(e),this.#v(e)&&e.postMessage(`${hu}:announce`,`*`)}#w(e,t){let n={peer:e,end:t};return this.#s.add(n),this.#c===void 0&&(this.#c=this.#t.setInterval(()=>{for(let e of this.#s)this.#v(e.peer)||e.end()},100)),()=>{this.#s.delete(n),this.#s.size===0&&(this.#t.clearInterval(this.#c),this.#c=void 0)}}};function vu(e,t,n){let r=e.defaultView?.origin,i=bu(e,t,n===r);if(!i)return!1;let a=(i.getAttribute(`allow`)??``).split(`;`).map(e=>e.trim().split(/\s+/u)).find(([e])=>e===`tools`);if(!a)return n===r;let o=a.length===1?[`'src'`]:a.slice(1);if(o.includes(`'none'`))return!1;let s=i.hasAttribute(`srcdoc`)?null:i.getAttribute(`src`),c=s?URL.parse(s,e.baseURI):null,l=!s||c?.protocol===`about:`?r:c?.origin;return o.some(e=>e===`*`||e===`'self'`&&n===r||e===`'src'`&&n===l||e===n)}function yu(e,t){if(t)try{return e.document}catch{return}}function bu(e,t,n){if(n)try{let n=t.frameElement;if(n?.ownerDocument===e)return n}catch{}return xu(e,t)}function xu(e,t){let n=e.querySelectorAll(`iframe, frame`);for(let e of n)if(e.contentWindow===t)return e;for(let n of e.querySelectorAll(`*`)){if(!n.shadowRoot)continue;let e=xu(n.shadowRoot,t);if(e)return e}}function Su(e){let t=e.defaultView;return t&&!t.closed&&t.document===e?t:void 0}function Cu(e){let t=e,n=Du(t.permissionsPolicy??t.featurePolicy);if(typeof n?.features!=`function`||typeof n.allowsFeature!=`function`)return;let r=n.features();return Array.isArray(r)&&r.includes(`tools`)?!!n.allowsFeature(`tools`):void 0}function wu(e,t,n){let r=e.serializedSchema===void 0?void 0:JSON.parse(e.serializedSchema);return{...e.annotations!==void 0&&{annotations:{...e.annotations}},description:e.description,...r!==void 0&&{inputSchema:r},name:e.name,origin:n,title:e.title,window:t}}function Tu(e){let t=Du(e);if(!t||typeof t.name!=`string`||typeof t.title!=`string`||typeof t.description!=`string`||t.serializedSchema!==void 0&&typeof t.serializedSchema!=`string`)throw TypeError(`Invalid tool metadata from the frame`);let n={name:t.name,title:t.title,description:t.description,annotations:void 0,serializedSchema:t.serializedSchema};if(t.annotations===void 0)return n;let r=Du(t.annotations);if(!r)throw TypeError(`Invalid tool annotations from the frame`);let i={};for(let e of mu){let t=r[e];if(t!==void 0){if(typeof t!=`boolean`)throw TypeError(`Invalid ${e} annotation from the frame`);i[e]=t}}return n.annotations=i,n}function Eu(e){if(typeof e!=`string`)return;let[t,n=``,r=``,i]=e.split(`:`);return t===hu&&i===void 0?{kind:n,id:r}:void 0}function Du(e){if(!(typeof e!=`object`||!e||Array.isArray(e)))return e}function Ou(e){try{return`postMessage`in e&&`window`in e}catch{return!1}}function q(){return new gu(`Tool execution failed`,`UnknownError`)}let ku=new WeakSet,Au=new WeakMap,ju=new WeakMap;function Mu(e){return e.isTrusted&&(ku.has(e)||e.eventPhase!==Event.NONE&&e.target instanceof HTMLFormElement&&ju.has(e.target))}function Nu(e,t){if(!Mu(e))throw new DOMException(`respondWith() is only available during an agent-invoked submit event`,`InvalidStateError`);if(!e.defaultPrevented)throw new DOMException(`respondWith() requires preventDefault() during an agent-invoked submit event`,`InvalidStateError`);if(e.eventPhase===Event.NONE)throw new DOMException(`respondWith() is only available while the submit event is being dispatched`,`InvalidStateError`);ku.add(e);let n=Promise.resolve(t);Au.set(e,n),e.target instanceof HTMLFormElement&&ju.get(e.target)?.respond(e)}let Pu=new Set([`email`,`password`,`search`,`tel`,`text`,`url`]),Fu=new Set([...Pu,`date`,`datetime-local`,`month`,`number`,`time`,`week`]);function Iu(e){return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement}function Lu(e){return Object.getOwnPropertyDescriptor(HTMLFormElement.prototype,`elements`)?.get?.call(e)}function Ru(e,t){return Element.prototype.getAttribute.call(e,t)}function zu(e,t){return Element.prototype.hasAttribute.call(e,t)}function Bu(e){return Object.getOwnPropertyDescriptor(Node.prototype,`isConnected`)?.get?.call(e)}function Vu(e){return Object.getOwnPropertyDescriptor(Element.prototype,`shadowRoot`)?.get?.call(e)}function Hu(e){return HTMLFormElement.prototype.checkValidity.call(e)}function Uu(e,t){HTMLFormElement.prototype.requestSubmit.call(e,t)}function Wu(e){return[...Lu(e)].filter(e=>Iu(e)&&!e.matches(`:disabled`)&&!(`readOnly`in e&&e.readOnly&&(e instanceof HTMLTextAreaElement||Fu.has(e.type))))}function Gu(e){let t=new Map;for(let n of Wu(e)){let e=n.name.trim(),r=t.get(e);r?r.push(n):t.set(e,[n])}return t}function Ku(e){return[...e.labels??[]].map(e=>{let t=e.cloneNode(!0);return t instanceof HTMLElement?(t.querySelectorAll(`button, input, meter, output, progress, select, textarea`).forEach(e=>e.remove()),t.textContent?.trim()??``):``}).filter(Boolean).join(`; `)}function qu(e,t){for(let n=t[0]?.parentElement;n&&n!==e;n=n.parentElement)if(n instanceof HTMLFieldSetElement&&t.every(e=>n.contains(e)))return n}function Ju(e,t){if(t.length===1){let e=t[0];return e&&(e.getAttribute(`toolparamdescription`)||Ku(e)||e.getAttribute(`aria-description`))||void 0}return qu(e,t)?.getAttribute(`toolparamdescription`)||void 0}function Yu(e,t,n,r){let i=Ju(t,n),a=i&&r?`${i} (${r})`:i||r;return a?{...e,description:a}:e}function Xu(e,t){let n=e.getAttribute(t);if(n===null||n.trim()===``)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function Zu(e,t){let n=Number(e.getAttribute(`step`));return Number.isFinite(n)&&n>0?n:t}function Qu(e,t){let n=e/t;return Math.abs(n-Math.round(n))<2**-52*16}function $u(e,t){let n=t.getAttribute(`pattern`);if(n===null)return e;try{new RegExp(n,`v`)}catch{return e}return{...e,pattern:n}}function ed(e){let t={type:`number`},n=Xu(e,`min`),r=Xu(e,`max`);if(n!==void 0&&(t.minimum=n),r!==void 0&&(t.maximum=r),e.getAttribute(`step`)!==`any`){let r=Zu(e,1),i=Number(e.getAttribute(`value`));Qu(n??(Number.isFinite(i)?i:0),r)&&(t.multipleOf=r)}return t}function td(e,t){let n=Zu(e,60);return n<1?`${t}(:[0-5][0-9](\\.[0-9]{1,3})?)?$`:n<60?`${t}(:[0-5][0-9])?$`:`${t}$`}function nd(e){return{anyOf:e.map(e=>({type:`string`,const:e.value,title:e.textContent??``})),enum:e.map(e=>e.value)}}function rd(e){return{anyOf:e.map(e=>{let t=Ku(e),n={type:`string`,const:e.value};return t&&(n.title=t),n}),enum:e.map(e=>e.value)}}function id(e,t){return e instanceof HTMLInputElement&&e.type===t}function ad(e){if(Pu.has(e.type))return $u({type:`string`},e);switch(e.type){case`hidden`:return e.getAttribute(`toolparamdescription`)?{type:`string`}:void 0;case`number`:return $u(ed(e),e);case`range`:{let t=ed(e);return t.minimum??=0,t.maximum??=100,t}case`checkbox`:return{type:`boolean`};case`date`:return{type:`string`,format:`date`};case`month`:return{type:`string`,format:`^[0-9]{4}-(0[1-9]|1[0-2])$`};case`week`:return{type:`string`,format:`^[0-9]{4}-W(0[1-9]|[1-4][0-9]|5[0-3])$`};case`time`:return{type:`string`,format:td(e,`^([01][0-9]|2[0-3]):[0-5][0-9]`)};case`datetime-local`:return{type:`string`,format:td(e,`^[0-9]{4}-(0[1-9]|1[0-2])-[0-9]{2}T([01][0-9]|2[0-3]):[0-5][0-9]`)};case`color`:return{type:`string`,format:`^#[0-9a-zA-Z]{6}$`};default:return}}function od(e,t){let[n]=t;if(!n)return;let r;if(t.every(e=>id(e,`radio`)))r={type:`string`,...rd(t)};else if(t.length>1)t.every(e=>id(e,`checkbox`))&&(r={type:`array`,items:{type:`string`,...rd(t)},uniqueItems:!0});else if(n instanceof HTMLTextAreaElement)r={type:`string`};else if(n instanceof HTMLSelectElement){let e=nd([...n.options]);r=n.multiple?{type:`array`,items:{type:`string`,...e},uniqueItems:!0}:{type:`string`,...e}}else r=ad(n);let i=n.type===`date`?`Dates MUST be provided in 'YYYY-MM-DD' format.`:void 0;return r&&Yu(r,e,t,i)}function sd(e){let t={},n=[];for(let[r,i]of Gu(e)){if(!r)continue;let a=od(e,i);a&&(Object.defineProperty(t,r,{configurable:!0,enumerable:!0,value:a,writable:!0}),i.some(e=>e.required)&&n.push(r))}return{type:`object`,properties:t,required:n}}function cd(e){return{name:Ru(e,`toolname`)??``,title:Ru(e,`tooltitle`)??``,description:Ru(e,`tooldescription`)??``,inputSchema:sd(e),autosubmit:zu(e,`toolautosubmit`)}}function ld(e){if(typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return String(e)}function ud(e){if(typeof e==`boolean`)return e;if(typeof e==`number`&&Number.isInteger(e))return e!==0;if(typeof e==`string`){if(e===`1`||e.toLowerCase()===`true`)return!0;if(e===`0`||e.toLowerCase()===`false`)return!1}}function dd(e,t){if(!Array.isArray(e))return!1;let n=new Set(t);for(let t of e){let e=ld(t);if(e===void 0||!n.delete(e))return!1}return!0}function fd(e,t){if(t===``)return e.type!==`number`&&e.type!==`range`;let n=e.ownerDocument.createElement(`input`);return n.type=e.type,n.value=t,n.value!==``}function pd(e,t,n){let[r]=t;if(!r||!od(e,t))return!1;let i=ld(n);if(t.every(e=>id(e,`radio`)))return t.some(e=>e.value===i);if(t.length>1)return dd(n,new Set(t.map(e=>e.value)));if(r instanceof HTMLSelectElement){let e=new Set([...r.options].map(e=>e.value));return r.multiple?dd(n,e):i!==void 0&&e.has(i)}return r instanceof HTMLTextAreaElement?i!==void 0:r.type===`checkbox`?ud(n)!==void 0:i!==void 0&&fd(r,i)}function md(e){e.dispatchEvent(new Event(`input`,{bubbles:!0,composed:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0}))}function hd(e,t){if(e.value===t)return;let n=e instanceof HTMLInputElement?HTMLInputElement.prototype:HTMLTextAreaElement.prototype;Object.getOwnPropertyDescriptor(n,`value`)?.set?.call(e,t),md(e)}function gd(e,t){e.checked!==t&&(Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,`checked`)?.set?.call(e,t),md(e))}function _d(e,t){let[n]=e,r=ld(t),i=new Set(Array.isArray(t)?t.map(ld):[]);if(e.every(e=>id(e,`radio`))){let t=e.find(e=>e.value===r);t&&gd(t,!0)}else if(e.length>1)for(let t of e)t instanceof HTMLInputElement&&gd(t,i.has(t.value));else if(n instanceof HTMLSelectElement)if(n.multiple){let e=!1;for(let t of n.options){let n=i.has(t.value);t.selected!==n&&(t.selected=n,e=!0)}e&&md(n)}else r!==void 0&&n.value!==r&&(n.value=r,md(n));else if(n&&id(n,`checkbox`)){let e=ud(t);e!==void 0&&gd(n,e)}else n&&r!==void 0&&hd(n,r)}function vd(e,t){if(Array.isArray(t))throw q();let n=Gu(e),r=[];for(let[i,a]of Object.entries(t)){let t=n.get(i);if(!t||!pd(e,t,a))throw q();r.push({controls:t,value:a})}for(let{controls:e,value:t}of r)_d(e,t)}function yd(e){return[...Lu(e)].find(e=>!e.matches(`:disabled`)&&(e instanceof HTMLButtonElement&&e.type===`submit`||e instanceof HTMLInputElement&&[`image`,`submit`].includes(e.type)))}function bd(e,t){let n=new Event(e);return Object.defineProperty(n,"toolName",{enumerable:!0,value:t}),n}function xd(e,t,n,r,i){let{form:a}=t;return t.cancelPending?.(q()),new Promise((o,s)=>{let c=!1,l=()=>{EventTarget.prototype.removeEventListener.call(a,`invalid`,p,!0),i.removeEventListener(`abort`,m),ju.delete(a),t.cancelPending===d&&delete t.cancelPending},u=e=>{c||(c=!0,l(),e())},d=e=>u(()=>s(e)),f=e=>{t.cancelPending===d&&delete t.cancelPending,e.then(e=>u(()=>o(e??null)),e=>u(()=>s(e)))},p=e=>{e.isTrusted&&queueMicrotask(()=>{Hu(a)||d(q())})},m=()=>{u(()=>{e.dispatchEvent(bd(`toolcancel`,n.name)),s(i.reason)})};if(ju.set(a,{complete(e){setTimeout(()=>{let t=Au.get(e);t?f(t):e.defaultPrevented?d(q()):u(()=>o(null))})},direct(){u(()=>o(null))},respond(e){queueMicrotask(()=>{let t=Au.get(e);t&&f(t)})}}),t.cancelPending=d,EventTarget.prototype.addEventListener.call(a,`invalid`,p,!0),i.addEventListener(`abort`,m,{once:!0}),!n.autosubmit){r?.focus(),e.dispatchEvent(bd(`toolactivated`,n.name));return}try{Uu(a,r),e.dispatchEvent(bd(`toolactivated`,n.name))}catch(e){d(e)}})}function Sd(e){let t=SubmitEvent.prototype;if(`agentInvoked`in t&&`respondWith`in t)return;`agentInvoked`in t||Object.defineProperty(t,"agentInvoked",{configurable:!0,enumerable:!0,get(){return Mu(this)}}),`respondWith`in t||Object.defineProperty(t,"respondWith",{configurable:!0,enumerable:!0,writable:!0,value(e){Nu(this,e)}});let n=new Map,r=new Map,i=new Map,a=e=>{if(!(e instanceof SubmitEvent)||!e.isTrusted||!(e.target instanceof HTMLFormElement))return;let t=ju.get(e.target);t&&(ku.add(e),t.complete(e))},o=e=>{if(!e.isTrusted||!(e.target instanceof HTMLFormElement))return;let t=e.target;setTimeout(()=>{e.defaultPrevented||n.get(t)?.cancelPending?.(q())})};function s(e){i.get(e)?.disconnect(),i.delete(e),e.removeEventListener(`reset`,o,!0),e.removeEventListener(`submit`,a,!0)}function c(e){if(i.has(e))return;let t=new MutationObserver(l);i.set(e,t),t.observe(e,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),e.addEventListener(`reset`,o,!0),e.addEventListener(`submit`,a,!0)}function l(){c(document);for(let e of i.keys())e instanceof ShadowRoot&&!e.host.isConnected&&s(e);let t=new Set,a=new Map,o=new Map;for(let e of i.keys())for(let n of e.querySelectorAll(`*`)){let e=Vu(n);if(e&&c(e),!(n instanceof HTMLFormElement)||!zu(n,`toolname`)||!zu(n,`tooldescription`)||!Bu(n))continue;let i=n;t.add(i);let s=cd(i),l=JSON.stringify(s),u=r.get(i);if(u===l)continue;r.delete(i);let d=o.get(s.name);if(d){if(u===void 0){r.set(i,l);continue}let e=a.get(d);e&&r.set(d,e.fingerprint),a.delete(d)}o.set(s.name,i),a.set(i,{definition:s,fingerprint:l})}for(let e of r.keys())t.has(e)||r.delete(e);for(let[e,t]of n)a.get(e)?.fingerprint!==t.fingerprint&&(t.cancelPending?.(q()),t.controller.abort(),n.delete(e));for(let[t,{definition:r,fingerprint:i}]of a){if(n.has(t))continue;let a=new AbortController,o={controller:a,fingerprint:i,form:t};n.set(t,o),e.registerTool({name:r.name,title:r.title,description:r.description,inputSchema:r.inputSchema,execute(n,i){let a=yd(t);if(!r.autosubmit&&!a)throw q();return vd(t,n),xd(e,o,r,a,i.signal)}},{signal:a.signal}).catch(e=>{a.abort(),!(e instanceof DOMException&&e.name===`AbortError`)&&console.error(`[webmcp] declarative form tool "${r.name}" was not registered:`,e)})}}let u=Object.getOwnPropertyDescriptor(Element.prototype,`attachShadow`);if(u?.configurable){let e=Element.prototype.attachShadow,t=function(t){let n=e.call(this,t);return n.mode===`open`&&Object.getOwnPropertyDescriptor(Node.prototype,`ownerDocument`)?.get?.call(this)===document&&Bu(this)&&c(n),n};Object.defineProperty(Element.prototype,"attachShadow",{...u,value:t})}let d=Object.getOwnPropertyDescriptor(HTMLFormElement.prototype,`submit`);if(d?.configurable){let e=HTMLFormElement.prototype.submit,t=function(){e.call(this),ju.get(this)?.direct()};Object.defineProperty(HTMLFormElement.prototype,"submit",{...d,value:t})}l()}
|
|
65
65
|
/*!
|
|
66
66
|
* Copyright (c) 2026 WebMCP polyfill contributors
|
|
67
67
|
* SPDX-License-Identifier: MIT
|
|
68
68
|
*/
|
|
69
|
-
let Cd=globalThis.DOMException,wd=Object.getOwnPropertyDescriptor(globalThis,`window`)?.get,Td=new WeakMap;function Ed(){if(typeof document>`u`||!globalThis.isSecureContext||`modelContext`in document)return;let e=Document.prototype,t=Object.getOwnPropertyDescriptor(e,`defaultView`).get,n=Object.getOwnPropertyDescriptor(globalThis,`ModelContext`);if(!Object.isExtensible(e)||n&&!n.configurable||!n&&!Object.isExtensible(globalThis))throw TypeError(`Cannot install WebMCP on this realm`);Object.defineProperty(globalThis,"ModelContext",{value:kd,configurable:!0,writable:!0});let{getModelContext:r}={getModelContext(){t.call(this);let e=Td.get(this);return e||(e=new Dd(this),Td.set(this,e)),e}};Object.defineProperty(r,"name",{value:`get modelContext`}),Object.defineProperty(e,"modelContext",{configurable:!0,enumerable:!0,get:r}),document.modelContext}var Dd=class extends EventTarget{#e;#t=new Map;#n;#r=null;#i=e=>{let t=this.#r;typeof t==`function`&&Reflect.apply(t,this,[e])===!1&&Event.prototype.preventDefault.call(e)};constructor(e){super(),this.#e=e;let t=Su(e);t&&(this.#n=new _u(t,{getTools:e=>this.#s(e),execute:(t,n,r,i)=>{let a=Wd(e).origin;return this.#a(n,r,a,t,i)},changed:()=>this.#c()}))}get ontoolchange(){return this.#r}set ontoolchange(e){let t=Nd(e)?e:null;!this.#r&&t&&this.addEventListener(`toolchange`,this.#i),this.#r&&!t&&this.removeEventListener(`toolchange`,this.#i),this.#r=t}async registerTool(e,t={}){let n=this.#e,{name:r,title:i,description:a,annotations:o,inputSchema:s,execute:c}=Ad(e),l=Pd(t),u=Vd(l.exposedTo),d=Bd(l.signal);Wd(n);let f=()=>{if(this.#t.has(r))throw new Cd(`A tool named ${r} is already registered`,`InvalidStateError`)};if(f(),!/^[A-Za-z0-9_.-]{1,128}$/u.test(r))throw new Cd(`Tool names are 1 to 128 characters of ASCII alphanumerics, "_", "-" or ".": ${r}`,`InvalidStateError`);if(!a)throw new Cd(`A tool description cannot be empty`,`InvalidStateError`);let p=s===void 0?void 0:zd(s);d?.throwIfAborted();let m=Hd(u),h={metadata:{name:r,title:i,description:a,annotations:o,serializedSchema:p},execute:c,exposedTo:m},g=await this.#o();return d?.throwIfAborted(),f(),new Promise((e,t)=>{d?.addEventListener(`abort`,()=>{this.#t.delete(r),g.notify(m),t(d.reason)},{once:!0}),this.#t.set(r,h),g.notify(m).then(e,t)})}async getTools(e={}){let t=this.#e,n=Vd(Pd(e).fromOrigins);Wd(t);let r=await this.#o(),i=Hd(n),a=await r.getTools(i);return a.sort((e,t)=>e.name===t.name?0:e.name<t.name?-1:1),new Promise(e=>{qd(()=>e(a))})}async executeTool(e,t={},n={}){let r=this.#e,i=jd(e),a=Bd(Pd(n).signal);Wd(r);let o=URL.parse(i.origin)?.origin;if(!o||o===`null`)throw new Cd(`Invalid or opaque origin`,`NotSupportedError`);if(!Nd(t))throw TypeError(`inputObject must be an object`);let s=zd(t);a?.throwIfAborted();let c=await this.#o();a?.throwIfAborted();let l=Wd(r);return i.window===l?this.#a(i.name,s,o,l.origin,a):c.execute(i.window,o,i.name,s,a)}#a(e,t,n,r,i){return new Promise((a,o)=>{i?.throwIfAborted();let s=new AbortController,c=!1,l=()=>{o(i.reason),qd(()=>{c||s.abort()})},u=()=>{c=!0,qd(()=>{i?.removeEventListener(`abort`,l),o(q())})},d=e=>{if(c=!0,!i?.aborted)try{let t=zd(e);qd(()=>{i?.removeEventListener(`abort`,l),a(t)})}catch{u()}};i?.addEventListener(`abort`,l,{once:!0}),qd(()=>{if(!i?.aborted)try{let i=Wd(this.#e),a=this.#t.get(e);if(!a||n!==i.origin||!Od(a,i.origin,r)){u();return}let o=JSON.parse(t);if(!Nd(o)){u();return}let c=a.execute,l=c(o,{signal:s.signal});Promise.resolve(l).then(d,u)}catch{u()}})})}async#o(){let e=this.#n;if(!e||!await e.allowed())throw new Cd(`WebMCP is disabled by Permissions Policy`,`NotAllowedError`);return Wd(this.#e),e}#s(e){let t=Wd(this.#e).origin,n=[];for(let r of this.#t.values())Od(r,t,e)&&n.push(r.metadata);return n}#c(){return new Promise(e=>{qd(()=>{this.dispatchEvent(new Event(`toolchange`)),e()})})}};function Od(e,t,n){return t===n||e.exposedTo.includes(n)}let kd=function(){throw TypeError(`Illegal constructor`)};Object.defineProperty(kd,"name",{value:`ModelContext`}),Object.defineProperty(kd,"prototype",{value:Dd.prototype,writable:!1}),Object.setPrototypeOf(kd,EventTarget),Object.defineProperties(Dd.prototype,{constructor:{value:kd,configurable:!0,writable:!0},[Symbol.toStringTag]:{value:`ModelContext`,configurable:!0},registerTool:{enumerable:!0},getTools:{enumerable:!0},executeTool:{enumerable:!0},ontoolchange:{enumerable:!0}});function Ad(e){let t=Pd(e),n=Fd(t.annotations),r=Id(Rd(t.description,`description`)),i=Rd(t.execute,`execute`);if(typeof i!=`function`)throw TypeError(`execute must be a function`);let a=i,o=Md(t.inputSchema),s=Id(Rd(t.name,`name`)),c=t.title;return{name:s,title:c===void 0?``:Ld(c),description:r,annotations:n,inputSchema:o,execute:a}}function jd(e){let t=Pd(e);Fd(t.annotations),Id(Rd(t.description,`description`)),Md(t.inputSchema);let n=Id(Rd(t.name,`name`)),r=Ld(Rd(t.origin,`origin`)),i=t.title;i!==void 0&&Id(i);let a=Rd(t.window,`window`);if(!Nd(a))throw TypeError(`window must be a Window`);return wd.call(a),{name:n,origin:r,window:a}}function Md(e){if(e!==void 0&&!Nd(e))throw TypeError(`inputSchema must be an object`);return e}function Nd(e){return typeof e==`object`&&!!e||typeof e==`function`}function Pd(e){if(e==null)return{};if(!Nd(e))throw TypeError(`Expected a dictionary`);return e}function Fd(e){if(e===void 0)return;let t=Pd(e),n={};for(let e of mu)n[e]=!!t[e];return n}function Id(e){if(typeof e==`symbol`)throw TypeError(`Cannot convert a Symbol to a string`);return String(e)}function Ld(e){return Id(e).toWellFormed()}function Rd(e,t){if(e===void 0)throw TypeError(`${t} is required`);return e}function zd(e){let t=JSON.stringify(e);if(t===void 0)throw TypeError(`Value is not JSON-serializable`);return t}function Bd(e){if(e!==void 0)return AbortSignal.any([e])}function Vd(e){if(e===void 0)return[];if(!Nd(e))throw TypeError(`Origins must be a sequence`);let t=Pd(e)[Symbol.iterator];if(typeof t!=`function`)throw TypeError(`Origins must be a sequence`);let n={[Symbol.iterator](){let n=Reflect.apply(t,e,[]);if(!Nd(n))throw TypeError(`Iterator must be an object`);let r=Pd(n).next;if(typeof r!=`function`)throw TypeError(`Iterator next must be a function`);return{next(){return Reflect.apply(r,n,[])}}}};return Array.from(n,Ld)}function Hd(e){return e.map(e=>{let t=URL.parse(e)?.origin;if(t===void 0)throw new Cd(`Invalid origin`,`SecurityError`);let n=URL.parse(t);if(!n||!Ud(n))throw new Cd(`Origin is not potentially trustworthy`,`SecurityError`);return t})}function Ud({protocol:e,hostname:t}){if([`https:`,`wss:`].includes(e))return!0;let n=t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t),r=t===`localhost`||t===`localhost.`||t.endsWith(`.localhost`)||t.endsWith(`.localhost.`);return[`http:`,`ws:`].includes(e)&&(n||r)}function Wd(e){let t=Su(e);if(!t)throw new Cd(`The document is not fully active`,`InvalidStateError`);if(t.originAgentCluster===!1&&t.location.protocol!==`file:`)throw new Cd(`An origin-keyed agent cluster is required`,`SecurityError`);if(Cu(e)===!1)throw new Cd(`WebMCP is disabled by Permissions Policy`,`NotAllowedError`);return t}let Gd,Kd=[];function qd(e){if(!Gd){let e=new MessageChannel;e.port1.onmessage=()=>Kd.shift()?.(),Gd=e.port2}Kd.push(e),Gd.postMessage(void 0)}function Jd(){if(typeof document>`u`||!globalThis.isSecureContext||typeof Promise.withResolvers!=`function`||typeof AbortSignal.any!=`function`||typeof String.prototype.toWellFormed!=`function`||typeof URL.parse!=`function`)return;Ed();let e=document.modelContext;e&&Sd(e)}let Yd=/^[A-Za-z0-9_.-]{1,128}$/u;function J(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xd(e){return e!==null&&(typeof e==`object`||typeof e==`function`)}function Zd(e){if(typeof e==`symbol`)throw TypeError(`Symbol values cannot be converted to a DOMString`);return String(e)}function Qd(e){let{name:t,description:n,title:r}=e;if(t===void 0)throw TypeError(`Tool "name" is required`);if(n===void 0)throw TypeError(`Tool "description" is required`);let{annotations:i,inputSchema:a,outputSchema:o,execute:s}=e,c=Zd(t),l=r===void 0?void 0:Zd(r).toWellFormed(),u={name:c,description:Zd(n),execute:s};if(l!==void 0&&(u.title=l),a!==void 0&&(u.inputSchema=a),o!==void 0&&(u.outputSchema=o),i!==void 0){let e=J(i)?i:{},t={readOnlyHint:!!e.readOnlyHint,untrustedContentHint:!!e.untrustedContentHint};e.title!==void 0&&(t.title=Zd(e.title).toWellFormed());for(let n of[`destructiveHint`,`idempotentHint`,`openWorldHint`,`consequentialHint`,`debugging`]){let r=e[n];r!==void 0&&(t[n]=!!r)}u.annotations=t}return ef(u),u}function $d(e){return new DOMException(e,`InvalidStateError`)}function ef(e){if(e.name===``)throw $d(`Tool "name" must be a non-empty string`);if(!Yd.test(e.name))throw $d(`Tool "name" must be 1–128 characters and contain only ASCII alphanumeric, underscore, hyphen, or period`);if(e.description.length===0)throw $d(`Tool "description" must be a non-empty string`);if(typeof e.execute!=`function`)throw TypeError(`Tool "execute" must be a function`)}function tf(e){if(!Xd(e))throw TypeError(`inputSchema must be an object`);let t=JSON.stringify(e);if(t===void 0)throw TypeError(`inputSchema must be JSON-serializable`);return t}let nf={type:`object`,properties:{}},rf=[`draft-2020-12`,`draft-07`];function af(e){if(!J(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function of(e,t=new WeakSet){if(e===null||typeof e==`string`||typeof e==`boolean`)return!0;if(typeof e==`number`)return Number.isFinite(e);if(typeof e!=`object`||t.has(e))return!1;t.add(e);try{return(Array.isArray(e)?e:af(e)?Object.values(e):null)?.every(e=>of(e,t))??!1}catch{return!1}finally{t.delete(e)}}function sf(e){if(!J(e))return!1;switch(e.type){case`text`:return typeof e.text==`string`;case`image`:case`audio`:return typeof e.data==`string`&&typeof e.mimeType==`string`;case`resource_link`:return typeof e.uri==`string`&&typeof e.name==`string`;case`resource`:{let t=e.resource;return J(t)&&typeof t.uri==`string`&&(typeof t.text==`string`||typeof t.blob==`string`)}default:return!1}}function cf(e){return J(e)&&of(e)&&Array.isArray(e.content)&&e.content.every(sf)&&(e.isError===void 0||typeof e.isError==`boolean`)&&(e._meta===void 0||J(e._meta))}function lf(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function uf(e){if(cf(e))return e;let t={content:[{type:`text`,text:lf(e)}],isError:!1};return of(e)&&(t.structuredContent=e),t}function df(e){if(!J(e))return null;let t=e[`~standard`];return J(t)?t:null}function ff(e){let t=df(e);return!!(t&&t.version===1&&typeof t.validate==`function`)}function pf(e){let t=df(e);return!t||t.version!==1||!J(t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function mf(e){let t=df(e);return!!(t&&t.version===1&&typeof t.vendor==`string`&&typeof t.validate==`function`&&J(t.jsonSchema)&&typeof t.jsonSchema.input==`function`&&typeof t.jsonSchema.output==`function`)}function hf(e){for(let t of rf)try{let n=e[`~standard`].jsonSchema.input({target:t}),r=JSON.parse(tf(n));if(J(r))return r}catch{}throw Error(`Failed to convert Standard JSON Schema inputSchema to a JSON Schema object`)}function gf(e){if(e===void 0)return{inputSchema:nf};if(pf(e)){let t=hf(e),n=tf(t);return ff(e)&&Object.defineProperty(t,"~standard",{value:e[`~standard`]}),{inputSchema:t,registeredInputSchema:n}}if(ff(e))throw Error(`Standard Schema inputSchema must provide ~standard.jsonSchema.input() for tool metadata`);let t=tf(e),n=JSON.parse(t);return!J(n)||Object.keys(n).length===0?{inputSchema:nf,registeredInputSchema:t}:{inputSchema:n.type===void 0?{type:`object`,...n}:n,registeredInputSchema:t}}var _f=Object.defineProperty,vf=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),yf=(e,t)=>{let n={};for(var r in e)_f(n,r,{get:e[r],enumerable:!0});return t&&_f(n,Symbol.toStringTag,{value:`Module`}),n};let bf=new Set([`https://json-schema.org/draft/2020-12/schema`,`http://json-schema.org/draft/2020-12/schema`]),xf=new Set([`https://json-schema.org/draft/2019-09/schema`,`http://json-schema.org/draft/2019-09/schema`]),Sf=new Set([`https://json-schema.org/draft-07/schema`,`http://json-schema.org/draft-07/schema`]),Cf=new Set([`https://json-schema.org/draft-06/schema`,`http://json-schema.org/draft-06/schema`]);function wf(e){return typeof e==`string`&&xf.has(e.replace(/#$/,``))}function Tf(e,t){if(!(`$schema`in e)||typeof e.$schema!=`string`)return`2020-12`;let n=e.$schema.replace(/#$/,``);if(bf.has(n))return`2020-12`;if(xf.has(n))return`2019-09`;if(Sf.has(n)||Cf.has(n))return`draft-7`;throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}let Ef=Symbol.for(`mcp.sdk.errorBrands`);function Df(e,t){let n=new Set,r=t;for(;typeof r==`function`;){let e=r.mcpBrand;Object.prototype.hasOwnProperty.call(r,`mcpBrand`)&&typeof e==`string`&&n.add(e),r=Object.getPrototypeOf(r)}n.size!==0&&Object.defineProperty(e,Ef,{value:n,enumerable:!1,configurable:!0})}function Of(e,t){try{if(typeof t==`object`&&t&&Object.prototype.hasOwnProperty.call(e,`mcpBrand`)&&typeof e.mcpBrand==`string`&&Object.prototype.hasOwnProperty.call(t,Ef)){let n=t[Ef];if(n&&typeof n.has==`function`&&n.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}(class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.OAuthError`})}static[Symbol.hasInstance](e){return Of(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Of(this,e)}constructor(e,t,n){super(t),this.code=e,this.errorUri=n,this.name=`OAuthError`,Df(this,new.target)}toResponseObject(){let e={error:this.code,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}});let Y=function(e){return e.NotConnected=`NOT_CONNECTED`,e.AlreadyConnected=`ALREADY_CONNECTED`,e.NotInitialized=`NOT_INITIALIZED`,e.CapabilityNotSupported=`CAPABILITY_NOT_SUPPORTED`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.ConnectionClosed=`CONNECTION_CLOSED`,e.SendFailed=`SEND_FAILED`,e.InvalidResult=`INVALID_RESULT`,e.UnsupportedResultType=`UNSUPPORTED_RESULT_TYPE`,e.InputRequiredRoundsExceeded=`INPUT_REQUIRED_ROUNDS_EXCEEDED`,e.ListPaginationExceeded=`LIST_PAGINATION_EXCEEDED`,e.MethodNotSupportedByProtocolVersion=`METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION`,e.EraNegotiationFailed=`ERA_NEGOTIATION_FAILED`,e.ClientHttpNotImplemented=`CLIENT_HTTP_NOT_IMPLEMENTED`,e.ClientHttpAuthentication=`CLIENT_HTTP_AUTHENTICATION`,e.ClientHttpForbidden=`CLIENT_HTTP_FORBIDDEN`,e.ClientHttpUnexpectedContent=`CLIENT_HTTP_UNEXPECTED_CONTENT`,e.ClientHttpFailedToOpenStream=`CLIENT_HTTP_FAILED_TO_OPEN_STREAM`,e.ClientHttpFailedToTerminateSession=`CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION`,e}({});var X=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SdkError`})}static[Symbol.hasInstance](e){return Of(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Of(this,e)}constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`SdkError`,Df(this,new.target)}};(class extends X{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SdkHttpError`})}constructor(e,t,n){super(e,t,n),this.name=`SdkHttpError`}get status(){return this.data.status}get statusText(){return this.data.statusText}});function kf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Af(e,t,n){return e===`elicitation`&&t===`form`&&n.form===void 0&&n.url===void 0}function jf(e){switch(e.method){case`elicitation/create`:return e.params?.mode===`url`?{elicitation:{url:{}}}:{elicitation:{form:{}}};case`sampling/createMessage`:{let t=e.params;return t!==void 0&&(t.tools!==void 0||t.toolChoice!==void 0)?{sampling:{tools:{}}}:{sampling:{}}}case`roots/list`:return{roots:{}};default:return}}function Mf(e,t){let n={};for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let e=t===void 0?void 0:t[r];if(e===void 0){n[r]=i;continue}if(kf(i)&&kf(e)){let t={};for(let[n,a]of Object.entries(i))a!==void 0&&e[n]===void 0&&!Af(r,n,e)&&(t[n]=a);Object.keys(t).length>0&&(n[r]=t)}}return Object.keys(n).length>0?n:void 0}function Nf(e){return e>=`2026-07-28`}function Pf(e){return e.filter(e=>!Nf(e))}function Ff(e){return e.filter(e=>Nf(e))}function If(e){let t=e.structuredContent;return t===void 0||!(typeof t!=`object`||!t||Array.isArray(t))||(e.content?.some(e=>e.type===`text`)??!1)?e:{...e,content:[...e.content??[],{type:`text`,text:JSON.stringify(t)}]}}let Lf=[`task`,`inputRequests`,`requestState`];function Rf(e){return typeof e!=`object`||!e||Array.isArray(e)||e.content!==void 0||Lf.some(t=>t in e)?e:{...e,content:[]}}function zf(){let e=Fo(()=>L([k(),j(),M(),Za(),R(k(),e),P(e)])),t=R(k(),e),n=L([k(),j().int()]),r=k(),i=F({ttl:j().optional()}),a=F({taskId:k()}),o=I({progressToken:n.optional(),"io.modelcontextprotocol/related-task":a.optional()}),s=F({_meta:o.optional()}),c=s.extend({task:i.optional()}),l=F({method:k(),params:s.loose().optional()}),u=F({_meta:o.optional()}),d=F({method:k(),params:u.loose().optional()}),f=I({_meta:o.optional()}),p=L([k(),j().int()]),m=f.strict(),h=u.extend({requestId:p.optional(),reason:k().optional()}),g=d.extend({method:B(`notifications/cancelled`),params:h}),_=F({src:k(),mimeType:k().optional(),sizes:P(k()).optional(),theme:z([`light`,`dark`]).optional()}),ee=F({icons:P(_).optional()}),te=F({name:k(),title:k().optional()}),ne=te.extend({...te.shape,...ee.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),re=zo(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,lo(F({form:lo(F({applyDefaults:M().optional()}),t).optional(),url:t.optional()}),t.optional())),ie=I({list:t.optional(),cancel:t.optional(),requests:I({sampling:I({createMessage:t.optional()}).optional(),elicitation:I({create:t.optional()}).optional()}).optional()}),ae=I({list:t.optional(),cancel:t.optional(),requests:I({tools:I({call:t.optional()}).optional()}).optional()}),oe=F({experimental:R(k(),t).optional(),sampling:F({context:t.optional(),tools:t.optional()}).optional(),elicitation:re.optional(),roots:F({listChanged:M().optional()}).optional(),tasks:ie.optional(),extensions:R(k(),t).optional()}),se=s.extend({protocolVersion:k(),capabilities:oe,clientInfo:ne}),ce=l.extend({method:B(`initialize`),params:se}),le=F({experimental:R(k(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:F({listChanged:M().optional()}).optional(),resources:F({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:F({listChanged:M().optional()}).optional(),tasks:ae.optional(),extensions:R(k(),t).optional()}),v=f.extend({protocolVersion:k(),capabilities:le,serverInfo:ne,instructions:k().optional()}),ue=d.extend({method:B(`notifications/initialized`),params:u.optional()}),de=l.extend({method:B(`ping`),params:s.optional()}),fe=F({progress:j(),total:V(j()),message:V(k())}),pe=F({...u.shape,...fe.shape,progressToken:n}),me=d.extend({method:B(`notifications/progress`),params:pe}),he=s.extend({cursor:r.optional()}),ge=l.extend({params:he.optional()}),_e=f.extend({nextCursor:r.optional()}),ve=F({uri:k(),mimeType:V(k()),_meta:R(k(),N()).optional()}),ye=ve.extend({text:k()}),be=k().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),xe=ve.extend({blob:be}),y=z([`user`,`assistant`]),b=F({audience:P(y).optional(),priority:j().min(0).max(1).optional(),lastModified:ta({offset:!0}).optional()}),Se=F({...te.shape,...ee.shape,uri:k(),description:V(k()),mimeType:V(k()),size:V(j()),annotations:b.optional(),_meta:V(I({}))}),Ce=F({...te.shape,...ee.shape,uriTemplate:k(),description:V(k()),mimeType:V(k()),annotations:b.optional(),_meta:V(I({}))}),we=ge.extend({method:B(`resources/list`)}),Te=_e.extend({resources:P(Se)}),x=ge.extend({method:B(`resources/templates/list`)}),Ee=_e.extend({resourceTemplates:P(Ce)}),De=s.extend({uri:k()}),Oe=De,ke=l.extend({method:B(`resources/read`),params:Oe}),Ae=f.extend({contents:P(L([ye,xe]))}),je=d.extend({method:B(`notifications/resources/list_changed`),params:u.optional()}),Me=De,Ne=l.extend({method:B(`resources/subscribe`),params:Me}),S=De,Pe=l.extend({method:B(`resources/unsubscribe`),params:S}),Fe=u.extend({uri:k()}),Ie=d.extend({method:B(`notifications/resources/updated`),params:Fe}),Le=F({name:k(),description:V(k()),required:V(M())}),Re=F({...te.shape,...ee.shape,description:V(k()),arguments:V(P(Le)),_meta:V(I({}))}),ze=ge.extend({method:B(`prompts/list`)}),Be=_e.extend({prompts:P(Re)}),Ve=s.extend({name:k(),arguments:R(k(),k()).optional()}),He=l.extend({method:B(`prompts/get`),params:Ve}),Ue=F({type:B(`text`),text:k(),annotations:b.optional(),_meta:R(k(),N()).optional()}),We=F({type:B(`image`),data:be,mimeType:k(),annotations:b.optional(),_meta:R(k(),N()).optional()}),Ge=F({type:B(`audio`),data:be,mimeType:k(),annotations:b.optional(),_meta:R(k(),N()).optional()}),Ke=F({type:B(`tool_use`),name:k(),id:k(),input:R(k(),N()),_meta:R(k(),N()).optional()}),qe=F({type:B(`resource`),resource:L([ye,xe]),annotations:b.optional(),_meta:R(k(),N()).optional()}),Je=Se.extend({type:B(`resource_link`)}),Ye=L([Ue,We,Ge,Je,qe]),Xe=F({role:y,content:Ye}),Ze=f.extend({description:k().optional(),messages:P(Xe)}),Qe=d.extend({method:B(`notifications/prompts/list_changed`),params:u.optional()}),$e=F({title:k().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),et=F({taskSupport:z([`required`,`optional`,`forbidden`]).optional()}),tt=F({...te.shape,...ee.shape,description:k().optional(),inputSchema:F({type:B(`object`),properties:R(k(),e).optional(),required:P(k()).optional()}).catchall(N()),outputSchema:F({type:B(`object`),properties:R(k(),e).optional(),required:P(k()).optional()}).catchall(N()).optional(),annotations:$e.optional(),execution:et.optional(),_meta:R(k(),N()).optional()}),nt=ge.extend({method:B(`tools/list`)}),rt=_e.extend({tools:P(tt)}),it=f.extend({content:P(Ye),structuredContent:R(k(),N()).optional(),isError:M().optional()}),C=c.extend({name:k(),arguments:R(k(),N()).optional()}),at=l.extend({method:B(`tools/call`),params:C}),ot=d.extend({method:B(`notifications/tools/list_changed`),params:u.optional()}),st=z([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),ct=s.extend({level:st}),lt=l.extend({method:B(`logging/setLevel`),params:ct}),ut=u.extend({level:st,logger:k().optional(),data:N()}),dt=d.extend({method:B(`notifications/message`),params:ut}),ft=F({name:k().optional()}),pt=F({hints:P(ft).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),mt=F({mode:z([`auto`,`required`,`none`]).optional()}),ht=F({type:B(`tool_result`),toolUseId:k().describe(`The unique identifier for the corresponding tool call.`),content:P(Ye),structuredContent:F({}).loose().optional(),isError:M().optional(),_meta:R(k(),N()).optional()}),gt=so(`type`,[Ue,We,Ge]),w=so(`type`,[Ue,We,Ge,Ke,ht]),_t=F({role:y,content:L([w,P(w)]),_meta:R(k(),N()).optional()}),vt=c.extend({messages:P(_t),modelPreferences:pt.optional(),systemPrompt:k().optional(),includeContext:z([`none`,`thisServer`,`allServers`]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:P(k()).optional(),metadata:t.optional(),tools:P(tt).optional(),toolChoice:mt.optional()}),yt=l.extend({method:B(`sampling/createMessage`),params:vt}),bt=f.extend({model:k(),stopReason:V(z([`endTurn`,`stopSequence`,`maxTokens`]).or(k())),role:y,content:gt}),xt=f.extend({model:k(),stopReason:V(z([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(k())),role:y,content:L([w,P(w)])}),St=F({type:B(`boolean`),title:k().optional(),description:k().optional(),default:M().optional()}),Ct=F({type:B(`string`),title:k().optional(),description:k().optional(),minLength:j().optional(),maxLength:j().optional(),format:z([`email`,`uri`,`date`,`date-time`]).optional(),default:k().optional()}),wt=F({type:z([`number`,`integer`]),title:k().optional(),description:k().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),Tt=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),default:k().optional()}),Et=F({type:B(`string`),title:k().optional(),description:k().optional(),oneOf:P(F({const:k(),title:k()})),default:k().optional()}),Dt=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),enumNames:P(k()).optional(),default:k().optional()}),Ot=L([Tt,Et]),kt=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({type:B(`string`),enum:P(k())}),default:P(k()).optional()}),At=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({anyOf:P(F({const:k(),title:k()}))}),default:P(k()).optional()}),jt=L([kt,At]),Mt=L([Dt,Ot,jt]),Nt=L([Mt,St,Ct,wt]),Pt=c.extend({mode:B(`form`).optional(),message:k(),requestedSchema:F({type:B(`object`),properties:R(k(),Nt),required:P(k()).optional()}).catchall(N())}),T=c.extend({mode:B(`url`),message:k(),elicitationId:k(),url:k().url()}),Ft=L([Pt,T]),E=l.extend({method:B(`elicitation/create`),params:Ft}),It=u.extend({elicitationId:k()}),Lt=d.extend({method:B(`notifications/elicitation/complete`),params:It}),Rt=f.extend({action:z([`accept`,`decline`,`cancel`]),content:zo(e=>e===null?void 0:e,R(k(),L([k(),j(),M(),P(k())])).optional())}),zt=F({type:B(`ref/resource`),uri:k()}),Bt=F({type:B(`ref/prompt`),name:k()}),Vt=s.extend({ref:L([Bt,zt]),argument:F({name:k(),value:k()}),context:F({arguments:R(k(),k()).optional()}).optional()}),Ht=l.extend({method:B(`completion/complete`),params:Vt}),Ut=f.extend({completion:I({values:P(k()).max(100),total:V(j().int()),hasMore:V(M())})}),Wt=F({uri:k().startsWith(`file://`),name:k().optional(),_meta:R(k(),N()).optional()}),Gt=l.extend({method:B(`roots/list`),params:s.optional()}),Kt=f.extend({roots:P(Wt)}),qt=d.extend({method:B(`notifications/roots/list_changed`),params:u.optional()}),Jt=I({ttl:j().optional(),pollInterval:j().optional()}),Yt=z([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Xt=F({taskId:k(),status:Yt,ttl:L([j(),Za()]),createdAt:k(),lastUpdatedAt:k(),pollInterval:V(j()),statusMessage:V(k())}),Zt=f.extend({task:Xt}),Qt=u.merge(Xt),$t=d.extend({method:B(`notifications/tasks/status`),params:Qt}),en=l.extend({method:B(`tasks/get`),params:s.extend({taskId:k()})}),tn=f.merge(Xt),nn=l.extend({method:B(`tasks/result`),params:s.extend({taskId:k()})}),rn=f.loose(),an=ge.extend({method:B(`tasks/list`)}),on=_e.extend({tasks:P(Xt)}),sn=l.extend({method:B(`tasks/cancel`),params:s.extend({taskId:k()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,TaskMetadataSchema:i,RelatedTaskMetadataSchema:a,RequestMetaSchema:o,BaseRequestParamsSchema:s,TaskAugmentedRequestParamsSchema:c,RequestSchema:l,NotificationsParamsSchema:u,NotificationSchema:d,ResultSchema:f,RequestIdSchema:p,EmptyResultSchema:m,CancelledNotificationParamsSchema:h,CancelledNotificationSchema:g,IconSchema:_,IconsSchema:ee,BaseMetadataSchema:te,ImplementationSchema:ne,ClientTasksCapabilitySchema:ie,ServerTasksCapabilitySchema:ae,ClientCapabilitiesSchema:oe,InitializeRequestParamsSchema:se,InitializeRequestSchema:ce,ServerCapabilitiesSchema:le,InitializeResultSchema:v,InitializedNotificationSchema:ue,PingRequestSchema:de,ProgressSchema:fe,ProgressNotificationParamsSchema:pe,ProgressNotificationSchema:me,PaginatedRequestParamsSchema:he,PaginatedRequestSchema:ge,PaginatedResultSchema:_e,ResourceContentsSchema:ve,TextResourceContentsSchema:ye,BlobResourceContentsSchema:xe,RoleSchema:y,AnnotationsSchema:b,ResourceSchema:Se,ResourceTemplateSchema:Ce,ListResourcesRequestSchema:we,ListResourcesResultSchema:Te,ListResourceTemplatesRequestSchema:x,ListResourceTemplatesResultSchema:Ee,ResourceRequestParamsSchema:De,ReadResourceRequestParamsSchema:Oe,ReadResourceRequestSchema:ke,ReadResourceResultSchema:Ae,ResourceListChangedNotificationSchema:je,SubscribeRequestParamsSchema:Me,SubscribeRequestSchema:Ne,UnsubscribeRequestParamsSchema:S,UnsubscribeRequestSchema:Pe,ResourceUpdatedNotificationParamsSchema:Fe,ResourceUpdatedNotificationSchema:Ie,PromptArgumentSchema:Le,PromptSchema:Re,ListPromptsRequestSchema:ze,ListPromptsResultSchema:Be,GetPromptRequestParamsSchema:Ve,GetPromptRequestSchema:He,TextContentSchema:Ue,ImageContentSchema:We,AudioContentSchema:Ge,ToolUseContentSchema:Ke,EmbeddedResourceSchema:qe,ResourceLinkSchema:Je,ContentBlockSchema:Ye,PromptMessageSchema:Xe,GetPromptResultSchema:Ze,PromptListChangedNotificationSchema:Qe,ToolAnnotationsSchema:$e,ToolExecutionSchema:et,ToolSchema:tt,ListToolsRequestSchema:nt,ListToolsResultSchema:rt,CallToolResultSchema:it,CallToolRequestParamsSchema:C,CallToolRequestSchema:at,ToolListChangedNotificationSchema:ot,LoggingLevelSchema:st,SetLevelRequestParamsSchema:ct,SetLevelRequestSchema:lt,LoggingMessageNotificationParamsSchema:ut,LoggingMessageNotificationSchema:dt,ModelHintSchema:ft,ModelPreferencesSchema:pt,ToolChoiceSchema:mt,ToolResultContentSchema:ht,SamplingContentSchema:gt,SamplingMessageContentBlockSchema:w,SamplingMessageSchema:_t,CreateMessageRequestParamsSchema:vt,CreateMessageRequestSchema:yt,CreateMessageResultSchema:bt,CreateMessageResultWithToolsSchema:xt,BooleanSchemaSchema:St,StringSchemaSchema:Ct,NumberSchemaSchema:wt,UntitledSingleSelectEnumSchemaSchema:Tt,TitledSingleSelectEnumSchemaSchema:Et,LegacyTitledEnumSchemaSchema:Dt,SingleSelectEnumSchemaSchema:Ot,UntitledMultiSelectEnumSchemaSchema:kt,TitledMultiSelectEnumSchemaSchema:At,MultiSelectEnumSchemaSchema:jt,EnumSchemaSchema:Mt,PrimitiveSchemaDefinitionSchema:Nt,ElicitRequestFormParamsSchema:Pt,ElicitRequestURLParamsSchema:T,ElicitRequestParamsSchema:Ft,ElicitRequestSchema:E,ElicitationCompleteNotificationParamsSchema:It,ElicitationCompleteNotificationSchema:Lt,ElicitResultSchema:Rt,ResourceTemplateReferenceSchema:zt,PromptReferenceSchema:Bt,CompleteRequestParamsSchema:Vt,CompleteRequestSchema:Ht,CompleteResultSchema:Ut,RootSchema:Wt,ListRootsRequestSchema:Gt,ListRootsResultSchema:Kt,RootsListChangedNotificationSchema:qt,TaskCreationParamsSchema:Jt,TaskStatusSchema:Yt,TaskSchema:Xt,CreateTaskResultSchema:Zt,TaskStatusNotificationParamsSchema:Qt,TaskStatusNotificationSchema:$t,GetTaskRequestSchema:en,GetTaskResultSchema:tn,GetTaskPayloadRequestSchema:nn,GetTaskPayloadResultSchema:rn,ListTasksRequestSchema:an,ListTasksResultSchema:on,CancelTaskRequestSchema:sn,CancelTaskResultSchema:f.merge(Xt),ClientRequestSchema:L([de,ce,Ht,lt,He,ze,we,x,ke,Ne,Pe,at,nt,en,nn,an,sn]),ClientNotificationSchema:L([g,me,ue,qt,$t]),ClientResultSchema:L([m,bt,xt,Rt,Kt,tn,on,Zt]),ServerRequestSchema:L([de,yt,E,Gt,en,nn,an,sn]),ServerNotificationSchema:L([g,me,dt,Ie,je,ot,Qe,$t,Lt]),ServerResultSchema:L([m,v,Ut,Ze,Be,Te,Ee,Ae,it,rt,tn,on,Zt]),CallToolResultWireSchema:N().superRefine((e,t)=>{if(!(typeof e!=`object`||!e||Array.isArray(e)||e.content!==void 0)){for(let n of Lf)if(n in e){t.addIssue({code:`custom`,message:`content is required when the body carries '${n}' — another result family cannot default into an empty tools/call success`});return}}}).transform(Rf).pipe(it)}}let Bf;function Vf(){return Bf??=zf()}function Hf(e){return e.type!==`object`}let Uf=new Set([`const`,`enum`,`default`,`examples`]),Wf=new Set([`properties`,`patternProperties`,`$defs`,`definitions`,`dependentSchemas`,`dependencies`]);function Gf(e){return e!==void 0&&!(typeof e==`string`&&e.startsWith(`#`))}function Kf(e){let t=typeof e.$schema==`string`?e.$schema:void 0;if(Gf(e.$id))return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:e},required:[`result`]};let n=wf(e.$schema)&&e.$recursiveAnchor!==!0,r=(e,t)=>{if(Array.isArray(e))return e.map(e=>r(e,!1));if(typeof e!=`object`||!e||!t&&Gf(e.$id))return e;let i={},a=!1;for(let[o,s]of Object.entries(e))t?i[o]=r(s,!1):(o===`$ref`||o===`$dynamicRef`)&&typeof s==`string`?i[o]=s===`#`?`#/properties/result`:s.startsWith(`#/`)?`#/properties/result${s.slice(1)}`:s:o===`$recursiveRef`&&s===`#`&&n?a=!0:Uf.has(o)?i[o]=s:Wf.has(o)?i[o]=r(s,!0):i[o]=r(s,!1);return a&&(`$ref`in i?i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:`#/properties/result`}]:i.$ref=`#/properties/result`),i};return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:r(e,!1)},required:[`result`]}}let qf={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Jf={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},Yf={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Xf;function Zf(){if(Xf)return Xf;let e=Vf();return Xf={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},Xf}function Qf(e){return Object.prototype.hasOwnProperty.call(qf,e)}function $f(e){return Object.prototype.hasOwnProperty.call(Jf,e)}function ep(e){return Object.prototype.hasOwnProperty.call(Yf,e)}function tp(e){return ep(e)?Zf().resultSchemas[e]:void 0}function np(e){return Qf(e)?Zf().requestSchemas[e]:void 0}function rp(e){return $f(e)?Zf().notificationSchemas[e]:void 0}function ip(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ap(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}let op={ok:!1,reason:`not-in-era`};function sp(e){return ip(e)&&ip(e.outputSchema)&&Hf(e.outputSchema)}function cp(e){return e}let lp={era:`2025-11-25`,hasRequestMethod:Qf,hasNotificationMethod:$f,validateRequest:(e,t)=>ap(np(e),t),validateResult:(e,t)=>ap(tp(e),t),validateNotification:(e,t)=>ap(rp(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>op,validateInputResponse:()=>op,samplingResultVariant:((e,t)=>{let n=Vf();return ap(e?n.CreateMessageResultWithToolsSchema:n.CreateMessageResultSchema,t)}),outboundEnvelope:e=>void 0,validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){let n=If(e),r=n.structuredContent;if(r===void 0)return n;let i=typeof r!=`object`||!r||Array.isArray(r),a=t!==void 0&&Hf(t);return!i&&!a?n:{...n,structuredContent:{result:r}}},decodeResult(e,t){if(ip(t)&&`resultType`in t){let e={...t};return delete e.resultType,{kind:`complete`,result:cp(e)}}return{kind:`complete`,result:cp(t)}},encodeResult(e,t){if(e!==`tools/list`)return t;let n=t.tools;return!Array.isArray(n)||!n.some(e=>sp(e))?t:{...t,tools:n.map(e=>sp(e)?{...e,outputSchema:Kf(e.outputSchema)}:e)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>void 0};function up(){let e=Fo(()=>L([k(),j(),M(),Za(),R(k(),e),P(e)])),t=R(k(),e),n=L([k(),j().int()]),r=k(),i=L([k(),j().int()]),a=z([`user`,`assistant`]),o=z([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),s=k().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),c=F({ttl:j().optional()}),l=F({taskId:k()}),u=I({progressToken:n.optional(),"io.modelcontextprotocol/related-task":l.optional()}),d=F({_meta:u.optional()}),f=d.extend({task:c.optional()}),p=F({_meta:u.optional()}),m=F({method:k(),params:p.loose().optional()}),h=F({src:k(),mimeType:k().optional(),sizes:P(k()).optional(),theme:z([`light`,`dark`]).optional()}),g=F({icons:P(h).optional()}),_=F({name:k(),title:k().optional()}),ee=_.extend({..._.shape,...g.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),te=zo(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,lo(F({form:lo(F({applyDefaults:M().optional()}),t).optional(),url:t.optional()}),t.optional())),ne=I({list:t.optional(),cancel:t.optional(),requests:I({sampling:I({createMessage:t.optional()}).optional(),elicitation:I({create:t.optional()}).optional()}).optional()}),re=I({list:t.optional(),cancel:t.optional(),requests:I({tools:I({call:t.optional()}).optional()}).optional()}),ie=F({experimental:R(k(),t).optional(),sampling:F({context:t.optional(),tools:t.optional()}).optional(),elicitation:te.optional(),roots:F({listChanged:M().optional()}).optional(),tasks:ne.optional(),extensions:R(k(),t).optional()}),ae=F({experimental:R(k(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:F({listChanged:M().optional()}).optional(),resources:F({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:F({listChanged:M().optional()}).optional(),tasks:re.optional(),extensions:R(k(),t).optional()}),oe=F({progress:j(),total:V(j()),message:V(k())}),se=F({...p.shape,...oe.shape,progressToken:n}),ce=m.extend({method:B(`notifications/progress`),params:se}),le=p.extend({level:o,logger:k().optional(),data:N()}),v=m.extend({method:B(`notifications/message`),params:le}),ue=F({uri:k(),mimeType:V(k()),_meta:R(k(),N()).optional()}),de=ue.extend({text:k()}),fe=ue.extend({blob:s}),pe=F({audience:P(a).optional(),priority:j().min(0).max(1).optional(),lastModified:ta({offset:!0}).optional()}),me=F({..._.shape,...g.shape,uri:k(),description:V(k()),mimeType:V(k()),size:V(j()),annotations:pe.optional(),_meta:V(I({}))}),he=F({..._.shape,...g.shape,uriTemplate:k(),description:V(k()),mimeType:V(k()),annotations:pe.optional(),_meta:V(I({}))}),ge=m.extend({method:B(`notifications/resources/list_changed`),params:p.optional()}),_e=p.extend({uri:k()}),ve=m.extend({method:B(`notifications/resources/updated`),params:_e}),ye=F({name:k(),description:V(k()),required:V(M())}),be=F({..._.shape,...g.shape,description:V(k()),arguments:V(P(ye)),_meta:V(I({}))}),xe=m.extend({method:B(`notifications/prompts/list_changed`),params:p.optional()}),y=F({type:B(`text`),text:k(),annotations:pe.optional(),_meta:R(k(),N()).optional()}),b=F({type:B(`image`),data:s,mimeType:k(),annotations:pe.optional(),_meta:R(k(),N()).optional()}),Se=F({type:B(`audio`),data:s,mimeType:k(),annotations:pe.optional(),_meta:R(k(),N()).optional()}),Ce=F({type:B(`tool_use`),name:k(),id:k(),input:R(k(),N()),_meta:R(k(),N()).optional()}),we=F({type:B(`resource`),resource:L([de,fe]),annotations:pe.optional(),_meta:R(k(),N()).optional()}),Te=me.extend({type:B(`resource_link`)}),x=L([y,b,Se,Te,we]),Ee=F({role:a,content:x}),De=F({title:k().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),Oe=m.extend({method:B(`notifications/tools/list_changed`),params:p.optional()}),ke=F({name:k().optional()}),Ae=F({hints:P(ke).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),je=F({mode:z([`auto`,`required`,`none`]).optional()}),Me=F({type:B(`boolean`),title:k().optional(),description:k().optional(),default:M().optional()}),Ne=F({type:B(`string`),title:k().optional(),description:k().optional(),minLength:j().optional(),maxLength:j().optional(),format:z([`email`,`uri`,`date`,`date-time`]).optional(),default:k().optional()}),S=F({type:z([`number`,`integer`]),title:k().optional(),description:k().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),Pe=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),default:k().optional()}),Fe=F({type:B(`string`),title:k().optional(),description:k().optional(),oneOf:P(F({const:k(),title:k()})),default:k().optional()}),Ie=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),enumNames:P(k()).optional(),default:k().optional()}),Le=L([Pe,Fe]),Re=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({type:B(`string`),enum:P(k())}),default:P(k()).optional()}),ze=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({anyOf:P(F({const:k(),title:k()}))}),default:P(k()).optional()}),Be=L([Re,ze]),Ve=L([Ie,Le,Be]),He=L([Ve,Me,Ne,S]),Ue=f.extend({mode:B(`form`).optional(),message:k(),requestedSchema:F({type:B(`object`),properties:R(k(),He),required:P(k()).optional()}).catchall(N())}),We=F({type:B(`ref/resource`),uri:k()}),Ge=F({type:B(`ref/prompt`),name:k()}),Ke=F({uri:k().startsWith(`file://`),name:k().optional(),_meta:R(k(),N()).optional()}),qe=ie.shape,Je=F({experimental:qe.experimental,sampling:qe.sampling,elicitation:qe.elicitation,roots:qe.roots,extensions:qe.extensions}),Ye=ae.shape,Xe=F({experimental:Ye.experimental,logging:Ye.logging,completions:Ye.completions,prompts:Ye.prompts,resources:Ye.resources,tools:Ye.tools,extensions:Ye.extensions}),Ze=I({progressToken:n.optional(),[Wo]:k(),[Go]:ee.optional(),[qo]:Je,[Jo]:o.optional()}),Qe=F({..._.shape,...g.shape,description:k().optional(),inputSchema:I({$schema:k().optional(),type:B(`object`)}),outputSchema:I({$schema:k().optional()}).optional(),annotations:De.optional(),_meta:R(k(),N()).optional()}),$e=F({type:B(`tool_result`),toolUseId:k(),content:P(x),structuredContent:N().optional(),isError:M().optional(),_meta:R(k(),N()).optional()}),et=L([y,b,Se,Ce,$e]),tt=F({role:a,content:L([et,P(et)]),_meta:R(k(),N()).optional()}),nt=k(),rt=I({[Ko]:ee.optional().catch(void 0)}),it=rt.optional();function C(e){return I({_meta:it,resultType:nt.default(`complete`),...e})}let at=C({}),ot=C({nextCursor:r.optional()}),st=C({content:P(x),structuredContent:N().optional(),isError:M().optional()}),ct=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),tools:P(Qe),nextCursor:r.optional()}),lt=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),prompts:P(be),nextCursor:r.optional()}),ut=C({description:k().optional(),messages:P(Ee)}),dt=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),resources:P(me),nextCursor:r.optional()}),ft=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),resourceTemplates:P(he),nextCursor:r.optional()}),pt=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),contents:P(L([de,fe]))}),mt=C({completion:F({values:P(k()).max(100),total:j().int().optional(),hasMore:M().optional()}).loose()}),ht=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`])}),gt=C({ttlMs:j().int().min(0).catch(0),cacheScope:z([`public`,`private`]).catch(`private`),supportedVersions:P(k()),capabilities:Xe,instructions:k().optional()}),w=F({messages:P(tt),modelPreferences:Ae.optional(),systemPrompt:k().optional(),includeContext:z([`none`,`thisServer`,`allServers`]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:P(k()).optional(),metadata:t.optional(),tools:P(Qe).optional(),toolChoice:je.optional()}),_t=F({method:B(`sampling/createMessage`),params:w}),vt=F({method:B(`roots/list`),params:F({_meta:R(k(),N()).optional()}).optional()}),yt=F({...tt.shape,model:k(),stopReason:k().optional()}),bt=F({roots:P(Ke)}),xt=F({action:z([`accept`,`decline`,`cancel`]),content:R(k(),L([k(),j(),M(),P(k())])).optional()}),St=F({mode:B(`url`),message:k(),url:k().url()}),Ct=L([Ue,St]),wt=F({method:B(`elicitation/create`),params:Ct}),Tt=L([_t,vt,wt]),Et=L([yt,bt,xt]),Dt=R(k(),Tt),Ot=R(k(),Et),kt=C({inputRequests:Dt.optional(),requestState:k().optional()}),At={inputResponses:Ot.optional(),requestState:k().optional()},jt=F({_meta:Ze,...At}),Mt=I({progressToken:n.optional()});function Nt(e,t){return F({method:B(e),params:F({_meta:Ze,...t})})}function Pt(e,t){return F({method:B(e),params:F({_meta:Mt.optional(),...t}).optional()})}let T={name:k(),arguments:R(k(),N()).optional(),...At},Ft={cursor:r.optional()},E=Nt(`tools/call`,T),It=Nt(`tools/list`,Ft),Lt=Nt(`prompts/list`,Ft),Rt=Nt(`prompts/get`,{name:k(),arguments:R(k(),k()).optional(),...At}),zt=Nt(`resources/list`,Ft),Bt=Nt(`resources/templates/list`,Ft),Vt=Nt(`resources/read`,{uri:k(),...At}),Ht={ref:L([Ge,We]),argument:F({name:k(),value:k()}),context:F({arguments:R(k(),k()).optional()}).optional()},Ut=Nt(`completion/complete`,Ht),Wt=Nt(`server/discover`,{}),Gt=F({toolsListChanged:M().optional(),promptsListChanged:M().optional(),resourcesListChanged:M().optional(),resourceSubscriptions:P(k()).optional()}),Kt={notifications:Gt},qt=Nt(`subscriptions/listen`,Kt),Jt=rt.extend({"io.modelcontextprotocol/subscriptionId":i}),Yt=I({_meta:Jt,resultType:nt.default(`complete`)}),Xt={"tools/call":Pt(`tools/call`,T),"tools/list":Pt(`tools/list`,Ft),"prompts/get":Pt(`prompts/get`,{name:k(),arguments:R(k(),k()).optional()}),"prompts/list":Pt(`prompts/list`,Ft),"resources/list":Pt(`resources/list`,Ft),"resources/templates/list":Pt(`resources/templates/list`,Ft),"resources/read":Pt(`resources/read`,{uri:k()}),"completion/complete":Pt(`completion/complete`,Ht),"server/discover":Pt(`server/discover`,{}),"subscriptions/listen":Pt(`subscriptions/listen`,Kt)};function Zt(e){return I({_meta:it,...e})}let Qt={"tools/call":Zt({content:P(x),structuredContent:N().optional(),isError:M().optional()}),"tools/list":Zt({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),tools:P(Qe),nextCursor:r.optional()}),"prompts/get":Zt({description:k().optional(),messages:P(Ee)}),"prompts/list":Zt({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),prompts:P(be),nextCursor:r.optional()}),"resources/list":Zt({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),resources:P(me),nextCursor:r.optional()}),"resources/templates/list":Zt({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),resourceTemplates:P(he),nextCursor:r.optional()}),"resources/read":Zt({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),contents:P(L([de,fe]))}),"completion/complete":Zt({completion:F({values:P(k()).max(100),total:j().int().optional(),hasMore:M().optional()}).loose()}),"server/discover":Zt({ttlMs:j().int().min(0).catch(0),cacheScope:z([`public`,`private`]).catch(`private`),supportedVersions:P(k()),capabilities:Xe,instructions:k().optional()}),"subscriptions/listen":Zt({})},$t=I({"io.modelcontextprotocol/subscriptionId":i.optional()}),en=F({method:B(`notifications/subscriptions/acknowledged`),params:F({_meta:$t.optional(),notifications:Gt})}),tn=F({_meta:$t.optional(),requestId:i,reason:k().optional()}),nn=F({method:B(`notifications/cancelled`),params:tn}),rn={"notifications/cancelled":nn,"notifications/progress":ce,"notifications/message":v,"notifications/resources/updated":ve,"notifications/resources/list_changed":ge,"notifications/tools/list_changed":Oe,"notifications/prompts/list_changed":xe,"notifications/subscriptions/acknowledged":en},an=e=>F({jsonrpc:B(`2.0`),id:L([k(),j().int()]),result:e}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,RequestIdSchema:i,RoleSchema:a,LoggingLevelSchema:o,TaskMetadataSchema:c,RelatedTaskMetadataSchema:l,RequestMetaSchema:u,BaseRequestParamsSchema:d,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:p,NotificationSchema:m,IconSchema:h,IconsSchema:g,BaseMetadataSchema:_,ImplementationSchema:ee,ClientTasksCapabilitySchema:ne,ServerTasksCapabilitySchema:re,ClientCapabilitiesSchema:ie,ServerCapabilitiesSchema:ae,ProgressSchema:oe,ProgressNotificationParamsSchema:se,ProgressNotificationSchema:ce,LoggingMessageNotificationParamsSchema:le,LoggingMessageNotificationSchema:v,ResourceContentsSchema:ue,TextResourceContentsSchema:de,BlobResourceContentsSchema:fe,AnnotationsSchema:pe,ResourceSchema:me,ResourceTemplateSchema:he,ResourceListChangedNotificationSchema:ge,ResourceUpdatedNotificationParamsSchema:_e,ResourceUpdatedNotificationSchema:ve,PromptArgumentSchema:ye,PromptSchema:be,PromptListChangedNotificationSchema:xe,TextContentSchema:y,ImageContentSchema:b,AudioContentSchema:Se,ToolUseContentSchema:Ce,EmbeddedResourceSchema:we,ResourceLinkSchema:Te,ContentBlockSchema:x,PromptMessageSchema:Ee,ToolAnnotationsSchema:De,ToolListChangedNotificationSchema:Oe,ModelHintSchema:ke,ModelPreferencesSchema:Ae,ToolChoiceSchema:je,BooleanSchemaSchema:Me,StringSchemaSchema:Ne,NumberSchemaSchema:S,UntitledSingleSelectEnumSchemaSchema:Pe,TitledSingleSelectEnumSchemaSchema:Fe,LegacyTitledEnumSchemaSchema:Ie,SingleSelectEnumSchemaSchema:Le,UntitledMultiSelectEnumSchemaSchema:Re,TitledMultiSelectEnumSchemaSchema:ze,MultiSelectEnumSchemaSchema:Be,EnumSchemaSchema:Ve,PrimitiveSchemaDefinitionSchema:He,ElicitRequestFormParamsSchema:Ue,ResourceTemplateReferenceSchema:We,PromptReferenceSchema:Ge,RootSchema:Ke,ClientCapabilities2026Schema:Je,ServerCapabilities2026Schema:Xe,RequestMetaEnvelopeSchema:Ze,ToolSchema:Qe,ToolResultContentSchema:$e,SamplingMessageContentBlockSchema:et,SamplingMessageSchema:tt,ResultTypeSchema:nt,ResultMetaSchema:rt,ResultSchema:at,PaginatedResultSchema:ot,CallToolResultSchema:st,ListToolsResultSchema:ct,ListPromptsResultSchema:lt,GetPromptResultSchema:ut,ListResourcesResultSchema:dt,ListResourceTemplatesResultSchema:ft,ReadResourceResultSchema:pt,CompleteResultSchema:mt,CacheableResultSchema:ht,DiscoverResultSchema:gt,CreateMessageRequestParamsSchema:w,CreateMessageRequestSchema:_t,ListRootsRequestSchema:vt,CreateMessageResultSchema:yt,ListRootsResultSchema:bt,ElicitResultSchema:xt,ElicitRequestURLParamsSchema:St,ElicitRequestParamsSchema:Ct,ElicitRequestSchema:wt,InputRequestSchema:Tt,InputResponseSchema:Et,InputRequestsSchema:Dt,InputResponsesSchema:Ot,InputRequiredResultSchema:kt,InputResponseRequestParamsSchema:jt,CallToolRequestSchema:E,ListToolsRequestSchema:It,ListPromptsRequestSchema:Lt,GetPromptRequestSchema:Rt,ListResourcesRequestSchema:zt,ListResourceTemplatesRequestSchema:Bt,ReadResourceRequestSchema:Vt,CompleteRequestSchema:Ut,DiscoverRequestSchema:Wt,SubscriptionFilterSchema:Gt,SubscriptionsListenRequestSchema:qt,SubscriptionsListenResultMetaSchema:Jt,SubscriptionsListenResultSchema:Yt,dispatchRequestSchemas:Xt,dispatchResultSchemas:Qt,NotificationMetaSchema:$t,SubscriptionsAcknowledgedNotificationSchema:en,CancelledNotificationParamsSchema:tn,CancelledNotificationSchema:nn,notificationSchemas2026:rn,JSONRPCResultResponseSchema:an(at),CallToolResultResponseSchema:an(L([st,kt])),ListToolsResultResponseSchema:an(ct),ListPromptsResultResponseSchema:an(lt),GetPromptResultResponseSchema:an(L([ut,kt])),ListResourcesResultResponseSchema:an(dt),ListResourceTemplatesResultResponseSchema:an(ft),ReadResourceResultResponseSchema:an(L([pt,kt])),CompleteResultResponseSchema:an(mt),DiscoverResultResponseSchema:an(gt)}}let dp;function fp(){return dp??=up()}let pp=[`tools/list`,`prompts/list`,`resources/list`,`resources/templates/list`,`resources/read`,`server/discover`];function mp(e){return pp.includes(e)}let hp=Symbol(`modelcontextprotocol.resultCacheHintFallback`);function gp(e,t){if(t===void 0)return e;let n=e[hp];if(n===void 0)return{...e,[hp]:t};let r={},i=n.ttlMs??t.ttlMs;i!==void 0&&(r.ttlMs=i);let a=n.cacheScope??t.cacheScope;return a!==void 0&&(r.cacheScope=a),{...e,[hp]:r}}function _p(e){return e[hp]}function vp(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function yp(e){return e===`public`||e===`private`}function bp(e,t){if(e.ttlMs!==void 0&&!vp(e.ttlMs))throw RangeError(`Invalid cache hint for ${t}: ttlMs must be a non-negative safe integer (got ${String(e.ttlMs)})`);if(e.cacheScope!==void 0&&!yp(e.cacheScope))throw RangeError(`Invalid cache hint for ${t}: cacheScope must be 'public' or 'private' (got ${String(e.cacheScope)})`)}let Z=function(e){return e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.ResourceNotFound=-32002]=`ResourceNotFound`,e[e.MissingRequiredClientCapability=-32021]=`MissingRequiredClientCapability`,e[e.UnsupportedProtocolVersion=-32022]=`UnsupportedProtocolVersion`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`,e}({});var Q=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.ProtocolError`})}static[Symbol.hasInstance](e){return Of(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Of(this,e)}constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`ProtocolError`,Df(this,new.target)}static fromError(t,n,r){if(t===Z.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Sp(e.elicitations,n)}if(t===Z.UnsupportedProtocolVersion&&r){let e=r;if(Array.isArray(e.supported)&&typeof e.requested==`string`)return new Cp({supported:e.supported,requested:e.requested},n)}if(t===Z.InvalidParams||t===Z.ResourceNotFound){let e=r;if(typeof e?.uri==`string`&&(t===Z.ResourceNotFound||Object.keys(e).length===1))return new xp(e.uri,n)}if(t===Z.MissingRequiredClientCapability&&r){let e=r;if(e.requiredCapabilities!==null&&typeof e.requiredCapabilities==`object`&&!Array.isArray(e.requiredCapabilities))return new wp({requiredCapabilities:e.requiredCapabilities},n)}return new e(t,n,r)}},xp=class extends Q{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.ResourceNotFoundError`})}constructor(e,t=`Resource not found: ${e}`){super(Z.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Sp=class extends Q{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UrlElicitationRequiredError`})}constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(Z.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Cp=class extends Q{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UnsupportedProtocolVersionError`})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(Z.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},wp=class extends Q{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.MissingRequiredClientCapabilityError`})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(`, `)}`){super(Z.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}};let Tp=[`tools/call`,`prompts/get`,`resources/read`];function Ep(e,t){let n=t.resultType;if(n===void 0)return{...t,resultType:`complete`};if(n===`complete`||Tp.includes(e))return t;throw new Q(Z.InternalError,`Handler for ${e} returned resultType '${String(n)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function Dp(e,t){let n=_p(t);if(t.resultType!==`complete`||!mp(e))return n===void 0?t:Mp(t);let r=t,i=vp(r.ttlMs)?r.ttlMs:Ap(n),a=yp(r.cacheScope)?r.cacheScope:jp(n),o={...r,ttlMs:i,cacheScope:a};return delete o[hp],o}function Op(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kp(e,t){if(t===void 0)return e;let n=e._meta;return n===void 0?{...e,_meta:{[Ko]:t}}:!Op(n)||n[`io.modelcontextprotocol/serverInfo`]!==void 0?e:{...e,_meta:{...n,[Ko]:t}}}function Ap(e){return e!==void 0&&vp(e.ttlMs)?e.ttlMs:0}function jp(e){return e!==void 0&&yp(e.cacheScope)?e.cacheScope:`private`}function Mp(e){let t={...e};return delete t[hp],t}let Np=[`elicitation/create`,`sampling/createMessage`,`roots/list`],Pp;function Fp(){if(Pp)return Pp;let e=fp();return Pp={request:{"elicitation/create":F({method:B(`elicitation/create`),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":F({method:B(`sampling/createMessage`),params:e.CreateMessageRequestParamsSchema}),"roots/list":F({method:B(`roots/list`),params:I({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Pp}function Ip(e){return Np.includes(e)}function Lp(e){return Ip(e)?Fp().request[e]:void 0}function Rp(e){return Ip(e)?Fp().response[e]:void 0}let zp={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},Bp={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function Vp(e){return Object.prototype.hasOwnProperty.call(zp,e)}function Hp(e){return Object.prototype.hasOwnProperty.call(Bp,e)}function Up(e){return Object.prototype.hasOwnProperty.call(zp,e)}function Wp(e){return Vp(e)?fp().dispatchRequestSchemas[e]:void 0}function Gp(e){return Up(e)?fp().dispatchResultSchemas[e]:void 0}function Kp(e){return Hp(e)?fp().notificationSchemas2026[e]:void 0}function qp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jp(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}let Yp={ok:!1,reason:`not-in-era`},Xp=[Wo,qo];function Zp(e,t){let n=t,r=!1,i=()=>(r||=(n={...n},!0),n),a=t.tools;e===`tools/list`&&Array.isArray(a)&&a.some(e=>qp(e)&&`execution`in e)&&(i().tools=a.map(e=>{if(!qp(e)||!(`execution`in e))return e;let t={...e};return delete t.execution,t}));let o=t.capabilities;if(qp(o)&&`tasks`in o){let e={...o};delete e.tasks,i().capabilities=e}return n}let Qp={era:`2026-07-28`,hasRequestMethod:Vp,hasNotificationMethod:Hp,hasInputRequestMethod:e=>Lp(e)!==void 0,validateRequest:(e,t)=>Jp(Wp(e),t),validateResult:(e,t)=>Jp(Gp(e),t),validateNotification:(e,t)=>Jp(Kp(e),t),validateInputRequest:(e,t)=>Jp(Lp(e),t),validateInputResponse:(e,t)=>Jp(Rp(e),t),samplingResultVariant:()=>Yp,outboundEnvelope(e){return{[Wo]:e.protocolVersion,[Go]:e.clientInfo,[qo]:e.clientCapabilities,...e.logLevel!==void 0&&{"io.modelcontextprotocol/logLevel":e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of Xp)n in e||t.push({key:n,problem:`missing`});let n=fp().RequestMetaEnvelopeSchema.safeParse(e);if(!n.success)for(let e of n.error.issues){let n=e.path.map(String),r=n.length>0?n.join(`.`):`_meta`;n.length===1&&t.some(e=>e.key===r&&e.problem===`missing`)||t.push({key:r,problem:e.message})}return t},projectCallToolResult:e=>If(e),inputRequestSchema:Lp,decodeResult(e,t){if(!qp(t))return{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let n=t.resultType;if(n===void 0)return{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:`missing-resultType`})};if(typeof n!=`string`)return{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:n})};if(n===`input_required`){let n=t.inputRequests,r=qp(n)?n:{},i=t.requestState;return Object.keys(r).length===0&&typeof i!=`string`?{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:`input-required-missing-both`})}:{kind:`input_required`,inputRequests:r,...typeof i==`string`&&{requestState:i}}}if(n!==`complete`)return{kind:`invalid`,error:new X(Y.UnsupportedResultType,`Unsupported result type '${n}' for ${e}`,{resultType:n,method:e})};let r=em(),i=Object.hasOwn(r,e)?r[e]:void 0;if(i!==void 0){let n=i.safeParse(t);if(!n.success)return{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: ${n.error}`,{method:e})}}let a={...t};return delete a.resultType,{kind:`complete`,result:a}},encodeResult(e,t,n){return kp(Dp(e,Ep(e,Zp(e,t))),n)},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return`Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)`;let t=fp().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(e=>e.message).join(`; `)}`}},$p;function em(){if($p)return $p;let e=fp();return $p={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},$p}function tm(e){return e!==void 0&&Nf(e)?Qp:lp}function nm(e){return e.revision===void 0?e.era===`modern`?Qp.era:lp.era:tm(e.revision).era}function rm(e){return am.some(t=>t.hasRequestMethod(e))}function im(e){return am.some(t=>t.hasNotificationMethod(e))}let am=[lp,Qp];var om=yf({AnnotationsSchema:()=>Us,AudioContentSchema:()=>Sc,BaseMetadataSchema:()=>vs,BaseRequestParamsSchema:()=>U,BlobResourceContentsSchema:()=>Vs,BooleanSchemaSchema:()=>rl,CallToolRequestParamsSchema:()=>Lc,CallToolRequestSchema:()=>Rc,CallToolResultSchema:()=>Fc,CancelTaskRequestSchema:()=>Ul,CancelTaskResultSchema:()=>Wl,CancelledNotificationParamsSchema:()=>ms,CancelledNotificationSchema:()=>hs,ClientCapabilitiesSchema:()=>Cs,ClientNotificationSchema:()=>Kl,ClientRequestSchema:()=>Gl,ClientResultSchema:()=>ql,ClientTasksCapabilitySchema:()=>xs,CompatibilityCallToolResultSchema:()=>Ic,CompleteRequestParamsSchema:()=>wl,CompleteRequestSchema:()=>Tl,CompleteResultSchema:()=>El,ContentBlockSchema:()=>Ec,CreateMessageRequestParamsSchema:()=>$c,CreateMessageRequestSchema:()=>el,CreateMessageResultSchema:()=>tl,CreateMessageResultWithToolsSchema:()=>nl,CreateTaskResultSchema:()=>Pl,CursorSchema:()=>Qo,DiscoverRequestSchema:()=>ks,DiscoverResultSchema:()=>As,ElicitRequestFormParamsSchema:()=>hl,ElicitRequestParamsSchema:()=>_l,ElicitRequestSchema:()=>vl,ElicitRequestURLParamsSchema:()=>gl,ElicitResultSchema:()=>xl,ElicitationCompleteNotificationParamsSchema:()=>yl,ElicitationCompleteNotificationSchema:()=>bl,EmbeddedResourceSchema:()=>wc,EmptyResultSchema:()=>ps,EnumSchemaSchema:()=>pl,GetPromptRequestParamsSchema:()=>vc,GetPromptRequestSchema:()=>yc,GetPromptResultSchema:()=>Oc,GetTaskPayloadRequestSchema:()=>zl,GetTaskPayloadResultSchema:()=>Bl,GetTaskRequestSchema:()=>Ll,GetTaskResultSchema:()=>Rl,IconSchema:()=>gs,IconsSchema:()=>_s,ImageContentSchema:()=>xc,ImplementationSchema:()=>ys,InitializeRequestParamsSchema:()=>ws,InitializeRequestSchema:()=>Ts,InitializeResultSchema:()=>Ds,InitializedNotificationSchema:()=>Os,JSONArraySchema:()=>Xo,JSONObjectSchema:()=>H,JSONRPCErrorResponseSchema:()=>us,JSONRPCMessageSchema:()=>ds,JSONRPCNotificationSchema:()=>cs,JSONRPCRequestSchema:()=>ss,JSONRPCResponseSchema:()=>fs,JSONRPCResultResponseSchema:()=>ls,JSONValueSchema:()=>Yo,LegacyTitledEnumSchemaSchema:()=>cl,ListChangedOptionsBaseSchema:()=>Bc,ListPromptsRequestSchema:()=>gc,ListPromptsResultSchema:()=>_c,ListResourceTemplatesRequestSchema:()=>Js,ListResourceTemplatesResultSchema:()=>Ys,ListResourcesRequestSchema:()=>Ks,ListResourcesResultSchema:()=>qs,ListRootsRequestSchema:()=>Ol,ListRootsResultSchema:()=>kl,ListTasksRequestSchema:()=>Vl,ListTasksResultSchema:()=>Hl,ListToolsRequestSchema:()=>Nc,ListToolsResultSchema:()=>Pc,LoggingLevelSchema:()=>Vc,LoggingMessageNotificationParamsSchema:()=>Wc,LoggingMessageNotificationSchema:()=>Gc,ModelHintSchema:()=>Kc,ModelPreferencesSchema:()=>qc,MultiSelectEnumSchemaSchema:()=>fl,NotificationSchema:()=>is,NotificationsParamsSchema:()=>rs,NumberSchemaSchema:()=>al,PaginatedRequestParamsSchema:()=>Fs,PaginatedRequestSchema:()=>Is,PaginatedResultSchema:()=>Ls,PingRequestSchema:()=>js,PrimitiveSchemaDefinitionSchema:()=>ml,ProgressNotificationParamsSchema:()=>Ns,ProgressNotificationSchema:()=>Ps,ProgressSchema:()=>Ms,ProgressTokenSchema:()=>Zo,PromptArgumentSchema:()=>mc,PromptListChangedNotificationSchema:()=>kc,PromptMessageSchema:()=>Dc,PromptReferenceSchema:()=>Cl,PromptSchema:()=>hc,ReadResourceRequestParamsSchema:()=>Zs,ReadResourceRequestSchema:()=>Qs,ReadResourceResultSchema:()=>$s,RelatedTaskMetadataSchema:()=>es,RequestIdSchema:()=>os,RequestMetaSchema:()=>ts,RequestSchema:()=>W,ResourceContentsSchema:()=>Rs,ResourceLinkSchema:()=>Tc,ResourceListChangedNotificationSchema:()=>ec,ResourceRequestParamsSchema:()=>Xs,ResourceSchema:()=>Ws,ResourceTemplateReferenceSchema:()=>Sl,ResourceTemplateSchema:()=>Gs,ResourceUpdatedNotificationParamsSchema:()=>fc,ResourceUpdatedNotificationSchema:()=>pc,ResultMetaObjectSchema:()=>as,ResultSchema:()=>G,RoleSchema:()=>Hs,RootSchema:()=>Dl,RootsListChangedNotificationSchema:()=>Al,SamplingContentSchema:()=>Xc,SamplingMessageContentBlockSchema:()=>Zc,SamplingMessageSchema:()=>Qc,ServerCapabilitiesSchema:()=>Es,ServerNotificationSchema:()=>Yl,ServerRequestSchema:()=>Jl,ServerResultSchema:()=>Xl,ServerTasksCapabilitySchema:()=>Ss,SetLevelRequestParamsSchema:()=>Hc,SetLevelRequestSchema:()=>Uc,SingleSelectEnumSchemaSchema:()=>ll,StringSchemaSchema:()=>il,SubscribeRequestParamsSchema:()=>tc,SubscribeRequestSchema:()=>nc,SubscriptionFilterSchema:()=>ac,SubscriptionsAcknowledgedNotificationParamsSchema:()=>cc,SubscriptionsAcknowledgedNotificationSchema:()=>lc,SubscriptionsListenRequestParamsSchema:()=>oc,SubscriptionsListenRequestSchema:()=>sc,SubscriptionsListenResultMetaSchema:()=>uc,SubscriptionsListenResultSchema:()=>dc,TaskAugmentedRequestParamsSchema:()=>ns,TaskCreationParamsSchema:()=>jl,TaskMetadataSchema:()=>$o,TaskSchema:()=>Nl,TaskStatusNotificationParamsSchema:()=>Fl,TaskStatusNotificationSchema:()=>Il,TaskStatusSchema:()=>Ml,TextContentSchema:()=>bc,TextResourceContentsSchema:()=>zs,TitledMultiSelectEnumSchemaSchema:()=>dl,TitledSingleSelectEnumSchemaSchema:()=>sl,ToolAnnotationsSchema:()=>Ac,ToolChoiceSchema:()=>Jc,ToolExecutionSchema:()=>jc,ToolListChangedNotificationSchema:()=>zc,ToolResultContentSchema:()=>Yc,ToolSchema:()=>Mc,ToolUseContentSchema:()=>Cc,UnsubscribeRequestParamsSchema:()=>rc,UnsubscribeRequestSchema:()=>ic,UntitledMultiSelectEnumSchemaSchema:()=>ul,UntitledSingleSelectEnumSchemaSchema:()=>ol});let sm=e=>ss.safeParse(e).success,cm=e=>cs.safeParse(e).success,lm=e=>ls.safeParse(e).success,um=e=>us.safeParse(e).success,dm=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&e.resultType===`input_required`;function fm(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function pm(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}let mm=`x-mcp-header`,hm=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,gm=new Set([`string`,`integer`,`boolean`,`number`]);function _m(e){let t=[],n=new Map,r=(e,i,a)=>{if(typeof e!=`object`||!e)return;let o=e;if(mm in o){if(!a||i.length===0)return`${bm(i)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let e=o[mm];if(typeof e!=`string`||e.length===0)return`${bm(i)}: x-mcp-header MUST be a non-empty string`;if(!hm.test(e))return`${bm(i)}: x-mcp-header '${e}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let r=typeof o.type==`string`?o.type:void 0;if(r===void 0||!gm.has(r))return`${bm(i)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${r??`<none>`}`;let s=e.toLowerCase(),c=n.get(s);if(c!==void 0)return`x-mcp-header '${e}' is not case-insensitively unique (also declared as '${c}')`;n.set(s,e),t.push({path:i,headerName:e,type:r})}let s=o.properties;if(typeof s==`object`&&s)for(let[e,t]of Object.entries(s)){let n=r(t,[...i,e],a);if(n!==void 0)return n}for(let e of vm){let t=o[e];if(t===void 0)continue;let n=Array.isArray(t)?t:typeof t==`object`&&t&&ym.has(e)?Object.values(t):[t];for(let t of n){let n=r(t,[...i,`<${e}>`],!1);if(n!==void 0)return n}}},i=r(e,[],!0);return i===void 0?{valid:!0,declarations:t}:{valid:!1,reason:i}}let vm=[`items`,`prefixItems`,`contains`,`additionalProperties`,`unevaluatedProperties`,`unevaluatedItems`,`propertyNames`,`patternProperties`,`dependentSchemas`,`oneOf`,`anyOf`,`allOf`,`not`,`if`,`then`,`else`,`$defs`,`definitions`],ym=new Set([`patternProperties`,`dependentSchemas`,`$defs`,`definitions`]);function bm(e){return e.length===0?`<root>`:e.join(`.`)}Z.InvalidRequest,Z.UnsupportedProtocolVersion,Z.InvalidParams,Z.MethodNotFound,Z.InvalidParams,Z.MissingRequiredClientCapability,Z.ParseError,Z.InvalidRequest,Z.MethodNotFound,Z.UnsupportedProtocolVersion,Z.MissingRequiredClientCapability;function xm(e,t){return da(e,t)}function Sm(e){return new Set(e.flatMap(e=>Object.keys(e.shape)))}function Cm(e){if(e==null)return!1;let t=typeof e;return t!==`object`&&t!==`function`||!(`~standard`in e)?!1:typeof e[`~standard`]?.validate==`function`}let wm=!1,Tm=`draft-2020-12`;function Em(e,t=`input`){let n=e[`~standard`],r;if(n.jsonSchema)r=n.jsonSchema[t]({target:Tm});else if(n.vendor===`zod`){if(!(`_zod`in e))throw Error(`Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().`);wm||(wm=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),r=$i(e,{target:Tm,io:t})}else throw Error(`Schema library "${n.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t===`output`)return r.type===void 0&&Dm(r)?{type:`object`,...r}:r;if(r.type!==void 0&&r.type!==`object`)throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(r.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:`object`,...r}}function Dm(e){if(`properties`in e||`patternProperties`in e||`additionalProperties`in e||`required`in e)return!0;for(let t of[`oneOf`,`anyOf`,`allOf`]){let n=e[t];if(Array.isArray(n)&&n.length>0)return n.every(e=>typeof e==`object`&&!!e&&(e.type===`object`||Dm(e)))}return!1}function Om(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function km(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>Om(e)).join(`, `)}:{success:!0,data:n.value}}function Am(e){let t=$i(e,{target:Tm,io:`input`});return typeof t.pattern==`string`?t.pattern:void 0}let jm=/\\\.\\d\{(\d+)\}/;function Mm(e){let t=jm.exec(e),n=[void 0,-1,0];return t&&n.push(Number(t[1])),[!1,!0].flatMap(e=>[!1,!0].flatMap(t=>n.map(n=>ta({local:e,offset:t,precision:n}))))}function Nm(e,t){let n;switch(e){case`email`:n=[Ea()];break;case`uri`:n=[Aa()];break;case`date`:n=[ra()];break;case`date-time`:n=Mm(t);break}return new Set(n.map(e=>Am(e)).filter(e=>e!==void 0))}function Pm(e,t,n){return n===`zod`?Nm(e,t).has(t):!0}function Fm(e){let t=Em(e,`input`),n=t.properties||{},r=t.required||[];return Object.entries(n).map(([e,t])=>({name:e,description:t?.description,required:r.includes(e)}))}function Im(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Lm(e){try{return Em(e,`input`)}catch(e){let t=e instanceof Error?e.message:String(e);throw new Q(Z.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${t}`)}}let Rm=new Set([`$comment`,`deprecated`,`description`,`examples`,`readOnly`,`title`,`writeOnly`]);function zm(e){return Rm.has(e)||e.startsWith(`x-`)}let Bm=new Set([`$schema`,...Object.keys(hl.shape.requestedSchema.shape)]),Vm={string:Sm([il,ol,sl,cl]),number:Sm([al]),integer:Sm([al]),boolean:Sm([rl]),array:Sm([ul,dl])},Hm=new Set(il.shape.format.unwrap().options);function Um(e,t,n,r){if(!Im(e))return e;let i=typeof e.type==`string`&&Object.hasOwn(Vm,e.type)?Vm[e.type]:void 0;if(i===void 0)return e;let a={};for(let[o,s]of Object.entries(e))i.has(o)||zm(o)?a[o]=s:o===`pattern`&&e.type===`string`&&typeof e.format==`string`?Hm.has(e.format)?(typeof s!=`string`||!Pm(e.format,s,n))&&r.push(`${t}.${o}`):a[o]=s:r.push(`${t}.${o}`);return a}function Wm(e,t){let n={},r=[];for(let[i,a]of Object.entries(e))i===`properties`&&Im(a)?n[i]=Object.fromEntries(Object.entries(a).map(([e,n])=>[e,Um(n,`properties.${e}`,t,r)])):Bm.has(i)?n[i]=a:zm(i)||r.push(i);if(r.length>0)throw new Q(Z.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${r.join(`, `)}`);return n}function Gm(e,t){if(!Im(e.properties))return t;let n=Object.entries(e.properties).filter(([,e])=>!xm(ml,e).success).map(([e])=>`properties.${e}`);return n.length>0?n.join(`, `):t}function Km(e,t,n=``){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((e,r)=>Km(e,t[r],`${n}[${r}]`)):!Im(e)||!Im(t)?[]:Object.entries(e).flatMap(([e,r])=>{let i=n?`${n}.${e}`:e;return Object.prototype.hasOwnProperty.call(t,e)?Km(r,t[e],i):zm(e)?[]:[i]})}function qm(e){if(!Cm(e.requestedSchema))return{...e,mode:`form`,requestedSchema:e.requestedSchema};let t=e.requestedSchema[`~standard`].vendor,n=Wm(Lm(e.requestedSchema),t),r=xm(hl.shape.requestedSchema,n);if(!r.success)throw new Q(Z.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${Gm(n,r.error.message)}`);let i=Km(n,r.data);if(i.length>0)throw new Q(Z.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${i.join(`, `)}`);let a=(r.data.required??[]).filter(e=>!Object.prototype.hasOwnProperty.call(r.data.properties,e));if(a.length>0)throw new Q(Z.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${a.join(`, `)}`);return{...e,mode:`form`,requestedSchema:r.data}}function Jm(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,n=typeof e.requestState==`string`;if(!t&&!n)throw TypeError(`inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)`);return{resultType:`input_required`,...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}Object.assign(Jm,{elicit(e){try{return{method:`elicitation/create`,params:qm(e)}}catch(e){throw e instanceof Q?TypeError(e.message,{cause:e}):e}},elicitUrl(e){return{method:`elicitation/create`,params:{...e,mode:`url`}}},createMessage(e){return{method:`sampling/createMessage`,params:e}},listRoots(){return{method:`roots/list`}}});function Ym(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function Xm(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason instanceof X?t.reason:new X(Y.RequestTimeout,String(t.reason)));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(t?.reason instanceof X?t.reason:new X(Y.RequestTimeout,String(t?.reason)))};t?.addEventListener(`abort`,a,{once:!0})})}function Zm(e){let t=new AbortController,n=()=>t.abort(e?.reason);return e?.addEventListener(`abort`,n,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:e=>t.abort(e),dispose:()=>e?.removeEventListener(`abort`,n)}}let Qm=`AnnotationsSchema.AudioContentSchema.BaseMetadataSchema.BlobResourceContentsSchema.BooleanSchemaSchema.CallToolRequestSchema.CallToolRequestParamsSchema.CallToolResultSchema.CancelledNotificationSchema.CancelledNotificationParamsSchema.CancelTaskRequestSchema.CancelTaskResultSchema.ClientCapabilitiesSchema.ClientNotificationSchema.ClientRequestSchema.ClientResultSchema.CompatibilityCallToolResultSchema.CompleteRequestSchema.CompleteRequestParamsSchema.CompleteResultSchema.ContentBlockSchema.CreateMessageRequestSchema.CreateMessageRequestParamsSchema.CreateMessageResultSchema.CreateMessageResultWithToolsSchema.CreateTaskResultSchema.CursorSchema.DiscoverRequestSchema.DiscoverResultSchema.ElicitationCompleteNotificationSchema.ElicitationCompleteNotificationParamsSchema.ElicitRequestSchema.ElicitRequestFormParamsSchema.ElicitRequestParamsSchema.ElicitRequestURLParamsSchema.ElicitResultSchema.EmbeddedResourceSchema.EmptyResultSchema.EnumSchemaSchema.GetPromptRequestSchema.GetPromptRequestParamsSchema.GetPromptResultSchema.GetTaskPayloadRequestSchema.GetTaskPayloadResultSchema.GetTaskRequestSchema.GetTaskResultSchema.IconSchema.IconsSchema.ImageContentSchema.ImplementationSchema.InitializedNotificationSchema.InitializeRequestSchema.InitializeRequestParamsSchema.InitializeResultSchema.JSONArraySchema.JSONObjectSchema.JSONRPCErrorResponseSchema.JSONRPCMessageSchema.JSONRPCNotificationSchema.JSONRPCRequestSchema.JSONRPCResponseSchema.JSONRPCResultResponseSchema.JSONValueSchema.LegacyTitledEnumSchemaSchema.ListPromptsRequestSchema.ListPromptsResultSchema.ListResourcesRequestSchema.ListResourcesResultSchema.ListResourceTemplatesRequestSchema.ListResourceTemplatesResultSchema.ListRootsRequestSchema.ListRootsResultSchema.ListTasksRequestSchema.ListTasksResultSchema.ListToolsRequestSchema.ListToolsResultSchema.LoggingLevelSchema.LoggingMessageNotificationSchema.LoggingMessageNotificationParamsSchema.ModelHintSchema.ModelPreferencesSchema.MultiSelectEnumSchemaSchema.NotificationSchema.NumberSchemaSchema.PaginatedRequestSchema.PaginatedRequestParamsSchema.PaginatedResultSchema.PingRequestSchema.PrimitiveSchemaDefinitionSchema.ProgressSchema.ProgressNotificationSchema.ProgressNotificationParamsSchema.ProgressTokenSchema.PromptSchema.PromptArgumentSchema.PromptListChangedNotificationSchema.PromptMessageSchema.PromptReferenceSchema.ReadResourceRequestSchema.ReadResourceRequestParamsSchema.ReadResourceResultSchema.RelatedTaskMetadataSchema.RequestSchema.RequestIdSchema.RequestMetaSchema.ResourceSchema.ResourceContentsSchema.ResourceLinkSchema.ResourceListChangedNotificationSchema.ResourceRequestParamsSchema.ResourceTemplateSchema.ResourceTemplateReferenceSchema.ResourceUpdatedNotificationSchema.ResourceUpdatedNotificationParamsSchema.ResultMetaObjectSchema.ResultSchema.RoleSchema.RootSchema.RootsListChangedNotificationSchema.SamplingContentSchema.SamplingMessageSchema.SamplingMessageContentBlockSchema.ServerCapabilitiesSchema.ServerNotificationSchema.ServerRequestSchema.ServerResultSchema.SetLevelRequestSchema.SetLevelRequestParamsSchema.SingleSelectEnumSchemaSchema.StringSchemaSchema.SubscribeRequestSchema.SubscribeRequestParamsSchema.SubscriptionFilterSchema.SubscriptionsAcknowledgedNotificationSchema.SubscriptionsAcknowledgedNotificationParamsSchema.SubscriptionsListenRequestSchema.SubscriptionsListenRequestParamsSchema.SubscriptionsListenResultSchema.SubscriptionsListenResultMetaSchema.TaskAugmentedRequestParamsSchema.TaskCreationParamsSchema.TaskMetadataSchema.TaskSchema.TaskStatusSchema.TaskStatusNotificationSchema.TaskStatusNotificationParamsSchema.TextContentSchema.TextResourceContentsSchema.TitledMultiSelectEnumSchemaSchema.TitledSingleSelectEnumSchemaSchema.ToolSchema.ToolAnnotationsSchema.ToolChoiceSchema.ToolExecutionSchema.ToolListChangedNotificationSchema.ToolResultContentSchema.ToolUseContentSchema.UnsubscribeRequestSchema.UnsubscribeRequestParamsSchema.UntitledMultiSelectEnumSchemaSchema.UntitledSingleSelectEnumSchemaSchema`.split(`.`),$m={IdJagTokenExchangeResponseSchema:nu,OAuthClientInformationFullSchema:su,OAuthClientInformationSchema:ou,OAuthClientMetadataSchema:au,OAuthClientRegistrationErrorSchema:cu,OAuthErrorResponseSchema:ru,OAuthMetadataSchema:Ql,OAuthProtectedResourceMetadataSchema:Zl,OAuthTokenRevocationRequestSchema:lu,OAuthTokensSchema:tu,OpenIdProviderDiscoveryMetadataSchema:eu,OpenIdProviderMetadataSchema:$l},eh={},th={};function nh(e,t){let n=e.slice(0,-6);eh[n]=t,th[n]=e=>t.safeParse(e).success}for(let e of Qm)nh(e,om[e]);for(let[e,t]of Object.entries($m))nh(e,t);Object.freeze(eh),Object.freeze(th);function rh(e){switch(e){case`initialize`:case`notifications/initialized`:return tm(void 0);case`server/discover`:return tm(`2026-07-28`);default:return}}let ih=[Wo,Go,qo,Jo],ah=[`inputResponses`,`requestState`];function oh(e,t){let n=e.params;if(!fh(n))return{message:e,lifted:{}};let r=n._meta,i=fh(r)?ih.filter(e=>e in r):[],a=t===`request`?ah.filter(e=>e in n):[];if(i.length===0&&a.length===0)return{message:e,lifted:{}};let o={},s={...n};if(i.length>0&&fh(r)){let e={},t={...r};for(let n of i)e[n]=r[n],delete t[n];o.envelope=e,Object.keys(t).length>0?s._meta=t:delete s._meta}for(let e of a)e===`inputResponses`&&(o.inputResponses=s[e]),e===`requestState`&&(o.requestState=s[e]),delete s[e];return{message:{...e,params:s},lifted:o}}function sh(e,t){let n=e.validateResult(t,void 0);if(!(!n.ok&&n.reason===`not-in-era`))return{"~standard":{version:1,vendor:`mcp-wire-codec`,validate(n){let r=e.validateResult(t,n);return r.ok?{value:r.value}:{issues:[{message:r.reason===`invalid`?r.message:`not-in-era: ${t}`}]}}}}}function ch(e){return()=>e}let lh=ch(void 0);function uh(e,t){return{...e,mcpReq:{...e.mcpReq,requestState:ch(t)}}}var dh=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Uo,this.setNotificationHandler(`notifications/cancelled`,e=>{this._oncancel(e)}),this.setNotificationHandler(`notifications/progress`,e=>{this._onprogress(e)}),this.setRequestHandler(`ping`,e=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let n=e.params??{};return{...e,params:{...n,_meta:{...t,...n._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new X(Y.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new X(Y.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),lm(e)||um(e)?this._onresponse(e):sm(e)?this._onrequest(e,t):cm(e)?this._onnotification(e,t):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let n=new X(Y.ConnectionClosed,`Connection closed`);this._transport=void 0;try{this.onclose?.()}finally{for(let t of e.values())t(n);for(let e of t.values())e.abort(n)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:n}=oh(e,`notification`),r=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)===`drop`)return;if(t?.classification!==void 0){let e=nm(t.classification);if(e!==r.era){this._onerror(Error(`Era mismatch on inbound notification '${n.method}': classified as ${e} but this instance serves ${r.era}`));return}}if(im(n.method)&&!r.hasNotificationMethod(n.method))return;let i=this._notificationHandlers.get(n.method),a=this.fallbackNotificationHandler;i===void 0&&a===void 0||Promise.resolve().then(()=>i===void 0?a(n):i(n,r)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let{message:n,lifted:r}=oh(e,`request`),i=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)===`drop`){this._onerror(Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let a=this._transport,o=(e,t,r)=>{let i={jsonrpc:`2.0`,id:n.id,error:{code:e,message:t,...r!==void 0&&{data:r}}};a?.send(i).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)))};if(t?.classification!==void 0){let e=nm(t.classification);if(e!==i.era){this._onerror(Error(`Era mismatch on inbound request '${n.method}': classified as ${e} but this instance serves ${i.era}`));let r=t.classification.revision??e;o(Z.UnsupportedProtocolVersion,`Unsupported protocol version: ${r}`,{supported:this._supportedProtocolVersions,requested:r});return}}if(rm(n.method)&&!i.hasRequestMethod(n.method)){o(Z.MethodNotFound,`Method not found`);return}let s=this._requestHandlers.get(n.method)??this.fallbackRequestHandler;if(s===void 0){o(Z.MethodNotFound,`Method not found`);return}let c=i.checkInboundEnvelope(r);if(c!==void 0){o(Z.InvalidParams,c);return}let l=(e,t)=>this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,{...t,relatedRequestId:n.id}),u=(e,t,r)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(e.method),e,t,{...r,relatedRequestId:n.id}),d=new AbortController;this._requestHandlerAbortControllers.set(n.id,d);let f=r.inputResponses===void 0?void 0:hh(r.inputResponses),p={sessionId:a?.sessionId,mcpReq:{id:n.id,method:n.method,_meta:n.params?._meta,...r.envelope!==void 0&&{envelope:r.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:r.requestState===void 0?lh:ch(r.requestState),signal:d.signal,send:((e,t,n)=>{let r=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(r,e.method),Cm(t))return u(e,t,n);let i=sh(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return u(e,i,t)}),notify:l},http:t?.authInfo?{authInfo:t.authInfo}:void 0},m=this.buildContext(p,t);Promise.resolve().then(()=>s(n,m)).then(async e=>{if(d.signal.aborted)return;let t;try{t=i.encodeResult(n.method,e,this._outboundServerInfo())}catch(e){this._onerror(Error(`Failed to encode result for ${n.method}: ${e}`)),o(Z.InternalError,`Internal error`);return}let r={result:t,jsonrpc:`2.0`,id:n.id};await a?.send(r)},async e=>{if(d.signal.aborted)return;let t=Number.isSafeInteger(e.code)?e.code:Z.InternalError,r={jsonrpc:`2.0`,id:n.id,error:{code:i.encodeErrorCode(t),message:e.message??`Internal error`,...e.data!==void 0&&{data:e.data}}};await a?.send(r)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(n.id)===d&&this._requestHandlerAbortControllers.delete(n.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._responseHandlers.get(t);if(n===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),lm(e)?n(e):n(Q.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,n){let r=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(r,e.method),Cm(t))return this._requestWithSchemaViaCodec(r,e,t,n);let i=sh(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(r,e,i,t)}_negotiatedWireCodec(){return tm(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=rh(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(rm(t)&&!e.hasRequestMethod(t))throw new X(Y.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,n){let r=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(r,e.method),this._requestWithSchemaViaCodec(r,e,t,n)}_requestWithSchemaViaCodec(e,t,n,r){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s}=r??{},c=Date.now(),l,u;return new Promise((d,f)=>{let p=e=>{f(e)};if(!this._transport){p(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(e){p(e);return}if(r?.signal?.aborted){let e=r.signal.reason;throw e instanceof X?e:new X(Y.RequestTimeout,String(e))}let m=e.era===`2026-07-28`&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,h=this._requestMessageId++;u=h;let g={...t,jsonrpc:`2.0`,id:h};r?.onprogress&&(this._progressHandlers.set(h,r.onprogress),g.params={...t.params,_meta:{...t.params?._meta,progressToken:h}});let _=this._envelopeOutbound(g),ee=!1,te=e=>{ee||(this._progressHandlers.delete(h),m===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:h,reason:String(e)}}),{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))):m.abort(),f(e instanceof X?e:new X(Y.RequestTimeout,String(e))))};this._responseHandlers.set(h,i=>{if(r?.signal?.aborted)return;if(ee=!0,i instanceof Error)return f(i);let a;try{a=e.decodeResult(t.method,i.result)}catch(e){return f(e instanceof Error?e:Error(String(e)))}if(a.kind===`invalid`)return f(a.error);if(a.kind===`input_required`){if(r?.allowInputRequired===!0)return d(gh(a));let i={codec:e,request:t,resultSchema:n,options:r,flowStartedAt:c,retry:(r,i)=>this._requestWithSchemaViaCodec(e,r===void 0?{method:t.method}:{method:t.method,params:r},n,i)};return d(this._resolveNonCompleteResult(a,i))}let o=a.result;km(n,o).then(e=>{e.success?d(e.data):f(new X(Y.InvalidResult,`Invalid result for ${t.method}: ${e.error}`))},f)}),l=()=>te(r?.signal?.reason),r?.signal?.addEventListener(`abort`,l,{once:!0});let ne=r?.timeout??6e4;this._setupTimeout(h,ne,r?.maxTotalTimeout,()=>te(new X(Y.RequestTimeout,`Request timed out`,{timeout:ne})),r?.resetTimeoutOnProgress??!1),this._transport.send(_,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s,requestSignal:m?.signal}).catch(e=>{this._progressHandlers.delete(h),f(e)})}).finally(()=>{l&&r?.signal?.removeEventListener(`abort`,l),u!==void 0&&(this._responseHandlers.delete(u),this._cleanupTimeout(u))})}async notification(e,t){return this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,n){if(!this._transport)throw new X(Y.NotConnected,`Not connected`);if(im(t.method)&&!e.hasNotificationMethod(t.method))throw new X(Y.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let r=this._envelopeOutbound({jsonrpc:`2.0`,...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!n?.relatedRequestId){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(r,n).catch(e=>this._onerror(e))});return}await this._transport.send(r,n)}setRequestHandler(e,t,n){this.assertRequestHandlerCapability(e);let r;if(typeof t==`function`){if(!rm(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);r=(n,r)=>{let i=this._negotiatedWireCodec(),a=i.validateRequest(e,n);if(!a.ok&&a.reason===`not-in-era`&&(a=i.validateInputRequest(e,n)),!a.ok)throw a.reason===`not-in-era`?new Q(Z.InternalError,`No wire schema for ${e} in the resolved era`):Error(a.message);return Promise.resolve(t(a.value,r))}}else if(n)r=async(r,i)=>{let a=await km(t.params,{...r.params});if(!a.success)throw new Q(Z.InvalidParams,`Invalid params for ${e}: ${a.error}`);return n(a.data,i)};else throw TypeError(`setRequestHandler: handler is required`);this._requestHandlers.set(e,this._wrapHandler(e,r))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,n){if(typeof t==`function`){if(!im(e))throw TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,r)=>{let i=r.validateNotification(e,n);if(!i.ok)throw i.reason===`not-in-era`?new Q(Z.InternalError,`No wire schema for ${e} in the resolved era`):Error(i.message);return Promise.resolve(t(i.value))});return}if(!n)throw TypeError(`setNotificationHandler: handler is required`);this._notificationHandlers.set(e,async r=>{let i=await km(t.params,{...r.params});if(!i.success)throw new Q(Z.InvalidParams,`Invalid params for notification ${e}: ${i.error}`);await n(i.data,r)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function fh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ph(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=fh(a)&&fh(i)?{...a,...i}:i}return n}function mh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hh(e){let t={},n=[];if(!mh(e))return{accepted:t,droppedKeys:n};for(let[r,i]of Object.entries(e)){if(!mh(i)||`method`in i||`result`in i){n.push(r);continue}t[r]=i}return{accepted:t,droppedKeys:n}}function gh(e){return{resultType:`input_required`,inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}
|
|
69
|
+
let Cd=globalThis.DOMException,wd=Object.getOwnPropertyDescriptor(globalThis,`window`)?.get,Td=new WeakMap;function Ed(){if(typeof document>`u`||!globalThis.isSecureContext||`modelContext`in document)return;let e=Document.prototype,t=Object.getOwnPropertyDescriptor(e,`defaultView`).get,n=Object.getOwnPropertyDescriptor(globalThis,`ModelContext`);if(!Object.isExtensible(e)||n&&!n.configurable||!n&&!Object.isExtensible(globalThis))throw TypeError(`Cannot install WebMCP on this realm`);Object.defineProperty(globalThis,"ModelContext",{value:kd,configurable:!0,writable:!0});let{getModelContext:r}={getModelContext(){t.call(this);let e=Td.get(this);return e||(e=new Dd(this),Td.set(this,e)),e}};Object.defineProperty(r,"name",{value:`get modelContext`}),Object.defineProperty(e,"modelContext",{configurable:!0,enumerable:!0,get:r}),document.modelContext}var Dd=class extends EventTarget{#e;#t=new Map;#n;#r=null;#i=e=>{let t=this.#r;typeof t==`function`&&Reflect.apply(t,this,[e])===!1&&Event.prototype.preventDefault.call(e)};constructor(e){super(),this.#e=e;let t=Su(e);t&&(this.#n=new _u(t,{getTools:e=>this.#s(e),execute:(t,n,r,i)=>{let a=Wd(e).origin;return this.#a(n,r,a,t,i)},changed:()=>this.#c()}))}get ontoolchange(){return this.#r}set ontoolchange(e){let t=Nd(e)?e:null;!this.#r&&t&&this.addEventListener(`toolchange`,this.#i),this.#r&&!t&&this.removeEventListener(`toolchange`,this.#i),this.#r=t}async registerTool(e,t={}){let n=this.#e,{name:r,title:i,description:a,annotations:o,inputSchema:s,execute:c}=Ad(e),l=Pd(t),u=Vd(l.exposedTo),d=Bd(l.signal);Wd(n);let f=()=>{if(this.#t.has(r))throw new Cd(`A tool named ${r} is already registered`,`InvalidStateError`)};if(f(),!/^[A-Za-z0-9_.-]{1,128}$/u.test(r))throw new Cd(`Tool names are 1 to 128 characters of ASCII alphanumerics, "_", "-" or ".": ${r}`,`InvalidStateError`);if(!a)throw new Cd(`A tool description cannot be empty`,`InvalidStateError`);let p=s===void 0?void 0:zd(s);d?.throwIfAborted();let m=Hd(u),h={metadata:{name:r,title:i,description:a,annotations:o,serializedSchema:p},execute:c,exposedTo:m},g=await this.#o();return d?.throwIfAborted(),f(),new Promise((e,t)=>{d?.addEventListener(`abort`,()=>{this.#t.delete(r),g.notify(m),t(d.reason)},{once:!0}),this.#t.set(r,h),g.notify(m).then(e,t)})}async getTools(e={}){let t=this.#e,n=Vd(Pd(e).fromOrigins);Wd(t);let r=await this.#o(),i=Hd(n),a=await r.getTools(i);return a.sort((e,t)=>e.name===t.name?0:e.name<t.name?-1:1),new Promise(e=>{qd(()=>e(a))})}async executeTool(e,t={},n={}){let r=this.#e,i=jd(e),a=Bd(Pd(n).signal);Wd(r);let o=URL.parse(i.origin)?.origin;if(!o||o===`null`)throw new Cd(`Invalid or opaque origin`,`NotSupportedError`);if(!Nd(t))throw TypeError(`inputObject must be an object`);let s=zd(t);a?.throwIfAborted();let c=await this.#o();a?.throwIfAborted();let l=Wd(r);return i.window===l?this.#a(i.name,s,o,l.origin,a):c.execute(i.window,o,i.name,s,a)}#a(e,t,n,r,i){return new Promise((a,o)=>{i?.throwIfAborted();let s=new AbortController,c=!1,l=()=>{o(i.reason),qd(()=>{c||s.abort()})},u=()=>{c=!0,qd(()=>{i?.removeEventListener(`abort`,l),o(q())})},d=e=>{if(c=!0,!i?.aborted)try{let t=zd(e);qd(()=>{i?.removeEventListener(`abort`,l),a(t)})}catch{u()}};i?.addEventListener(`abort`,l,{once:!0}),qd(()=>{if(!i?.aborted)try{let i=Wd(this.#e),a=this.#t.get(e);if(!a||n!==i.origin||!Od(a,i.origin,r)){u();return}let o=JSON.parse(t);if(!Nd(o)){u();return}let c=a.execute,l=c(o,{signal:s.signal});Promise.resolve(l).then(d,u)}catch{u()}})})}async#o(){let e=this.#n;if(!e||!await e.allowed())throw new Cd(`WebMCP is disabled by Permissions Policy`,`NotAllowedError`);return Wd(this.#e),e}#s(e){let t=Wd(this.#e).origin,n=[];for(let r of this.#t.values())Od(r,t,e)&&n.push(r.metadata);return n}#c(){return new Promise(e=>{qd(()=>{this.dispatchEvent(new Event(`toolchange`)),e()})})}};function Od(e,t,n){return t===n||e.exposedTo.includes(n)}let kd=function(){throw TypeError(`Illegal constructor`)};Object.defineProperty(kd,"name",{value:`ModelContext`}),Object.defineProperty(kd,"prototype",{value:Dd.prototype,writable:!1}),Object.setPrototypeOf(kd,EventTarget),Object.defineProperties(Dd.prototype,{constructor:{value:kd,configurable:!0,writable:!0},[Symbol.toStringTag]:{value:`ModelContext`,configurable:!0},registerTool:{enumerable:!0},getTools:{enumerable:!0},executeTool:{enumerable:!0},ontoolchange:{enumerable:!0}});function Ad(e){let t=Pd(e),n=Fd(t.annotations),r=Id(Rd(t.description,`description`)),i=Rd(t.execute,`execute`);if(typeof i!=`function`)throw TypeError(`execute must be a function`);let a=i,o=Md(t.inputSchema),s=Id(Rd(t.name,`name`)),c=t.title;return{name:s,title:c===void 0?``:Ld(c),description:r,annotations:n,inputSchema:o,execute:a}}function jd(e){let t=Pd(e);Fd(t.annotations),Id(Rd(t.description,`description`)),Md(t.inputSchema);let n=Id(Rd(t.name,`name`)),r=Ld(Rd(t.origin,`origin`)),i=t.title;i!==void 0&&Id(i);let a=Rd(t.window,`window`);if(!Nd(a))throw TypeError(`window must be a Window`);return wd.call(a),{name:n,origin:r,window:a}}function Md(e){if(e!==void 0&&!Nd(e))throw TypeError(`inputSchema must be an object`);return e}function Nd(e){return typeof e==`object`&&!!e||typeof e==`function`}function Pd(e){if(e==null)return{};if(!Nd(e))throw TypeError(`Expected a dictionary`);return e}function Fd(e){if(e===void 0)return;let t=Pd(e),n={};for(let e of mu)n[e]=!!t[e];return n}function Id(e){if(typeof e==`symbol`)throw TypeError(`Cannot convert a Symbol to a string`);return String(e)}function Ld(e){return Id(e).toWellFormed()}function Rd(e,t){if(e===void 0)throw TypeError(`${t} is required`);return e}function zd(e){let t=JSON.stringify(e);if(t===void 0)throw TypeError(`Value is not JSON-serializable`);return t}function Bd(e){if(e!==void 0)return AbortSignal.any([e])}function Vd(e){if(e===void 0)return[];if(!Nd(e))throw TypeError(`Origins must be a sequence`);let t=Pd(e)[Symbol.iterator];if(typeof t!=`function`)throw TypeError(`Origins must be a sequence`);let n={[Symbol.iterator](){let n=Reflect.apply(t,e,[]);if(!Nd(n))throw TypeError(`Iterator must be an object`);let r=Pd(n).next;if(typeof r!=`function`)throw TypeError(`Iterator next must be a function`);return{next(){return Reflect.apply(r,n,[])}}}};return Array.from(n,Ld)}function Hd(e){return e.map(e=>{let t=URL.parse(e)?.origin;if(t===void 0)throw new Cd(`Invalid origin`,`SecurityError`);let n=URL.parse(t);if(!n||!Ud(n))throw new Cd(`Origin is not potentially trustworthy`,`SecurityError`);return t})}function Ud({protocol:e,hostname:t}){if([`https:`,`wss:`].includes(e))return!0;let n=t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t),r=t===`localhost`||t===`localhost.`||t.endsWith(`.localhost`)||t.endsWith(`.localhost.`);return[`http:`,`ws:`].includes(e)&&(n||r)}function Wd(e){let t=Su(e);if(!t)throw new Cd(`The document is not fully active`,`InvalidStateError`);if(Cu(e)===!1)throw new Cd(`WebMCP is disabled by Permissions Policy`,`NotAllowedError`);return t}let Gd,Kd=[];function qd(e){if(!Gd){let e=new MessageChannel;e.port1.onmessage=()=>Kd.shift()?.(),Gd=e.port2}Kd.push(e),Gd.postMessage(void 0)}function Jd(){if(typeof document>`u`||!globalThis.isSecureContext||typeof Promise.withResolvers!=`function`||typeof AbortSignal.any!=`function`||typeof String.prototype.toWellFormed!=`function`||typeof URL.parse!=`function`)return;Ed();let e=document.modelContext;e&&Sd(e)}let Yd=/^[A-Za-z0-9_.-]{1,128}$/u;function J(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xd(e){return e!==null&&(typeof e==`object`||typeof e==`function`)}function Zd(e){if(typeof e==`symbol`)throw TypeError(`Symbol values cannot be converted to a DOMString`);return String(e)}function Qd(e){let{name:t,description:n,title:r}=e;if(t===void 0)throw TypeError(`Tool "name" is required`);if(n===void 0)throw TypeError(`Tool "description" is required`);let{annotations:i,inputSchema:a,outputSchema:o,execute:s}=e,c=Zd(t),l=r===void 0?void 0:Zd(r).toWellFormed(),u={name:c,description:Zd(n),execute:s};if(l!==void 0&&(u.title=l),a!==void 0&&(u.inputSchema=a),o!==void 0&&(u.outputSchema=o),i!==void 0){let e=J(i)?i:{},t={readOnlyHint:!!e.readOnlyHint,untrustedContentHint:!!e.untrustedContentHint};e.title!==void 0&&(t.title=Zd(e.title).toWellFormed());for(let n of[`destructiveHint`,`idempotentHint`,`openWorldHint`,`consequentialHint`,`debugging`]){let r=e[n];r!==void 0&&(t[n]=!!r)}u.annotations=t}return ef(u),u}function $d(e){return new DOMException(e,`InvalidStateError`)}function ef(e){if(e.name===``)throw $d(`Tool "name" must be a non-empty string`);if(!Yd.test(e.name))throw $d(`Tool "name" must be 1–128 characters and contain only ASCII alphanumeric, underscore, hyphen, or period`);if(e.description.length===0)throw $d(`Tool "description" must be a non-empty string`);if(typeof e.execute!=`function`)throw TypeError(`Tool "execute" must be a function`)}function tf(e){if(!Xd(e))throw TypeError(`inputSchema must be an object`);let t=JSON.stringify(e);if(t===void 0)throw TypeError(`inputSchema must be JSON-serializable`);return t}let nf={type:`object`,properties:{}},rf=[`draft-2020-12`,`draft-07`];function af(e){if(!J(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function of(e,t=new WeakSet){if(e===null||typeof e==`string`||typeof e==`boolean`)return!0;if(typeof e==`number`)return Number.isFinite(e);if(typeof e!=`object`||t.has(e))return!1;t.add(e);try{return(Array.isArray(e)?e:af(e)?Object.values(e):null)?.every(e=>of(e,t))??!1}catch{return!1}finally{t.delete(e)}}function sf(e){if(!J(e))return!1;switch(e.type){case`text`:return typeof e.text==`string`;case`image`:case`audio`:return typeof e.data==`string`&&typeof e.mimeType==`string`;case`resource_link`:return typeof e.uri==`string`&&typeof e.name==`string`;case`resource`:{let t=e.resource;return J(t)&&typeof t.uri==`string`&&(typeof t.text==`string`||typeof t.blob==`string`)}default:return!1}}function cf(e){return J(e)&&of(e)&&Array.isArray(e.content)&&e.content.every(sf)&&(e.isError===void 0||typeof e.isError==`boolean`)&&(e._meta===void 0||J(e._meta))}function lf(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function uf(e){if(cf(e))return e;let t={content:[{type:`text`,text:lf(e)}],isError:!1};return of(e)&&(t.structuredContent=e),t}function df(e){if(!J(e))return null;let t=e[`~standard`];return J(t)?t:null}function ff(e){let t=df(e);return!!(t&&t.version===1&&typeof t.validate==`function`)}function pf(e){let t=df(e);return!t||t.version!==1||!J(t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function mf(e){let t=df(e);return!!(t&&t.version===1&&typeof t.vendor==`string`&&typeof t.validate==`function`&&J(t.jsonSchema)&&typeof t.jsonSchema.input==`function`&&typeof t.jsonSchema.output==`function`)}function hf(e){for(let t of rf)try{let n=e[`~standard`].jsonSchema.input({target:t}),r=JSON.parse(tf(n));if(J(r))return r}catch{}throw Error(`Failed to convert Standard JSON Schema inputSchema to a JSON Schema object`)}function gf(e){if(e===void 0)return{inputSchema:nf};if(pf(e)){let t=hf(e),n=tf(t);return ff(e)&&Object.defineProperty(t,"~standard",{value:e[`~standard`]}),{inputSchema:t,registeredInputSchema:n}}if(ff(e))throw Error(`Standard Schema inputSchema must provide ~standard.jsonSchema.input() for tool metadata`);let t=tf(e),n=JSON.parse(t);return!J(n)||Object.keys(n).length===0?{inputSchema:nf,registeredInputSchema:t}:{inputSchema:n.type===void 0?{type:`object`,...n}:n,registeredInputSchema:t}}var _f=Object.defineProperty,vf=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),yf=(e,t)=>{let n={};for(var r in e)_f(n,r,{get:e[r],enumerable:!0});return t&&_f(n,Symbol.toStringTag,{value:`Module`}),n};let bf=new Set([`https://json-schema.org/draft/2020-12/schema`,`http://json-schema.org/draft/2020-12/schema`]),xf=new Set([`https://json-schema.org/draft/2019-09/schema`,`http://json-schema.org/draft/2019-09/schema`]),Sf=new Set([`https://json-schema.org/draft-07/schema`,`http://json-schema.org/draft-07/schema`]),Cf=new Set([`https://json-schema.org/draft-06/schema`,`http://json-schema.org/draft-06/schema`]);function wf(e){return typeof e==`string`&&xf.has(e.replace(/#$/,``))}function Tf(e,t){if(!(`$schema`in e)||typeof e.$schema!=`string`)return`2020-12`;let n=e.$schema.replace(/#$/,``);if(bf.has(n))return`2020-12`;if(xf.has(n))return`2019-09`;if(Sf.has(n)||Cf.has(n))return`draft-7`;throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}let Ef=Symbol.for(`mcp.sdk.errorBrands`);function Df(e,t){let n=new Set,r=t;for(;typeof r==`function`;){let e=r.mcpBrand;Object.prototype.hasOwnProperty.call(r,`mcpBrand`)&&typeof e==`string`&&n.add(e),r=Object.getPrototypeOf(r)}n.size!==0&&Object.defineProperty(e,Ef,{value:n,enumerable:!1,configurable:!0})}function Of(e,t){try{if(typeof t==`object`&&t&&Object.prototype.hasOwnProperty.call(e,`mcpBrand`)&&typeof e.mcpBrand==`string`&&Object.prototype.hasOwnProperty.call(t,Ef)){let n=t[Ef];if(n&&typeof n.has==`function`&&n.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}(class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.OAuthError`})}static[Symbol.hasInstance](e){return Of(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Of(this,e)}constructor(e,t,n){super(t),this.code=e,this.errorUri=n,this.name=`OAuthError`,Df(this,new.target)}toResponseObject(){let e={error:this.code,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}});let Y=function(e){return e.NotConnected=`NOT_CONNECTED`,e.AlreadyConnected=`ALREADY_CONNECTED`,e.NotInitialized=`NOT_INITIALIZED`,e.CapabilityNotSupported=`CAPABILITY_NOT_SUPPORTED`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.ConnectionClosed=`CONNECTION_CLOSED`,e.SendFailed=`SEND_FAILED`,e.InvalidResult=`INVALID_RESULT`,e.UnsupportedResultType=`UNSUPPORTED_RESULT_TYPE`,e.InputRequiredRoundsExceeded=`INPUT_REQUIRED_ROUNDS_EXCEEDED`,e.ListPaginationExceeded=`LIST_PAGINATION_EXCEEDED`,e.MethodNotSupportedByProtocolVersion=`METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION`,e.EraNegotiationFailed=`ERA_NEGOTIATION_FAILED`,e.ClientHttpNotImplemented=`CLIENT_HTTP_NOT_IMPLEMENTED`,e.ClientHttpAuthentication=`CLIENT_HTTP_AUTHENTICATION`,e.ClientHttpForbidden=`CLIENT_HTTP_FORBIDDEN`,e.ClientHttpUnexpectedContent=`CLIENT_HTTP_UNEXPECTED_CONTENT`,e.ClientHttpFailedToOpenStream=`CLIENT_HTTP_FAILED_TO_OPEN_STREAM`,e.ClientHttpFailedToTerminateSession=`CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION`,e}({});var X=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SdkError`})}static[Symbol.hasInstance](e){return Of(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Of(this,e)}constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`SdkError`,Df(this,new.target)}};(class extends X{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SdkHttpError`})}constructor(e,t,n){super(e,t,n),this.name=`SdkHttpError`}get status(){return this.data.status}get statusText(){return this.data.statusText}});function kf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Af(e,t,n){return e===`elicitation`&&t===`form`&&n.form===void 0&&n.url===void 0}function jf(e){switch(e.method){case`elicitation/create`:return e.params?.mode===`url`?{elicitation:{url:{}}}:{elicitation:{form:{}}};case`sampling/createMessage`:{let t=e.params;return t!==void 0&&(t.tools!==void 0||t.toolChoice!==void 0)?{sampling:{tools:{}}}:{sampling:{}}}case`roots/list`:return{roots:{}};default:return}}function Mf(e,t){let n={};for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let e=t===void 0?void 0:t[r];if(e===void 0){n[r]=i;continue}if(kf(i)&&kf(e)){let t={};for(let[n,a]of Object.entries(i))a!==void 0&&e[n]===void 0&&!Af(r,n,e)&&(t[n]=a);Object.keys(t).length>0&&(n[r]=t)}}return Object.keys(n).length>0?n:void 0}function Nf(e){return e>=`2026-07-28`}function Pf(e){return e.filter(e=>!Nf(e))}function Ff(e){return e.filter(e=>Nf(e))}function If(e){let t=e.structuredContent;return t===void 0||!(typeof t!=`object`||!t||Array.isArray(t))||(e.content?.some(e=>e.type===`text`)??!1)?e:{...e,content:[...e.content??[],{type:`text`,text:JSON.stringify(t)}]}}let Lf=[`task`,`inputRequests`,`requestState`];function Rf(e){return typeof e!=`object`||!e||Array.isArray(e)||e.content!==void 0||Lf.some(t=>t in e)?e:{...e,content:[]}}function zf(){let e=Fo(()=>L([k(),j(),M(),Za(),R(k(),e),P(e)])),t=R(k(),e),n=L([k(),j().int()]),r=k(),i=F({ttl:j().optional()}),a=F({taskId:k()}),o=I({progressToken:n.optional(),"io.modelcontextprotocol/related-task":a.optional()}),s=F({_meta:o.optional()}),c=s.extend({task:i.optional()}),l=F({method:k(),params:s.loose().optional()}),u=F({_meta:o.optional()}),d=F({method:k(),params:u.loose().optional()}),f=I({_meta:o.optional()}),p=L([k(),j().int()]),m=f.strict(),h=u.extend({requestId:p.optional(),reason:k().optional()}),g=d.extend({method:B(`notifications/cancelled`),params:h}),_=F({src:k(),mimeType:k().optional(),sizes:P(k()).optional(),theme:z([`light`,`dark`]).optional()}),ee=F({icons:P(_).optional()}),te=F({name:k(),title:k().optional()}),ne=te.extend({...te.shape,...ee.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),re=zo(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,lo(F({form:lo(F({applyDefaults:M().optional()}),t).optional(),url:t.optional()}),t.optional())),ie=I({list:t.optional(),cancel:t.optional(),requests:I({sampling:I({createMessage:t.optional()}).optional(),elicitation:I({create:t.optional()}).optional()}).optional()}),ae=I({list:t.optional(),cancel:t.optional(),requests:I({tools:I({call:t.optional()}).optional()}).optional()}),oe=F({experimental:R(k(),t).optional(),sampling:F({context:t.optional(),tools:t.optional()}).optional(),elicitation:re.optional(),roots:F({listChanged:M().optional()}).optional(),tasks:ie.optional(),extensions:R(k(),t).optional()}),se=s.extend({protocolVersion:k(),capabilities:oe,clientInfo:ne}),ce=l.extend({method:B(`initialize`),params:se}),le=F({experimental:R(k(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:F({listChanged:M().optional()}).optional(),resources:F({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:F({listChanged:M().optional()}).optional(),tasks:ae.optional(),extensions:R(k(),t).optional()}),v=f.extend({protocolVersion:k(),capabilities:le,serverInfo:ne,instructions:k().optional()}),ue=d.extend({method:B(`notifications/initialized`),params:u.optional()}),de=l.extend({method:B(`ping`),params:s.optional()}),fe=F({progress:j(),total:V(j()),message:V(k())}),pe=F({...u.shape,...fe.shape,progressToken:n}),me=d.extend({method:B(`notifications/progress`),params:pe}),he=s.extend({cursor:r.optional()}),ge=l.extend({params:he.optional()}),_e=f.extend({nextCursor:r.optional()}),ve=F({uri:k(),mimeType:V(k()),_meta:R(k(),N()).optional()}),ye=ve.extend({text:k()}),be=k().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),xe=ve.extend({blob:be}),y=z([`user`,`assistant`]),b=F({audience:P(y).optional(),priority:j().min(0).max(1).optional(),lastModified:ta({offset:!0}).optional()}),Se=F({...te.shape,...ee.shape,uri:k(),description:V(k()),mimeType:V(k()),size:V(j()),annotations:b.optional(),_meta:V(I({}))}),Ce=F({...te.shape,...ee.shape,uriTemplate:k(),description:V(k()),mimeType:V(k()),annotations:b.optional(),_meta:V(I({}))}),we=ge.extend({method:B(`resources/list`)}),Te=_e.extend({resources:P(Se)}),x=ge.extend({method:B(`resources/templates/list`)}),Ee=_e.extend({resourceTemplates:P(Ce)}),De=s.extend({uri:k()}),Oe=De,ke=l.extend({method:B(`resources/read`),params:Oe}),Ae=f.extend({contents:P(L([ye,xe]))}),je=d.extend({method:B(`notifications/resources/list_changed`),params:u.optional()}),Me=De,Ne=l.extend({method:B(`resources/subscribe`),params:Me}),S=De,Pe=l.extend({method:B(`resources/unsubscribe`),params:S}),Fe=u.extend({uri:k()}),Ie=d.extend({method:B(`notifications/resources/updated`),params:Fe}),Le=F({name:k(),description:V(k()),required:V(M())}),Re=F({...te.shape,...ee.shape,description:V(k()),arguments:V(P(Le)),_meta:V(I({}))}),ze=ge.extend({method:B(`prompts/list`)}),Be=_e.extend({prompts:P(Re)}),Ve=s.extend({name:k(),arguments:R(k(),k()).optional()}),He=l.extend({method:B(`prompts/get`),params:Ve}),Ue=F({type:B(`text`),text:k(),annotations:b.optional(),_meta:R(k(),N()).optional()}),We=F({type:B(`image`),data:be,mimeType:k(),annotations:b.optional(),_meta:R(k(),N()).optional()}),Ge=F({type:B(`audio`),data:be,mimeType:k(),annotations:b.optional(),_meta:R(k(),N()).optional()}),Ke=F({type:B(`tool_use`),name:k(),id:k(),input:R(k(),N()),_meta:R(k(),N()).optional()}),qe=F({type:B(`resource`),resource:L([ye,xe]),annotations:b.optional(),_meta:R(k(),N()).optional()}),Je=Se.extend({type:B(`resource_link`)}),Ye=L([Ue,We,Ge,Je,qe]),Xe=F({role:y,content:Ye}),Ze=f.extend({description:k().optional(),messages:P(Xe)}),Qe=d.extend({method:B(`notifications/prompts/list_changed`),params:u.optional()}),$e=F({title:k().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),et=F({taskSupport:z([`required`,`optional`,`forbidden`]).optional()}),tt=F({...te.shape,...ee.shape,description:k().optional(),inputSchema:F({type:B(`object`),properties:R(k(),e).optional(),required:P(k()).optional()}).catchall(N()),outputSchema:F({type:B(`object`),properties:R(k(),e).optional(),required:P(k()).optional()}).catchall(N()).optional(),annotations:$e.optional(),execution:et.optional(),_meta:R(k(),N()).optional()}),nt=ge.extend({method:B(`tools/list`)}),rt=_e.extend({tools:P(tt)}),it=f.extend({content:P(Ye),structuredContent:R(k(),N()).optional(),isError:M().optional()}),C=c.extend({name:k(),arguments:R(k(),N()).optional()}),at=l.extend({method:B(`tools/call`),params:C}),ot=d.extend({method:B(`notifications/tools/list_changed`),params:u.optional()}),st=z([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),ct=s.extend({level:st}),lt=l.extend({method:B(`logging/setLevel`),params:ct}),ut=u.extend({level:st,logger:k().optional(),data:N()}),dt=d.extend({method:B(`notifications/message`),params:ut}),ft=F({name:k().optional()}),pt=F({hints:P(ft).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),mt=F({mode:z([`auto`,`required`,`none`]).optional()}),ht=F({type:B(`tool_result`),toolUseId:k().describe(`The unique identifier for the corresponding tool call.`),content:P(Ye),structuredContent:F({}).loose().optional(),isError:M().optional(),_meta:R(k(),N()).optional()}),gt=so(`type`,[Ue,We,Ge]),w=so(`type`,[Ue,We,Ge,Ke,ht]),_t=F({role:y,content:L([w,P(w)]),_meta:R(k(),N()).optional()}),vt=c.extend({messages:P(_t),modelPreferences:pt.optional(),systemPrompt:k().optional(),includeContext:z([`none`,`thisServer`,`allServers`]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:P(k()).optional(),metadata:t.optional(),tools:P(tt).optional(),toolChoice:mt.optional()}),yt=l.extend({method:B(`sampling/createMessage`),params:vt}),bt=f.extend({model:k(),stopReason:V(z([`endTurn`,`stopSequence`,`maxTokens`]).or(k())),role:y,content:gt}),xt=f.extend({model:k(),stopReason:V(z([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(k())),role:y,content:L([w,P(w)])}),St=F({type:B(`boolean`),title:k().optional(),description:k().optional(),default:M().optional()}),Ct=F({type:B(`string`),title:k().optional(),description:k().optional(),minLength:j().optional(),maxLength:j().optional(),format:z([`email`,`uri`,`date`,`date-time`]).optional(),default:k().optional()}),wt=F({type:z([`number`,`integer`]),title:k().optional(),description:k().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),Tt=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),default:k().optional()}),Et=F({type:B(`string`),title:k().optional(),description:k().optional(),oneOf:P(F({const:k(),title:k()})),default:k().optional()}),Dt=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),enumNames:P(k()).optional(),default:k().optional()}),Ot=L([Tt,Et]),kt=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({type:B(`string`),enum:P(k())}),default:P(k()).optional()}),At=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({anyOf:P(F({const:k(),title:k()}))}),default:P(k()).optional()}),jt=L([kt,At]),Mt=L([Dt,Ot,jt]),Nt=L([Mt,St,Ct,wt]),Pt=c.extend({mode:B(`form`).optional(),message:k(),requestedSchema:F({type:B(`object`),properties:R(k(),Nt),required:P(k()).optional()}).catchall(N())}),T=c.extend({mode:B(`url`),message:k(),elicitationId:k(),url:k().url()}),Ft=L([Pt,T]),E=l.extend({method:B(`elicitation/create`),params:Ft}),It=u.extend({elicitationId:k()}),Lt=d.extend({method:B(`notifications/elicitation/complete`),params:It}),Rt=f.extend({action:z([`accept`,`decline`,`cancel`]),content:zo(e=>e===null?void 0:e,R(k(),L([k(),j(),M(),P(k())])).optional())}),zt=F({type:B(`ref/resource`),uri:k()}),Bt=F({type:B(`ref/prompt`),name:k()}),Vt=s.extend({ref:L([Bt,zt]),argument:F({name:k(),value:k()}),context:F({arguments:R(k(),k()).optional()}).optional()}),Ht=l.extend({method:B(`completion/complete`),params:Vt}),Ut=f.extend({completion:I({values:P(k()).max(100),total:V(j().int()),hasMore:V(M())})}),Wt=F({uri:k().startsWith(`file://`),name:k().optional(),_meta:R(k(),N()).optional()}),Gt=l.extend({method:B(`roots/list`),params:s.optional()}),Kt=f.extend({roots:P(Wt)}),qt=d.extend({method:B(`notifications/roots/list_changed`),params:u.optional()}),Jt=I({ttl:j().optional(),pollInterval:j().optional()}),Yt=z([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Xt=F({taskId:k(),status:Yt,ttl:L([j(),Za()]),createdAt:k(),lastUpdatedAt:k(),pollInterval:V(j()),statusMessage:V(k())}),Zt=f.extend({task:Xt}),Qt=u.merge(Xt),$t=d.extend({method:B(`notifications/tasks/status`),params:Qt}),en=l.extend({method:B(`tasks/get`),params:s.extend({taskId:k()})}),tn=f.merge(Xt),nn=l.extend({method:B(`tasks/result`),params:s.extend({taskId:k()})}),rn=f.loose(),an=ge.extend({method:B(`tasks/list`)}),on=_e.extend({tasks:P(Xt)}),sn=l.extend({method:B(`tasks/cancel`),params:s.extend({taskId:k()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,TaskMetadataSchema:i,RelatedTaskMetadataSchema:a,RequestMetaSchema:o,BaseRequestParamsSchema:s,TaskAugmentedRequestParamsSchema:c,RequestSchema:l,NotificationsParamsSchema:u,NotificationSchema:d,ResultSchema:f,RequestIdSchema:p,EmptyResultSchema:m,CancelledNotificationParamsSchema:h,CancelledNotificationSchema:g,IconSchema:_,IconsSchema:ee,BaseMetadataSchema:te,ImplementationSchema:ne,ClientTasksCapabilitySchema:ie,ServerTasksCapabilitySchema:ae,ClientCapabilitiesSchema:oe,InitializeRequestParamsSchema:se,InitializeRequestSchema:ce,ServerCapabilitiesSchema:le,InitializeResultSchema:v,InitializedNotificationSchema:ue,PingRequestSchema:de,ProgressSchema:fe,ProgressNotificationParamsSchema:pe,ProgressNotificationSchema:me,PaginatedRequestParamsSchema:he,PaginatedRequestSchema:ge,PaginatedResultSchema:_e,ResourceContentsSchema:ve,TextResourceContentsSchema:ye,BlobResourceContentsSchema:xe,RoleSchema:y,AnnotationsSchema:b,ResourceSchema:Se,ResourceTemplateSchema:Ce,ListResourcesRequestSchema:we,ListResourcesResultSchema:Te,ListResourceTemplatesRequestSchema:x,ListResourceTemplatesResultSchema:Ee,ResourceRequestParamsSchema:De,ReadResourceRequestParamsSchema:Oe,ReadResourceRequestSchema:ke,ReadResourceResultSchema:Ae,ResourceListChangedNotificationSchema:je,SubscribeRequestParamsSchema:Me,SubscribeRequestSchema:Ne,UnsubscribeRequestParamsSchema:S,UnsubscribeRequestSchema:Pe,ResourceUpdatedNotificationParamsSchema:Fe,ResourceUpdatedNotificationSchema:Ie,PromptArgumentSchema:Le,PromptSchema:Re,ListPromptsRequestSchema:ze,ListPromptsResultSchema:Be,GetPromptRequestParamsSchema:Ve,GetPromptRequestSchema:He,TextContentSchema:Ue,ImageContentSchema:We,AudioContentSchema:Ge,ToolUseContentSchema:Ke,EmbeddedResourceSchema:qe,ResourceLinkSchema:Je,ContentBlockSchema:Ye,PromptMessageSchema:Xe,GetPromptResultSchema:Ze,PromptListChangedNotificationSchema:Qe,ToolAnnotationsSchema:$e,ToolExecutionSchema:et,ToolSchema:tt,ListToolsRequestSchema:nt,ListToolsResultSchema:rt,CallToolResultSchema:it,CallToolRequestParamsSchema:C,CallToolRequestSchema:at,ToolListChangedNotificationSchema:ot,LoggingLevelSchema:st,SetLevelRequestParamsSchema:ct,SetLevelRequestSchema:lt,LoggingMessageNotificationParamsSchema:ut,LoggingMessageNotificationSchema:dt,ModelHintSchema:ft,ModelPreferencesSchema:pt,ToolChoiceSchema:mt,ToolResultContentSchema:ht,SamplingContentSchema:gt,SamplingMessageContentBlockSchema:w,SamplingMessageSchema:_t,CreateMessageRequestParamsSchema:vt,CreateMessageRequestSchema:yt,CreateMessageResultSchema:bt,CreateMessageResultWithToolsSchema:xt,BooleanSchemaSchema:St,StringSchemaSchema:Ct,NumberSchemaSchema:wt,UntitledSingleSelectEnumSchemaSchema:Tt,TitledSingleSelectEnumSchemaSchema:Et,LegacyTitledEnumSchemaSchema:Dt,SingleSelectEnumSchemaSchema:Ot,UntitledMultiSelectEnumSchemaSchema:kt,TitledMultiSelectEnumSchemaSchema:At,MultiSelectEnumSchemaSchema:jt,EnumSchemaSchema:Mt,PrimitiveSchemaDefinitionSchema:Nt,ElicitRequestFormParamsSchema:Pt,ElicitRequestURLParamsSchema:T,ElicitRequestParamsSchema:Ft,ElicitRequestSchema:E,ElicitationCompleteNotificationParamsSchema:It,ElicitationCompleteNotificationSchema:Lt,ElicitResultSchema:Rt,ResourceTemplateReferenceSchema:zt,PromptReferenceSchema:Bt,CompleteRequestParamsSchema:Vt,CompleteRequestSchema:Ht,CompleteResultSchema:Ut,RootSchema:Wt,ListRootsRequestSchema:Gt,ListRootsResultSchema:Kt,RootsListChangedNotificationSchema:qt,TaskCreationParamsSchema:Jt,TaskStatusSchema:Yt,TaskSchema:Xt,CreateTaskResultSchema:Zt,TaskStatusNotificationParamsSchema:Qt,TaskStatusNotificationSchema:$t,GetTaskRequestSchema:en,GetTaskResultSchema:tn,GetTaskPayloadRequestSchema:nn,GetTaskPayloadResultSchema:rn,ListTasksRequestSchema:an,ListTasksResultSchema:on,CancelTaskRequestSchema:sn,CancelTaskResultSchema:f.merge(Xt),ClientRequestSchema:L([de,ce,Ht,lt,He,ze,we,x,ke,Ne,Pe,at,nt,en,nn,an,sn]),ClientNotificationSchema:L([g,me,ue,qt,$t]),ClientResultSchema:L([m,bt,xt,Rt,Kt,tn,on,Zt]),ServerRequestSchema:L([de,yt,E,Gt,en,nn,an,sn]),ServerNotificationSchema:L([g,me,dt,Ie,je,ot,Qe,$t,Lt]),ServerResultSchema:L([m,v,Ut,Ze,Be,Te,Ee,Ae,it,rt,tn,on,Zt]),CallToolResultWireSchema:N().superRefine((e,t)=>{if(!(typeof e!=`object`||!e||Array.isArray(e)||e.content!==void 0)){for(let n of Lf)if(n in e){t.addIssue({code:`custom`,message:`content is required when the body carries '${n}' — another result family cannot default into an empty tools/call success`});return}}}).transform(Rf).pipe(it)}}let Bf;function Vf(){return Bf??=zf()}function Hf(e){return e.type!==`object`}let Uf=new Set([`const`,`enum`,`default`,`examples`]),Wf=new Set([`properties`,`patternProperties`,`$defs`,`definitions`,`dependentSchemas`,`dependencies`]);function Gf(e){return e!==void 0&&!(typeof e==`string`&&e.startsWith(`#`))}function Kf(e){let t=typeof e.$schema==`string`?e.$schema:void 0;if(Gf(e.$id))return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:e},required:[`result`]};let n=wf(e.$schema)&&e.$recursiveAnchor!==!0,r=(e,t)=>{if(Array.isArray(e))return e.map(e=>r(e,!1));if(typeof e!=`object`||!e||!t&&Gf(e.$id))return e;let i={},a=!1;for(let[o,s]of Object.entries(e))t?i[o]=r(s,!1):(o===`$ref`||o===`$dynamicRef`)&&typeof s==`string`?i[o]=s===`#`?`#/properties/result`:s.startsWith(`#/`)?`#/properties/result${s.slice(1)}`:s:o===`$recursiveRef`&&s===`#`&&n?a=!0:Uf.has(o)?i[o]=s:Wf.has(o)?i[o]=r(s,!0):i[o]=r(s,!1);return a&&(`$ref`in i?i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:`#/properties/result`}]:i.$ref=`#/properties/result`),i};return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:r(e,!1)},required:[`result`]}}let qf={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Jf={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},Yf={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Xf;function Zf(){if(Xf)return Xf;let e=Vf();return Xf={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},Xf}function Qf(e){return Object.prototype.hasOwnProperty.call(qf,e)}function $f(e){return Object.prototype.hasOwnProperty.call(Jf,e)}function ep(e){return Object.prototype.hasOwnProperty.call(Yf,e)}function tp(e){return ep(e)?Zf().resultSchemas[e]:void 0}function np(e){return Qf(e)?Zf().requestSchemas[e]:void 0}function rp(e){return $f(e)?Zf().notificationSchemas[e]:void 0}function ip(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ap(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}let op={ok:!1,reason:`not-in-era`};function sp(e){return ip(e)&&ip(e.outputSchema)&&Hf(e.outputSchema)}function cp(e){return e}let lp={era:`2025-11-25`,hasRequestMethod:Qf,hasNotificationMethod:$f,validateRequest:(e,t)=>ap(np(e),t),validateResult:(e,t)=>ap(tp(e),t),validateNotification:(e,t)=>ap(rp(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>op,validateInputResponse:()=>op,samplingResultVariant:((e,t)=>{let n=Vf();return ap(e?n.CreateMessageResultWithToolsSchema:n.CreateMessageResultSchema,t)}),outboundEnvelope:e=>void 0,validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){let n=If(e),r=n.structuredContent;if(r===void 0)return n;let i=typeof r!=`object`||!r||Array.isArray(r),a=t!==void 0&&Hf(t);return!i&&!a?n:{...n,structuredContent:{result:r}}},decodeResult(e,t){if(ip(t)&&`resultType`in t){let e={...t};return delete e.resultType,{kind:`complete`,result:cp(e)}}return{kind:`complete`,result:cp(t)}},encodeResult(e,t){if(e!==`tools/list`)return t;let n=t.tools;return!Array.isArray(n)||!n.some(e=>sp(e))?t:{...t,tools:n.map(e=>sp(e)?{...e,outputSchema:Kf(e.outputSchema)}:e)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>void 0};function up(){let e=Fo(()=>L([k(),j(),M(),Za(),R(k(),e),P(e)])),t=R(k(),e),n=L([k(),j().int()]),r=k(),i=L([k(),j().int()]),a=z([`user`,`assistant`]),o=z([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),s=k().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),c=F({ttl:j().optional()}),l=F({taskId:k()}),u=I({progressToken:n.optional(),"io.modelcontextprotocol/related-task":l.optional()}),d=F({_meta:u.optional()}),f=d.extend({task:c.optional()}),p=F({_meta:u.optional()}),m=F({method:k(),params:p.loose().optional()}),h=F({src:k(),mimeType:k().optional(),sizes:P(k()).optional(),theme:z([`light`,`dark`]).optional()}),g=F({icons:P(h).optional()}),_=F({name:k(),title:k().optional()}),ee=_.extend({..._.shape,...g.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),te=zo(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,lo(F({form:lo(F({applyDefaults:M().optional()}),t).optional(),url:t.optional()}),t.optional())),ne=I({list:t.optional(),cancel:t.optional(),requests:I({sampling:I({createMessage:t.optional()}).optional(),elicitation:I({create:t.optional()}).optional()}).optional()}),re=I({list:t.optional(),cancel:t.optional(),requests:I({tools:I({call:t.optional()}).optional()}).optional()}),ie=F({experimental:R(k(),t).optional(),sampling:F({context:t.optional(),tools:t.optional()}).optional(),elicitation:te.optional(),roots:F({listChanged:M().optional()}).optional(),tasks:ne.optional(),extensions:R(k(),t).optional()}),ae=F({experimental:R(k(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:F({listChanged:M().optional()}).optional(),resources:F({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:F({listChanged:M().optional()}).optional(),tasks:re.optional(),extensions:R(k(),t).optional()}),oe=F({progress:j(),total:V(j()),message:V(k())}),se=F({...p.shape,...oe.shape,progressToken:n}),ce=m.extend({method:B(`notifications/progress`),params:se}),le=p.extend({level:o,logger:k().optional(),data:N()}),v=m.extend({method:B(`notifications/message`),params:le}),ue=F({uri:k(),mimeType:V(k()),_meta:R(k(),N()).optional()}),de=ue.extend({text:k()}),fe=ue.extend({blob:s}),pe=F({audience:P(a).optional(),priority:j().min(0).max(1).optional(),lastModified:ta({offset:!0}).optional()}),me=F({..._.shape,...g.shape,uri:k(),description:V(k()),mimeType:V(k()),size:V(j()),annotations:pe.optional(),_meta:V(I({}))}),he=F({..._.shape,...g.shape,uriTemplate:k(),description:V(k()),mimeType:V(k()),annotations:pe.optional(),_meta:V(I({}))}),ge=m.extend({method:B(`notifications/resources/list_changed`),params:p.optional()}),_e=p.extend({uri:k()}),ve=m.extend({method:B(`notifications/resources/updated`),params:_e}),ye=F({name:k(),description:V(k()),required:V(M())}),be=F({..._.shape,...g.shape,description:V(k()),arguments:V(P(ye)),_meta:V(I({}))}),xe=m.extend({method:B(`notifications/prompts/list_changed`),params:p.optional()}),y=F({type:B(`text`),text:k(),annotations:pe.optional(),_meta:R(k(),N()).optional()}),b=F({type:B(`image`),data:s,mimeType:k(),annotations:pe.optional(),_meta:R(k(),N()).optional()}),Se=F({type:B(`audio`),data:s,mimeType:k(),annotations:pe.optional(),_meta:R(k(),N()).optional()}),Ce=F({type:B(`tool_use`),name:k(),id:k(),input:R(k(),N()),_meta:R(k(),N()).optional()}),we=F({type:B(`resource`),resource:L([de,fe]),annotations:pe.optional(),_meta:R(k(),N()).optional()}),Te=me.extend({type:B(`resource_link`)}),x=L([y,b,Se,Te,we]),Ee=F({role:a,content:x}),De=F({title:k().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),Oe=m.extend({method:B(`notifications/tools/list_changed`),params:p.optional()}),ke=F({name:k().optional()}),Ae=F({hints:P(ke).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),je=F({mode:z([`auto`,`required`,`none`]).optional()}),Me=F({type:B(`boolean`),title:k().optional(),description:k().optional(),default:M().optional()}),Ne=F({type:B(`string`),title:k().optional(),description:k().optional(),minLength:j().optional(),maxLength:j().optional(),format:z([`email`,`uri`,`date`,`date-time`]).optional(),default:k().optional()}),S=F({type:z([`number`,`integer`]),title:k().optional(),description:k().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),Pe=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),default:k().optional()}),Fe=F({type:B(`string`),title:k().optional(),description:k().optional(),oneOf:P(F({const:k(),title:k()})),default:k().optional()}),Ie=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),enumNames:P(k()).optional(),default:k().optional()}),Le=L([Pe,Fe]),Re=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({type:B(`string`),enum:P(k())}),default:P(k()).optional()}),ze=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({anyOf:P(F({const:k(),title:k()}))}),default:P(k()).optional()}),Be=L([Re,ze]),Ve=L([Ie,Le,Be]),He=L([Ve,Me,Ne,S]),Ue=f.extend({mode:B(`form`).optional(),message:k(),requestedSchema:F({type:B(`object`),properties:R(k(),He),required:P(k()).optional()}).catchall(N())}),We=F({type:B(`ref/resource`),uri:k()}),Ge=F({type:B(`ref/prompt`),name:k()}),Ke=F({uri:k().startsWith(`file://`),name:k().optional(),_meta:R(k(),N()).optional()}),qe=ie.shape,Je=F({experimental:qe.experimental,sampling:qe.sampling,elicitation:qe.elicitation,roots:qe.roots,extensions:qe.extensions}),Ye=ae.shape,Xe=F({experimental:Ye.experimental,logging:Ye.logging,completions:Ye.completions,prompts:Ye.prompts,resources:Ye.resources,tools:Ye.tools,extensions:Ye.extensions}),Ze=I({progressToken:n.optional(),[Wo]:k(),[Go]:ee.optional(),[qo]:Je,[Jo]:o.optional()}),Qe=F({..._.shape,...g.shape,description:k().optional(),inputSchema:I({$schema:k().optional(),type:B(`object`)}),outputSchema:I({$schema:k().optional()}).optional(),annotations:De.optional(),_meta:R(k(),N()).optional()}),$e=F({type:B(`tool_result`),toolUseId:k(),content:P(x),structuredContent:N().optional(),isError:M().optional(),_meta:R(k(),N()).optional()}),et=L([y,b,Se,Ce,$e]),tt=F({role:a,content:L([et,P(et)]),_meta:R(k(),N()).optional()}),nt=k(),rt=I({[Ko]:ee.optional().catch(void 0)}),it=rt.optional();function C(e){return I({_meta:it,resultType:nt.default(`complete`),...e})}let at=C({}),ot=C({nextCursor:r.optional()}),st=C({content:P(x),structuredContent:N().optional(),isError:M().optional()}),ct=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),tools:P(Qe),nextCursor:r.optional()}),lt=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),prompts:P(be),nextCursor:r.optional()}),ut=C({description:k().optional(),messages:P(Ee)}),dt=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),resources:P(me),nextCursor:r.optional()}),ft=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),resourceTemplates:P(he),nextCursor:r.optional()}),pt=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),contents:P(L([de,fe]))}),mt=C({completion:F({values:P(k()).max(100),total:j().int().optional(),hasMore:M().optional()}).loose()}),ht=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`])}),gt=C({ttlMs:j().int().min(0).catch(0),cacheScope:z([`public`,`private`]).catch(`private`),supportedVersions:P(k()),capabilities:Xe,instructions:k().optional()}),w=F({messages:P(tt),modelPreferences:Ae.optional(),systemPrompt:k().optional(),includeContext:z([`none`,`thisServer`,`allServers`]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:P(k()).optional(),metadata:t.optional(),tools:P(Qe).optional(),toolChoice:je.optional()}),_t=F({method:B(`sampling/createMessage`),params:w}),vt=F({method:B(`roots/list`),params:F({_meta:R(k(),N()).optional()}).optional()}),yt=F({...tt.shape,model:k(),stopReason:k().optional()}),bt=F({roots:P(Ke)}),xt=F({action:z([`accept`,`decline`,`cancel`]),content:R(k(),L([k(),j(),M(),P(k())])).optional()}),St=F({mode:B(`url`),message:k(),url:k().url()}),Ct=L([Ue,St]),wt=F({method:B(`elicitation/create`),params:Ct}),Tt=L([_t,vt,wt]),Et=L([yt,bt,xt]),Dt=R(k(),Tt),Ot=R(k(),Et),kt=C({inputRequests:Dt.optional(),requestState:k().optional()}),At={inputResponses:Ot.optional(),requestState:k().optional()},jt=F({_meta:Ze,...At}),Mt=I({progressToken:n.optional()});function Nt(e,t){return F({method:B(e),params:F({_meta:Ze,...t})})}function Pt(e,t){return F({method:B(e),params:F({_meta:Mt.optional(),...t}).optional()})}let T={name:k(),arguments:R(k(),N()).optional(),...At},Ft={cursor:r.optional()},E=Nt(`tools/call`,T),It=Nt(`tools/list`,Ft),Lt=Nt(`prompts/list`,Ft),Rt=Nt(`prompts/get`,{name:k(),arguments:R(k(),k()).optional(),...At}),zt=Nt(`resources/list`,Ft),Bt=Nt(`resources/templates/list`,Ft),Vt=Nt(`resources/read`,{uri:k(),...At}),Ht={ref:L([Ge,We]),argument:F({name:k(),value:k()}),context:F({arguments:R(k(),k()).optional()}).optional()},Ut=Nt(`completion/complete`,Ht),Wt=Nt(`server/discover`,{}),Gt=F({toolsListChanged:M().optional(),promptsListChanged:M().optional(),resourcesListChanged:M().optional(),resourceSubscriptions:P(k()).optional()}),Kt={notifications:Gt},qt=Nt(`subscriptions/listen`,Kt),Jt=rt.extend({"io.modelcontextprotocol/subscriptionId":i}),Yt=I({_meta:Jt,resultType:nt.default(`complete`)}),Xt={"tools/call":Pt(`tools/call`,T),"tools/list":Pt(`tools/list`,Ft),"prompts/get":Pt(`prompts/get`,{name:k(),arguments:R(k(),k()).optional()}),"prompts/list":Pt(`prompts/list`,Ft),"resources/list":Pt(`resources/list`,Ft),"resources/templates/list":Pt(`resources/templates/list`,Ft),"resources/read":Pt(`resources/read`,{uri:k()}),"completion/complete":Pt(`completion/complete`,Ht),"server/discover":Pt(`server/discover`,{}),"subscriptions/listen":Pt(`subscriptions/listen`,Kt)};function Zt(e){return I({_meta:it,...e})}let Qt={"tools/call":Zt({content:P(x),structuredContent:N().optional(),isError:M().optional()}),"tools/list":Zt({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),tools:P(Qe),nextCursor:r.optional()}),"prompts/get":Zt({description:k().optional(),messages:P(Ee)}),"prompts/list":Zt({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),prompts:P(be),nextCursor:r.optional()}),"resources/list":Zt({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),resources:P(me),nextCursor:r.optional()}),"resources/templates/list":Zt({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),resourceTemplates:P(he),nextCursor:r.optional()}),"resources/read":Zt({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),contents:P(L([de,fe]))}),"completion/complete":Zt({completion:F({values:P(k()).max(100),total:j().int().optional(),hasMore:M().optional()}).loose()}),"server/discover":Zt({ttlMs:j().int().min(0).catch(0),cacheScope:z([`public`,`private`]).catch(`private`),supportedVersions:P(k()),capabilities:Xe,instructions:k().optional()}),"subscriptions/listen":Zt({})},$t=I({"io.modelcontextprotocol/subscriptionId":i.optional()}),en=F({method:B(`notifications/subscriptions/acknowledged`),params:F({_meta:$t.optional(),notifications:Gt})}),tn=F({_meta:$t.optional(),requestId:i,reason:k().optional()}),nn=F({method:B(`notifications/cancelled`),params:tn}),rn={"notifications/cancelled":nn,"notifications/progress":ce,"notifications/message":v,"notifications/resources/updated":ve,"notifications/resources/list_changed":ge,"notifications/tools/list_changed":Oe,"notifications/prompts/list_changed":xe,"notifications/subscriptions/acknowledged":en},an=e=>F({jsonrpc:B(`2.0`),id:L([k(),j().int()]),result:e}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,RequestIdSchema:i,RoleSchema:a,LoggingLevelSchema:o,TaskMetadataSchema:c,RelatedTaskMetadataSchema:l,RequestMetaSchema:u,BaseRequestParamsSchema:d,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:p,NotificationSchema:m,IconSchema:h,IconsSchema:g,BaseMetadataSchema:_,ImplementationSchema:ee,ClientTasksCapabilitySchema:ne,ServerTasksCapabilitySchema:re,ClientCapabilitiesSchema:ie,ServerCapabilitiesSchema:ae,ProgressSchema:oe,ProgressNotificationParamsSchema:se,ProgressNotificationSchema:ce,LoggingMessageNotificationParamsSchema:le,LoggingMessageNotificationSchema:v,ResourceContentsSchema:ue,TextResourceContentsSchema:de,BlobResourceContentsSchema:fe,AnnotationsSchema:pe,ResourceSchema:me,ResourceTemplateSchema:he,ResourceListChangedNotificationSchema:ge,ResourceUpdatedNotificationParamsSchema:_e,ResourceUpdatedNotificationSchema:ve,PromptArgumentSchema:ye,PromptSchema:be,PromptListChangedNotificationSchema:xe,TextContentSchema:y,ImageContentSchema:b,AudioContentSchema:Se,ToolUseContentSchema:Ce,EmbeddedResourceSchema:we,ResourceLinkSchema:Te,ContentBlockSchema:x,PromptMessageSchema:Ee,ToolAnnotationsSchema:De,ToolListChangedNotificationSchema:Oe,ModelHintSchema:ke,ModelPreferencesSchema:Ae,ToolChoiceSchema:je,BooleanSchemaSchema:Me,StringSchemaSchema:Ne,NumberSchemaSchema:S,UntitledSingleSelectEnumSchemaSchema:Pe,TitledSingleSelectEnumSchemaSchema:Fe,LegacyTitledEnumSchemaSchema:Ie,SingleSelectEnumSchemaSchema:Le,UntitledMultiSelectEnumSchemaSchema:Re,TitledMultiSelectEnumSchemaSchema:ze,MultiSelectEnumSchemaSchema:Be,EnumSchemaSchema:Ve,PrimitiveSchemaDefinitionSchema:He,ElicitRequestFormParamsSchema:Ue,ResourceTemplateReferenceSchema:We,PromptReferenceSchema:Ge,RootSchema:Ke,ClientCapabilities2026Schema:Je,ServerCapabilities2026Schema:Xe,RequestMetaEnvelopeSchema:Ze,ToolSchema:Qe,ToolResultContentSchema:$e,SamplingMessageContentBlockSchema:et,SamplingMessageSchema:tt,ResultTypeSchema:nt,ResultMetaSchema:rt,ResultSchema:at,PaginatedResultSchema:ot,CallToolResultSchema:st,ListToolsResultSchema:ct,ListPromptsResultSchema:lt,GetPromptResultSchema:ut,ListResourcesResultSchema:dt,ListResourceTemplatesResultSchema:ft,ReadResourceResultSchema:pt,CompleteResultSchema:mt,CacheableResultSchema:ht,DiscoverResultSchema:gt,CreateMessageRequestParamsSchema:w,CreateMessageRequestSchema:_t,ListRootsRequestSchema:vt,CreateMessageResultSchema:yt,ListRootsResultSchema:bt,ElicitResultSchema:xt,ElicitRequestURLParamsSchema:St,ElicitRequestParamsSchema:Ct,ElicitRequestSchema:wt,InputRequestSchema:Tt,InputResponseSchema:Et,InputRequestsSchema:Dt,InputResponsesSchema:Ot,InputRequiredResultSchema:kt,InputResponseRequestParamsSchema:jt,CallToolRequestSchema:E,ListToolsRequestSchema:It,ListPromptsRequestSchema:Lt,GetPromptRequestSchema:Rt,ListResourcesRequestSchema:zt,ListResourceTemplatesRequestSchema:Bt,ReadResourceRequestSchema:Vt,CompleteRequestSchema:Ut,DiscoverRequestSchema:Wt,SubscriptionFilterSchema:Gt,SubscriptionsListenRequestSchema:qt,SubscriptionsListenResultMetaSchema:Jt,SubscriptionsListenResultSchema:Yt,dispatchRequestSchemas:Xt,dispatchResultSchemas:Qt,NotificationMetaSchema:$t,SubscriptionsAcknowledgedNotificationSchema:en,CancelledNotificationParamsSchema:tn,CancelledNotificationSchema:nn,notificationSchemas2026:rn,JSONRPCResultResponseSchema:an(at),CallToolResultResponseSchema:an(L([st,kt])),ListToolsResultResponseSchema:an(ct),ListPromptsResultResponseSchema:an(lt),GetPromptResultResponseSchema:an(L([ut,kt])),ListResourcesResultResponseSchema:an(dt),ListResourceTemplatesResultResponseSchema:an(ft),ReadResourceResultResponseSchema:an(L([pt,kt])),CompleteResultResponseSchema:an(mt),DiscoverResultResponseSchema:an(gt)}}let dp;function fp(){return dp??=up()}let pp=[`tools/list`,`prompts/list`,`resources/list`,`resources/templates/list`,`resources/read`,`server/discover`];function mp(e){return pp.includes(e)}let hp=Symbol(`modelcontextprotocol.resultCacheHintFallback`);function gp(e,t){if(t===void 0)return e;let n=e[hp];if(n===void 0)return{...e,[hp]:t};let r={},i=n.ttlMs??t.ttlMs;i!==void 0&&(r.ttlMs=i);let a=n.cacheScope??t.cacheScope;return a!==void 0&&(r.cacheScope=a),{...e,[hp]:r}}function _p(e){return e[hp]}function vp(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function yp(e){return e===`public`||e===`private`}function bp(e,t){if(e.ttlMs!==void 0&&!vp(e.ttlMs))throw RangeError(`Invalid cache hint for ${t}: ttlMs must be a non-negative safe integer (got ${String(e.ttlMs)})`);if(e.cacheScope!==void 0&&!yp(e.cacheScope))throw RangeError(`Invalid cache hint for ${t}: cacheScope must be 'public' or 'private' (got ${String(e.cacheScope)})`)}let Z=function(e){return e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.ResourceNotFound=-32002]=`ResourceNotFound`,e[e.MissingRequiredClientCapability=-32021]=`MissingRequiredClientCapability`,e[e.UnsupportedProtocolVersion=-32022]=`UnsupportedProtocolVersion`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`,e}({});var Q=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.ProtocolError`})}static[Symbol.hasInstance](e){return Of(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Of(this,e)}constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`ProtocolError`,Df(this,new.target)}static fromError(t,n,r){if(t===Z.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Sp(e.elicitations,n)}if(t===Z.UnsupportedProtocolVersion&&r){let e=r;if(Array.isArray(e.supported)&&typeof e.requested==`string`)return new Cp({supported:e.supported,requested:e.requested},n)}if(t===Z.InvalidParams||t===Z.ResourceNotFound){let e=r;if(typeof e?.uri==`string`&&(t===Z.ResourceNotFound||Object.keys(e).length===1))return new xp(e.uri,n)}if(t===Z.MissingRequiredClientCapability&&r){let e=r;if(e.requiredCapabilities!==null&&typeof e.requiredCapabilities==`object`&&!Array.isArray(e.requiredCapabilities))return new wp({requiredCapabilities:e.requiredCapabilities},n)}return new e(t,n,r)}},xp=class extends Q{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.ResourceNotFoundError`})}constructor(e,t=`Resource not found: ${e}`){super(Z.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Sp=class extends Q{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UrlElicitationRequiredError`})}constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(Z.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Cp=class extends Q{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UnsupportedProtocolVersionError`})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(Z.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},wp=class extends Q{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.MissingRequiredClientCapabilityError`})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(`, `)}`){super(Z.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}};let Tp=[`tools/call`,`prompts/get`,`resources/read`];function Ep(e,t){let n=t.resultType;if(n===void 0)return{...t,resultType:`complete`};if(n===`complete`||Tp.includes(e))return t;throw new Q(Z.InternalError,`Handler for ${e} returned resultType '${String(n)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function Dp(e,t){let n=_p(t);if(t.resultType!==`complete`||!mp(e))return n===void 0?t:Mp(t);let r=t,i=vp(r.ttlMs)?r.ttlMs:Ap(n),a=yp(r.cacheScope)?r.cacheScope:jp(n),o={...r,ttlMs:i,cacheScope:a};return delete o[hp],o}function Op(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kp(e,t){if(t===void 0)return e;let n=e._meta;return n===void 0?{...e,_meta:{[Ko]:t}}:!Op(n)||n[`io.modelcontextprotocol/serverInfo`]!==void 0?e:{...e,_meta:{...n,[Ko]:t}}}function Ap(e){return e!==void 0&&vp(e.ttlMs)?e.ttlMs:0}function jp(e){return e!==void 0&&yp(e.cacheScope)?e.cacheScope:`private`}function Mp(e){let t={...e};return delete t[hp],t}let Np=[`elicitation/create`,`sampling/createMessage`,`roots/list`],Pp;function Fp(){if(Pp)return Pp;let e=fp();return Pp={request:{"elicitation/create":F({method:B(`elicitation/create`),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":F({method:B(`sampling/createMessage`),params:e.CreateMessageRequestParamsSchema}),"roots/list":F({method:B(`roots/list`),params:I({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Pp}function Ip(e){return Np.includes(e)}function Lp(e){return Ip(e)?Fp().request[e]:void 0}function Rp(e){return Ip(e)?Fp().response[e]:void 0}let zp={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},Bp={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function Vp(e){return Object.prototype.hasOwnProperty.call(zp,e)}function Hp(e){return Object.prototype.hasOwnProperty.call(Bp,e)}function Up(e){return Object.prototype.hasOwnProperty.call(zp,e)}function Wp(e){return Vp(e)?fp().dispatchRequestSchemas[e]:void 0}function Gp(e){return Up(e)?fp().dispatchResultSchemas[e]:void 0}function Kp(e){return Hp(e)?fp().notificationSchemas2026[e]:void 0}function qp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jp(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}let Yp={ok:!1,reason:`not-in-era`},Xp=[Wo,qo];function Zp(e,t){let n=t,r=!1,i=()=>(r||=(n={...n},!0),n),a=t.tools;e===`tools/list`&&Array.isArray(a)&&a.some(e=>qp(e)&&`execution`in e)&&(i().tools=a.map(e=>{if(!qp(e)||!(`execution`in e))return e;let t={...e};return delete t.execution,t}));let o=t.capabilities;if(qp(o)&&`tasks`in o){let e={...o};delete e.tasks,i().capabilities=e}return n}let Qp={era:`2026-07-28`,hasRequestMethod:Vp,hasNotificationMethod:Hp,hasInputRequestMethod:e=>Lp(e)!==void 0,validateRequest:(e,t)=>Jp(Wp(e),t),validateResult:(e,t)=>Jp(Gp(e),t),validateNotification:(e,t)=>Jp(Kp(e),t),validateInputRequest:(e,t)=>Jp(Lp(e),t),validateInputResponse:(e,t)=>Jp(Rp(e),t),samplingResultVariant:()=>Yp,outboundEnvelope(e){return{[Wo]:e.protocolVersion,[Go]:e.clientInfo,[qo]:e.clientCapabilities,...e.logLevel!==void 0&&{"io.modelcontextprotocol/logLevel":e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of Xp)n in e||t.push({key:n,problem:`missing`});let n=fp().RequestMetaEnvelopeSchema.safeParse(e);if(!n.success)for(let e of n.error.issues){let n=e.path.map(String),r=n.length>0?n.join(`.`):`_meta`;n.length===1&&t.some(e=>e.key===r&&e.problem===`missing`)||t.push({key:r,problem:e.message})}return t},projectCallToolResult:e=>If(e),inputRequestSchema:Lp,decodeResult(e,t){if(!qp(t))return{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let n=t.resultType;if(n===void 0)return{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:`missing-resultType`})};if(typeof n!=`string`)return{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:n})};if(n===`input_required`){let n=t.inputRequests,r=qp(n)?n:{},i=t.requestState;return Object.keys(r).length===0&&typeof i!=`string`?{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:`input-required-missing-both`})}:{kind:`input_required`,inputRequests:r,...typeof i==`string`&&{requestState:i}}}if(n!==`complete`)return{kind:`invalid`,error:new X(Y.UnsupportedResultType,`Unsupported result type '${n}' for ${e}`,{resultType:n,method:e})};let r=em(),i=Object.hasOwn(r,e)?r[e]:void 0;if(i!==void 0){let n=i.safeParse(t);if(!n.success)return{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: ${n.error}`,{method:e})}}let a={...t};return delete a.resultType,{kind:`complete`,result:a}},encodeResult(e,t,n){return kp(Dp(e,Ep(e,Zp(e,t))),n)},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return`Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)`;let t=fp().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(e=>e.message).join(`; `)}`}},$p;function em(){if($p)return $p;let e=fp();return $p={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},$p}function tm(e){return e!==void 0&&Nf(e)?Qp:lp}function nm(e){return e.revision===void 0?e.era===`modern`?Qp.era:lp.era:tm(e.revision).era}function rm(e){return am.some(t=>t.hasRequestMethod(e))}function im(e){return am.some(t=>t.hasNotificationMethod(e))}let am=[lp,Qp];var om=yf({AnnotationsSchema:()=>Us,AudioContentSchema:()=>Sc,BaseMetadataSchema:()=>vs,BaseRequestParamsSchema:()=>U,BlobResourceContentsSchema:()=>Vs,BooleanSchemaSchema:()=>rl,CallToolRequestParamsSchema:()=>Lc,CallToolRequestSchema:()=>Rc,CallToolResultSchema:()=>Fc,CancelTaskRequestSchema:()=>Ul,CancelTaskResultSchema:()=>Wl,CancelledNotificationParamsSchema:()=>ms,CancelledNotificationSchema:()=>hs,ClientCapabilitiesSchema:()=>Cs,ClientNotificationSchema:()=>Kl,ClientRequestSchema:()=>Gl,ClientResultSchema:()=>ql,ClientTasksCapabilitySchema:()=>xs,CompatibilityCallToolResultSchema:()=>Ic,CompleteRequestParamsSchema:()=>wl,CompleteRequestSchema:()=>Tl,CompleteResultSchema:()=>El,ContentBlockSchema:()=>Ec,CreateMessageRequestParamsSchema:()=>$c,CreateMessageRequestSchema:()=>el,CreateMessageResultSchema:()=>tl,CreateMessageResultWithToolsSchema:()=>nl,CreateTaskResultSchema:()=>Pl,CursorSchema:()=>Qo,DiscoverRequestSchema:()=>ks,DiscoverResultSchema:()=>As,ElicitRequestFormParamsSchema:()=>hl,ElicitRequestParamsSchema:()=>_l,ElicitRequestSchema:()=>vl,ElicitRequestURLParamsSchema:()=>gl,ElicitResultSchema:()=>xl,ElicitationCompleteNotificationParamsSchema:()=>yl,ElicitationCompleteNotificationSchema:()=>bl,EmbeddedResourceSchema:()=>wc,EmptyResultSchema:()=>ps,EnumSchemaSchema:()=>pl,GetPromptRequestParamsSchema:()=>vc,GetPromptRequestSchema:()=>yc,GetPromptResultSchema:()=>Oc,GetTaskPayloadRequestSchema:()=>zl,GetTaskPayloadResultSchema:()=>Bl,GetTaskRequestSchema:()=>Ll,GetTaskResultSchema:()=>Rl,IconSchema:()=>gs,IconsSchema:()=>_s,ImageContentSchema:()=>xc,ImplementationSchema:()=>ys,InitializeRequestParamsSchema:()=>ws,InitializeRequestSchema:()=>Ts,InitializeResultSchema:()=>Ds,InitializedNotificationSchema:()=>Os,JSONArraySchema:()=>Xo,JSONObjectSchema:()=>H,JSONRPCErrorResponseSchema:()=>us,JSONRPCMessageSchema:()=>ds,JSONRPCNotificationSchema:()=>cs,JSONRPCRequestSchema:()=>ss,JSONRPCResponseSchema:()=>fs,JSONRPCResultResponseSchema:()=>ls,JSONValueSchema:()=>Yo,LegacyTitledEnumSchemaSchema:()=>cl,ListChangedOptionsBaseSchema:()=>Bc,ListPromptsRequestSchema:()=>gc,ListPromptsResultSchema:()=>_c,ListResourceTemplatesRequestSchema:()=>Js,ListResourceTemplatesResultSchema:()=>Ys,ListResourcesRequestSchema:()=>Ks,ListResourcesResultSchema:()=>qs,ListRootsRequestSchema:()=>Ol,ListRootsResultSchema:()=>kl,ListTasksRequestSchema:()=>Vl,ListTasksResultSchema:()=>Hl,ListToolsRequestSchema:()=>Nc,ListToolsResultSchema:()=>Pc,LoggingLevelSchema:()=>Vc,LoggingMessageNotificationParamsSchema:()=>Wc,LoggingMessageNotificationSchema:()=>Gc,ModelHintSchema:()=>Kc,ModelPreferencesSchema:()=>qc,MultiSelectEnumSchemaSchema:()=>fl,NotificationSchema:()=>is,NotificationsParamsSchema:()=>rs,NumberSchemaSchema:()=>al,PaginatedRequestParamsSchema:()=>Fs,PaginatedRequestSchema:()=>Is,PaginatedResultSchema:()=>Ls,PingRequestSchema:()=>js,PrimitiveSchemaDefinitionSchema:()=>ml,ProgressNotificationParamsSchema:()=>Ns,ProgressNotificationSchema:()=>Ps,ProgressSchema:()=>Ms,ProgressTokenSchema:()=>Zo,PromptArgumentSchema:()=>mc,PromptListChangedNotificationSchema:()=>kc,PromptMessageSchema:()=>Dc,PromptReferenceSchema:()=>Cl,PromptSchema:()=>hc,ReadResourceRequestParamsSchema:()=>Zs,ReadResourceRequestSchema:()=>Qs,ReadResourceResultSchema:()=>$s,RelatedTaskMetadataSchema:()=>es,RequestIdSchema:()=>os,RequestMetaSchema:()=>ts,RequestSchema:()=>W,ResourceContentsSchema:()=>Rs,ResourceLinkSchema:()=>Tc,ResourceListChangedNotificationSchema:()=>ec,ResourceRequestParamsSchema:()=>Xs,ResourceSchema:()=>Ws,ResourceTemplateReferenceSchema:()=>Sl,ResourceTemplateSchema:()=>Gs,ResourceUpdatedNotificationParamsSchema:()=>fc,ResourceUpdatedNotificationSchema:()=>pc,ResultMetaObjectSchema:()=>as,ResultSchema:()=>G,RoleSchema:()=>Hs,RootSchema:()=>Dl,RootsListChangedNotificationSchema:()=>Al,SamplingContentSchema:()=>Xc,SamplingMessageContentBlockSchema:()=>Zc,SamplingMessageSchema:()=>Qc,ServerCapabilitiesSchema:()=>Es,ServerNotificationSchema:()=>Yl,ServerRequestSchema:()=>Jl,ServerResultSchema:()=>Xl,ServerTasksCapabilitySchema:()=>Ss,SetLevelRequestParamsSchema:()=>Hc,SetLevelRequestSchema:()=>Uc,SingleSelectEnumSchemaSchema:()=>ll,StringSchemaSchema:()=>il,SubscribeRequestParamsSchema:()=>tc,SubscribeRequestSchema:()=>nc,SubscriptionFilterSchema:()=>ac,SubscriptionsAcknowledgedNotificationParamsSchema:()=>cc,SubscriptionsAcknowledgedNotificationSchema:()=>lc,SubscriptionsListenRequestParamsSchema:()=>oc,SubscriptionsListenRequestSchema:()=>sc,SubscriptionsListenResultMetaSchema:()=>uc,SubscriptionsListenResultSchema:()=>dc,TaskAugmentedRequestParamsSchema:()=>ns,TaskCreationParamsSchema:()=>jl,TaskMetadataSchema:()=>$o,TaskSchema:()=>Nl,TaskStatusNotificationParamsSchema:()=>Fl,TaskStatusNotificationSchema:()=>Il,TaskStatusSchema:()=>Ml,TextContentSchema:()=>bc,TextResourceContentsSchema:()=>zs,TitledMultiSelectEnumSchemaSchema:()=>dl,TitledSingleSelectEnumSchemaSchema:()=>sl,ToolAnnotationsSchema:()=>Ac,ToolChoiceSchema:()=>Jc,ToolExecutionSchema:()=>jc,ToolListChangedNotificationSchema:()=>zc,ToolResultContentSchema:()=>Yc,ToolSchema:()=>Mc,ToolUseContentSchema:()=>Cc,UnsubscribeRequestParamsSchema:()=>rc,UnsubscribeRequestSchema:()=>ic,UntitledMultiSelectEnumSchemaSchema:()=>ul,UntitledSingleSelectEnumSchemaSchema:()=>ol});let sm=e=>ss.safeParse(e).success,cm=e=>cs.safeParse(e).success,lm=e=>ls.safeParse(e).success,um=e=>us.safeParse(e).success,dm=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&e.resultType===`input_required`;function fm(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function pm(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}let mm=`x-mcp-header`,hm=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,gm=new Set([`string`,`integer`,`boolean`,`number`]);function _m(e){let t=[],n=new Map,r=(e,i,a)=>{if(typeof e!=`object`||!e)return;let o=e;if(mm in o){if(!a||i.length===0)return`${bm(i)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let e=o[mm];if(typeof e!=`string`||e.length===0)return`${bm(i)}: x-mcp-header MUST be a non-empty string`;if(!hm.test(e))return`${bm(i)}: x-mcp-header '${e}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let r=typeof o.type==`string`?o.type:void 0;if(r===void 0||!gm.has(r))return`${bm(i)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${r??`<none>`}`;let s=e.toLowerCase(),c=n.get(s);if(c!==void 0)return`x-mcp-header '${e}' is not case-insensitively unique (also declared as '${c}')`;n.set(s,e),t.push({path:i,headerName:e,type:r})}let s=o.properties;if(typeof s==`object`&&s)for(let[e,t]of Object.entries(s)){let n=r(t,[...i,e],a);if(n!==void 0)return n}for(let e of vm){let t=o[e];if(t===void 0)continue;let n=Array.isArray(t)?t:typeof t==`object`&&t&&ym.has(e)?Object.values(t):[t];for(let t of n){let n=r(t,[...i,`<${e}>`],!1);if(n!==void 0)return n}}},i=r(e,[],!0);return i===void 0?{valid:!0,declarations:t}:{valid:!1,reason:i}}let vm=[`items`,`prefixItems`,`contains`,`additionalProperties`,`unevaluatedProperties`,`unevaluatedItems`,`propertyNames`,`patternProperties`,`dependentSchemas`,`oneOf`,`anyOf`,`allOf`,`not`,`if`,`then`,`else`,`$defs`,`definitions`],ym=new Set([`patternProperties`,`dependentSchemas`,`$defs`,`definitions`]);function bm(e){return e.length===0?`<root>`:e.join(`.`)}Z.InvalidRequest,Z.UnsupportedProtocolVersion,Z.InvalidParams,Z.MethodNotFound,Z.InvalidParams,Z.MissingRequiredClientCapability,Z.ParseError,Z.InvalidRequest,Z.MethodNotFound,Z.UnsupportedProtocolVersion,Z.MissingRequiredClientCapability;function xm(e,t){return da(e,t)}function Sm(e){return new Set(e.flatMap(e=>Object.keys(e.shape)))}function Cm(e){if(e==null)return!1;let t=typeof e;return t!==`object`&&t!==`function`||!(`~standard`in e)?!1:typeof e[`~standard`]?.validate==`function`}let wm=!1,Tm=`draft-2020-12`;function Em(e,t=`input`){let n=e[`~standard`],r;if(n.jsonSchema)r=n.jsonSchema[t]({target:Tm});else if(n.vendor===`zod`){if(!(`_zod`in e))throw Error(`Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().`);wm||(wm=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),r=$i(e,{target:Tm,io:t})}else throw Error(`Schema library "${n.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t===`output`)return r.type===void 0&&Dm(r)?{type:`object`,...r}:r;if(r.type!==void 0&&r.type!==`object`)throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(r.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:`object`,...r}}function Dm(e){if(`properties`in e||`patternProperties`in e||`additionalProperties`in e||`required`in e)return!0;for(let t of[`oneOf`,`anyOf`,`allOf`]){let n=e[t];if(Array.isArray(n)&&n.length>0)return n.every(e=>typeof e==`object`&&!!e&&(e.type===`object`||Dm(e)))}return!1}function Om(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function km(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>Om(e)).join(`, `)}:{success:!0,data:n.value}}function Am(e){let t=$i(e,{target:Tm,io:`input`});return typeof t.pattern==`string`?t.pattern:void 0}let jm=/\\\.\\d\{(\d+)\}/;function Mm(e){let t=jm.exec(e),n=[void 0,-1,0];return t&&n.push(Number(t[1])),[!1,!0].flatMap(e=>[!1,!0].flatMap(t=>n.map(n=>ta({local:e,offset:t,precision:n}))))}function Nm(e,t){let n;switch(e){case`email`:n=[Ea()];break;case`uri`:n=[Aa()];break;case`date`:n=[ra()];break;case`date-time`:n=Mm(t);break}return new Set(n.map(e=>Am(e)).filter(e=>e!==void 0))}function Pm(e,t,n){return n===`zod`?Nm(e,t).has(t):!0}function Fm(e){let t=Em(e,`input`),n=t.properties||{},r=t.required||[];return Object.entries(n).map(([e,t])=>({name:e,description:t?.description,required:r.includes(e)}))}function Im(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Lm(e){try{return Em(e,`input`)}catch(e){let t=e instanceof Error?e.message:String(e);throw new Q(Z.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${t}`)}}let Rm=new Set([`$comment`,`deprecated`,`description`,`examples`,`readOnly`,`title`,`writeOnly`]);function zm(e){return Rm.has(e)||e.startsWith(`x-`)}let Bm=new Set([`$schema`,...Object.keys(hl.shape.requestedSchema.shape)]),Vm={string:Sm([il,ol,sl,cl]),number:Sm([al]),integer:Sm([al]),boolean:Sm([rl]),array:Sm([ul,dl])},Hm=new Set(il.shape.format.unwrap().options);function Um(e,t,n,r){if(!Im(e))return e;let i=typeof e.type==`string`&&Object.hasOwn(Vm,e.type)?Vm[e.type]:void 0;if(i===void 0)return e;let a={};for(let[o,s]of Object.entries(e))i.has(o)||zm(o)?a[o]=s:o===`pattern`&&e.type===`string`&&typeof e.format==`string`?Hm.has(e.format)?(typeof s!=`string`||!Pm(e.format,s,n))&&r.push(`${t}.${o}`):a[o]=s:r.push(`${t}.${o}`);return a}function Wm(e,t){let n={},r=[];for(let[i,a]of Object.entries(e))i===`properties`&&Im(a)?n[i]=Object.fromEntries(Object.entries(a).map(([e,n])=>[e,Um(n,`properties.${e}`,t,r)])):Bm.has(i)?n[i]=a:zm(i)||r.push(i);if(r.length>0)throw new Q(Z.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${r.join(`, `)}`);return n}function Gm(e,t){if(!Im(e.properties))return t;let n=Object.entries(e.properties).filter(([,e])=>!xm(ml,e).success).map(([e])=>`properties.${e}`);return n.length>0?n.join(`, `):t}function Km(e,t,n=``){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((e,r)=>Km(e,t[r],`${n}[${r}]`)):!Im(e)||!Im(t)?[]:Object.entries(e).flatMap(([e,r])=>{let i=n?`${n}.${e}`:e;return Object.prototype.hasOwnProperty.call(t,e)?Km(r,t[e],i):zm(e)?[]:[i]})}function qm(e){if(!Cm(e.requestedSchema))return{...e,mode:`form`,requestedSchema:e.requestedSchema};let t=e.requestedSchema[`~standard`].vendor,n=Wm(Lm(e.requestedSchema),t),r=xm(hl.shape.requestedSchema,n);if(!r.success)throw new Q(Z.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${Gm(n,r.error.message)}`);let i=Km(n,r.data);if(i.length>0)throw new Q(Z.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${i.join(`, `)}`);let a=(r.data.required??[]).filter(e=>!Object.prototype.hasOwnProperty.call(r.data.properties,e));if(a.length>0)throw new Q(Z.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${a.join(`, `)}`);return{...e,mode:`form`,requestedSchema:r.data}}function Jm(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,n=typeof e.requestState==`string`;if(!t&&!n)throw TypeError(`inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)`);return{resultType:`input_required`,...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}Object.assign(Jm,{elicit(e){try{return{method:`elicitation/create`,params:qm(e)}}catch(e){throw e instanceof Q?TypeError(e.message,{cause:e}):e}},elicitUrl(e){return{method:`elicitation/create`,params:{...e,mode:`url`}}},createMessage(e){return{method:`sampling/createMessage`,params:e}},listRoots(){return{method:`roots/list`}}});function Ym(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function Xm(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason instanceof X?t.reason:new X(Y.RequestTimeout,String(t.reason)));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(t?.reason instanceof X?t.reason:new X(Y.RequestTimeout,String(t?.reason)))};t?.addEventListener(`abort`,a,{once:!0})})}function Zm(e){let t=new AbortController,n=()=>t.abort(e?.reason);return e?.addEventListener(`abort`,n,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:e=>t.abort(e),dispose:()=>e?.removeEventListener(`abort`,n)}}let Qm=`AnnotationsSchema.AudioContentSchema.BaseMetadataSchema.BlobResourceContentsSchema.BooleanSchemaSchema.CallToolRequestSchema.CallToolRequestParamsSchema.CallToolResultSchema.CancelledNotificationSchema.CancelledNotificationParamsSchema.CancelTaskRequestSchema.CancelTaskResultSchema.ClientCapabilitiesSchema.ClientNotificationSchema.ClientRequestSchema.ClientResultSchema.CompatibilityCallToolResultSchema.CompleteRequestSchema.CompleteRequestParamsSchema.CompleteResultSchema.ContentBlockSchema.CreateMessageRequestSchema.CreateMessageRequestParamsSchema.CreateMessageResultSchema.CreateMessageResultWithToolsSchema.CreateTaskResultSchema.CursorSchema.DiscoverRequestSchema.DiscoverResultSchema.ElicitationCompleteNotificationSchema.ElicitationCompleteNotificationParamsSchema.ElicitRequestSchema.ElicitRequestFormParamsSchema.ElicitRequestParamsSchema.ElicitRequestURLParamsSchema.ElicitResultSchema.EmbeddedResourceSchema.EmptyResultSchema.EnumSchemaSchema.GetPromptRequestSchema.GetPromptRequestParamsSchema.GetPromptResultSchema.GetTaskPayloadRequestSchema.GetTaskPayloadResultSchema.GetTaskRequestSchema.GetTaskResultSchema.IconSchema.IconsSchema.ImageContentSchema.ImplementationSchema.InitializedNotificationSchema.InitializeRequestSchema.InitializeRequestParamsSchema.InitializeResultSchema.JSONArraySchema.JSONObjectSchema.JSONRPCErrorResponseSchema.JSONRPCMessageSchema.JSONRPCNotificationSchema.JSONRPCRequestSchema.JSONRPCResponseSchema.JSONRPCResultResponseSchema.JSONValueSchema.LegacyTitledEnumSchemaSchema.ListPromptsRequestSchema.ListPromptsResultSchema.ListResourcesRequestSchema.ListResourcesResultSchema.ListResourceTemplatesRequestSchema.ListResourceTemplatesResultSchema.ListRootsRequestSchema.ListRootsResultSchema.ListTasksRequestSchema.ListTasksResultSchema.ListToolsRequestSchema.ListToolsResultSchema.LoggingLevelSchema.LoggingMessageNotificationSchema.LoggingMessageNotificationParamsSchema.ModelHintSchema.ModelPreferencesSchema.MultiSelectEnumSchemaSchema.NotificationSchema.NumberSchemaSchema.PaginatedRequestSchema.PaginatedRequestParamsSchema.PaginatedResultSchema.PingRequestSchema.PrimitiveSchemaDefinitionSchema.ProgressSchema.ProgressNotificationSchema.ProgressNotificationParamsSchema.ProgressTokenSchema.PromptSchema.PromptArgumentSchema.PromptListChangedNotificationSchema.PromptMessageSchema.PromptReferenceSchema.ReadResourceRequestSchema.ReadResourceRequestParamsSchema.ReadResourceResultSchema.RelatedTaskMetadataSchema.RequestSchema.RequestIdSchema.RequestMetaSchema.ResourceSchema.ResourceContentsSchema.ResourceLinkSchema.ResourceListChangedNotificationSchema.ResourceRequestParamsSchema.ResourceTemplateSchema.ResourceTemplateReferenceSchema.ResourceUpdatedNotificationSchema.ResourceUpdatedNotificationParamsSchema.ResultMetaObjectSchema.ResultSchema.RoleSchema.RootSchema.RootsListChangedNotificationSchema.SamplingContentSchema.SamplingMessageSchema.SamplingMessageContentBlockSchema.ServerCapabilitiesSchema.ServerNotificationSchema.ServerRequestSchema.ServerResultSchema.SetLevelRequestSchema.SetLevelRequestParamsSchema.SingleSelectEnumSchemaSchema.StringSchemaSchema.SubscribeRequestSchema.SubscribeRequestParamsSchema.SubscriptionFilterSchema.SubscriptionsAcknowledgedNotificationSchema.SubscriptionsAcknowledgedNotificationParamsSchema.SubscriptionsListenRequestSchema.SubscriptionsListenRequestParamsSchema.SubscriptionsListenResultSchema.SubscriptionsListenResultMetaSchema.TaskAugmentedRequestParamsSchema.TaskCreationParamsSchema.TaskMetadataSchema.TaskSchema.TaskStatusSchema.TaskStatusNotificationSchema.TaskStatusNotificationParamsSchema.TextContentSchema.TextResourceContentsSchema.TitledMultiSelectEnumSchemaSchema.TitledSingleSelectEnumSchemaSchema.ToolSchema.ToolAnnotationsSchema.ToolChoiceSchema.ToolExecutionSchema.ToolListChangedNotificationSchema.ToolResultContentSchema.ToolUseContentSchema.UnsubscribeRequestSchema.UnsubscribeRequestParamsSchema.UntitledMultiSelectEnumSchemaSchema.UntitledSingleSelectEnumSchemaSchema`.split(`.`),$m={IdJagTokenExchangeResponseSchema:nu,OAuthClientInformationFullSchema:su,OAuthClientInformationSchema:ou,OAuthClientMetadataSchema:au,OAuthClientRegistrationErrorSchema:cu,OAuthErrorResponseSchema:ru,OAuthMetadataSchema:Ql,OAuthProtectedResourceMetadataSchema:Zl,OAuthTokenRevocationRequestSchema:lu,OAuthTokensSchema:tu,OpenIdProviderDiscoveryMetadataSchema:eu,OpenIdProviderMetadataSchema:$l},eh={},th={};function nh(e,t){let n=e.slice(0,-6);eh[n]=t,th[n]=e=>t.safeParse(e).success}for(let e of Qm)nh(e,om[e]);for(let[e,t]of Object.entries($m))nh(e,t);Object.freeze(eh),Object.freeze(th);function rh(e){switch(e){case`initialize`:case`notifications/initialized`:return tm(void 0);case`server/discover`:return tm(`2026-07-28`);default:return}}let ih=[Wo,Go,qo,Jo],ah=[`inputResponses`,`requestState`];function oh(e,t){let n=e.params;if(!fh(n))return{message:e,lifted:{}};let r=n._meta,i=fh(r)?ih.filter(e=>e in r):[],a=t===`request`?ah.filter(e=>e in n):[];if(i.length===0&&a.length===0)return{message:e,lifted:{}};let o={},s={...n};if(i.length>0&&fh(r)){let e={},t={...r};for(let n of i)e[n]=r[n],delete t[n];o.envelope=e,Object.keys(t).length>0?s._meta=t:delete s._meta}for(let e of a)e===`inputResponses`&&(o.inputResponses=s[e]),e===`requestState`&&(o.requestState=s[e]),delete s[e];return{message:{...e,params:s},lifted:o}}function sh(e,t){let n=e.validateResult(t,void 0);if(!(!n.ok&&n.reason===`not-in-era`))return{"~standard":{version:1,vendor:`mcp-wire-codec`,validate(n){let r=e.validateResult(t,n);return r.ok?{value:r.value}:{issues:[{message:r.reason===`invalid`?r.message:`not-in-era: ${t}`}]}}}}}function ch(e){return()=>e}let lh=ch(void 0);function uh(e,t){return{...e,mcpReq:{...e.mcpReq,requestState:ch(t)}}}var dh=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Uo,this.setNotificationHandler(`notifications/cancelled`,e=>{this._oncancel(e)}),this.setNotificationHandler(`notifications/progress`,e=>{this._onprogress(e)}),this.setRequestHandler(`ping`,e=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let n=e.params??{};return{...e,params:{...n,_meta:{...t,...n._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new X(Y.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new X(Y.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),lm(e)||um(e)?this._onresponse(e):sm(e)?this._onrequest(e,t):cm(e)?this._onnotification(e,t):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let n=new X(Y.ConnectionClosed,`Connection closed`);this._transport=void 0;try{this.onclose?.()}finally{for(let t of e.values())t(n);for(let e of t.values())e.abort(n)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:n}=oh(e,`notification`),r=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)===`drop`)return;if(t?.classification!==void 0){let e=nm(t.classification);if(e!==r.era){this._onerror(Error(`Era mismatch on inbound notification '${n.method}': classified as ${e} but this instance serves ${r.era}`));return}}if(im(n.method)&&!r.hasNotificationMethod(n.method))return;let i=this._notificationHandlers.get(n.method),a=this.fallbackNotificationHandler;i===void 0&&a===void 0||Promise.resolve().then(()=>i===void 0?a(n):i(n,r)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let{message:n,lifted:r}=oh(e,`request`),i=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)===`drop`){this._onerror(Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let a=this._transport,o=(e,t,r)=>{let i={jsonrpc:`2.0`,id:n.id,error:{code:e,message:t,...r!==void 0&&{data:r}}};a?.send(i).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)))};if(t?.classification!==void 0){let e=nm(t.classification);if(e!==i.era){this._onerror(Error(`Era mismatch on inbound request '${n.method}': classified as ${e} but this instance serves ${i.era}`));let r=t.classification.revision??e;o(Z.UnsupportedProtocolVersion,`Unsupported protocol version: ${r}`,{supported:this._supportedProtocolVersions,requested:r});return}}if(rm(n.method)&&!i.hasRequestMethod(n.method)){o(Z.MethodNotFound,`Method not found`);return}let s=this._requestHandlers.get(n.method)??this.fallbackRequestHandler;if(s===void 0){o(Z.MethodNotFound,`Method not found`);return}let c=i.checkInboundEnvelope(r);if(c!==void 0){o(Z.InvalidParams,c);return}let l=(e,t)=>this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,{...t,relatedRequestId:n.id}),u=(e,t,r)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(e.method),e,t,{...r,relatedRequestId:n.id}),d=new AbortController;this._requestHandlerAbortControllers.set(n.id,d);let f=r.inputResponses===void 0?void 0:hh(r.inputResponses),p={sessionId:a?.sessionId,mcpReq:{id:n.id,method:n.method,_meta:n.params?._meta,...r.envelope!==void 0&&{envelope:r.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:r.requestState===void 0?lh:ch(r.requestState),signal:d.signal,send:((e,t,n)=>{let r=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(r,e.method),Cm(t))return u(e,t,n);let i=sh(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return u(e,i,t)}),notify:l},http:t?.authInfo?{authInfo:t.authInfo}:void 0},m=this.buildContext(p,t);Promise.resolve().then(()=>s(n,m)).then(async e=>{if(d.signal.aborted)return;let t;try{t=i.encodeResult(n.method,e,this._outboundServerInfo())}catch(e){this._onerror(Error(`Failed to encode result for ${n.method}: ${e}`)),o(Z.InternalError,`Internal error`);return}let r={result:t,jsonrpc:`2.0`,id:n.id};await a?.send(r)},async e=>{if(d.signal.aborted)return;let t=Number.isSafeInteger(e.code)?e.code:Z.InternalError,r={jsonrpc:`2.0`,id:n.id,error:{code:i.encodeErrorCode(t),message:e.message??`Internal error`,...e.data!==void 0&&{data:e.data}}};await a?.send(r)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(n.id)===d&&this._requestHandlerAbortControllers.delete(n.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._responseHandlers.get(t);if(n===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),lm(e)?n(e):n(Q.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,n){let r=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(r,e.method),Cm(t))return this._requestWithSchemaViaCodec(r,e,t,n);let i=sh(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(r,e,i,t)}_negotiatedWireCodec(){return tm(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=rh(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(rm(t)&&!e.hasRequestMethod(t))throw new X(Y.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,n){let r=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(r,e.method),this._requestWithSchemaViaCodec(r,e,t,n)}_requestWithSchemaViaCodec(e,t,n,r){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s}=r??{},c=Date.now(),l,u;return new Promise((d,f)=>{let p=e=>{f(e)};if(!this._transport){p(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(e){p(e);return}if(r?.signal?.aborted){let e=r.signal.reason;throw e instanceof X?e:new X(Y.RequestTimeout,String(e))}let m=e.era===`2026-07-28`&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,h=this._requestMessageId++;u=h;let g={...t,jsonrpc:`2.0`,id:h};r?.onprogress&&(this._progressHandlers.set(h,r.onprogress),g.params={...t.params,_meta:{...t.params?._meta,progressToken:h}});let _=this._envelopeOutbound(g),ee=!1,te=e=>{ee||(this._progressHandlers.delete(h),m===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:h,reason:String(e)}}),{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))):m.abort(),f(e instanceof X?e:new X(Y.RequestTimeout,String(e))))};this._responseHandlers.set(h,i=>{if(r?.signal?.aborted)return;if(ee=!0,i instanceof Error)return f(i);let a;try{a=e.decodeResult(t.method,i.result)}catch(e){return f(e instanceof Error?e:Error(String(e)))}if(a.kind===`invalid`)return f(a.error);if(a.kind===`input_required`){if(r?.allowInputRequired===!0)return d(gh(a));let i={codec:e,request:t,resultSchema:n,options:r,flowStartedAt:c,retry:(r,i)=>this._requestWithSchemaViaCodec(e,r===void 0?{method:t.method}:{method:t.method,params:r},n,i)};return d(this._resolveNonCompleteResult(a,i))}let o=a.result;km(n,o).then(e=>{e.success?d(e.data):f(new X(Y.InvalidResult,`Invalid result for ${t.method}: ${e.error}`))},f)}),l=()=>te(r?.signal?.reason),r?.signal?.addEventListener(`abort`,l,{once:!0});let ne=r?.timeout??6e4;this._setupTimeout(h,ne,r?.maxTotalTimeout,()=>te(new X(Y.RequestTimeout,`Request timed out`,{timeout:ne})),r?.resetTimeoutOnProgress??!1),this._transport.send(_,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s,requestSignal:m?.signal}).catch(e=>{this._progressHandlers.delete(h),f(e)})}).finally(()=>{l&&r?.signal?.removeEventListener(`abort`,l),u!==void 0&&(this._responseHandlers.delete(u),this._cleanupTimeout(u))})}async notification(e,t){return this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,n){if(!this._transport)throw new X(Y.NotConnected,`Not connected`);if(im(t.method)&&!e.hasNotificationMethod(t.method))throw new X(Y.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let r=this._envelopeOutbound({jsonrpc:`2.0`,...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!n?.relatedRequestId){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(r,n).catch(e=>this._onerror(e))});return}await this._transport.send(r,n)}setRequestHandler(e,t,n){this.assertRequestHandlerCapability(e);let r;if(typeof t==`function`){if(!rm(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);r=(n,r)=>{let i=this._negotiatedWireCodec(),a=i.validateRequest(e,n);if(!a.ok&&a.reason===`not-in-era`&&(a=i.validateInputRequest(e,n)),!a.ok)throw a.reason===`not-in-era`?new Q(Z.InternalError,`No wire schema for ${e} in the resolved era`):Error(a.message);return Promise.resolve(t(a.value,r))}}else if(n)r=async(r,i)=>{let a=await km(t.params,{...r.params});if(!a.success)throw new Q(Z.InvalidParams,`Invalid params for ${e}: ${a.error}`);return n(a.data,i)};else throw TypeError(`setRequestHandler: handler is required`);this._requestHandlers.set(e,this._wrapHandler(e,r))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,n){if(typeof t==`function`){if(!im(e))throw TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,r)=>{let i=r.validateNotification(e,n);if(!i.ok)throw i.reason===`not-in-era`?new Q(Z.InternalError,`No wire schema for ${e} in the resolved era`):Error(i.message);return Promise.resolve(t(i.value))});return}if(!n)throw TypeError(`setNotificationHandler: handler is required`);this._notificationHandlers.set(e,async r=>{let i=await km(t.params,{...r.params});if(!i.success)throw new Q(Z.InvalidParams,`Invalid params for notification ${e}: ${i.error}`);await n(i.data,r)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function fh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ph(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=fh(a)&&fh(i)?{...a,...i}:i}return n}function mh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hh(e){let t={},n=[];if(!mh(e))return{accepted:t,droppedKeys:n};for(let[r,i]of Object.entries(e)){if(!mh(i)||`method`in i||`result`in i){n.push(r);continue}t[r]=i}return{accepted:t,droppedKeys:n}}function gh(e){return{resultType:`input_required`,inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}
|
|
70
70
|
/*!
|
|
71
71
|
* content-type
|
|
72
72
|
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
73
73
|
* MIT Licensed
|
|
74
74
|
*/
|
|
75
75
|
vf((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,n=/\\([\u000b\u0020-\u00ff])/g,r=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=i;function i(e){if(!e)throw TypeError(`argument string is required`);var i=typeof e==`object`?a(e):e;if(typeof i!=`string`)throw TypeError(`argument string is required to be a string`);var s=i.indexOf(`;`),c=s===-1?i.trim():i.slice(0,s).trim();if(!r.test(c))throw TypeError(`invalid media type`);var l=new o(c.toLowerCase());if(s!==-1){var u,d,f;for(t.lastIndex=s;d=t.exec(i);){if(d.index!==s)throw TypeError(`invalid parameter format`);s+=d[0].length,u=d[1].toLowerCase(),f=d[2],f.charCodeAt(0)===34&&(f=f.slice(1,-1),f.indexOf(`\\`)!==-1&&(f=f.replace(n,`$1`))),l.parameters[u]=f}if(s!==i.length)throw TypeError(`invalid parameter format`)}return l}function a(e){var t;if(typeof e.getHeader==`function`?t=e.getHeader(`content-type`):typeof e.headers==`object`&&(t=e.headers&&e.headers[`content-type`]),typeof t!=`string`)throw TypeError(`content-type header is missing from object`);return t}function o(e){this.parameters=Object.create(null),this.type=e}}))();let _h=/^[A-Za-z0-9._-]{1,128}$/;function vh(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!_h.test(e)){let n=[...e].filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function yh(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function bh(e){let t=vh(e);return yh(e,t.warnings),t.isValid}let xh=1e6,Sh=1e6,Ch=1e4;var wh=class e{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,t,n){if(e.length>t)throw Error(`${n} exceeds maximum length of ${t} characters (got ${e.length})`)}template;parts;get variableNames(){return this.parts.flatMap(e=>typeof e==`string`?[]:e.names)}constructor(t){e.validateLength(t,xh,`Template`),this.template=t,this.parts=this.parse(t)}toString(){return this.template}parse(t){let n=[],r=``,i=0,a=0;for(;i<t.length;)if(t[i]===`{`){r&&=(n.push(r),``);let o=t.indexOf(`}`,i);if(o===-1)throw Error(`Unclosed template expression`);if(a++,a>Ch)throw Error(`Template contains too many expressions (max ${Ch})`);let s=t.slice(i+1,o),c=this.getOperator(s),l=s.includes(`*`),u=this.getNames(s),d=u[0];for(let t of u)e.validateLength(t,Sh,`Variable name`);n.push({name:d,operator:c,names:u,exploded:l}),i=o+1}else r+=t[i],i++;return r&&n.push(r),n}getOperator(e){return[`+`,`#`,`.`,`/`,`?`,`&`].find(t=>e.startsWith(t))||``}getNames(e){let t=this.getOperator(e);return e.slice(t.length).split(`,`).map(e=>e.replace(`*`,``).trim()).filter(e=>e.length>0)}encodeValue(t,n){return e.validateLength(t,Sh,`Variable value`),n===`+`||n===`#`?encodeURI(t):encodeURIComponent(t)}expandPart(e,t){if(e.operator===`?`||e.operator===`&`){let n=e.names.map(n=>{let r=t[n];return r===void 0?``:`${n}=${Array.isArray(r)?r.map(t=>this.encodeValue(t,e.operator)).join(`,`):this.encodeValue(r.toString(),e.operator)}`}).filter(e=>e.length>0);return n.length===0?``:(e.operator===`?`?`?`:`&`)+n.join(`&`)}if(e.names.length>1){let n=e.names.map(e=>t[e]).filter(e=>e!==void 0);return n.length===0?``:n.map(e=>Array.isArray(e)?e[0]:e).join(`,`)}let n=t[e.name];if(n===void 0)return``;let r=(Array.isArray(n)?n:[n]).map(t=>this.encodeValue(t,e.operator));switch(e.operator){case``:return r.join(`,`);case`+`:return r.join(`,`);case`#`:return`#`+r.join(`,`);case`.`:return`.`+r.join(`.`);case`/`:return`/`+r.join(`/`);default:return r.join(`,`)}}expand(e){let t=``,n=!1;for(let r of this.parts){if(typeof r==`string`){t+=r;continue}let i=this.expandPart(r,e);i&&(t+=(r.operator===`?`||r.operator===`&`)&&n?i.replace(`?`,`&`):i,(r.operator===`?`||r.operator===`&`)&&(n=!0))}return t}escapeRegExp(e){return e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(t){let n=[];for(let n of t.names)e.validateLength(n,Sh,`Variable name`);if(t.operator===`?`||t.operator===`&`){for(let e=0;e<t.names.length;e++){let r=t.names[e],i=e===0?`\\`+t.operator:`&`;n.push({pattern:i+this.escapeRegExp(r)+`=([^&]+)`,name:r})}return n}let r,i=t.name;switch(t.operator){case``:r=t.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`;break;case`+`:case`#`:r=`(.+)`;break;case`.`:r=String.raw`\.([^/,]+)`;break;case`/`:r=`/`+(t.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`);break;default:r=`([^/]+)`}return n.push({pattern:r,name:i}),n}match(t){e.validateLength(t,xh,`URI`);let n=`^`,r=[];for(let e of this.parts)if(typeof e==`string`)n+=this.escapeRegExp(e);else{let t=this.partToRegExp(e);for(let{pattern:i,name:a}of t)n+=i,r.push({name:a,exploded:e.exploded})}n+=`$`,e.validateLength(n,1e6,`Generated regex pattern`);let i=new RegExp(n),a=t.match(i);if(!a)return null;let o={};for(let[e,t]of r.entries()){let{name:n,exploded:r}=t,i=a[e+1],s=n.replace(`*`,``);o[s]=r&&i.includes(`,`)?i.split(`,`):i}return o}};function Th(e){return typeof e==`object`&&!!e&&`_zod`in e}function Eh(e){return typeof e==`object`&&!!e&&!(`_zod`in e)&&`_def`in e&&typeof e._def?.typeName==`string`}function Dh(e){if(typeof e!=`object`||!e||Cm(e))return!1;let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:Object.values(e).every(e=>Th(e))}function Oh(e){if(e!==void 0){if(Dh(e))return F(e);if(typeof e==`object`&&e&&!Cm(e)&&Object.values(e).some(e=>Eh(e)))throw TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!Cm(e))throw TypeError(`inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).`);return e}}function kh(e,t){let n=t.getValidator(e);return{"~standard":{version:1,vendor:`mcp`,jsonSchema:{input:()=>e,output:()=>e},validate:e=>{let t=n(e);return t.valid?{value:t.data}:{issues:[{message:t.errorMessage}]}}}}}function Ah(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!Ah(e[r],t[r]))return!1;return!0}if(n===`object`){if(!e||!t)return e===t;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!Ah(e[r],t[r]))return!1;return!0}return e===t}function jh(e){return encodeURI(Mh(e))}function Mh(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}let Nh={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Ph={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Fh={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!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},Ih=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 Lh(e,t=Object.create(null),n=Ih,r=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,n.href);a.hash.length>1?t[a.href]=e:(a.hash=``,r===``?n=a:Lh(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)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}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(Fh[i])continue;let a=`${r}/${jh(i)}`,o=e[i];if(Array.isArray(o)){if(Nh[i]){let e=o.length;for(let r=0;r<e;r++)Lh(o[r],t,n,`${a}/${r}`)}}else if(Ph[i])for(let e in o)Lh(o[e],t,n,`${a}/${jh(e)}`);else Lh(o,t,n,a)}return t}let Rh=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,zh=[0,31,28,31,30,31,30,31,31,30,31,30,31],Bh=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Vh=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,Hh=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,Uh=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Wh=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Gh=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Kh=/^(?:\/(?:[^~/]|~0|~1)*)*$/,qh=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Jh=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Yh=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},Xh=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Zh=/^((([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,Qh=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 $h(e){return e.test.bind(e)}let eg={date:ng,time:rg.bind(void 0,!1),"date-time":ag,duration:Qh,uri:cg,"uri-reference":$h(Hh),"uri-template":$h(Uh),url:$h(Wh),email:Yh,hostname:$h(Vh),ipv4:$h(Xh),ipv6:$h(Zh),regex:ug,uuid:$h(Gh),"json-pointer":$h(Kh),"json-pointer-uri-fragment":$h(qh),"relative-json-pointer":$h(Jh)};function tg(e){return e%4==0&&(e%100!=0||e%400==0)}function ng(e){let t=e.match(Rh);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&tg(n)?29:zh[r])}function rg(e,t){let n=t.match(Bh);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}let ig=/t|\s/i;function ag(e){let t=e.split(ig);return t.length==2&&ng(t[0])&&rg(!0,t[1])}let og=/\/|:/,sg=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function cg(e){return og.test(e)&&sg.test(e)}let lg=/[^\\]\\Z/;function ug(e){if(lg.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function dg(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}function $(e,t,n=`2019-09`,r=Lh(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:ee,anyOf:te,allOf:ne,oneOf:re,if:ie,then:ae,else:oe,format:se,properties:ce,patternProperties:le,additionalProperties:v,unevaluatedProperties:ue,minProperties:de,maxProperties:fe,propertyNames:pe,dependentRequired:me,dependentSchemas:he,dependencies:ge,prefixItems:_e,items:ve,additionalItems:ye,unevaluatedItems:be,contains:xe,minContains:y,maxContains:b,minItems:Se,maxItems:Ce,uniqueItems:we,minimum:Te,maximum:x,exclusiveMinimum:Ee,exclusiveMaximum:De,multipleOf:Oe,minLength:ke,maxLength:Ae,pattern:je,__absolute_ref__:Me,__absolute_recursive_ref__:Ne}=t,S=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[Ne]:a,u=`${s}/$recursiveRef`,d=$(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||S.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[Me||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw Me&&Me!==d&&(e+=` Absolute URI "${Me}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
|
|
76
|
-
- `)}`,Error(e)}let l=`${s}/$ref`,u=$(e,t,n,r,i,a,o,l,c);if(u.valid||S.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:S.length===0,errors:S}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||S.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&S.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&S.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?Ah(e,h)||S.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&S.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u===`object`||u===`array`?g.some(t=>Ah(e,t))||S.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||S.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),ee!==void 0){let t=`${s}/not`;$(e,ee,n,r,i,a,o,t).valid&&S.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Pe=[];if(te!==void 0){let t=`${s}/anyOf`,l=S.length,u=!1;for(let s=0;s<te.length;s++){let l=te[s],d=Object.create(c),f=$(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);S.push(...f.errors),u||=f.valid,f.valid&&Pe.push(d)}u?S.length=l:S.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(ne!==void 0){let t=`${s}/allOf`,l=S.length,u=!0;for(let s=0;s<ne.length;s++){let l=ne[s],d=Object.create(c),f=$(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);S.push(...f.errors),u&&=f.valid,f.valid&&Pe.push(d)}u?S.length=l:S.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(re!==void 0){let t=`${s}/oneOf`,l=S.length,u=re.filter((s,l)=>{let u=Object.create(c),d=$(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return S.push(...d.errors),d.valid&&Pe.push(u),d.valid}).length;u===1?S.length=l:S.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...Pe),ie!==void 0){let t=`${s}/if`;if($(e,ie,n,r,i,a,o,t,c).valid){if(ae!==void 0){let l=$(e,ae,n,r,i,a,o,`${s}/then`,c);l.valid||S.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(oe!==void 0){let l=$(e,oe,n,r,i,a,o,`${s}/else`,c);l.valid||S.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(_!==void 0)for(let t of _)t in e||S.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(de!==void 0&&t.length<de&&S.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${de} properties.`}),fe!==void 0&&t.length>fe&&S.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${fe} properties.`}),pe!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${jh(s)}`,c=$(s,pe,n,r,i,a,e,t);c.valid||S.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(me!==void 0){let t=`${s}/dependantRequired`;for(let n in me)if(n in e){let r=me[n];for(let i of r)i in e||S.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(he!==void 0)for(let t in he){let l=`${s}/dependentSchemas`;if(t in e){let s=$(e,he[t],n,r,i,a,o,`${l}/${jh(t)}`,c);s.valid||S.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(ge!==void 0){let t=`${s}/dependencies`;for(let s in ge)if(s in e){let c=ge[s];if(Array.isArray(c))for(let n of c)n in e||S.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=$(e,c,n,r,i,a,o,`${t}/${jh(s)}`);l.valid||S.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(ce!==void 0){let t=`${s}/properties`;for(let s in ce){if(!(s in e))continue;let d=`${o}/${jh(s)}`,f=$(e[s],ce[s],n,r,i,a,d,`${t}/${jh(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,S.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&le!==void 0){let t=`${s}/patternProperties`;for(let s in le){let d=new RegExp(s,`u`),f=le[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${jh(p)}`,h=$(e[p],f,n,r,i,a,m,`${t}/${jh(s)}`);h.valid?c[p]=l[p]=!0:(u=i,S.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&v!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${jh(s)}`,f=$(e[s],v,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,S.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&ue!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${jh(s)}`,u=$(e[s],ue,n,r,i,a,l,t);u.valid?c[s]=!0:S.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){Ce!==void 0&&e.length>Ce&&S.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${Ce}).`}),Se!==void 0&&e.length<Se&&S.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${Se}).`});let t=e.length,l=0,u=!1;if(_e!==void 0){let d=`${s}/prefixItems`,f=Math.min(_e.length,t);for(;l<f;l++){let t=$(e[l],_e[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,S.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(ve!==void 0){let d=`${s}/items`;if(Array.isArray(ve)){let s=Math.min(ve.length,t);for(;l<s;l++){let t=$(e[l],ve[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,S.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=$(e[l],ve,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,S.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&ye!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=$(e[l],ye,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,S.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(xe!==void 0)if(t===0&&y===void 0)S.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(y!==void 0&&t<y)S.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${y}).`});else{let l=`${s}/contains`,u=S.length,d=0;for(let s=0;s<t;s++){let t=$(e[s],xe,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):S.push(...t.errors)}d>=(y||0)&&(S.length=u),y===void 0&&b===void 0&&d===0?S.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):y!==void 0&&d<y?S.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${y} items matching schema. Only ${d} items were found.`}):b!==void 0&&d>b&&S.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${b} items matching schema. ${d} items were found.`})}if(!u&&be!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=$(e[l],be,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||S.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(we)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&Ah(r,t))&&(S.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(Te!==void 0&&(Ee===!0&&e<=Te||e<Te)&&S.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${Ee?`or equal to `:``} ${Te}.`}),x!==void 0&&(De===!0&&e>=x||e>x)&&S.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${De?`or equal to `:``} ${x}.`})):(Te!==void 0&&e<Te&&S.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${Te}.`}),x!==void 0&&e>x&&S.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${x}.`}),Ee!==void 0&&e<=Ee&&S.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${Ee}.`}),De!==void 0&&e>=De&&S.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${De}.`})),Oe!==void 0){let t=e%Oe;Math.abs(0-t)>=1.1920929e-7&&Math.abs(Oe-t)>=1.1920929e-7&&S.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${Oe}.`})}}else if(u===`string`){let t=ke===void 0&&Ae===void 0?0:dg(e);ke!==void 0&&t<ke&&S.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${ke}).`}),Ae!==void 0&&t>Ae&&S.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${Ae}).`}),je!==void 0&&!new RegExp(je,`u`).test(e)&&S.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),se!==void 0&&eg[se]&&!eg[se](e)&&S.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${se}".`})}return{valid:S.length===0,errors:S}}var fg=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Lh(e)}validate(e){return $(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Lh(e,this.lookup)}},pg=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=Tf(e,`pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.`);return t===`draft-7`?`7`:t}getValidator(e){let t=new fg(e,this.draft??this._draftFor(e),this.shortcircuit);return e=>{let n=t.validate(e);return n.valid?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:n.errors.map(e=>`${e.instanceLocation}: ${e.error}`).join(`; `)}}}};let mg=Symbol.for(`mcp.completable`);function hg(e){return!!e&&typeof e==`object`&&mg in e}function gg(e){return e[mg]?.complete}function _g(e){if(e?.maxRounds!==void 0&&(!Number.isInteger(e.maxRounds)||e.maxRounds<1))throw RangeError(`inputRequired.maxRounds must be a positive integer (got ${e.maxRounds})`);if(e?.roundTimeoutMs!==void 0&&(!Number.isFinite(e.roundTimeoutMs)||e.roundTimeoutMs<=0))throw RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${e.roundTimeoutMs})`);return{maxRounds:e?.maxRounds??8,roundTimeoutMs:e?.roundTimeoutMs??6e5,legacyShim:e?.legacyShim??!0}}function vg(e,t,n){if(typeof n!=`object`||!n||typeof n.method!=`string`)throw new Q(Z.InternalError,`Handler for ${e} returned an invalid input request '${t}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);let r=n,i=jf(r);if(i===void 0)throw new Q(Z.InternalError,`Handler for ${e} returned an input request '${t}' of kind '${r.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded:r,required:i}}function yg(){let e=globalThis.crypto;if(e?.randomUUID!==void 0)return e.randomUUID();let t=new Uint8Array(16);e.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(e=>e.toString(16).padStart(2,`0`)).join(``);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function bg(e,t){if(e===`tools/call`)return{content:[{type:`text`,text:t}],isError:!0};throw new Q(Z.InternalError,t)}var xg=class{constructor(e){this._host=e}async fulfill(e,t,n,r,i){let{maxRounds:a,roundTimeoutMs:o}=this._host,s=r.mcpReq.signal,c=i,l=0;for(;;){if(l+=1,l>a)return bg(e,Ym(e,a));let i=c.inputRequests,u=i!=null&&Object.keys(i).length>0,d=typeof c.requestState==`string`?c.requestState:void 0;if(!u&&d===void 0)throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);let f;if(u){let t=this._host.resolvedClientCapabilities(r),n=[];for(let[r,a]of Object.entries(i)){let{embedded:i,required:o}=vg(e,r,a);if(i.method!==`roots/list`&&i.params===void 0)throw new Q(Z.InternalError,`Handler for ${e} returned an input request '${r}' of kind '${i.method}' without params`);if(Mf(o,t)!==void 0)return bg(e,`Cannot request input '${r}' (${i.method}): the client on this 2025-era connection did not declare the required capability${t===void 0?` (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)`:``}`);n.push([r,i])}let a=Zm(s);try{let e={relatedRequestId:r.mcpReq.id,timeout:o,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:a.signal},t=await Promise.all(n.map(async([t,n])=>{try{return[t,await this._dispatchLeg(n,e)]}catch(e){throw a.abort(e),e}}));f=Object.fromEntries(t)}catch(t){if(s.aborted)throw t;return bg(e,`Fulfilling input required by '${e}' failed: ${t instanceof Error?t.message:String(t)}`)}finally{a.dispose()}}else await Xm(250,s);let p={...r,mcpReq:{...r.mcpReq,inputResponses:f,droppedInputResponseKeys:void 0,requestState:ch(d)}};if(d!==void 0){let t=await this._host.verifyRequestState(d,p,e);t!==void 0&&(p=uh(p,t))}let m=await t(n,p);if(!dm(m))return m;c=m}}async _dispatchLeg(e,t){switch(e.method){case`elicitation/create`:{let n=e.params;return n.mode===`url`&&n.elicitationId===void 0&&(n={...n,elicitationId:yg()}),await this._host.sendElicitation(n,t)}case`sampling/createMessage`:return await this._host.sendSampling(e.params,t);case`roots/list`:return await this._host.listRoots(e.params,t)}}};let Sg=new Set([`tools/call`,`prompts/get`,`resources/read`]);var Cg=class extends dh{_clientCapabilities;_clientVersion;_capabilities;_instructions;_jsonSchemaValidator;_cacheHints;_requestStateVerify;_inputRequiredServing;_legacyShim;_legacyInputRequiredShim(){return this._legacyShim??=new xg({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:e=>this._inputRequestCapabilityView(e),verifyRequestState:(e,t,n)=>this._verifyRequestState(e,t,n),sendElicitation:(e,t)=>this._sendElicitationLeg(e,t,{validateAcceptedContent:!1}),sendSampling:(e,t)=>this.createMessage(e,t),listRoots:(e,t)=>this.listRoots(e,t)})}oninitialized;constructor(e,t){if(super(t),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new pg,this._requestStateVerify=t?.requestState?.verify,this._inputRequiredServing=_g(t?.inputRequired),t?.cacheHints!==void 0){for(let[e,n]of Object.entries(t.cacheHints))n!==void 0&&bp(n,`cacheHints['${e}']`);this._cacheHints=t.cacheHints}this.setRequestHandler(`initialize`,e=>this._oninitialize(e)),this.setNotificationHandler(`notifications/initialized`,()=>this.oninitialized?.()),Ff(this._supportedProtocolVersions).length>0&&this.setRequestHandler(`server/discover`,()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}_registerLoggingHandler(){this.setRequestHandler(`logging/setLevel`,async(e,t)=>{let n=t.sessionId||t.http?.req?.headers.get(`mcp-session-id`)||void 0,{level:r}=e.params,i=xm(Vc,r);return i.success&&this._loggingLevels.set(n,i.data),{}})}buildContext(e,t){let n=e.http||t?.request||t?.closeSSEStream||t?.closeStandaloneSSEStream;return{...e,mcpReq:{...e.mcpReq,log:(t,n,r)=>{if(!this._capabilities.logging)return Promise.resolve();let i;if(this._servedModernEra()){if(i=e.mcpReq.envelope?.[Jo],i===void 0)return Promise.resolve()}else i=this._loggingLevels.get(e.sessionId)??this._loggingLevels.get(void 0);return i!==void 0&&this.LOG_LEVEL_SEVERITY.get(t)<this.LOG_LEVEL_SEVERITY.get(i)?Promise.resolve():e.mcpReq.notify({method:`notifications/message`,params:{level:t,data:n,logger:r}})},elicitInput:(e,t)=>this.elicitInput(e,t),requestSampling:(e,t)=>this.createMessage(e,t)},http:n?{...e.http,req:t?.request,closeSSE:t?.closeSSEStream,closeStandaloneSSE:t?.closeStandaloneSSEStream}:void 0}}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Vc.options.map((e,t)=>[e,t]));isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1};registerCapabilities(e){if(this.transport)throw new X(Y.AlreadyConnected,`Cannot register capabilities after connecting to transport`);let t=!!this._capabilities.logging;this._capabilities=ph(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(e,t){if(e!==`tools/call`){let n=this._cacheHints?.[e],r=Sg.has(e);return n===void 0&&!r?async(n,r)=>{let i=await t(n,r);if(dm(i))throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return i}:async(i,a)=>{let o=r?await this._invokeInputRequiredCapableHandler(e,t,i,a):await t(i,a);if(dm(o)){if(!r)throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return o}return n===void 0?o:gp(o,n)}}return async(e,n)=>{let r=tm(this._negotiatedProtocolVersion),i=r.validateRequest(`tools/call`,e);if(!i.ok)throw new Q(i.reason===`not-in-era`?Z.InternalError:Z.InvalidParams,i.reason===`not-in-era`?`No wire schema for tools/call in the resolved era`:`Invalid tools/call request: ${i.message}`);let a=await this._invokeInputRequiredCapableHandler(`tools/call`,t,e,n);if(dm(a))return a;let o=Rf(a),s=r.validateResult(`tools/call`,o);if(!s.ok)throw new Q(s.reason===`not-in-era`?Z.InternalError:Z.InvalidParams,s.reason===`not-in-era`?`No wire schema for tools/call in the resolved era`:`Invalid tools/call result: ${s.message}`);return s.value}}_servedModernEra(){return this._negotiatedProtocolVersion!==void 0&&Nf(this._negotiatedProtocolVersion)}async _invokeInputRequiredCapableHandler(e,t,n,r){let i=this._servedModernEra(),a=r.mcpReq.requestState();if(a!==void 0&&typeof a!=`string`)throw new Q(Z.InvalidParams,`Invalid or expired requestState`,{reason:`invalid_request_state`});let o=r;if(typeof a==`string`){let t=await this._verifyRequestState(a,r,e);t!==void 0&&(o=uh(r,t))}let s;try{s=await t(n,o)}catch(e){throw e instanceof Q&&e.code===Z.UrlElicitationRequired&&i?new Q(Z.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`):e}if(!dm(s))return s;if(!i){if(!this._inputRequiredServing.legacyShim)throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??`2025-11-25`}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(e,t,n,o,s)}let c=s.inputRequests,l=c!=null&&Object.keys(c).length>0,u=typeof s.requestState==`string`;if(!l&&!u)throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(l){let t=this._inputRequestCapabilityView(r);for(let[n,r]of Object.entries(c)){let{embedded:i,required:a}=vg(e,n,r),o=Mf(a,t);if(o!==void 0)throw new wp({requiredCapabilities:o},`Cannot request input '${n}' (${i.method}): the request's client capabilities do not declare the required capability`)}}return s}async _verifyRequestState(e,t,n){if(this._requestStateVerify!==void 0)try{return await this._requestStateVerify(e,t)}catch(e){throw this.onerror?.(Error(`requestState verification rejected ${n}: ${e instanceof Error?e.message:String(e)}`)),new Q(Z.InvalidParams,`Invalid or expired requestState`,{reason:`invalid_request_state`})}}_inputRequestCapabilityView(e){return this._servedModernEra()?e.mcpReq.envelope?.[qo]:this._clientCapabilities}_assertPushApiInServedEra(e){if(this._servedModernEra())throw new X(Y.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${e}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method:e,era:`2026-07-28`})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw new X(Y.CapabilityNotSupported,`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw new X(Y.CapabilityNotSupported,`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw new X(Y.CapabilityNotSupported,`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw new X(Y.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw new X(Y.CapabilityNotSupported,`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw new X(Y.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw new X(Y.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw new X(Y.CapabilityNotSupported,`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){switch(e){case`completion/complete`:if(!this._capabilities.completions)throw new X(Y.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw new X(Y.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw new X(Y.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw new X(Y.CapabilityNotSupported,`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw new X(Y.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case`ping`:case`initialize`:break}}async _oninitialize(e){let t=e.params.protocolVersion;this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo;let n=Pf(this._supportedProtocolVersions),r=n.includes(t)?t:n[0]??`2025-11-25`;return this._negotiatedProtocolVersion=r,this.transport?.setProtocolVersion?.(r),{protocolVersion:r,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:Ff(this._supportedProtocolVersions),capabilities:wg(this.getCapabilities()),...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(e,t){return this._wireCodec().projectCallToolResult(e,t)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra(`ping`),this.request({method:`ping`})}async createMessage(e,t){if(this._assertPushApiInServedEra(`sampling/createMessage`),(e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new X(Y.CapabilityNotSupported,`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages.at(-1),n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages.at(-2):void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw new Q(Z.InvalidParams,`The last message must contain only tool_result content if any is present`);if(!o)throw new Q(Z.InvalidParams,`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw new Q(Z.InvalidParams,`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}let n=!!(e.tools||e.toolChoice),r=await this.request({method:`sampling/createMessage`,params:e},t),i=this._wireCodec().samplingResultVariant(n,r);if(!i.ok)throw new X(Y.InvalidResult,`Invalid sampling/createMessage result: ${i.reason===`invalid`?i.message:i.reason}`);return i.value}async elicitInput(e,t){switch(this._assertPushApiInServedEra(`elicitation/create`),e.mode??`form`){case`url`:if(!this._clientCapabilities?.elicitation?.url)throw new X(Y.CapabilityNotSupported,`Client does not support url elicitation.`);break;case`form`:if(!this._clientCapabilities?.elicitation?.form)throw new X(Y.CapabilityNotSupported,`Client does not support form elicitation.`);break}return this._sendElicitationLeg(e,t)}async _sendElicitationLeg(e,t,n){let r=e.mode??`form`,i=n?.validateAcceptedContent??!0;switch(r){case`url`:{let n=e;return this.request({method:`elicitation/create`,params:n},t)}case`form`:{let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},t);if(i&&r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new Q(Z.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof Q?e:new Q(Z.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new X(Y.CapabilityNotSupported,`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this._assertPushApiInServedEra(`roots/list`),this.request({method:`roots/list`,params:e},t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};function wg(e){return{...e}}var Tg=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_toolInputSchemaJson={};toolInputSchemaJson(e){let t=this._registeredTools[e];if(!(t===void 0||!t.enabled)){if(Object.hasOwn(this._toolInputSchemaJson,e))return this._toolInputSchemaJson[e];if(t.inputSchema===void 0)return Og;try{let n=Em(t.inputSchema,`input`);return this._toolInputSchemaJson[e]=n,n}catch{return}}}constructor(e,t){this.server=new Cg(e,t),t?.capabilities?.tools&&this.setToolRequestHandlers(),t?.capabilities?.resources&&this.setResourceRequestHandlers(),t?.capabilities?.prompts&&this.setPromptRequestHandlers()}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(`tools/list`),this.server.assertCanSetRequestHandler(`tools/call`),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler(`tools/list`,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?Em(t.inputSchema,`input`):Og,annotations:t.annotations,icons:t.icons,execution:t.execution,_meta:t._meta};return t.outputSchema&&(n.outputSchema=Em(t.outputSchema,`output`)),n})})),this.server.setRequestHandler(`tools/call`,async(e,t)=>{let n=this._registeredTools[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Tool ${e.params.name} disabled`);try{let r=await this.validateToolInput(n,e.params.arguments,e.params.name),i=await this.executeToolHandler(n,r,t);return await this.validateToolOutput(n,i,e.params.name),dm(i)?i:this.server.projectCallToolResult(i,n.outputSchemaJson)}catch(e){if(e instanceof Q&&e.code===Z.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await km(e.inputSchema,t??{});if(!r.success)throw new Q(Z.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${r.error}`);return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||dm(t)||t.isError)return;if(t.structuredContent===void 0)throw new Q(Z.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await km(e.outputSchema,t.structuredContent);if(!r.success)throw new Q(Z.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${r.error}`)}async executeToolHandler(e,t,n){return e.executor(t,n)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(`completion/complete`),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(`completion/complete`,async e=>{switch(e.params.ref.type){case`ref/prompt`:return fm(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return pm(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Q(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Mg;let r=Fg(Ng(n.argsSchema)?.[e.params.argument.name]);if(!hg(r))return Mg;let i=gg(r);return i?jg(await i(e.params.argument.value,e.params.context)):Mg}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return Mg;throw new Q(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?jg(await r(e.params.argument.value,e.params.context)):Mg}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(`resources/list`),this.server.assertCanSetRequestHandler(`resources/templates/list`),this.server.assertCanSetRequestHandler(`resources/read`),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler(`resources/list`,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(`resources/templates/list`,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(`resources/read`,async(e,t)=>{let n;try{n=new URL(e.params.uri)}catch{throw new Q(Z.InvalidParams,`Resource URI ${e.params.uri} is invalid`,{uri:e.params.uri,reason:`invalid_uri`})}let r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new Q(Z.InvalidParams,`Resource ${n} disabled`);return gp(await r.readCallback(n,t),r.cacheHint)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return gp(await e.readCallback(n,r,t),e.cacheHint)}throw new xp(e.params.uri)}),!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(`prompts/list`),this.server.assertCanSetRequestHandler(`prompts/get`),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler(`prompts/list`,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Fm(t.argsSchema):void 0,icons:t.icons,_meta:t._meta}))})),this.server.setRequestHandler(`prompts/get`,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} disabled`);return n.handler(e.params.arguments,t)}),!0)}registerResource(e,t,n,r){let i=n.cacheHint,a=n;if(i!==void 0){bp(i,`resource ${e}`);let t={...n};delete t.cacheHint,a=t}if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,n.title,t,a,r);return i!==void 0&&(o.cacheHint=i),this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,t,a,r);return i!==void 0&&(o.cacheHint=i),this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i,a,o){let s=r,c=i,l={title:t,description:n,argsSchema:r,icons:a,_meta:o,handler:Ag(e,r,i),enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.icons!==void 0&&(l.icons=t.icons),t._meta!==void 0&&(l._meta=t._meta);let n=!1;t.argsSchema!==void 0&&(l.argsSchema=t.argsSchema,s=t.argsSchema,n=!0),t.callback!==void 0&&(c=t.callback,n=!0),n&&(l.handler=Ag(e,s,c)),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=l,r){let e=Ng(r);e&&Object.values(e).some(e=>hg(Fg(e)))&&this.setCompletionRequestHandler()}return l}_createRegisteredTool(e,t,n,r,i,a,o,s,c,l){if(bh(e),r!==void 0)try{let t=Em(r,`input`);this._toolInputSchemaJson[e]=t;let n=_m(t);n.valid||console.warn(`[mcp-sdk] tool '${e}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${n.reason}`)}catch{}let u=l,d={title:t,description:n,inputSchema:r,outputSchema:i,outputSchemaJson:kg(i),annotations:a,icons:o,execution:s,_meta:c,handler:l,executor:Dg(r,l),enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&bh(t.name),delete this._registeredTools[e],delete this._toolInputSchemaJson[e],t.name&&(delete this._toolInputSchemaJson[t.name],this._registeredTools[t.name]=d,e=t.name)),t.title!==void 0&&(d.title=t.title),t.description!==void 0&&(d.description=t.description);let n=!1;t.paramsSchema!==void 0&&(d.inputSchema=t.paramsSchema,delete this._toolInputSchemaJson[e],n=!0),t.callback!==void 0&&(d.handler=t.callback,u=t.callback,n=!0),n&&(d.executor=Dg(d.inputSchema,u)),t.outputSchema!==void 0&&(d.outputSchema=t.outputSchema,d.outputSchemaJson=kg(t.outputSchema)),t.annotations!==void 0&&(d.annotations=t.annotations),t.icons!==void 0&&(d.icons=t.icons),t._meta!==void 0&&(d._meta=t._meta),t.enabled!==void 0&&(d.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,icons:c,_meta:l}=t;return this._createRegisteredTool(e,r,i,Oh(a),Oh(o),s,c,void 0,l,n)}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a,icons:o,_meta:s}=t,c=this._createRegisteredPrompt(e,r,i,Oh(a),n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),c}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},Eg=class{_uriTemplate;constructor(e,t){this._callbacks=t,this._uriTemplate=typeof e==`string`?new wh(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}};function Dg(e,t){if(e){let e=t;return async(t,n)=>e(t,n)}let n=t;return async(e,t)=>n(t)}let Og={type:`object`,properties:{}};function kg(e){if(e!==void 0)try{return Em(e,`output`)}catch{return}}function Ag(e,t,n){if(t){let r=n;return async(n,i)=>{let a=await km(t,n);if(!a.success)throw new Q(Z.InvalidParams,`Invalid arguments for prompt ${e}: ${a.error}`);return r(a.data,i)}}else{let e=n;return async(t,n)=>e(n)}}function jg(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}let Mg={completion:{values:[],hasMore:!1}};function Ng(e){let t=e;if(t.shape&&typeof t.shape==`object`)return t.shape}function Pg(e){return e?.type===`optional`}function Fg(e){return Pg(e)?e.def?.innerType??e:e}let Ig;function Lg(e,t){return kh(e,t??(Ig??=new pg))}let Rg=gf(void 0).inputSchema,zg=`__isBrowserMcpServer`;function Bg(e){return typeof e==`object`&&!!e&&zg in e&&e[zg]===!0}function Vg(e){return`clientOrigin`in e&&(e.clientOrigin===void 0||typeof e.clientOrigin==`string`)&&(!(`onclientorigin`in e)||e.onclientorigin===void 0||typeof e.onclientorigin==`function`)}function Hg(e){let t;try{t=JSON.parse(e)}catch{t=e}return J(t)?t:{content:[{type:`text`,text:typeof t==`string`?t:e}]}}function Ug(e,t){return new Promise((n,r)=>{t.throwIfAborted();let i=()=>r(t.reason);t.addEventListener(`abort`,i,{once:!0}),Promise.resolve().then(e).then(n,r).finally(()=>t.removeEventListener(`abort`,i))})}function Wg(e){return mf(e.inputSchema)?e.inputSchema:Lg(e.inputSchema)}var Gg=class extends EventTarget{[zg]=!0;mcpServer;native;ownerDocument;tools=new Map;peerOrigin;stopObservingPeerOrigin;registrations=new Set;nativeToolAbortControllers=new Map;nativeBackfilledTools=new Map;pendingTools=new Map;removingNativeTools=new Set;nativeSyncQueue=Promise.resolve();nativeToolChangeQueue=Promise.resolve();nativeToolChangeListener;closed=!1;closePromise;eventHandlers=new Map;eventHandlerListener=e=>{this.eventHandlers.get(e.type)?.call(this,e)};nativeLifecycleListener=e=>{if(this.closed)return;let t=new Event(e.type);`toolName`in e&&Object.defineProperty(t,"toolName",{enumerable:!0,value:e.toolName}),this.dispatchEvent(t)};constructor(e,t={}){super();let{native:n,...r}=t;!n&&!globalThis.document?.modelContext&&Jd(),this.mcpServer=new Tg(e,{...r,capabilities:ph(r.capabilities??{},{tools:{listChanged:!0},resources:{listChanged:!0},prompts:{listChanged:!0}})}),this.native=n??globalThis.document?.modelContext,this.ownerDocument=globalThis.document??null,this.nativeToolChangeListener=()=>{this.closed||(this.nativeToolChangeQueue=this.nativeToolChangeQueue.then(async()=>{try{await this.syncNativeTools()}catch(e){console.warn(`[BrowserMcpServer] Native WebMCP tool reconciliation failed:`,e)}await this.notifyProducerToolsChanged()}))},this.native?.addEventListener(`toolchange`,this.nativeToolChangeListener),this.native?.addEventListener(`toolactivated`,this.nativeLifecycleListener),this.native?.addEventListener(`toolcancel`,this.nativeLifecycleListener)}getEventHandler(e){return this.eventHandlers.get(e)??null}setEventHandler(e,t){typeof t==`function`?(this.eventHandlers.has(e)||super.addEventListener(e,this.eventHandlerListener),this.eventHandlers.set(e,t)):this.eventHandlers.delete(e)&&super.removeEventListener(e,this.eventHandlerListener)}get ontoolchange(){return this.getEventHandler(`toolchange`)}set ontoolchange(e){this.setEventHandler(`toolchange`,e)}get ontoolactivated(){return this.getEventHandler(`toolactivated`)}set ontoolactivated(e){this.setEventHandler(`toolactivated`,e)}get ontoolcancel(){return this.getEventHandler(`toolcancel`)}set ontoolcancel(e){this.setEventHandler(`toolcancel`,e)}async notifyProducerToolsChanged(){this.closed||(await new Promise(e=>setTimeout(e,0)),this.closed||this.dispatchEvent(new Event(`toolchange`)))}async registerNativeToolMirror(e,t,n,r,i){let a=this.native;if(!a)return;let o=n.signal?AbortSignal.any([n.signal,i.signal]):i.signal,s={name:e.name,description:e.description,execute:r};if(e.title!==void 0&&(s.title=e.title),t.registeredInputSchema!==void 0){let e=JSON.parse(t.registeredInputSchema);if(!J(e))throw TypeError(`inputSchema must be an object`);s.inputSchema=e}e.annotations&&(s.annotations=e.annotations),this.nativeToolAbortControllers.set(e.name,i);try{await a.registerTool(s,{...n,signal:o})}catch(t){throw i.abort(),this.nativeToolAbortControllers.get(e.name)===i&&this.nativeToolAbortControllers.delete(e.name),t}this.nativeToolAbortControllers.get(e.name)===i&&this.removingNativeTools.delete(e.name)}abortNativeToolMirror(e,t=this.nativeToolAbortControllers.get(e)){!t||this.nativeToolAbortControllers.get(e)!==t||(this.removingNativeTools.add(e),t.abort(),this.nativeToolAbortControllers.delete(e))}registerToolInMcp(e,t,n,r){let i={name:e.name,description:e.description,inputSchema:t.inputSchema};e.title!==void 0&&(i.title=e.title),e.outputSchema!==void 0&&(i.outputSchema=structuredClone(e.outputSchema)),e.annotations&&(i.annotations=e.annotations);let a={description:e.description};if(i.outputSchema!==void 0&&(a.outputSchema=Lg(i.outputSchema)),e.title!==void 0&&(a.title=e.title),e.annotations){let{untrustedContentHint:t,...n}=e.annotations;a.annotations=n}let o;t.inputSchema.type===void 0||t.inputSchema.type===`object`?(a.inputSchema=Wg(t),o=this.mcpServer.registerTool(e.name,a,async(t,r)=>{let i=await n(t,{signal:r.mcpReq.signal});if(dm(i))throw Error(`WebMCP tool "${e.name}" returned input_required. Multi-round tool flows require BrowserMcpServer.mcpServer.registerTool().`);return uf(i)}),o.disable()):console.warn(`[BrowserMcpServer] Tool "${e.name}" remains available through WebMCP but cannot be exposed over MCP because MCP input schemas require an object root.`);let s={item:i,mcpHandle:o};return r?.length&&(s.exposedTo=r),s}registerTool=async(e,t={})=>{let{signal:n,exposedTo:r}=t??{},i={};if(n&&(i.signal=n),r&&(i.exposedTo=[...r]),this.closed)throw $d(`BrowserMcpServer is closed`);if(!J(e))throw TypeError(`registerTool(tool) requires a tool object`);let a=Qd(e);if(this.tools.has(a.name)&&!this.nativeBackfilledTools.has(a.name)||this.pendingTools.has(a.name))throw $d(`Tool already registered: ${a.name}`);let o=gf(a.inputSchema);i.signal?.throwIfAborted();let s=a.execute,c=(e,t)=>Ug(()=>s(e,t),t.signal),l=new AbortController,u=i.exposedTo?.map(e=>URL.parse(e)?.origin??e),d,f=()=>{this.pendingTools.get(a.name)===l&&this.pendingTools.delete(a.name),d&&this.tools.get(a.name)===d?this.removeTool(a.name):(d?.mcpHandle?.remove(),this.abortNativeToolMirror(a.name,l)),d=void 0};i.signal?.addEventListener(`abort`,f,{once:!0}),this.pendingTools.set(a.name,l);try{if(this.nativeBackfilledTools.has(a.name)||(d=this.registerToolInMcp(a,o,c,u)),i.signal?.throwIfAborted(),await this.registerNativeToolMirror(a,o,i,c,l),this.closed)throw $d(`BrowserMcpServer is closed`);i.signal?.throwIfAborted(),this.removeTool(a.name,{skipNative:!0}),d??=this.registerToolInMcp(a,o,c,u),this.tools.set(a.name,d),this.applyToolExposure(),i.signal?.aborted&&(f(),i.signal.throwIfAborted())}catch(e){throw d?.mcpHandle?.remove(),this.abortNativeToolMirror(a.name,l),i.signal?.removeEventListener(`abort`,f),i.signal?.throwIfAborted(),e}finally{this.pendingTools.get(a.name)===l&&this.pendingTools.delete(a.name)}if(i.signal&&(d.abortSignal=i.signal,d.abortListener=f),this.tools.get(a.name)===d&&await this.nativeToolChangeQueue,this.closed)throw $d(`BrowserMcpServer is closed`);i.signal?.throwIfAborted()};removeTool(e,t){let n=this.tools.get(e);n&&(n.abortSignal&&n.abortListener&&n.abortSignal.removeEventListener(`abort`,n.abortListener),this.tools.delete(e),this.nativeBackfilledTools.delete(e),n.mcpHandle?.remove()),t?.skipNative||this.abortNativeToolMirror(e)}syncNativeTools(){let e=this.native,t=this.nativeSyncQueue.then(async()=>{this.closed||!e||await this.backfillNativeStandardTools(e)});return this.nativeSyncQueue=t.then(()=>void 0,()=>void 0),t}async backfillNativeStandardTools(e){let t=this.ownerDocument?.defaultView,n=(await e.getTools()).filter(e=>{if(e.window===t)return!0;if(t?.parent!==t)return!1;let n=e.window;for(;n;){if(n===t)return!0;let e=n.parent;if(e===n)break;n=e}return!1});if(this.closed)return;for(let e of this.removingNativeTools)n.some(n=>n.name===e&&n.window===t)||this.removingNativeTools.delete(e);let r=new Map;for(let e of n){if(r.has(e.name)||this.pendingTools.has(e.name)||this.removingNativeTools.has(e.name))continue;let t;try{t=JSON.parse(tf(e.inputSchema??Rg))}catch{}if(!J(t)){console.warn(`[BrowserMcpServer] Native tool "${e.name}" was not exposed over MCP because its input schema is malformed.`);continue}let n={name:e.name,description:e.description,inputSchema:t};e.title!==void 0&&(n.title=e.title),e.annotations&&(n.annotations=e.annotations),r.set(e.name,{source:e,item:n,fingerprint:JSON.stringify(n)})}for(let[e,t]of this.nativeBackfilledTools){let n=r.get(e);n?.fingerprint===t.fingerprint?this.nativeBackfilledTools.set(e,n):this.removeTool(e,{skipNative:!0})}for(let[t,n]of r){if(this.tools.has(t))continue;let r=async(n,r)=>{let i=this.nativeBackfilledTools.get(t)?.source;if(!i)throw Error(`Native tool not found: ${t}`);try{return Hg(await e.executeTool(i,n,r))}catch(e){throw i.window.closed&&this.nativeToolChangeListener(),e}},i={...n.item,execute:r};try{let e=gf(i.inputSchema);this.tools.set(t,this.registerToolInMcp(i,e,r)),this.nativeBackfilledTools.set(t,n)}catch(e){console.warn(`[BrowserMcpServer] Native tool "${t}" was not exposed over MCP because its schema could not be compiled:`,e)}}this.applyToolExposure()}registerResource(e){if(this.closed)throw $d(`BrowserMcpServer is closed`);let t={...e},n={};t.description!==void 0&&(n.description=t.description),t.mimeType!==void 0&&(n.mimeType=t.mimeType);let r=t.uri.includes(`{`)?new Eg(t.uri,{list:void 0}):void 0,i=r?this.mcpServer.registerResource(t.name,r,n,async(e,n)=>t.read(e,n)):this.mcpServer.registerResource(t.name,t.uri,n,async e=>t.read(e));return this.registrations.add(i),{unregister:()=>{this.registrations.delete(i)&&i.remove()}}}registerPrompt(e){if(this.closed)throw $d(`BrowserMcpServer is closed`);let t={...e};e.argsSchema!==void 0&&(t.argsSchema=structuredClone(e.argsSchema));let n=t.argsSchema===void 0?void 0:Lg(t.argsSchema),r={};t.description!==void 0&&(r.description=t.description),n&&(r.argsSchema=n);let i=this.mcpServer.registerPrompt(t.name,r,async e=>t.get(e??{}));return this.registrations.add(i),{unregister:()=>{this.registrations.delete(i)&&i.remove()}}}listTools(){return structuredClone([...this.tools.values()].map(({item:e})=>e))}async getTools(e){if(this.closed)throw $d(`BrowserMcpServer is closed`);if(!this.native)throw $d(`BrowserMcpServer has no WebMCP context`);return this.native.getTools(e)}async executeTool(...e){if(this.closed)throw $d(`BrowserMcpServer is closed`);if(!this.native)throw $d(`BrowserMcpServer has no WebMCP context`);return this.native.executeTool(...e)}applyToolExposure(){for(let{exposedTo:e,mcpHandle:t}of this.tools.values()){if(!t)continue;let n=!e?.length||this.peerOrigin!==void 0&&this.peerOrigin!==`null`&&e.includes(this.peerOrigin);n!==t.enabled&&(n?t.enable():t.disable())}}observePeerOrigin(e){if(this.stopObservingPeerOrigin?.(),this.stopObservingPeerOrigin=void 0,this.peerOrigin=void 0,this.applyToolExposure(),!Vg(e))return;let t=e;this.peerOrigin=t.clientOrigin,this.applyToolExposure();let n=t.onclientorigin,r=!0,i=e=>{n?.(e),r&&(this.peerOrigin=e,this.applyToolExposure())};t.onclientorigin=i,this.stopObservingPeerOrigin=()=>{r=!1,t.onclientorigin===i&&(t.onclientorigin=n)}}async connect(e){if(this.closed)throw $d(`BrowserMcpServer is closed`);if(this.mcpServer.server.transport)throw $d(`BrowserMcpServer is already connected`);this.observePeerOrigin(e);let t=this.stopObservingPeerOrigin;try{await this.mcpServer.connect(e)}catch(n){throw this.stopObservingPeerOrigin===t&&(t?.(),this.stopObservingPeerOrigin=void 0,this.peerOrigin=void 0,this.applyToolExposure()),this.mcpServer.server.transport===e&&await this.mcpServer.close(),n}}close(){return this.closePromise?this.closePromise:(this.closed=!0,this.stopObservingPeerOrigin?.(),this.stopObservingPeerOrigin=void 0,this.closePromise=(async()=>{this.native?.removeEventListener(`toolchange`,this.nativeToolChangeListener),this.native?.removeEventListener(`toolactivated`,this.nativeLifecycleListener),this.native?.removeEventListener(`toolcancel`,this.nativeLifecycleListener);for(let e of this.nativeToolAbortControllers.keys())this.abortNativeToolMirror(e);for(let e of this.tools.keys())this.removeTool(e);for(let e of this.registrations)e.remove();this.registrations.clear(),this.nativeBackfilledTools.clear(),this.removingNativeTools.clear(),await this.mcpServer.close()})(),this.closePromise)}};let Kg=null;function qg(e){if(window.parent!==window&&e?.iframeServer!==!1)return new fu(e?.iframeServer||{allowedOrigins:[`*`]});if(e?.tabServer===!1)throw Error(`tabServer transport is disabled and iframe transport was not selected`);return new pu(e?.tabServer||{allowedOrigins:[`*`]})}function Jg(e){if(!globalThis.window||!globalThis.document||globalThis.isSecureContext===!1||Kg||Bg(document.modelContext))return;Jd();let t=document.modelContext;if(!t)throw Error(`modelContext is not available`);let n=Object.getOwnPropertyDescriptor(document,`modelContext`);if(n?!n.configurable:!Object.isExtensible(document))return;let r=qg(e?.transport),i=new Gg({name:`${window.location.hostname||`localhost`}-webmcp`,version:`1.0.0`},{native:t});try{Object.defineProperty(document,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:i}),Kg={server:i,transport:r,previousDescriptor:n}}catch(e){throw i.close(),r.close(),e}(async()=>{try{await i.syncNativeTools()}catch(e){console.warn(`[WebModelContext] Native WebMCP tool synchronization failed:`,e)}if(Kg?.server===i)try{await i.connect(r)}catch(e){console.error(`[WebModelContext] Failed to connect MCP transport:`,e),Kg?.server===i&&Yg()}})()}function Yg(){if(!Kg)return;let{server:e,transport:t,previousDescriptor:n}=Kg;Kg=null,e.close(),t.close(),n?Object.defineProperty(document,"modelContext",n):Reflect.deleteProperty(document,`modelContext`)}let Xg=globalThis.window?.__webModelContextOptions;if(Xg?.autoInitialize!==!1)try{Jg(Xg)}catch(e){console.error(`[WebModelContext] Auto-initialization failed:`,e)}return e.cleanupWebModelContext=Yg,e.initializeWebModelContext=Jg,e})({});
|
|
76
|
+
- `)}`,Error(e)}let l=`${s}/$ref`,u=$(e,t,n,r,i,a,o,l,c);if(u.valid||S.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:S.length===0,errors:S}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||S.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&S.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&S.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?Ah(e,h)||S.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&S.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u===`object`||u===`array`?g.some(t=>Ah(e,t))||S.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||S.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),ee!==void 0){let t=`${s}/not`;$(e,ee,n,r,i,a,o,t).valid&&S.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Pe=[];if(te!==void 0){let t=`${s}/anyOf`,l=S.length,u=!1;for(let s=0;s<te.length;s++){let l=te[s],d=Object.create(c),f=$(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);S.push(...f.errors),u||=f.valid,f.valid&&Pe.push(d)}u?S.length=l:S.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(ne!==void 0){let t=`${s}/allOf`,l=S.length,u=!0;for(let s=0;s<ne.length;s++){let l=ne[s],d=Object.create(c),f=$(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);S.push(...f.errors),u&&=f.valid,f.valid&&Pe.push(d)}u?S.length=l:S.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(re!==void 0){let t=`${s}/oneOf`,l=S.length,u=re.filter((s,l)=>{let u=Object.create(c),d=$(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return S.push(...d.errors),d.valid&&Pe.push(u),d.valid}).length;u===1?S.length=l:S.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...Pe),ie!==void 0){let t=`${s}/if`;if($(e,ie,n,r,i,a,o,t,c).valid){if(ae!==void 0){let l=$(e,ae,n,r,i,a,o,`${s}/then`,c);l.valid||S.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(oe!==void 0){let l=$(e,oe,n,r,i,a,o,`${s}/else`,c);l.valid||S.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(_!==void 0)for(let t of _)t in e||S.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(de!==void 0&&t.length<de&&S.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${de} properties.`}),fe!==void 0&&t.length>fe&&S.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${fe} properties.`}),pe!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${jh(s)}`,c=$(s,pe,n,r,i,a,e,t);c.valid||S.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(me!==void 0){let t=`${s}/dependantRequired`;for(let n in me)if(n in e){let r=me[n];for(let i of r)i in e||S.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(he!==void 0)for(let t in he){let l=`${s}/dependentSchemas`;if(t in e){let s=$(e,he[t],n,r,i,a,o,`${l}/${jh(t)}`,c);s.valid||S.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(ge!==void 0){let t=`${s}/dependencies`;for(let s in ge)if(s in e){let c=ge[s];if(Array.isArray(c))for(let n of c)n in e||S.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=$(e,c,n,r,i,a,o,`${t}/${jh(s)}`);l.valid||S.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(ce!==void 0){let t=`${s}/properties`;for(let s in ce){if(!(s in e))continue;let d=`${o}/${jh(s)}`,f=$(e[s],ce[s],n,r,i,a,d,`${t}/${jh(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,S.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&le!==void 0){let t=`${s}/patternProperties`;for(let s in le){let d=new RegExp(s,`u`),f=le[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${jh(p)}`,h=$(e[p],f,n,r,i,a,m,`${t}/${jh(s)}`);h.valid?c[p]=l[p]=!0:(u=i,S.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&v!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${jh(s)}`,f=$(e[s],v,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,S.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&ue!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${jh(s)}`,u=$(e[s],ue,n,r,i,a,l,t);u.valid?c[s]=!0:S.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){Ce!==void 0&&e.length>Ce&&S.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${Ce}).`}),Se!==void 0&&e.length<Se&&S.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${Se}).`});let t=e.length,l=0,u=!1;if(_e!==void 0){let d=`${s}/prefixItems`,f=Math.min(_e.length,t);for(;l<f;l++){let t=$(e[l],_e[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,S.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(ve!==void 0){let d=`${s}/items`;if(Array.isArray(ve)){let s=Math.min(ve.length,t);for(;l<s;l++){let t=$(e[l],ve[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,S.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=$(e[l],ve,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,S.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&ye!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=$(e[l],ye,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,S.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(xe!==void 0)if(t===0&&y===void 0)S.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(y!==void 0&&t<y)S.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${y}).`});else{let l=`${s}/contains`,u=S.length,d=0;for(let s=0;s<t;s++){let t=$(e[s],xe,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):S.push(...t.errors)}d>=(y||0)&&(S.length=u),y===void 0&&b===void 0&&d===0?S.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):y!==void 0&&d<y?S.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${y} items matching schema. Only ${d} items were found.`}):b!==void 0&&d>b&&S.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${b} items matching schema. ${d} items were found.`})}if(!u&&be!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=$(e[l],be,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||S.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(we)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&Ah(r,t))&&(S.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(Te!==void 0&&(Ee===!0&&e<=Te||e<Te)&&S.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${Ee?`or equal to `:``} ${Te}.`}),x!==void 0&&(De===!0&&e>=x||e>x)&&S.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${De?`or equal to `:``} ${x}.`})):(Te!==void 0&&e<Te&&S.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${Te}.`}),x!==void 0&&e>x&&S.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${x}.`}),Ee!==void 0&&e<=Ee&&S.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${Ee}.`}),De!==void 0&&e>=De&&S.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${De}.`})),Oe!==void 0){let t=e%Oe;Math.abs(0-t)>=1.1920929e-7&&Math.abs(Oe-t)>=1.1920929e-7&&S.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${Oe}.`})}}else if(u===`string`){let t=ke===void 0&&Ae===void 0?0:dg(e);ke!==void 0&&t<ke&&S.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${ke}).`}),Ae!==void 0&&t>Ae&&S.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${Ae}).`}),je!==void 0&&!new RegExp(je,`u`).test(e)&&S.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),se!==void 0&&eg[se]&&!eg[se](e)&&S.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${se}".`})}return{valid:S.length===0,errors:S}}var fg=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Lh(e)}validate(e){return $(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Lh(e,this.lookup)}},pg=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=Tf(e,`pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.`);return t===`draft-7`?`7`:t}getValidator(e){let t=new fg(e,this.draft??this._draftFor(e),this.shortcircuit);return e=>{let n=t.validate(e);return n.valid?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:n.errors.map(e=>`${e.instanceLocation}: ${e.error}`).join(`; `)}}}};let mg=Symbol.for(`mcp.completable`);function hg(e){return!!e&&typeof e==`object`&&mg in e}function gg(e){return e[mg]?.complete}function _g(e){if(e?.maxRounds!==void 0&&(!Number.isInteger(e.maxRounds)||e.maxRounds<1))throw RangeError(`inputRequired.maxRounds must be a positive integer (got ${e.maxRounds})`);if(e?.roundTimeoutMs!==void 0&&(!Number.isFinite(e.roundTimeoutMs)||e.roundTimeoutMs<=0))throw RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${e.roundTimeoutMs})`);return{maxRounds:e?.maxRounds??8,roundTimeoutMs:e?.roundTimeoutMs??6e5,legacyShim:e?.legacyShim??!0}}function vg(e,t,n){if(typeof n!=`object`||!n||typeof n.method!=`string`)throw new Q(Z.InternalError,`Handler for ${e} returned an invalid input request '${t}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);let r=n,i=jf(r);if(i===void 0)throw new Q(Z.InternalError,`Handler for ${e} returned an input request '${t}' of kind '${r.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded:r,required:i}}function yg(){let e=globalThis.crypto;if(e?.randomUUID!==void 0)return e.randomUUID();let t=new Uint8Array(16);e.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(e=>e.toString(16).padStart(2,`0`)).join(``);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function bg(e,t){if(e===`tools/call`)return{content:[{type:`text`,text:t}],isError:!0};throw new Q(Z.InternalError,t)}var xg=class{constructor(e){this._host=e}async fulfill(e,t,n,r,i){let{maxRounds:a,roundTimeoutMs:o}=this._host,s=r.mcpReq.signal,c=i,l=0;for(;;){if(l+=1,l>a)return bg(e,Ym(e,a));let i=c.inputRequests,u=i!=null&&Object.keys(i).length>0,d=typeof c.requestState==`string`?c.requestState:void 0;if(!u&&d===void 0)throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);let f;if(u){let t=this._host.resolvedClientCapabilities(r),n=[];for(let[r,a]of Object.entries(i)){let{embedded:i,required:o}=vg(e,r,a);if(i.method!==`roots/list`&&i.params===void 0)throw new Q(Z.InternalError,`Handler for ${e} returned an input request '${r}' of kind '${i.method}' without params`);if(Mf(o,t)!==void 0)return bg(e,`Cannot request input '${r}' (${i.method}): the client on this 2025-era connection did not declare the required capability${t===void 0?` (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)`:``}`);n.push([r,i])}let a=Zm(s);try{let e={relatedRequestId:r.mcpReq.id,timeout:o,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:a.signal},t=await Promise.all(n.map(async([t,n])=>{try{return[t,await this._dispatchLeg(n,e)]}catch(e){throw a.abort(e),e}}));f=Object.fromEntries(t)}catch(t){if(s.aborted)throw t;return bg(e,`Fulfilling input required by '${e}' failed: ${t instanceof Error?t.message:String(t)}`)}finally{a.dispose()}}else await Xm(250,s);let p={...r,mcpReq:{...r.mcpReq,inputResponses:f,droppedInputResponseKeys:void 0,requestState:ch(d)}};if(d!==void 0){let t=await this._host.verifyRequestState(d,p,e);t!==void 0&&(p=uh(p,t))}let m=await t(n,p);if(!dm(m))return m;c=m}}async _dispatchLeg(e,t){switch(e.method){case`elicitation/create`:{let n=e.params;return n.mode===`url`&&n.elicitationId===void 0&&(n={...n,elicitationId:yg()}),await this._host.sendElicitation(n,t)}case`sampling/createMessage`:return await this._host.sendSampling(e.params,t);case`roots/list`:return await this._host.listRoots(e.params,t)}}};let Sg=new Set([`tools/call`,`prompts/get`,`resources/read`]);var Cg=class extends dh{_clientCapabilities;_clientVersion;_capabilities;_instructions;_jsonSchemaValidator;_cacheHints;_requestStateVerify;_inputRequiredServing;_legacyShim;_legacyInputRequiredShim(){return this._legacyShim??=new xg({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:e=>this._inputRequestCapabilityView(e),verifyRequestState:(e,t,n)=>this._verifyRequestState(e,t,n),sendElicitation:(e,t)=>this._sendElicitationLeg(e,t,{validateAcceptedContent:!1}),sendSampling:(e,t)=>this.createMessage(e,t),listRoots:(e,t)=>this.listRoots(e,t)})}oninitialized;constructor(e,t){if(super(t),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new pg,this._requestStateVerify=t?.requestState?.verify,this._inputRequiredServing=_g(t?.inputRequired),t?.cacheHints!==void 0){for(let[e,n]of Object.entries(t.cacheHints))n!==void 0&&bp(n,`cacheHints['${e}']`);this._cacheHints=t.cacheHints}this.setRequestHandler(`initialize`,e=>this._oninitialize(e)),this.setNotificationHandler(`notifications/initialized`,()=>this.oninitialized?.()),Ff(this._supportedProtocolVersions).length>0&&this.setRequestHandler(`server/discover`,()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}_registerLoggingHandler(){this.setRequestHandler(`logging/setLevel`,async(e,t)=>{let n=t.sessionId||t.http?.req?.headers.get(`mcp-session-id`)||void 0,{level:r}=e.params,i=xm(Vc,r);return i.success&&this._loggingLevels.set(n,i.data),{}})}buildContext(e,t){let n=e.http||t?.request||t?.closeSSEStream||t?.closeStandaloneSSEStream;return{...e,mcpReq:{...e.mcpReq,log:(t,n,r)=>{if(!this._capabilities.logging)return Promise.resolve();let i;if(this._servedModernEra()){if(i=e.mcpReq.envelope?.[Jo],i===void 0)return Promise.resolve()}else i=this._loggingLevels.get(e.sessionId)??this._loggingLevels.get(void 0);return i!==void 0&&this.LOG_LEVEL_SEVERITY.get(t)<this.LOG_LEVEL_SEVERITY.get(i)?Promise.resolve():e.mcpReq.notify({method:`notifications/message`,params:{level:t,data:n,logger:r}})},elicitInput:(e,t)=>this.elicitInput(e,t),requestSampling:(e,t)=>this.createMessage(e,t)},http:n?{...e.http,req:t?.request,closeSSE:t?.closeSSEStream,closeStandaloneSSE:t?.closeStandaloneSSEStream}:void 0}}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Vc.options.map((e,t)=>[e,t]));isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1};registerCapabilities(e){if(this.transport)throw new X(Y.AlreadyConnected,`Cannot register capabilities after connecting to transport`);let t=!!this._capabilities.logging;this._capabilities=ph(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(e,t){if(e!==`tools/call`){let n=this._cacheHints?.[e],r=Sg.has(e);return n===void 0&&!r?async(n,r)=>{let i=await t(n,r);if(dm(i))throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return i}:async(i,a)=>{let o=r?await this._invokeInputRequiredCapableHandler(e,t,i,a):await t(i,a);if(dm(o)){if(!r)throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return o}return n===void 0?o:gp(o,n)}}return async(e,n)=>{let r=tm(this._negotiatedProtocolVersion),i=r.validateRequest(`tools/call`,e);if(!i.ok)throw new Q(i.reason===`not-in-era`?Z.InternalError:Z.InvalidParams,i.reason===`not-in-era`?`No wire schema for tools/call in the resolved era`:`Invalid tools/call request: ${i.message}`);let a=await this._invokeInputRequiredCapableHandler(`tools/call`,t,e,n);if(dm(a))return a;let o=Rf(a),s=r.validateResult(`tools/call`,o);if(!s.ok)throw new Q(s.reason===`not-in-era`?Z.InternalError:Z.InvalidParams,s.reason===`not-in-era`?`No wire schema for tools/call in the resolved era`:`Invalid tools/call result: ${s.message}`);return s.value}}_servedModernEra(){return this._negotiatedProtocolVersion!==void 0&&Nf(this._negotiatedProtocolVersion)}async _invokeInputRequiredCapableHandler(e,t,n,r){let i=this._servedModernEra(),a=r.mcpReq.requestState();if(a!==void 0&&typeof a!=`string`)throw new Q(Z.InvalidParams,`Invalid or expired requestState`,{reason:`invalid_request_state`});let o=r;if(typeof a==`string`){let t=await this._verifyRequestState(a,r,e);t!==void 0&&(o=uh(r,t))}let s;try{s=await t(n,o)}catch(e){throw e instanceof Q&&e.code===Z.UrlElicitationRequired&&i?new Q(Z.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`):e}if(!dm(s))return s;if(!i){if(!this._inputRequiredServing.legacyShim)throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??`2025-11-25`}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(e,t,n,o,s)}let c=s.inputRequests,l=c!=null&&Object.keys(c).length>0,u=typeof s.requestState==`string`;if(!l&&!u)throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(l){let t=this._inputRequestCapabilityView(r);for(let[n,r]of Object.entries(c)){let{embedded:i,required:a}=vg(e,n,r),o=Mf(a,t);if(o!==void 0)throw new wp({requiredCapabilities:o},`Cannot request input '${n}' (${i.method}): the request's client capabilities do not declare the required capability`)}}return s}async _verifyRequestState(e,t,n){if(this._requestStateVerify!==void 0)try{return await this._requestStateVerify(e,t)}catch(e){throw this.onerror?.(Error(`requestState verification rejected ${n}: ${e instanceof Error?e.message:String(e)}`)),new Q(Z.InvalidParams,`Invalid or expired requestState`,{reason:`invalid_request_state`})}}_inputRequestCapabilityView(e){return this._servedModernEra()?e.mcpReq.envelope?.[qo]:this._clientCapabilities}_assertPushApiInServedEra(e){if(this._servedModernEra())throw new X(Y.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${e}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method:e,era:`2026-07-28`})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw new X(Y.CapabilityNotSupported,`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw new X(Y.CapabilityNotSupported,`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw new X(Y.CapabilityNotSupported,`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw new X(Y.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw new X(Y.CapabilityNotSupported,`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw new X(Y.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw new X(Y.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw new X(Y.CapabilityNotSupported,`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){switch(e){case`completion/complete`:if(!this._capabilities.completions)throw new X(Y.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw new X(Y.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw new X(Y.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw new X(Y.CapabilityNotSupported,`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw new X(Y.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case`ping`:case`initialize`:break}}async _oninitialize(e){let t=e.params.protocolVersion;this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo;let n=Pf(this._supportedProtocolVersions),r=n.includes(t)?t:n[0]??`2025-11-25`;return this._negotiatedProtocolVersion=r,this.transport?.setProtocolVersion?.(r),{protocolVersion:r,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:Ff(this._supportedProtocolVersions),capabilities:wg(this.getCapabilities()),...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(e,t){return this._wireCodec().projectCallToolResult(e,t)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra(`ping`),this.request({method:`ping`})}async createMessage(e,t){if(this._assertPushApiInServedEra(`sampling/createMessage`),(e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new X(Y.CapabilityNotSupported,`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages.at(-1),n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages.at(-2):void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw new Q(Z.InvalidParams,`The last message must contain only tool_result content if any is present`);if(!o)throw new Q(Z.InvalidParams,`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw new Q(Z.InvalidParams,`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}let n=!!(e.tools||e.toolChoice),r=await this.request({method:`sampling/createMessage`,params:e},t),i=this._wireCodec().samplingResultVariant(n,r);if(!i.ok)throw new X(Y.InvalidResult,`Invalid sampling/createMessage result: ${i.reason===`invalid`?i.message:i.reason}`);return i.value}async elicitInput(e,t){switch(this._assertPushApiInServedEra(`elicitation/create`),e.mode??`form`){case`url`:if(!this._clientCapabilities?.elicitation?.url)throw new X(Y.CapabilityNotSupported,`Client does not support url elicitation.`);break;case`form`:if(!this._clientCapabilities?.elicitation?.form)throw new X(Y.CapabilityNotSupported,`Client does not support form elicitation.`);break}return this._sendElicitationLeg(e,t)}async _sendElicitationLeg(e,t,n){let r=e.mode??`form`,i=n?.validateAcceptedContent??!0;switch(r){case`url`:{let n=e;return this.request({method:`elicitation/create`,params:n},t)}case`form`:{let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},t);if(i&&r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new Q(Z.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof Q?e:new Q(Z.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new X(Y.CapabilityNotSupported,`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this._assertPushApiInServedEra(`roots/list`),this.request({method:`roots/list`,params:e},t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};function wg(e){return{...e}}var Tg=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_toolInputSchemaJson={};toolInputSchemaJson(e){let t=this._registeredTools[e];if(!(t===void 0||!t.enabled)){if(Object.hasOwn(this._toolInputSchemaJson,e))return this._toolInputSchemaJson[e];if(t.inputSchema===void 0)return Og;try{let n=Em(t.inputSchema,`input`);return this._toolInputSchemaJson[e]=n,n}catch{return}}}constructor(e,t){this.server=new Cg(e,t),t?.capabilities?.tools&&this.setToolRequestHandlers(),t?.capabilities?.resources&&this.setResourceRequestHandlers(),t?.capabilities?.prompts&&this.setPromptRequestHandlers()}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(`tools/list`),this.server.assertCanSetRequestHandler(`tools/call`),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler(`tools/list`,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?Em(t.inputSchema,`input`):Og,annotations:t.annotations,icons:t.icons,execution:t.execution,_meta:t._meta};return t.outputSchema&&(n.outputSchema=Em(t.outputSchema,`output`)),n})})),this.server.setRequestHandler(`tools/call`,async(e,t)=>{let n=this._registeredTools[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Tool ${e.params.name} disabled`);try{let r=await this.validateToolInput(n,e.params.arguments,e.params.name),i=await this.executeToolHandler(n,r,t);return await this.validateToolOutput(n,i,e.params.name),dm(i)?i:this.server.projectCallToolResult(i,n.outputSchemaJson)}catch(e){if(e instanceof Q&&e.code===Z.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await km(e.inputSchema,t??{});if(!r.success)throw new Q(Z.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${r.error}`);return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||dm(t)||t.isError)return;if(t.structuredContent===void 0)throw new Q(Z.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await km(e.outputSchema,t.structuredContent);if(!r.success)throw new Q(Z.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${r.error}`)}async executeToolHandler(e,t,n){return e.executor(t,n)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(`completion/complete`),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(`completion/complete`,async e=>{switch(e.params.ref.type){case`ref/prompt`:return fm(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return pm(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Q(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Mg;let r=Fg(Ng(n.argsSchema)?.[e.params.argument.name]);if(!hg(r))return Mg;let i=gg(r);return i?jg(await i(e.params.argument.value,e.params.context)):Mg}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return Mg;throw new Q(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?jg(await r(e.params.argument.value,e.params.context)):Mg}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(`resources/list`),this.server.assertCanSetRequestHandler(`resources/templates/list`),this.server.assertCanSetRequestHandler(`resources/read`),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler(`resources/list`,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(`resources/templates/list`,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(`resources/read`,async(e,t)=>{let n;try{n=new URL(e.params.uri)}catch{throw new Q(Z.InvalidParams,`Resource URI ${e.params.uri} is invalid`,{uri:e.params.uri,reason:`invalid_uri`})}let r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new Q(Z.InvalidParams,`Resource ${n} disabled`);return gp(await r.readCallback(n,t),r.cacheHint)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return gp(await e.readCallback(n,r,t),e.cacheHint)}throw new xp(e.params.uri)}),!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(`prompts/list`),this.server.assertCanSetRequestHandler(`prompts/get`),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler(`prompts/list`,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Fm(t.argsSchema):void 0,icons:t.icons,_meta:t._meta}))})),this.server.setRequestHandler(`prompts/get`,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} disabled`);return n.handler(e.params.arguments,t)}),!0)}registerResource(e,t,n,r){let i=n.cacheHint,a=n;if(i!==void 0){bp(i,`resource ${e}`);let t={...n};delete t.cacheHint,a=t}if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,n.title,t,a,r);return i!==void 0&&(o.cacheHint=i),this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,t,a,r);return i!==void 0&&(o.cacheHint=i),this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i,a,o){let s=r,c=i,l={title:t,description:n,argsSchema:r,icons:a,_meta:o,handler:Ag(e,r,i),enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.icons!==void 0&&(l.icons=t.icons),t._meta!==void 0&&(l._meta=t._meta);let n=!1;t.argsSchema!==void 0&&(l.argsSchema=t.argsSchema,s=t.argsSchema,n=!0),t.callback!==void 0&&(c=t.callback,n=!0),n&&(l.handler=Ag(e,s,c)),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=l,r){let e=Ng(r);e&&Object.values(e).some(e=>hg(Fg(e)))&&this.setCompletionRequestHandler()}return l}_createRegisteredTool(e,t,n,r,i,a,o,s,c,l){if(bh(e),r!==void 0)try{let t=Em(r,`input`);this._toolInputSchemaJson[e]=t;let n=_m(t);n.valid||console.warn(`[mcp-sdk] tool '${e}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${n.reason}`)}catch{}let u=l,d={title:t,description:n,inputSchema:r,outputSchema:i,outputSchemaJson:kg(i),annotations:a,icons:o,execution:s,_meta:c,handler:l,executor:Dg(r,l),enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&bh(t.name),delete this._registeredTools[e],delete this._toolInputSchemaJson[e],t.name&&(delete this._toolInputSchemaJson[t.name],this._registeredTools[t.name]=d,e=t.name)),t.title!==void 0&&(d.title=t.title),t.description!==void 0&&(d.description=t.description);let n=!1;t.paramsSchema!==void 0&&(d.inputSchema=t.paramsSchema,delete this._toolInputSchemaJson[e],n=!0),t.callback!==void 0&&(d.handler=t.callback,u=t.callback,n=!0),n&&(d.executor=Dg(d.inputSchema,u)),t.outputSchema!==void 0&&(d.outputSchema=t.outputSchema,d.outputSchemaJson=kg(t.outputSchema)),t.annotations!==void 0&&(d.annotations=t.annotations),t.icons!==void 0&&(d.icons=t.icons),t._meta!==void 0&&(d._meta=t._meta),t.enabled!==void 0&&(d.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,icons:c,_meta:l}=t;return this._createRegisteredTool(e,r,i,Oh(a),Oh(o),s,c,void 0,l,n)}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a,icons:o,_meta:s}=t,c=this._createRegisteredPrompt(e,r,i,Oh(a),n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),c}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},Eg=class{_uriTemplate;constructor(e,t){this._callbacks=t,this._uriTemplate=typeof e==`string`?new wh(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}};function Dg(e,t){if(e){let e=t;return async(t,n)=>e(t,n)}let n=t;return async(e,t)=>n(t)}let Og={type:`object`,properties:{}};function kg(e){if(e!==void 0)try{return Em(e,`output`)}catch{return}}function Ag(e,t,n){if(t){let r=n;return async(n,i)=>{let a=await km(t,n);if(!a.success)throw new Q(Z.InvalidParams,`Invalid arguments for prompt ${e}: ${a.error}`);return r(a.data,i)}}else{let e=n;return async(t,n)=>e(n)}}function jg(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}let Mg={completion:{values:[],hasMore:!1}};function Ng(e){let t=e;if(t.shape&&typeof t.shape==`object`)return t.shape}function Pg(e){return e?.type===`optional`}function Fg(e){return Pg(e)?e.def?.innerType??e:e}let Ig;function Lg(e,t){return kh(e,t??(Ig??=new pg))}let Rg=gf(void 0).inputSchema,zg=`__isBrowserMcpServer`;function Bg(e){return typeof e==`object`&&!!e&&zg in e&&e[zg]===!0}function Vg(e){return`clientOrigin`in e&&(e.clientOrigin===void 0||typeof e.clientOrigin==`string`)&&(!(`onclientorigin`in e)||e.onclientorigin===void 0||typeof e.onclientorigin==`function`)}function Hg(e){let t;try{t=JSON.parse(e)}catch{t=e}return J(t)?t:{content:[{type:`text`,text:typeof t==`string`?t:e}]}}function Ug(e,t){return new Promise((n,r)=>{t.throwIfAborted();let i=()=>r(t.reason);t.addEventListener(`abort`,i,{once:!0}),Promise.resolve().then(e).then(n,r).finally(()=>t.removeEventListener(`abort`,i))})}function Wg(e){return mf(e.inputSchema)?e.inputSchema:Lg(e.inputSchema)}var Gg=class extends EventTarget{[zg]=!0;mcpServer;native;ownerDocument;tools=new Map;peerOrigin;stopObservingPeerOrigin;registrations=new Set;nativeToolAbortControllers=new Map;nativeBackfilledTools=new Map;pendingTools=new Map;removingNativeTools=new Set;nativeSyncQueue=Promise.resolve();nativeToolChangeQueue=Promise.resolve();nativeToolChangeListener;closed=!1;closePromise;eventHandlers=new Map;eventHandlerListener=e=>{this.eventHandlers.get(e.type)?.call(this,e)};nativeLifecycleListener=e=>{if(this.closed)return;let t=new Event(e.type);`toolName`in e&&Object.defineProperty(t,"toolName",{enumerable:!0,value:e.toolName}),this.dispatchEvent(t)};constructor(e,t={}){super();let{native:n,...r}=t;!n&&!globalThis.document?.modelContext&&Jd(),this.mcpServer=new Tg(e,{...r,capabilities:ph(r.capabilities??{},{tools:{listChanged:!0},resources:{listChanged:!0},prompts:{listChanged:!0}})}),this.native=n??globalThis.document?.modelContext,this.ownerDocument=globalThis.document??null,this.nativeToolChangeListener=()=>{this.closed||(this.nativeToolChangeQueue=this.nativeToolChangeQueue.then(async()=>{try{await this.syncNativeTools()}catch(e){console.warn(`[BrowserMcpServer] Native WebMCP tool reconciliation failed:`,e)}await this.notifyProducerToolsChanged()}))},this.native?.addEventListener(`toolchange`,this.nativeToolChangeListener),this.native?.addEventListener(`toolactivated`,this.nativeLifecycleListener),this.native?.addEventListener(`toolcancel`,this.nativeLifecycleListener)}getEventHandler(e){return this.eventHandlers.get(e)??null}setEventHandler(e,t){typeof t==`function`?(this.eventHandlers.has(e)||super.addEventListener(e,this.eventHandlerListener),this.eventHandlers.set(e,t)):this.eventHandlers.delete(e)&&super.removeEventListener(e,this.eventHandlerListener)}get ontoolchange(){return this.getEventHandler(`toolchange`)}set ontoolchange(e){this.setEventHandler(`toolchange`,e)}get ontoolactivated(){return this.getEventHandler(`toolactivated`)}set ontoolactivated(e){this.setEventHandler(`toolactivated`,e)}get ontoolcancel(){return this.getEventHandler(`toolcancel`)}set ontoolcancel(e){this.setEventHandler(`toolcancel`,e)}async notifyProducerToolsChanged(){this.closed||(await new Promise(e=>setTimeout(e,0)),this.closed||this.dispatchEvent(new Event(`toolchange`)))}async registerNativeToolMirror(e,t,n,r,i){let a=this.native;if(!a)return;let o=n.signal?AbortSignal.any([n.signal,i.signal]):i.signal,s={name:e.name,description:e.description,execute:r};if(e.title!==void 0&&(s.title=e.title),t.registeredInputSchema!==void 0){let e=JSON.parse(t.registeredInputSchema);if(!J(e))throw TypeError(`inputSchema must be an object`);s.inputSchema=e}e.annotations&&(s.annotations=e.annotations),this.nativeToolAbortControllers.set(e.name,i);try{await a.registerTool(s,{...n,signal:o})}catch(t){if(i.abort(),this.nativeToolAbortControllers.get(e.name)===i&&this.nativeToolAbortControllers.delete(e.name),t instanceof DOMException&&t.name===`NotAllowedError`){console.warn(`[BrowserMcpServer] Tool "${e.name}" is available over MCP only: ${t.message}. Grant allow="tools" on the iframe to expose it to WebMCP.`);return}throw t}this.nativeToolAbortControllers.get(e.name)===i&&this.removingNativeTools.delete(e.name)}abortNativeToolMirror(e,t=this.nativeToolAbortControllers.get(e)){!t||this.nativeToolAbortControllers.get(e)!==t||(this.removingNativeTools.add(e),t.abort(),this.nativeToolAbortControllers.delete(e))}registerToolInMcp(e,t,n,r){let i={name:e.name,description:e.description,inputSchema:t.inputSchema};e.title!==void 0&&(i.title=e.title),e.outputSchema!==void 0&&(i.outputSchema=structuredClone(e.outputSchema)),e.annotations&&(i.annotations=e.annotations);let a={description:e.description};if(i.outputSchema!==void 0&&(a.outputSchema=Lg(i.outputSchema)),e.title!==void 0&&(a.title=e.title),e.annotations){let{untrustedContentHint:t,...n}=e.annotations;a.annotations=n}let o;t.inputSchema.type===void 0||t.inputSchema.type===`object`?(a.inputSchema=Wg(t),o=this.mcpServer.registerTool(e.name,a,async(t,r)=>{let i=await n(t,{signal:r.mcpReq.signal});if(dm(i))throw Error(`WebMCP tool "${e.name}" returned input_required. Multi-round tool flows require BrowserMcpServer.mcpServer.registerTool().`);return uf(i)}),o.disable()):console.warn(`[BrowserMcpServer] Tool "${e.name}" remains available through WebMCP but cannot be exposed over MCP because MCP input schemas require an object root.`);let s={item:i,mcpHandle:o};return r?.length&&(s.exposedTo=r),s}registerTool=async(e,t={})=>{let{signal:n,exposedTo:r}=t??{},i={};if(n&&(i.signal=n),r&&(i.exposedTo=[...r]),this.closed)throw $d(`BrowserMcpServer is closed`);if(!J(e))throw TypeError(`registerTool(tool) requires a tool object`);let a=Qd(e);if(this.tools.has(a.name)&&!this.nativeBackfilledTools.has(a.name)||this.pendingTools.has(a.name))throw $d(`Tool already registered: ${a.name}`);let o=gf(a.inputSchema);i.signal?.throwIfAborted();let s=a.execute,c=(e,t)=>Ug(()=>s(e,t),t.signal),l=new AbortController,u=i.exposedTo?.map(e=>URL.parse(e)?.origin??e),d,f=()=>{this.pendingTools.get(a.name)===l&&this.pendingTools.delete(a.name),d&&this.tools.get(a.name)===d?this.removeTool(a.name):(d?.mcpHandle?.remove(),this.abortNativeToolMirror(a.name,l)),d=void 0};i.signal?.addEventListener(`abort`,f,{once:!0}),this.pendingTools.set(a.name,l);try{if(this.nativeBackfilledTools.has(a.name)||(d=this.registerToolInMcp(a,o,c,u)),i.signal?.throwIfAborted(),await this.registerNativeToolMirror(a,o,i,c,l),this.closed)throw $d(`BrowserMcpServer is closed`);i.signal?.throwIfAborted(),this.removeTool(a.name,{skipNative:!0}),d??=this.registerToolInMcp(a,o,c,u),this.tools.set(a.name,d),this.applyToolExposure(),i.signal?.aborted&&(f(),i.signal.throwIfAborted())}catch(e){throw d?.mcpHandle?.remove(),this.abortNativeToolMirror(a.name,l),i.signal?.removeEventListener(`abort`,f),i.signal?.throwIfAborted(),e}finally{this.pendingTools.get(a.name)===l&&this.pendingTools.delete(a.name)}if(i.signal&&(d.abortSignal=i.signal,d.abortListener=f),this.tools.get(a.name)===d&&await this.nativeToolChangeQueue,this.closed)throw $d(`BrowserMcpServer is closed`);i.signal?.throwIfAborted()};removeTool(e,t){let n=this.tools.get(e);n&&(n.abortSignal&&n.abortListener&&n.abortSignal.removeEventListener(`abort`,n.abortListener),this.tools.delete(e),this.nativeBackfilledTools.delete(e),n.mcpHandle?.remove()),t?.skipNative||this.abortNativeToolMirror(e)}syncNativeTools(){let e=this.native,t=this.nativeSyncQueue.then(async()=>{this.closed||!e||await this.backfillNativeStandardTools(e)});return this.nativeSyncQueue=t.then(()=>void 0,()=>void 0),t}async backfillNativeStandardTools(e){let t=this.ownerDocument?.defaultView,n=(await e.getTools()).filter(e=>{if(e.window===t)return!0;if(t?.parent!==t)return!1;let n=e.window;for(;n;){if(n===t)return!0;let e=n.parent;if(e===n)break;n=e}return!1});if(this.closed)return;for(let e of this.removingNativeTools)n.some(n=>n.name===e&&n.window===t)||this.removingNativeTools.delete(e);let r=new Map;for(let e of n){if(r.has(e.name)||this.pendingTools.has(e.name)||this.removingNativeTools.has(e.name))continue;let t;try{t=JSON.parse(tf(e.inputSchema??Rg))}catch{}if(!J(t)){console.warn(`[BrowserMcpServer] Native tool "${e.name}" was not exposed over MCP because its input schema is malformed.`);continue}let n={name:e.name,description:e.description,inputSchema:t};e.title!==void 0&&(n.title=e.title),e.annotations&&(n.annotations=e.annotations),r.set(e.name,{source:e,item:n,fingerprint:JSON.stringify(n)})}for(let[e,t]of this.nativeBackfilledTools){let n=r.get(e);n?.fingerprint===t.fingerprint?this.nativeBackfilledTools.set(e,n):this.removeTool(e,{skipNative:!0})}for(let[t,n]of r){if(this.tools.has(t))continue;let r=async(n,r)=>{let i=this.nativeBackfilledTools.get(t)?.source;if(!i)throw Error(`Native tool not found: ${t}`);try{return Hg(await e.executeTool(i,n,r))}catch(e){throw i.window.closed&&this.nativeToolChangeListener(),e}},i={...n.item,execute:r};try{let e=gf(i.inputSchema);this.tools.set(t,this.registerToolInMcp(i,e,r)),this.nativeBackfilledTools.set(t,n)}catch(e){console.warn(`[BrowserMcpServer] Native tool "${t}" was not exposed over MCP because its schema could not be compiled:`,e)}}this.applyToolExposure()}registerResource(e){if(this.closed)throw $d(`BrowserMcpServer is closed`);let t={...e},n={};t.description!==void 0&&(n.description=t.description),t.mimeType!==void 0&&(n.mimeType=t.mimeType);let r=t.uri.includes(`{`)?new Eg(t.uri,{list:void 0}):void 0,i=r?this.mcpServer.registerResource(t.name,r,n,async(e,n)=>t.read(e,n)):this.mcpServer.registerResource(t.name,t.uri,n,async e=>t.read(e));return this.registrations.add(i),{unregister:()=>{this.registrations.delete(i)&&i.remove()}}}registerPrompt(e){if(this.closed)throw $d(`BrowserMcpServer is closed`);let t={...e};e.argsSchema!==void 0&&(t.argsSchema=structuredClone(e.argsSchema));let n=t.argsSchema===void 0?void 0:Lg(t.argsSchema),r={};t.description!==void 0&&(r.description=t.description),n&&(r.argsSchema=n);let i=this.mcpServer.registerPrompt(t.name,r,async e=>t.get(e??{}));return this.registrations.add(i),{unregister:()=>{this.registrations.delete(i)&&i.remove()}}}listTools(){return structuredClone([...this.tools.values()].map(({item:e})=>e))}async getTools(e){if(this.closed)throw $d(`BrowserMcpServer is closed`);if(!this.native)throw $d(`BrowserMcpServer has no WebMCP context`);return this.native.getTools(e)}async executeTool(...e){if(this.closed)throw $d(`BrowserMcpServer is closed`);if(!this.native)throw $d(`BrowserMcpServer has no WebMCP context`);return this.native.executeTool(...e)}applyToolExposure(){for(let{exposedTo:e,mcpHandle:t}of this.tools.values()){if(!t)continue;let n=!e?.length||this.peerOrigin!==void 0&&this.peerOrigin!==`null`&&e.includes(this.peerOrigin);n!==t.enabled&&(n?t.enable():t.disable())}}observePeerOrigin(e){if(this.stopObservingPeerOrigin?.(),this.stopObservingPeerOrigin=void 0,this.peerOrigin=void 0,this.applyToolExposure(),!Vg(e))return;let t=e;this.peerOrigin=t.clientOrigin,this.applyToolExposure();let n=t.onclientorigin,r=!0,i=e=>{n?.(e),r&&(this.peerOrigin=e,this.applyToolExposure())};t.onclientorigin=i,this.stopObservingPeerOrigin=()=>{r=!1,t.onclientorigin===i&&(t.onclientorigin=n)}}async connect(e){if(this.closed)throw $d(`BrowserMcpServer is closed`);if(this.mcpServer.server.transport)throw $d(`BrowserMcpServer is already connected`);this.observePeerOrigin(e);let t=this.stopObservingPeerOrigin;try{await this.mcpServer.connect(e)}catch(n){throw this.stopObservingPeerOrigin===t&&(t?.(),this.stopObservingPeerOrigin=void 0,this.peerOrigin=void 0,this.applyToolExposure()),this.mcpServer.server.transport===e&&await this.mcpServer.close(),n}}close(){return this.closePromise?this.closePromise:(this.closed=!0,this.stopObservingPeerOrigin?.(),this.stopObservingPeerOrigin=void 0,this.closePromise=(async()=>{this.native?.removeEventListener(`toolchange`,this.nativeToolChangeListener),this.native?.removeEventListener(`toolactivated`,this.nativeLifecycleListener),this.native?.removeEventListener(`toolcancel`,this.nativeLifecycleListener);for(let e of this.nativeToolAbortControllers.keys())this.abortNativeToolMirror(e);for(let e of this.tools.keys())this.removeTool(e);for(let e of this.registrations)e.remove();this.registrations.clear(),this.nativeBackfilledTools.clear(),this.removingNativeTools.clear(),await this.mcpServer.close()})(),this.closePromise)}};let Kg=null;function qg(e){if(window.parent!==window&&e?.iframeServer!==!1)return new fu(e?.iframeServer||{allowedOrigins:[`*`]});if(e?.tabServer===!1)throw Error(`tabServer transport is disabled and iframe transport was not selected`);return new pu(e?.tabServer||{allowedOrigins:[`*`]})}function Jg(e){if(!globalThis.window||!globalThis.document||globalThis.isSecureContext===!1||Kg||Bg(document.modelContext))return;Jd();let t=document.modelContext;if(!t)throw Error(`modelContext is not available`);let n=Object.getOwnPropertyDescriptor(document,`modelContext`);if(n?!n.configurable:!Object.isExtensible(document))return;let r=qg(e?.transport),i=new Gg({name:`${window.location.hostname||`localhost`}-webmcp`,version:`1.0.0`},{native:t});try{Object.defineProperty(document,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:i}),Kg={server:i,transport:r,previousDescriptor:n}}catch(e){throw i.close(),r.close(),e}(async()=>{try{await i.syncNativeTools()}catch(e){console.warn(`[WebModelContext] Native WebMCP tool synchronization failed:`,e)}if(Kg?.server===i)try{await i.connect(r)}catch(e){console.error(`[WebModelContext] Failed to connect MCP transport:`,e),Kg?.server===i&&Yg()}})()}function Yg(){if(!Kg)return;let{server:e,transport:t,previousDescriptor:n}=Kg;Kg=null,e.close(),t.close(),n?Object.defineProperty(document,"modelContext",n):Reflect.deleteProperty(document,`modelContext`)}let Xg=globalThis.window?.__webModelContextOptions;if(Xg?.autoInitialize!==!1)try{Jg(Xg)}catch(e){console.error(`[WebModelContext] Auto-initialization failed:`,e)}return e.cleanupWebModelContext=Yg,e.initializeWebModelContext=Jg,e})({});
|