@sequenzy/mcp 0.0.93 → 0.0.94

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/dist/index.js CHANGED
@@ -26,7 +26,7 @@ var FH=Object.create;var{getPrototypeOf:qH,defineProperty:TQ,getOwnPropertyNames
26
26
  newResult[${C}] = ${y}.value;
27
27
  }
28
28
 
29
- `)}L.write("payload.value = newResult;"),L.write("return payload;");let k=L.compile();return(S,y)=>k(K,S,y)},$,J=j1,z=!Y6.jitless,U=z&&vQ.value,A=Y.catchall,B;Q._zod.parse=(K,L)=>{B??(B=W.value);let O=K.value;if(!J(O))return K.issues.push({expected:"object",code:"invalid_type",input:O,inst:Q}),K;if(z&&U&&L?.async===!1&&L.jitless!==!0){if(!$)$=G(Y.shape);if(K=$(K,L),!A)return K;return LW([],O,K,L,B,Q)}return X(K,L)}});function R8(Q,Y,X,W){for(let $ of Q)if($.issues.length===0)return Y.value=$.value,Y;let G=Q.filter(($)=>!A1($));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map(($)=>$.issues.map((J)=>x0(J,W,T0())))}),Y}var iQ=q("$ZodUnion",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),n(Q._zod,"optout",()=>Y.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),n(Q._zod,"values",()=>{if(Y.options.every((G)=>G._zod.values))return new Set(Y.options.flatMap((G)=>Array.from(G._zod.values)));return}),n(Q._zod,"pattern",()=>{if(Y.options.every((G)=>G._zod.pattern)){let G=Y.options.map(($)=>$._zod.pattern);return new RegExp(`^(${G.map(($)=>z4($.source)).join("|")})$`)}return});let X=Y.options.length===1,W=Y.options[0]._zod.run;Q._zod.parse=(G,$)=>{if(X)return W(G,$);let J=!1,z=[];for(let H of Y.options){let U=H._zod.run({value:G.value,issues:[]},$);if(U instanceof Promise)z.push(U),J=!0;else{if(U.issues.length===0)return U;z.push(U)}}if(!J)return R8(z,G,Q,$);return Promise.all(z).then((H)=>{return R8(H,G,Q,$)})}}),qW=q("$ZodDiscriminatedUnion",(Q,Y)=>{iQ.init(Q,Y);let X=Q._zod.parse;n(Q._zod,"propValues",()=>{let G={};for(let $ of Y.options){let J=$._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf($)}"`);for(let[z,H]of Object.entries(J)){if(!G[z])G[z]=new Set;for(let U of H)G[z].add(U)}}return G});let W=g1(()=>{let G=Y.options,$=new Map;for(let J of G){let z=J._zod.propValues?.[Y.discriminator];if(!z||z.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(J)}"`);for(let H of z){if($.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);$.set(H,J)}}return $});Q._zod.parse=(G,$)=>{let J=G.value;if(!j1(J))return G.issues.push({code:"invalid_type",expected:"object",input:J,inst:Q}),G;let z=W.value.get(J?.[Y.discriminator]);if(z)return z._zod.run(G,$);if(Y.unionFallback)return X(G,$);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,input:J,path:[Y.discriminator],inst:Q}),G}}),OW=q("$ZodIntersection",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value,$=Y.left._zod.run({value:G,issues:[]},W),J=Y.right._zod.run({value:G,issues:[]},W);if($ instanceof Promise||J instanceof Promise)return Promise.all([$,J]).then(([H,U])=>{return C8(X,H,U)});return C8(X,$,J)}});function cQ(Q,Y){if(Q===Y)return{valid:!0,data:Q};if(Q instanceof Date&&Y instanceof Date&&+Q===+Y)return{valid:!0,data:Q};if(U1(Q)&&U1(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter(($)=>X.indexOf($)!==-1),G={...Q,...Y};for(let $ of W){let J=cQ(Q[$],Y[$]);if(!J.valid)return{valid:!1,mergeErrorPath:[$,...J.mergeErrorPath]};G[$]=J.data}return{valid:!0,data:G}}if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let W=0;W<Q.length;W++){let G=Q[W],$=Y[W],J=cQ(G,$);if(!J.valid)return{valid:!1,mergeErrorPath:[W,...J.mergeErrorPath]};X.push(J.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function C8(Q,Y,X){if(Y.issues.length)Q.issues.push(...Y.issues);if(X.issues.length)Q.issues.push(...X.issues);if(A1(Q))return Q;let W=cQ(Y.value,X.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return Q.value=W.data,Q}var MW=q("$ZodRecord",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!U1(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let $=[];if(Y.keyType._zod.values){let J=Y.keyType._zod.values;X.value={};for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let U=Y.valueType._zod.run({value:G[H],issues:[]},W);if(U instanceof Promise)$.push(U.then((A)=>{if(A.issues.length)X.issues.push(...a0(H,A.issues));X.value[H]=A.value}));else{if(U.issues.length)X.issues.push(...a0(H,U.issues));X.value[H]=U.value}}let z;for(let H in G)if(!J.has(H))z=z??[],z.push(H);if(z&&z.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:z})}else{X.value={};for(let J of Reflect.ownKeys(G)){if(J==="__proto__")continue;let z=Y.keyType._zod.run({value:J,issues:[]},W);if(z instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(z.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:z.issues.map((U)=>x0(U,W,T0())),input:J,path:[J],inst:Q}),X.value[z.value]=z.value;continue}let H=Y.valueType._zod.run({value:G[J],issues:[]},W);if(H instanceof Promise)$.push(H.then((U)=>{if(U.issues.length)X.issues.push(...a0(J,U.issues));X.value[z.value]=U.value}));else{if(H.issues.length)X.issues.push(...a0(J,H.issues));X.value[z.value]=H.value}}}if($.length)return Promise.all($).then(()=>X);return X}});var VW=q("$ZodEnum",(Q,Y)=>{o.init(Q,Y);let X=CQ(Y.entries),W=new Set(X);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${X.filter((G)=>xQ.has(typeof G)).map((G)=>typeof G==="string"?t0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,$)=>{let J=G.value;if(W.has(J))return G;return G.issues.push({code:"invalid_value",values:X,input:J,inst:Q}),G}}),ZW=q("$ZodLiteral",(Q,Y)=>{if(o.init(Q,Y),Y.values.length===0)throw Error("Cannot create literal schema with no valid values");Q._zod.values=new Set(Y.values),Q._zod.pattern=new RegExp(`^(${Y.values.map((X)=>typeof X==="string"?t0(X):X?t0(X.toString()):String(X)).join("|")})$`),Q._zod.parse=(X,W)=>{let G=X.value;if(Q._zod.values.has(G))return X;return X.issues.push({code:"invalid_value",values:Y.values,input:G,inst:Q}),X}});var NW=q("$ZodTransform",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new G4(Q.constructor.name);let G=Y.transform(X.value,X);if(W.async)return(G instanceof Promise?G:Promise.resolve(G)).then((J)=>{return X.value=J,X});if(G instanceof Promise)throw new o0;return X.value=G,X}});function k8(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var wW=q("$ZodOptional",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",n(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),n(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${z4(X.source)})?$`):void 0}),Q._zod.parse=(X,W)=>{if(Y.innerType._zod.optin==="optional"){let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>k8($,X.value));return k8(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),PW=q("$ZodNullable",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),n(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${z4(X.source)}|null)$`):void 0}),n(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,null]):void 0}),Q._zod.parse=(X,W)=>{if(X.value===null)return X;return Y.innerType._zod.run(X,W)}}),bW=q("$ZodDefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)return X.value=Y.defaultValue,X;let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>v8($,Y));return v8(G,Y)}});function v8(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var jW=q("$ZodPrefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)X.value=Y.defaultValue;return Y.innerType._zod.run(X,W)}}),IW=q("$ZodNonOptional",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"values",()=>{let X=Y.innerType._zod.values;return X?new Set([...X].filter((W)=>W!==void 0)):void 0}),Q._zod.parse=(X,W)=>{let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>x8($,Q));return x8(G,Q)}});function x8(Q,Y){if(!Q.issues.length&&Q.value===void 0)Q.issues.push({code:"invalid_type",expected:"nonoptional",input:Q.value,inst:Y});return Q}var EW=q("$ZodCatch",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>{if(X.value=$.value,$.issues.length)X.value=Y.catchValue({...X,error:{issues:$.issues.map((J)=>x0(J,W,T0()))},input:X.value}),X.issues=[];return X});if(X.value=G.value,G.issues.length)X.value=Y.catchValue({...X,error:{issues:G.issues.map(($)=>x0($,W,T0()))},input:X.value}),X.issues=[];return X}});var TW=q("$ZodPipe",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"values",()=>Y.in._zod.values),n(Q._zod,"optin",()=>Y.in._zod.optin),n(Q._zod,"optout",()=>Y.out._zod.optout),n(Q._zod,"propValues",()=>Y.in._zod.propValues),Q._zod.parse=(X,W)=>{if(W.direction==="backward"){let $=Y.out._zod.run(X,W);if($ instanceof Promise)return $.then((J)=>B6(J,Y.in,W));return B6($,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>B6($,Y.out,W));return B6(G,Y.out,W)}});function B6(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var SW=q("$ZodReadonly",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"propValues",()=>Y.innerType._zod.propValues),n(Q._zod,"values",()=>Y.innerType._zod.values),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(_8);return _8(G)}});function _8(Q){return Q.value=Object.freeze(Q.value),Q}var RW=q("$ZodCustom",(Q,Y)=>{U0.init(Q,Y),o.init(Q,Y),Q._zod.parse=(X,W)=>{return X},Q._zod.check=(X)=>{let W=X.value,G=Y.fn(W);if(G instanceof Promise)return G.then(($)=>g8($,X,W,Q));g8(G,X,W,Q);return}});function g8(Q,Y,X,W){if(!Q){let G={code:"custom",input:X,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)G.params=W._zod.def.params;Y.issues.push(y1(G))}}var H3=(Q)=>{let Y=typeof Q;switch(Y){case"number":return Number.isNaN(Q)?"NaN":"number";case"object":{if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Object.getPrototypeOf(Q)!==Object.prototype&&Q.constructor)return Q.constructor.name}}return Y},U3=()=>{let Q={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function Y(W){return Q[W]??null}let X={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${H3(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${$6(W.values[0])}`;return`Invalid option: expected one of ${X6(W.values,"|")}`;case"too_big":{let G=W.inclusive?"<=":"<",$=Y(W.origin);if($)return`Too big: expected ${W.origin??"value"} to have ${G}${W.maximum.toString()} ${$.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${G}${W.maximum.toString()}`}case"too_small":{let G=W.inclusive?">=":">",$=Y(W.origin);if($)return`Too small: expected ${W.origin} to have ${G}${W.minimum.toString()} ${$.unit}`;return`Too small: expected ${W.origin} to be ${G}${W.minimum.toString()}`}case"invalid_format":{let G=W;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${X[G.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${X6(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};function nQ(){return{localeError:U3()}}var SZ=Symbol("ZodOutput"),RZ=Symbol("ZodInput");class CW{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Q,...Y){let X=Y[0];if(this._map.set(Q,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.id,Q)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Q){let Y=this._map.get(Q);if(Y&&typeof Y==="object"&&"id"in Y)this._idmap.delete(Y.id);return this._map.delete(Q),this}get(Q){let Y=Q._zod.parent;if(Y){let X={...this.get(Y)??{}};delete X.id;let W={...X,...this._map.get(Q)};return Object.keys(W).length?W:void 0}return this._map.get(Q)}has(Q){return this._map.has(Q)}}function A3(){return new CW}var D4=A3();function kW(Q,Y){return new Q({type:"string",...E(Y)})}function vW(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...E(Y)})}function rQ(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...E(Y)})}function xW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...E(Y)})}function _W(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...E(Y)})}function gW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...E(Y)})}function yW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...E(Y)})}function uW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...E(Y)})}function hW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...E(Y)})}function fW(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...E(Y)})}function lW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...E(Y)})}function mW(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...E(Y)})}function cW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...E(Y)})}function pW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...E(Y)})}function iW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...E(Y)})}function nW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...E(Y)})}function rW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...E(Y)})}function dW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...E(Y)})}function oW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...E(Y)})}function tW(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...E(Y)})}function aW(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...E(Y)})}function sW(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...E(Y)})}function eW(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...E(Y)})}function QG(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...E(Y)})}function YG(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...E(Y)})}function XG(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...E(Y)})}function WG(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...E(Y)})}function GG(Q,Y){return new Q({type:"number",checks:[],...E(Y)})}function $G(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...E(Y)})}function JG(Q,Y){return new Q({type:"boolean",...E(Y)})}function zG(Q,Y){return new Q({type:"null",...E(Y)})}function HG(Q){return new Q({type:"unknown"})}function UG(Q,Y){return new Q({type:"never",...E(Y)})}function L6(Q,Y){return new fQ({check:"less_than",...E(Y),value:Q,inclusive:!1})}function L4(Q,Y){return new fQ({check:"less_than",...E(Y),value:Q,inclusive:!0})}function F6(Q,Y){return new lQ({check:"greater_than",...E(Y),value:Q,inclusive:!1})}function F4(Q,Y){return new lQ({check:"greater_than",...E(Y),value:Q,inclusive:!0})}function q6(Q,Y){return new F8({check:"multiple_of",...E(Y),value:Q})}function O6(Q,Y){return new O8({check:"max_length",...E(Y),maximum:Q})}function u1(Q,Y){return new M8({check:"min_length",...E(Y),minimum:Q})}function M6(Q,Y){return new V8({check:"length_equals",...E(Y),length:Q})}function dQ(Q,Y){return new Z8({check:"string_format",format:"regex",...E(Y),pattern:Q})}function oQ(Q){return new N8({check:"string_format",format:"lowercase",...E(Q)})}function tQ(Q){return new w8({check:"string_format",format:"uppercase",...E(Q)})}function aQ(Q,Y){return new P8({check:"string_format",format:"includes",...E(Y),includes:Q})}function sQ(Q,Y){return new b8({check:"string_format",format:"starts_with",...E(Y),prefix:Q})}function eQ(Q,Y){return new j8({check:"string_format",format:"ends_with",...E(Y),suffix:Q})}function I1(Q){return new I8({check:"overwrite",tx:Q})}function Q9(Q){return I1((Y)=>Y.normalize(Q))}function Y9(){return I1((Q)=>Q.trim())}function X9(){return I1((Q)=>Q.toLowerCase())}function W9(){return I1((Q)=>Q.toUpperCase())}function AG(Q,Y,X){return new Q({type:"array",element:Y,...E(X)})}function BG(Q,Y,X){let W=E(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function KG(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...E(X)})}function DG(Q){let Y=B3((X)=>{return X.addIssue=(W)=>{if(typeof W==="string")X.issues.push(y1(W,X.value,Y._zod.def));else{let G=W;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=X.value),G.inst??(G.inst=Y),G.continue??(G.continue=!Y._zod.def.abort),X.issues.push(y1(G))}},Q(X.value,X)});return Y}function B3(Q,Y){let X=new U0({check:"custom",...E(Y)});return X._zod.check=Q,X}function h1(Q){return!!Q._zod}function B1(Q,Y){if(h1(Q))return A4(Q,Y);return Q.safeParse(Y)}function V6(Q){if(!Q)return;let Y;if(h1(Q))Y=Q._zod?.def?.shape;else Y=Q.shape;if(!Y)return;if(typeof Y==="function")try{return Y()}catch{return}return Y}function LG(Q){if(h1(Q)){let $=Q._zod?.def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}}let X=Q._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let W=Q.value;if(W!==void 0)return W;return}var O4={};DX(O4,{time:()=>J9,duration:()=>z9,datetime:()=>G9,date:()=>$9,ZodISOTime:()=>OG,ZodISODuration:()=>MG,ZodISODateTime:()=>FG,ZodISODate:()=>qG});var FG=q("ZodISODateTime",(Q,Y)=>{d8.init(Q,Y),s.init(Q,Y)});function G9(Q){return QG(FG,Q)}var qG=q("ZodISODate",(Q,Y)=>{o8.init(Q,Y),s.init(Q,Y)});function $9(Q){return YG(qG,Q)}var OG=q("ZodISOTime",(Q,Y)=>{t8.init(Q,Y),s.init(Q,Y)});function J9(Q){return XG(OG,Q)}var MG=q("ZodISODuration",(Q,Y)=>{a8.init(Q,Y),s.init(Q,Y)});function z9(Q){return WG(MG,Q)}var VG=(Q,Y)=>{J6.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>RX(Q,X)},flatten:{value:(X)=>SX(Q,X)},addIssue:{value:(X)=>{Q.issues.push(X),Q.message=JSON.stringify(Q.issues,_1,2)}},addIssues:{value:(X)=>{Q.issues.push(...X),Q.message=JSON.stringify(Q.issues,_1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},FN=q("ZodError",VG),I0=q("ZodError",VG,{Parent:Error});var ZG=z6(I0),NG=H6(I0),wG=U4(I0),PG=B4(I0),bG=CX(I0),jG=kX(I0),IG=vX(I0),EG=xX(I0),TG=_X(I0),SG=gX(I0),RG=yX(I0),CG=uX(I0);var X0=q("ZodType",(Q,Y)=>{return o.init(Q,Y),Q.def=Y,Q.type=Y.type,Object.defineProperty(Q,"_def",{value:Y}),Q.check=(...X)=>{return Q.clone(m.mergeDefs(Y,{checks:[...Y.checks??[],...X.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},Q.clone=(X,W)=>v0(Q,X,W),Q.brand=()=>Q,Q.register=(X,W)=>{return X.add(Q,W),Q},Q.parse=(X,W)=>ZG(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>wG(Q,X,W),Q.parseAsync=async(X,W)=>NG(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>PG(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>bG(Q,X,W),Q.decode=(X,W)=>jG(Q,X,W),Q.encodeAsync=async(X,W)=>IG(Q,X,W),Q.decodeAsync=async(X,W)=>EG(Q,X,W),Q.safeEncode=(X,W)=>TG(Q,X,W),Q.safeDecode=(X,W)=>SG(Q,X,W),Q.safeEncodeAsync=async(X,W)=>RG(Q,X,W),Q.safeDecodeAsync=async(X,W)=>CG(Q,X,W),Q.refine=(X,W)=>Q.check(zU(X,W)),Q.superRefine=(X)=>Q.check(HU(X)),Q.overwrite=(X)=>Q.check(I1(X)),Q.optional=()=>Y0(Q),Q.nullable=()=>xG(Q),Q.nullish=()=>Y0(xG(Q)),Q.nonoptional=(X)=>YU(Q,X),Q.array=()=>u(Q),Q.or=(X)=>d([Q,X]),Q.and=(X)=>N6(Q,X),Q.transform=(X)=>U9(Q,hG(X)),Q.default=(X)=>s3(Q,X),Q.prefault=(X)=>QU(Q,X),Q.catch=(X)=>WU(Q,X),Q.pipe=(X)=>U9(Q,X),Q.readonly=()=>JU(Q),Q.describe=(X)=>{let W=Q.clone();return D4.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return D4.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return D4.get(Q);let W=Q.clone();return D4.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),_G=q("_ZodString",(Q,Y)=>{D6.init(Q,Y),X0.init(Q,Y);let X=Q._zod.bag;Q.format=X.format??null,Q.minLength=X.minimum??null,Q.maxLength=X.maximum??null,Q.regex=(...W)=>Q.check(dQ(...W)),Q.includes=(...W)=>Q.check(aQ(...W)),Q.startsWith=(...W)=>Q.check(sQ(...W)),Q.endsWith=(...W)=>Q.check(eQ(...W)),Q.min=(...W)=>Q.check(u1(...W)),Q.max=(...W)=>Q.check(O6(...W)),Q.length=(...W)=>Q.check(M6(...W)),Q.nonempty=(...W)=>Q.check(u1(1,...W)),Q.lowercase=(W)=>Q.check(oQ(W)),Q.uppercase=(W)=>Q.check(tQ(W)),Q.trim=()=>Q.check(Y9()),Q.normalize=(...W)=>Q.check(Q9(...W)),Q.toLowerCase=()=>Q.check(X9()),Q.toUpperCase=()=>Q.check(W9())}),Z3=q("ZodString",(Q,Y)=>{D6.init(Q,Y),_G.init(Q,Y),Q.email=(X)=>Q.check(vW(N3,X)),Q.url=(X)=>Q.check(uW(w3,X)),Q.jwt=(X)=>Q.check(eW(y3,X)),Q.emoji=(X)=>Q.check(hW(P3,X)),Q.guid=(X)=>Q.check(rQ(kG,X)),Q.uuid=(X)=>Q.check(xW(Z6,X)),Q.uuidv4=(X)=>Q.check(_W(Z6,X)),Q.uuidv6=(X)=>Q.check(gW(Z6,X)),Q.uuidv7=(X)=>Q.check(yW(Z6,X)),Q.nanoid=(X)=>Q.check(fW(b3,X)),Q.guid=(X)=>Q.check(rQ(kG,X)),Q.cuid=(X)=>Q.check(lW(j3,X)),Q.cuid2=(X)=>Q.check(mW(I3,X)),Q.ulid=(X)=>Q.check(cW(E3,X)),Q.base64=(X)=>Q.check(tW(x3,X)),Q.base64url=(X)=>Q.check(aW(_3,X)),Q.xid=(X)=>Q.check(pW(T3,X)),Q.ksuid=(X)=>Q.check(iW(S3,X)),Q.ipv4=(X)=>Q.check(nW(R3,X)),Q.ipv6=(X)=>Q.check(rW(C3,X)),Q.cidrv4=(X)=>Q.check(dW(k3,X)),Q.cidrv6=(X)=>Q.check(oW(v3,X)),Q.e164=(X)=>Q.check(sW(g3,X)),Q.datetime=(X)=>Q.check(G9(X)),Q.date=(X)=>Q.check($9(X)),Q.time=(X)=>Q.check(J9(X)),Q.duration=(X)=>Q.check(z9(X))});function F(Q){return kW(Z3,Q)}var s=q("ZodStringFormat",(Q,Y)=>{t.init(Q,Y),_G.init(Q,Y)}),N3=q("ZodEmail",(Q,Y)=>{h8.init(Q,Y),s.init(Q,Y)});var kG=q("ZodGUID",(Q,Y)=>{y8.init(Q,Y),s.init(Q,Y)});var Z6=q("ZodUUID",(Q,Y)=>{u8.init(Q,Y),s.init(Q,Y)});var w3=q("ZodURL",(Q,Y)=>{f8.init(Q,Y),s.init(Q,Y)});var P3=q("ZodEmoji",(Q,Y)=>{l8.init(Q,Y),s.init(Q,Y)});var b3=q("ZodNanoID",(Q,Y)=>{m8.init(Q,Y),s.init(Q,Y)});var j3=q("ZodCUID",(Q,Y)=>{c8.init(Q,Y),s.init(Q,Y)});var I3=q("ZodCUID2",(Q,Y)=>{p8.init(Q,Y),s.init(Q,Y)});var E3=q("ZodULID",(Q,Y)=>{i8.init(Q,Y),s.init(Q,Y)});var T3=q("ZodXID",(Q,Y)=>{n8.init(Q,Y),s.init(Q,Y)});var S3=q("ZodKSUID",(Q,Y)=>{r8.init(Q,Y),s.init(Q,Y)});var R3=q("ZodIPv4",(Q,Y)=>{s8.init(Q,Y),s.init(Q,Y)});var C3=q("ZodIPv6",(Q,Y)=>{e8.init(Q,Y),s.init(Q,Y)});var k3=q("ZodCIDRv4",(Q,Y)=>{QW.init(Q,Y),s.init(Q,Y)});var v3=q("ZodCIDRv6",(Q,Y)=>{YW.init(Q,Y),s.init(Q,Y)});var x3=q("ZodBase64",(Q,Y)=>{WW.init(Q,Y),s.init(Q,Y)});var _3=q("ZodBase64URL",(Q,Y)=>{GW.init(Q,Y),s.init(Q,Y)});var g3=q("ZodE164",(Q,Y)=>{$W.init(Q,Y),s.init(Q,Y)});var y3=q("ZodJWT",(Q,Y)=>{JW.init(Q,Y),s.init(Q,Y)});var gG=q("ZodNumber",(Q,Y)=>{pQ.init(Q,Y),X0.init(Q,Y),Q.gt=(W,G)=>Q.check(F6(W,G)),Q.gte=(W,G)=>Q.check(F4(W,G)),Q.min=(W,G)=>Q.check(F4(W,G)),Q.lt=(W,G)=>Q.check(L6(W,G)),Q.lte=(W,G)=>Q.check(L4(W,G)),Q.max=(W,G)=>Q.check(L4(W,G)),Q.int=(W)=>Q.check(vG(W)),Q.safe=(W)=>Q.check(vG(W)),Q.positive=(W)=>Q.check(F6(0,W)),Q.nonnegative=(W)=>Q.check(F4(0,W)),Q.negative=(W)=>Q.check(L6(0,W)),Q.nonpositive=(W)=>Q.check(L4(0,W)),Q.multipleOf=(W,G)=>Q.check(q6(W,G)),Q.step=(W,G)=>Q.check(q6(W,G)),Q.finite=()=>Q;let X=Q._zod.bag;Q.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Q.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Q.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Q.isFinite=!0,Q.format=X.format??null});function i(Q){return GG(gG,Q)}var u3=q("ZodNumberFormat",(Q,Y)=>{zW.init(Q,Y),gG.init(Q,Y)});function vG(Q){return $G(u3,Q)}var h3=q("ZodBoolean",(Q,Y)=>{HW.init(Q,Y),X0.init(Q,Y)});function H0(Q){return JG(h3,Q)}var f3=q("ZodNull",(Q,Y)=>{UW.init(Q,Y),X0.init(Q,Y)});function A9(Q){return zG(f3,Q)}var l3=q("ZodUnknown",(Q,Y)=>{AW.init(Q,Y),X0.init(Q,Y)});function e(){return HG(l3)}var m3=q("ZodNever",(Q,Y)=>{BW.init(Q,Y),X0.init(Q,Y)});function c3(Q){return UG(m3,Q)}var p3=q("ZodArray",(Q,Y)=>{KW.init(Q,Y),X0.init(Q,Y),Q.element=Y.element,Q.min=(X,W)=>Q.check(u1(X,W)),Q.nonempty=(X)=>Q.check(u1(1,X)),Q.max=(X,W)=>Q.check(O6(X,W)),Q.length=(X,W)=>Q.check(M6(X,W)),Q.unwrap=()=>Q.element});function u(Q,Y){return AG(p3,Q,Y)}var yG=q("ZodObject",(Q,Y)=>{FW.init(Q,Y),X0.init(Q,Y),m.defineLazy(Q,"shape",()=>{return Y.shape}),Q.keyof=()=>V0(Object.keys(Q._zod.def.shape)),Q.catchall=(X)=>Q.clone({...Q._zod.def,catchall:X}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:c3()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(X)=>{return m.extend(Q,X)},Q.safeExtend=(X)=>{return m.safeExtend(Q,X)},Q.merge=(X)=>m.merge(Q,X),Q.pick=(X)=>m.pick(Q,X),Q.omit=(X)=>m.omit(Q,X),Q.partial=(...X)=>m.partial(fG,Q,X[0]),Q.required=(...X)=>m.required(lG,Q,X[0])});function b(Q,Y){let X={type:"object",shape:Q??{},...m.normalizeParams(Y)};return new yG(X)}function q0(Q,Y){return new yG({type:"object",shape:Q,catchall:e(),...m.normalizeParams(Y)})}var uG=q("ZodUnion",(Q,Y)=>{iQ.init(Q,Y),X0.init(Q,Y),Q.options=Y.options});function d(Q,Y){return new uG({type:"union",options:Q,...m.normalizeParams(Y)})}var i3=q("ZodDiscriminatedUnion",(Q,Y)=>{uG.init(Q,Y),qW.init(Q,Y)});function B9(Q,Y,X){return new i3({type:"union",options:Y,discriminator:Q,...m.normalizeParams(X)})}var n3=q("ZodIntersection",(Q,Y)=>{OW.init(Q,Y),X0.init(Q,Y)});function N6(Q,Y){return new n3({type:"intersection",left:Q,right:Y})}var r3=q("ZodRecord",(Q,Y)=>{MW.init(Q,Y),X0.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function Q0(Q,Y,X){return new r3({type:"record",keyType:Q,valueType:Y,...m.normalizeParams(X)})}var H9=q("ZodEnum",(Q,Y)=>{VW.init(Q,Y),X0.init(Q,Y),Q.enum=Y.entries,Q.options=Object.values(Y.entries);let X=new Set(Object.keys(Y.entries));Q.extract=(W,G)=>{let $={};for(let J of W)if(X.has(J))$[J]=Y.entries[J];else throw Error(`Key ${J} not found in enum`);return new H9({...Y,checks:[],...m.normalizeParams(G),entries:$})},Q.exclude=(W,G)=>{let $={...Y.entries};for(let J of W)if(X.has(J))delete $[J];else throw Error(`Key ${J} not found in enum`);return new H9({...Y,checks:[],...m.normalizeParams(G),entries:$})}});function V0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new H9({type:"enum",entries:X,...m.normalizeParams(Y)})}var d3=q("ZodLiteral",(Q,Y)=>{ZW.init(Q,Y),X0.init(Q,Y),Q.values=new Set(Y.values),Object.defineProperty(Q,"value",{get(){if(Y.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return Y.values[0]}})});function j(Q,Y){return new d3({type:"literal",values:Array.isArray(Q)?Q:[Q],...m.normalizeParams(Y)})}var o3=q("ZodTransform",(Q,Y)=>{NW.init(Q,Y),X0.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new G4(Q.constructor.name);X.addIssue=($)=>{if(typeof $==="string")X.issues.push(m.issue($,X.value,Y));else{let J=$;if(J.fatal)J.continue=!1;J.code??(J.code="custom"),J.input??(J.input=X.value),J.inst??(J.inst=Q),X.issues.push(m.issue(J))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then(($)=>{return X.value=$,X});return X.value=G,X}});function hG(Q){return new o3({type:"transform",transform:Q})}var fG=q("ZodOptional",(Q,Y)=>{wW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function Y0(Q){return new fG({type:"optional",innerType:Q})}var t3=q("ZodNullable",(Q,Y)=>{PW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function xG(Q){return new t3({type:"nullable",innerType:Q})}var a3=q("ZodDefault",(Q,Y)=>{bW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function s3(Q,Y){return new a3({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var e3=q("ZodPrefault",(Q,Y)=>{jW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function QU(Q,Y){return new e3({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var lG=q("ZodNonOptional",(Q,Y)=>{IW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function YU(Q,Y){return new lG({type:"nonoptional",innerType:Q,...m.normalizeParams(Y)})}var XU=q("ZodCatch",(Q,Y)=>{EW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function WU(Q,Y){return new XU({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var GU=q("ZodPipe",(Q,Y)=>{TW.init(Q,Y),X0.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function U9(Q,Y){return new GU({type:"pipe",in:Q,out:Y})}var $U=q("ZodReadonly",(Q,Y)=>{SW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function JU(Q){return new $U({type:"readonly",innerType:Q})}var mG=q("ZodCustom",(Q,Y)=>{RW.init(Q,Y),X0.init(Q,Y)});function cG(Q,Y){return BG(mG,Q??(()=>!0),Y)}function zU(Q,Y={}){return KG(mG,Q,Y)}function HU(Q){return DG(Q)}function K9(Q,Y){return U9(hG(Q),Y)}T0(nQ());var D9="2025-11-25";var pG=[D9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],K1="io.modelcontextprotocol/related-task",P6="2.0",A0=cG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),iG=d([F(),i().int()]),nG=F(),Aw=q0({ttl:d([i(),A9()]).optional(),pollInterval:i().optional()}),UU=b({ttl:i().optional()}),AU=b({taskId:F()}),L9=q0({progressToken:iG.optional(),[K1]:AU.optional()}),E0=b({_meta:L9.optional()}),M4=E0.extend({task:UU.optional()}),rG=(Q)=>M4.safeParse(Q).success,B0=b({method:F(),params:E0.loose().optional()}),S0=b({_meta:L9.optional()}),R0=b({method:F(),params:S0.loose().optional()}),K0=q0({_meta:L9.optional()}),b6=d([F(),i().int()]),dG=b({jsonrpc:j(P6),id:b6,...B0.shape}).strict(),F9=(Q)=>dG.safeParse(Q).success,oG=b({jsonrpc:j(P6),...R0.shape}).strict(),tG=(Q)=>oG.safeParse(Q).success,q9=b({jsonrpc:j(P6),id:b6,result:K0}).strict(),V4=(Q)=>q9.safeParse(Q).success;var h;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(h||(h={}));var O9=b({jsonrpc:j(P6),id:b6.optional(),error:b({code:i().int(),message:F(),data:e().optional()})}).strict();var aG=(Q)=>O9.safeParse(Q).success;var sG=d([dG,oG,q9,O9]),Bw=d([q9,O9]),j6=K0.strict(),BU=S0.extend({requestId:b6.optional(),reason:F().optional()}),I6=R0.extend({method:j("notifications/cancelled"),params:BU}),KU=b({src:F(),mimeType:F().optional(),sizes:u(F()).optional(),theme:V0(["light","dark"]).optional()}),Z4=b({icons:u(KU).optional()}),f1=b({name:F(),title:F().optional()}),eG=f1.extend({...f1.shape,...Z4.shape,version:F(),websiteUrl:F().optional(),description:F().optional()}),DU=N6(b({applyDefaults:H0().optional()}),Q0(F(),e())),LU=K9((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},N6(b({form:DU.optional(),url:A0.optional()}),Q0(F(),e()).optional())),FU=q0({list:A0.optional(),cancel:A0.optional(),requests:q0({sampling:q0({createMessage:A0.optional()}).optional(),elicitation:q0({create:A0.optional()}).optional()}).optional()}),qU=q0({list:A0.optional(),cancel:A0.optional(),requests:q0({tools:q0({call:A0.optional()}).optional()}).optional()}),OU=b({experimental:Q0(F(),A0).optional(),sampling:b({context:A0.optional(),tools:A0.optional()}).optional(),elicitation:LU.optional(),roots:b({listChanged:H0().optional()}).optional(),tasks:FU.optional()}),MU=E0.extend({protocolVersion:F(),capabilities:OU,clientInfo:eG}),M9=B0.extend({method:j("initialize"),params:MU});var VU=b({experimental:Q0(F(),A0).optional(),logging:A0.optional(),completions:A0.optional(),prompts:b({listChanged:H0().optional()}).optional(),resources:b({subscribe:H0().optional(),listChanged:H0().optional()}).optional(),tools:b({listChanged:H0().optional()}).optional(),tasks:qU.optional()}),ZU=K0.extend({protocolVersion:F(),capabilities:VU,serverInfo:eG,instructions:F().optional()}),V9=R0.extend({method:j("notifications/initialized"),params:S0.optional()});var E6=B0.extend({method:j("ping"),params:E0.optional()}),NU=b({progress:i(),total:Y0(i()),message:Y0(F())}),wU=b({...S0.shape,...NU.shape,progressToken:iG}),T6=R0.extend({method:j("notifications/progress"),params:wU}),PU=E0.extend({cursor:nG.optional()}),N4=B0.extend({params:PU.optional()}),w4=K0.extend({nextCursor:nG.optional()}),bU=V0(["working","input_required","completed","failed","cancelled"]),P4=b({taskId:F(),status:bU,ttl:d([i(),A9()]),createdAt:F(),lastUpdatedAt:F(),pollInterval:Y0(i()),statusMessage:Y0(F())}),l1=K0.extend({task:P4}),jU=S0.merge(P4),b4=R0.extend({method:j("notifications/tasks/status"),params:jU}),S6=B0.extend({method:j("tasks/get"),params:E0.extend({taskId:F()})}),R6=K0.merge(P4),C6=B0.extend({method:j("tasks/result"),params:E0.extend({taskId:F()})}),Kw=K0.loose(),k6=N4.extend({method:j("tasks/list")}),v6=w4.extend({tasks:u(P4)}),x6=B0.extend({method:j("tasks/cancel"),params:E0.extend({taskId:F()})}),Q$=K0.merge(P4),Y$=b({uri:F(),mimeType:Y0(F()),_meta:Q0(F(),e()).optional()}),X$=Y$.extend({text:F()}),Z9=F().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),W$=Y$.extend({blob:Z9}),j4=V0(["user","assistant"]),m1=b({audience:u(j4).optional(),priority:i().min(0).max(1).optional(),lastModified:O4.datetime({offset:!0}).optional()}),G$=b({...f1.shape,...Z4.shape,uri:F(),description:Y0(F()),mimeType:Y0(F()),annotations:m1.optional(),_meta:Y0(q0({}))}),IU=b({...f1.shape,...Z4.shape,uriTemplate:F(),description:Y0(F()),mimeType:Y0(F()),annotations:m1.optional(),_meta:Y0(q0({}))}),N9=N4.extend({method:j("resources/list")}),EU=w4.extend({resources:u(G$)}),TU=N4.extend({method:j("resources/templates/list")}),SU=w4.extend({resourceTemplates:u(IU)}),w9=E0.extend({uri:F()}),RU=w9,P9=B0.extend({method:j("resources/read"),params:RU}),CU=K0.extend({contents:u(d([X$,W$]))}),kU=R0.extend({method:j("notifications/resources/list_changed"),params:S0.optional()}),vU=w9,xU=B0.extend({method:j("resources/subscribe"),params:vU}),_U=w9,gU=B0.extend({method:j("resources/unsubscribe"),params:_U}),yU=S0.extend({uri:F()}),uU=R0.extend({method:j("notifications/resources/updated"),params:yU}),hU=b({name:F(),description:Y0(F()),required:Y0(H0())}),fU=b({...f1.shape,...Z4.shape,description:Y0(F()),arguments:Y0(u(hU)),_meta:Y0(q0({}))}),lU=N4.extend({method:j("prompts/list")}),mU=w4.extend({prompts:u(fU)}),cU=E0.extend({name:F(),arguments:Q0(F(),F()).optional()}),pU=B0.extend({method:j("prompts/get"),params:cU}),b9=b({type:j("text"),text:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),j9=b({type:j("image"),data:Z9,mimeType:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),I9=b({type:j("audio"),data:Z9,mimeType:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),iU=b({type:j("tool_use"),name:F(),id:F(),input:Q0(F(),e()),_meta:Q0(F(),e()).optional()}),nU=b({type:j("resource"),resource:d([X$,W$]),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),rU=G$.extend({type:j("resource_link")}),E9=d([b9,j9,I9,rU,nU]),dU=b({role:j4,content:E9}),oU=K0.extend({description:F().optional(),messages:u(dU)}),tU=R0.extend({method:j("notifications/prompts/list_changed"),params:S0.optional()}),aU=b({title:F().optional(),readOnlyHint:H0().optional(),destructiveHint:H0().optional(),idempotentHint:H0().optional(),openWorldHint:H0().optional()}),sU=b({taskSupport:V0(["required","optional","forbidden"]).optional()}),$$=b({...f1.shape,...Z4.shape,description:F().optional(),inputSchema:b({type:j("object"),properties:Q0(F(),A0).optional(),required:u(F()).optional()}).catchall(e()),outputSchema:b({type:j("object"),properties:Q0(F(),A0).optional(),required:u(F()).optional()}).catchall(e()).optional(),annotations:aU.optional(),execution:sU.optional(),_meta:Q0(F(),e()).optional()}),T9=N4.extend({method:j("tools/list")}),eU=w4.extend({tools:u($$)}),_6=K0.extend({content:u(E9).default([]),structuredContent:Q0(F(),e()).optional(),isError:H0().optional()}),Dw=_6.or(K0.extend({toolResult:e()})),QA=M4.extend({name:F(),arguments:Q0(F(),e()).optional()}),I4=B0.extend({method:j("tools/call"),params:QA}),YA=R0.extend({method:j("notifications/tools/list_changed"),params:S0.optional()}),Lw=b({autoRefresh:H0().default(!0),debounceMs:i().int().nonnegative().default(300)}),E4=V0(["debug","info","notice","warning","error","critical","alert","emergency"]),XA=E0.extend({level:E4}),S9=B0.extend({method:j("logging/setLevel"),params:XA}),WA=S0.extend({level:E4,logger:F().optional(),data:e()}),GA=R0.extend({method:j("notifications/message"),params:WA}),$A=b({name:F().optional()}),JA=b({hints:u($A).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),zA=b({mode:V0(["auto","required","none"]).optional()}),HA=b({type:j("tool_result"),toolUseId:F().describe("The unique identifier for the corresponding tool call."),content:u(E9).default([]),structuredContent:b({}).loose().optional(),isError:H0().optional(),_meta:Q0(F(),e()).optional()}),UA=B9("type",[b9,j9,I9]),w6=B9("type",[b9,j9,I9,iU,HA]),AA=b({role:j4,content:d([w6,u(w6)]),_meta:Q0(F(),e()).optional()}),BA=M4.extend({messages:u(AA),modelPreferences:JA.optional(),systemPrompt:F().optional(),includeContext:V0(["none","thisServer","allServers"]).optional(),temperature:i().optional(),maxTokens:i().int(),stopSequences:u(F()).optional(),metadata:A0.optional(),tools:u($$).optional(),toolChoice:zA.optional()}),KA=B0.extend({method:j("sampling/createMessage"),params:BA}),R9=K0.extend({model:F(),stopReason:Y0(V0(["endTurn","stopSequence","maxTokens"]).or(F())),role:j4,content:UA}),C9=K0.extend({model:F(),stopReason:Y0(V0(["endTurn","stopSequence","maxTokens","toolUse"]).or(F())),role:j4,content:d([w6,u(w6)])}),DA=b({type:j("boolean"),title:F().optional(),description:F().optional(),default:H0().optional()}),LA=b({type:j("string"),title:F().optional(),description:F().optional(),minLength:i().optional(),maxLength:i().optional(),format:V0(["email","uri","date","date-time"]).optional(),default:F().optional()}),FA=b({type:V0(["number","integer"]),title:F().optional(),description:F().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),qA=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),default:F().optional()}),OA=b({type:j("string"),title:F().optional(),description:F().optional(),oneOf:u(b({const:F(),title:F()})),default:F().optional()}),MA=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),enumNames:u(F()).optional(),default:F().optional()}),VA=d([qA,OA]),ZA=b({type:j("array"),title:F().optional(),description:F().optional(),minItems:i().optional(),maxItems:i().optional(),items:b({type:j("string"),enum:u(F())}),default:u(F()).optional()}),NA=b({type:j("array"),title:F().optional(),description:F().optional(),minItems:i().optional(),maxItems:i().optional(),items:b({anyOf:u(b({const:F(),title:F()}))}),default:u(F()).optional()}),wA=d([ZA,NA]),PA=d([MA,VA,wA]),bA=d([PA,DA,LA,FA]),jA=M4.extend({mode:j("form").optional(),message:F(),requestedSchema:b({type:j("object"),properties:Q0(F(),bA),required:u(F()).optional()})}),IA=M4.extend({mode:j("url"),message:F(),elicitationId:F(),url:F().url()}),EA=d([jA,IA]),TA=B0.extend({method:j("elicitation/create"),params:EA}),SA=S0.extend({elicitationId:F()}),RA=R0.extend({method:j("notifications/elicitation/complete"),params:SA}),g6=K0.extend({action:V0(["accept","decline","cancel"]),content:K9((Q)=>Q===null?void 0:Q,Q0(F(),d([F(),i(),H0(),u(F())])).optional())}),CA=b({type:j("ref/resource"),uri:F()});var kA=b({type:j("ref/prompt"),name:F()}),vA=E0.extend({ref:d([kA,CA]),argument:b({name:F(),value:F()}),context:b({arguments:Q0(F(),F()).optional()}).optional()}),xA=B0.extend({method:j("completion/complete"),params:vA});var _A=K0.extend({completion:q0({values:u(F()).max(100),total:Y0(i().int()),hasMore:Y0(H0())})}),gA=b({uri:F().startsWith("file://"),name:F().optional(),_meta:Q0(F(),e()).optional()}),yA=B0.extend({method:j("roots/list"),params:E0.optional()}),k9=K0.extend({roots:u(gA)}),uA=R0.extend({method:j("notifications/roots/list_changed"),params:S0.optional()}),Fw=d([E6,M9,xA,S9,pU,lU,N9,TU,P9,xU,gU,I4,T9,S6,C6,k6,x6]),qw=d([I6,T6,V9,uA,b4]),Ow=d([j6,R9,C9,g6,k9,R6,v6,l1]),Mw=d([E6,KA,TA,yA,S6,C6,k6,x6]),Vw=d([I6,T6,GA,uU,kU,YA,tU,b4,RA]),Zw=d([j6,ZU,_A,oU,mU,EU,SU,CU,_6,eU,R6,v6,l1]);class _ extends Error{constructor(Q,Y,X){super(`MCP error ${Q}: ${Y}`);this.code=Q,this.data=X,this.name="McpError"}static fromError(Q,Y,X){if(Q===h.UrlElicitationRequired&&X){let W=X;if(W.elicitations)return new J$(W.elicitations,Y)}return new _(Q,Y,X)}}class J$ extends _{constructor(Q,Y=`URL elicitation${Q.length>1?"s":""} required`){super(h.UrlElicitationRequired,Y,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function D1(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var hA=Symbol("Let zodToJsonSchema decide on which parser to use");var ew=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function v9(Q){let X=V6(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=LG(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function x9(Q,Y){let X=B1(Q,Y);if(!X.success)throw X.error;return X.data}var iA=60000;class _9{constructor(Q){if(this._options=Q,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(I6,(Y)=>{this._oncancel(Y)}),this.setNotificationHandler(T6,(Y)=>{this._onprogress(Y)}),this.setRequestHandler(E6,(Y)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(S6,async(Y,X)=>{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(C6,async(Y,X)=>{let W=async()=>{let G=Y.params.taskId;if(this._taskMessageQueue){let J;while(J=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(J.type==="response"||J.type==="error"){let z=J.message,H=z.id,U=this._requestResolvers.get(H);if(U)if(this._requestResolvers.delete(H),J.type==="response")U(z);else{let A=z,B=new _(A.error.code,A.error.message,A.error.data);U(B)}else{let A=J.type==="response"?"Response":"Error";this._onerror(Error(`${A} handler missing for request ${H}`))}continue}await this._transport?.send(J.message,{relatedRequestId:X.requestId})}}let $=await this._taskStore.getTask(G,X.sessionId);if(!$)throw new _(h.InvalidParams,`Task not found: ${G}`);if(!D1($.status))return await this._waitForTaskUpdate(G,X.signal),await W();if(D1($.status)){let J=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...J,_meta:{...J._meta,[K1]:{taskId:G}}}}return await W()};return await W()}),this.setRequestHandler(k6,async(Y,X)=>{try{let{tasks:W,nextCursor:G}=await this._taskStore.listTasks(Y.params?.cursor,X.sessionId);return{tasks:W,nextCursor:G,_meta:{}}}catch(W){throw new _(h.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(x6,async(Y,X)=>{try{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,`Task not found: ${Y.params.taskId}`);if(D1(W.status))throw new _(h.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(Y.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Y.params.taskId);let G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new _(h.InvalidParams,`Task not found after cancellation: ${Y.params.taskId}`);return{_meta:{},...G}}catch(W){if(W instanceof _)throw W;throw new _(h.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,Y,X,W,G=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,Y),startTime:Date.now(),timeout:Y,maxTotalTimeout:X,resetTimeoutOnProgress:G,onTimeout:W})}_resetTimeout(Q){let Y=this._timeoutInfo.get(Q);if(!Y)return!1;let X=Date.now()-Y.startTime;if(Y.maxTotalTimeout&&X>=Y.maxTotalTimeout)throw this._timeoutInfo.delete(Q),_.fromError(h.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Y.maxTotalTimeout,totalElapsed:X});return clearTimeout(Y.timeoutId),Y.timeoutId=setTimeout(Y.onTimeout,Y.timeout),!0}_cleanupTimeout(Q){let Y=this._timeoutInfo.get(Q);if(Y)clearTimeout(Y.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let Y=this.transport?.onclose;this._transport.onclose=()=>{Y?.(),this._onclose()};let X=this.transport?.onerror;this._transport.onerror=(G)=>{X?.(G),this._onerror(G)};let W=this._transport?.onmessage;this._transport.onmessage=(G,$)=>{if(W?.(G,$),V4(G)||aG(G))this._onresponse(G);else if(F9(G))this._onrequest(G,$);else if(tG(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let Y=_.fromError(h.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of Q.values())X(Y)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let Y=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(Y===void 0)return;Promise.resolve().then(()=>Y(Q)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(Q,Y){let X=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,G=Q.params?._meta?.[K1]?.taskId;if(X===void 0){let U={jsonrpc:"2.0",id:Q.id,error:{code:h.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId).catch((A)=>this._onerror(Error(`Failed to enqueue error response: ${A}`)));else W?.send(U).catch((A)=>this._onerror(Error(`Failed to send an error response: ${A}`)));return}let $=new AbortController;this._requestHandlerAbortControllers.set(Q.id,$);let J=rG(Q.params)?Q.params.task:void 0,z=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:$.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(U)=>{let A={relatedRequestId:Q.id};if(G)A.relatedTask={taskId:G};await this.notification(U,A)},sendRequest:async(U,A,B)=>{let K={...B,relatedRequestId:Q.id};if(G&&!K.relatedTask)K.relatedTask={taskId:G};let L=K.relatedTask?.taskId??G;if(L&&z)await z.updateTaskStatus(L,"input_required");return await this.request(U,A,K)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:z,taskRequestedTtl:J?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(J)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(U)=>{if($.signal.aborted)return;let A={result:U,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)},async(U)=>{if($.signal.aborted)return;let A={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(U.code)?U.code:h.InternalError,message:U.message??"Internal error",...U.data!==void 0&&{data:U.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)}).catch((U)=>this._onerror(Error(`Failed to send response: ${U}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:Y,...X}=Q.params,W=Number(Y),G=this._progressHandlers.get(W);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let $=this._responseHandlers.get(W),J=this._timeoutInfo.get(W);if(J&&$&&J.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(z){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),$(z);return}G(X)}_onresponse(Q){let Y=Number(Q.id),X=this._requestResolvers.get(Y);if(X){if(this._requestResolvers.delete(Y),V4(Q))X(Q);else{let $=new _(Q.error.code,Q.error.message,Q.error.data);X($)}return}let W=this._responseHandlers.get(Y);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(Y),this._cleanupTimeout(Y);let G=!1;if(V4(Q)&&Q.result&&typeof Q.result==="object"){let $=Q.result;if($.task&&typeof $.task==="object"){let J=$.task;if(typeof J.taskId==="string")G=!0,this._taskProgressTokens.set(J.taskId,Y)}}if(!G)this._progressHandlers.delete(Y);if(V4(Q))W(Q);else{let $=_.fromError(Q.error.code,Q.error.message,Q.error.data);W($)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,Y,X){let{task:W}=X??{};if(!W){try{yield{type:"result",result:await this.request(Q,Y,X)}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}return}let G;try{let $=await this.request(Q,l1,X);if($.task)G=$.task.taskId,yield{type:"taskCreated",task:$.task};else throw new _(h.InternalError,"Task creation did not return a task");while(!0){let J=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:J},D1(J.status)){if(J.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(J.status==="failed")yield{type:"error",error:new _(h.InternalError,`Task ${G} failed`)};else if(J.status==="cancelled")yield{type:"error",error:new _(h.InternalError,`Task ${G} was cancelled`)};return}if(J.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let z=J.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,z)),X?.signal?.throwIfAborted()}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$,task:J,relatedTask:z}=X??{};return new Promise((H,U)=>{let A=(Z)=>{U(Z)};if(!this._transport){A(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),J)this.assertTaskCapability(Q.method)}catch(Z){A(Z);return}X?.signal?.throwIfAborted();let B=this._requestMessageId++,K={...Q,jsonrpc:"2.0",id:B};if(X?.onprogress)this._progressHandlers.set(B,X.onprogress),K.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:B}};if(J)K.params={...K.params,task:J};if(z)K.params={...K.params,_meta:{...K.params?._meta||{},[K1]:z}};let L=(Z)=>{this._responseHandlers.delete(B),this._progressHandlers.delete(B),this._cleanupTimeout(B),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:B,reason:String(Z)}},{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let k=Z instanceof _?Z:new _(h.RequestTimeout,String(Z));U(k)};this._responseHandlers.set(B,(Z)=>{if(X?.signal?.aborted)return;if(Z instanceof Error)return U(Z);try{let k=B1(Y,Z.result);if(!k.success)U(k.error);else H(k.data)}catch(k){U(k)}}),X?.signal?.addEventListener("abort",()=>{L(X?.signal?.reason)});let O=X?.timeout??iA,M=()=>L(_.fromError(h.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(B,O,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let w=z?.taskId;if(w){let Z=(k)=>{let S=this._responseHandlers.get(B);if(S)S(k);else this._onerror(Error(`Response handler missing for side-channeled request ${B}`))};this._requestResolvers.set(B,Z),this._enqueueTaskMessage(w,{type:"request",message:K,timestamp:Date.now()}).catch((k)=>{this._cleanupTimeout(B),U(k)})}else this._transport.send(K,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((Z)=>{this._cleanupTimeout(B),U(Z)})})}async getTask(Q,Y){return this.request({method:"tasks/get",params:Q},R6,Y)}async getTaskResult(Q,Y,X){return this.request({method:"tasks/result",params:Q},Y,X)}async listTasks(Q,Y){return this.request({method:"tasks/list",params:Q},v6,Y)}async cancelTask(Q,Y){return this.request({method:"tasks/cancel",params:Q},Q$,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let J={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[K1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:J,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!Y?.relatedRequestId&&!Y?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let J={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[K1]:Y.relatedTask}}};this._transport?.send(J,Y).catch((z)=>this._onerror(z))});return}let $={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)$={...$,params:{...$.params,_meta:{...$.params?._meta||{},[K1]:Y.relatedTask}}};await this._transport.send($,Y)}setRequestHandler(Q,Y){let X=v9(Q);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(W,G)=>{let $=x9(Q,W);return Promise.resolve(Y($,G))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,Y){let X=v9(Q);this._notificationHandlers.set(X,(W)=>{let G=x9(Q,W);return Promise.resolve(Y(G))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let Y=this._taskProgressTokens.get(Q);if(Y!==void 0)this._progressHandlers.delete(Y),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,Y,X){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,Y,X,W)}async _clearTaskQueue(Q,Y){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll(Q,Y);for(let W of X)if(W.type==="request"&&F9(W.message)){let G=W.message.id,$=this._requestResolvers.get(G);if($)$(new _(h.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,Y){let X=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)X=W.pollInterval}catch{}return new Promise((W,G)=>{if(Y.aborted){G(new _(h.InvalidRequest,"Request cancelled"));return}let $=setTimeout(W,X);Y.addEventListener("abort",()=>{clearTimeout($),G(new _(h.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,Y){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await X.createTask(W,Q.id,{method:Q.method,params:Q.params},Y)},getTask:async(W)=>{let G=await X.getTask(W,Y);if(!G)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(W,G,$)=>{await X.storeTaskResult(W,G,$,Y);let J=await X.getTask(W,Y);if(J){let z=b4.parse({method:"notifications/tasks/status",params:J});if(await this.notification(z),D1(J.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,$)=>{let J=await X.getTask(W,Y);if(!J)throw new _(h.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(D1(J.status))throw new _(h.InvalidParams,`Cannot update task "${W}" from terminal status "${J.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,$,Y);let z=await X.getTask(W,Y);if(z){let H=b4.parse({method:"notifications/tasks/status",params:z});if(await this.notification(H),D1(z.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function z$(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function H$(Q,Y){let X={...Q};for(let W in Y){let G=W,$=Y[G];if($===void 0)continue;let J=X[G];if(z$(J)&&z$($))X[G]={...J,...$};else X[G]=$}return X}var h5=KX(SY(),1),f5=KX(u5(),1);function QV(){let Q=new h5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return f5.default(Q),Q}class hY{constructor(Q){this._ajv=Q??QV()}getValidator(Q){let Y="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(X)=>{if(Y(X))return{valid:!0,data:X,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(Y.errors)}}}}class fY{constructor(Q){this._server=Q}requestStream(Q,Y,X){return this._server.requestStream(Q,Y,X)}async getTask(Q,Y){return this._server.getTask({taskId:Q},Y)}async getTaskResult(Q,Y,X){return this._server.getTaskResult({taskId:Q},Y,X)}async listTasks(Q,Y){return this._server.listTasks(Q?{cursor:Q}:void 0,Y)}async cancelTask(Q,Y){return this._server.cancelTask({taskId:Q},Y)}}function l5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"tools/call":if(!Q.tools?.call)throw Error(`${X} does not support task creation for tools/call (required for ${Y})`);break;default:break}}function m5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${X} does not support task creation for sampling/createMessage (required for ${Y})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${X} does not support task creation for elicitation/create (required for ${Y})`);break;default:break}}class lY extends _9{constructor(Q,Y){super(Y);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(E4.options.map((X,W)=>[X,W])),this.isMessageIgnored=(X,W)=>{let G=this._loggingLevels.get(W);return G?this.LOG_LEVEL_SEVERITY.get(X)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=Y?.capabilities??{},this._instructions=Y?.instructions,this._jsonSchemaValidator=Y?.jsonSchemaValidator??new hY,this.setRequestHandler(M9,(X)=>this._oninitialize(X)),this.setNotificationHandler(V9,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(S9,async(X,W)=>{let G=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:$}=X.params,J=E4.safeParse($);if(J.success)this._loggingLevels.set(G,J.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new fY(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=H$(this._capabilities,Q)}setRequestHandler(Q,Y){let W=V6(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let G;if(h1(W)){let J=W;G=J._zod?.def?.value??J.value}else{let J=W;G=J._def?.value??J.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let J=async(z,H)=>{let U=B1(I4,z);if(!U.success){let L=U.error instanceof Error?U.error.message:String(U.error);throw new _(h.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:A}=U.data,B=await Promise.resolve(Y(z,H));if(A.task){let L=B1(l1,B);if(!L.success){let O=L.error instanceof Error?L.error.message:String(L.error);throw new _(h.InvalidParams,`Invalid task creation result: ${O}`)}return L.data}let K=B1(_6,B);if(!K.success){let L=K.error instanceof Error?K.error.message:String(K.error);throw new _(h.InvalidParams,`Invalid tools/call result: ${L}`)}return K.data};return super.setRequestHandler(Q,J)}return super.setRequestHandler(Q,Y)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){m5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;l5(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let Y=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:pG.includes(Y)?Y:D9,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},j6)}async createMessage(Q,Y){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let X=Q.messages[Q.messages.length-1],W=Array.isArray(X.content)?X.content:[X.content],G=W.some((H)=>H.type==="tool_result"),$=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,J=$?Array.isArray($.content)?$.content:[$.content]:[],z=J.some((H)=>H.type==="tool_use");if(G){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!z)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(z){let H=new Set(J.filter((A)=>A.type==="tool_use").map((A)=>A.id)),U=new Set(W.filter((A)=>A.type==="tool_result").map((A)=>A.toolUseId));if(H.size!==U.size||![...H].every((A)=>U.has(A)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},C9,Y);return this.request({method:"sampling/createMessage",params:Q},R9,Y)}async elicitInput(Q,Y){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},g6,Y)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},G=await this.request({method:"elicitation/create",params:W},g6,Y);if(G.action==="accept"&&G.content&&W.requestedSchema)try{let J=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!J.valid)throw new _(h.InvalidParams,`Elicitation response content does not match requested schema: ${J.errorMessage}`)}catch($){if($ instanceof _)throw $;throw new _(h.InternalError,`Error validating elicitation response: ${$ instanceof Error?$.message:String($)}`)}return G}}}createElicitationCompletionNotifier(Q,Y){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},Y)}async listRoots(Q,Y){return this.request({method:"roots/list",params:Q},k9,Y)}async sendLoggingMessage(Q,Y){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,Y))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}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"})}}var c5={name:"@sequenzy/mcp",version:"0.0.93",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^5.8.0"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var mY=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],p5={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",landingPages:"/dashboard/company/{companyId}/landing-pages",landingPage:"/dashboard/company/{companyId}/landing-pages/{landingPageId}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function XV(Q){let X=(Q??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return X.length>0?X:"https://sequenzy.com"}function l0(Q){let Y=Q?.trim();return Y?Y:void 0}function r0(Q){return encodeURIComponent(Q)}function $0(Q,Y){return`${Q}${Y}`}function J0(Q,Y=""){return`/dashboard/company/${r0(Q)}${Y}`}function i5(Q,Y,X){return $0(Q,`${J0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function WV(Q,Y){let X=mY.map((W)=>[W,Y?i5(Q,Y,W):""]);return Object.fromEntries(X)}function N1(Q={},Y){let X=XV(Y),W=l0(Q.companyId),G={},$=WV(X,W);if(!W)return{appUrl:X,routeTemplates:p5,settingsTabValues:mY,urls:G,settingsUrls:$};G.dashboard=$0(X,J0(W)),G.campaigns=$0(X,J0(W,"/campaign")),G.landingPages=$0(X,J0(W,"/landing-pages")),G.sequences=$0(X,J0(W,"/sequences")),G.settings=$0(X,J0(W,"/settings")),G.emails=$0(X,J0(W,"/emails")),G.subscribers=$0(X,J0(W,"/subscribers")),G.sentEmails=$0(X,J0(W,"/sent-emails")),G.segments=$0(X,J0(W,"/segments")),G.metrics=$0(X,J0(W,"/metrics")),G.transactional=$0(X,J0(W,"/transactional"));let J=l0(Q.campaignId);if(J)G.campaign=$0(X,J0(W,`/campaign/${r0(J)}`)),G.campaignPreview=`${G.campaign}?step=review`;let z=l0(Q.landingPageId);if(z)G.landingPage=$0(X,J0(W,`/landing-pages/${r0(z)}`));let H=l0(Q.sequenceId);if(H)G.sequence=$0(X,J0(W,`/sequences/${r0(H)}`));let U=l0(Q.emailId)??l0(Q.templateId);if(U)G.email=$0(X,J0(W,`/emails/${r0(U)}`)),G.template=G.email;let A=l0(Q.transactionalId);if(A)G.transactionalEmail=$0(X,J0(W,`/transactional/${r0(A)}`));let B=l0(Q.emailSendId);if(B)G.emailSend=$0(X,J0(W,`/sent-emails/${r0(B)}`));let K=l0(Q.domainId);if(K)G.domain=$0(X,J0(W,`/settings/domain/${r0(K)}`)),G.domainVerify=`${G.domain}/verify`;let L=l0(Q.status);if(L)G.campaignList=$0(X,J0(W,`/campaign/list/${r0(L)}`)),G.sequenceList=$0(X,J0(W,`/sequences/list/${r0(L)}`));let O=l0(Q.settingsTab);if(O)G.settingsTab=i5(X,W,O);return{appUrl:X,routeTemplates:p5,settingsTabValues:mY,urls:G,settingsUrls:$}}var n5=[{uri:"sequenzy://dashboard",name:"Dashboard Overview",description:"Live overview stats for the last 7 days",mimeType:"application/json"},{uri:"sequenzy://company",name:"Current Company",description:"The currently selected company, including localization settings",mimeType:"application/json"},{uri:"sequenzy://campaigns/recent",name:"Recent Campaigns",description:"Last 10 campaigns with status and basic stats",mimeType:"application/json"},{uri:"sequenzy://subscribers/recent",name:"Recent Subscribers",description:"Most recently added subscribers",mimeType:"application/json"},{uri:"sequenzy://subscribers/engaged",name:"Engaged Subscribers",description:"Most active/engaged subscribers",mimeType:"application/json"},{uri:"sequenzy://sequences",name:"Sequences",description:"All email sequences with status",mimeType:"application/json"},{uri:"sequenzy://templates",name:"Templates",description:"All available email templates with localization status",mimeType:"application/json"},{uri:"sequenzy://segments",name:"Segments",description:"All defined segments with subscriber counts",mimeType:"application/json"},{uri:"sequenzy://tags",name:"Tags",description:"All tags with usage counts",mimeType:"application/json"},{uri:"sequenzy://health",name:"Deliverability Health",description:"Email deliverability metrics and health status",mimeType:"application/json"},{uri:"sequenzy://app-routes",name:"Dashboard URL Routes",description:"Route templates and settings tabs for building Sequenzy dashboard links",mimeType:"application/json"}];async function r5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await D("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await D("GET","/api/v1/account"),W=J1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await D("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await D("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await D("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await D("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await D("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await D("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await D("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await D("GET","/api/v1/tags");break;case"sequenzy://health":Y=await D("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=N1();break;default:throw Error(`Unknown resource: ${Q}`)}return{contents:[{uri:Q,mimeType:"application/json",text:JSON.stringify(Y,null,2)}]}}catch(Y){return{contents:[{uri:Q,mimeType:"text/plain",text:$1(Y)}]}}}import{readFileSync as GV,statSync as $V}from"node:fs";import{basename as JV}from"node:path";var WX=' Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in the transactional send `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" } where the text before the colon is a {{merge tag}} path (nested paths like "order.total" or "event.plan" work) and the text after it is the comparison value. `field` may also be "attribute" (same "name:value" form) or "email"/"firstName"/"lastName" (the value is the plain comparison string). Operators: is, is_not, contains, not_contains, gt, gte, lt, lte, is_empty, is_not_empty. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block.',s4=`Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. For provider-migrated HTML from another email platform, prefer the \`html\` field instead; Sequenzy stores it as one raw HTML block to preserve the original design. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.${WX}`,Q4=`Replacement Sequenzy email blocks. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`.${WX}`,tY=`Sequenzy email blocks. Provide blocks or html for email steps. For migrated provider HTML, prefer \`html\`; Sequenzy stores it as one raw HTML block and does not recreate it as native blocks. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Blocks can include repeat blocks over array variables such as items.${WX}`,NQ="Complete Sequenzy landing page content JSON. Use this when replacing the page structure. The content must be the editor-compatible landing page schema with version, template, seo, theme, and blocks. Landing pages must include exactly one footer block and at most one form block.",zV="Optional template key for default content, such as from-scratch, waitlist, lead-magnet, launch, demo-request, webinar, newsletter, product-hunt, pricing-offer, agency-lead-gen, or feature-announcement.",d5=500,o5=500,w1={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},cY=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay"],t5={type:"object",description:"Optional send window for every email step in the sequence. When set, email actions that become due outside the window wait until the next allowed local time. Omit days to allow every day.",properties:{enabled:{type:"boolean",description:"Set false to disable the sending window when creating a sequence. For updates, prefer clearSendingWindow."},timezone:{type:"string",description:"IANA timezone for the window, e.g. Europe/Kiev or America/New_York."},startTime:{type:"string",description:"Earliest local send time in 24-hour HH:mm format, e.g. 08:00."},endTime:{type:"string",description:"Latest local send cutoff in 24-hour HH:mm format, e.g. 20:00. Must be later than startTime."},days:{type:"array",description:"Allowed local days. Use full names or short names such as monday, tuesday, mon, tue. Omit for every day.",items:{type:"string"}}},additionalProperties:!1},HV={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},aY={type:"object",description:"Wait until a date from the trigger event before this step. Use this for renewal reminders, appointment follow-ups, trial-expiry nudges, and other subscriber-specific dates. The field value must be an ISO date string or Unix timestamp.",properties:{field:{type:"string",description:"Dot-path into the trigger event properties, e.g. renews_at or booking.startsAt."},untilDateField:{type:"string",description:"Alias for field."},offset:HV,days:{type:"number",description:"Offset days shorthand. Ignored when offset is provided."},hours:{type:"number",description:"Offset hours shorthand. Ignored when offset is provided."},minutes:{type:"number",description:"Offset minutes shorthand. Ignored when offset is provided."},direction:{type:"string",enum:["before","after"],description:"Whether the offset applies before or after the resolved date. Defaults to after."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"Alias for direction."},missingAction:{type:"string",enum:["continue","exit"],description:"What to do if the event field is missing or invalid. Defaults to continue."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"Alias for missingAction."}},additionalProperties:!1},sY={type:"object",description:"Fixed delay before this step. For a dynamic wait-until-date delay, either set mode:'until_date' plus untilDateField here, or use waitUntil.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"},mode:{type:"string",enum:["duration","until_date"],description:"Use duration for a fixed wait, or until_date to resolve a date from the trigger event."},untilDateField:{type:"string",description:"For mode:'until_date', dot-path into the trigger event properties."},field:{type:"string",description:"Alias for untilDateField."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"For mode:'until_date', whether days/hours/minutes are before or after the event date. Defaults to after."},direction:{type:"string",enum:["before","after"],description:"Alias for untilOffsetDirection."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"For mode:'until_date', what to do when the field is missing or invalid. Defaults to continue."},missingAction:{type:"string",enum:["continue","exit"],description:"Alias for untilMissingAction."}},additionalProperties:!1},PQ=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],bQ=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","sequence.finished","sequence.failed"],UV=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_websites","check_website","get_integration_guide","get_subscriber","list_subscriber_notes","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_email_send","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_transactional_emails","get_transactional_email","get_stats","get_campaign_stats","get_sequence_stats","list_campaign_events","list_sequence_events","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_sequence","generate_subject_lines","generate_sms","get_sms_settings"]),AV=new Set(["select_company","create_company","update_company","update_sync_rules","update_shopify_automation_settings","create_api_key","add_website","add_subscriber","update_subscriber","add_subscriber_note","remove_subscriber","delete_subscriber_note","upsert_products","delete_product","attach_product_file","remove_product_file","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","delete_template","restart_ab_test","update_ab_test_variant","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","send_test_sms","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_landing_page","update_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","update_sequence","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery","submit_feedback"]),BV=new Set(["send_test_email","send_test_sms","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","enable_sequence","resume_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery"]),KV=new Set(["remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","disable_sequence","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook"]);function DV(Q){let Y=UV.has(Q),X=AV.has(Q);if(Y===X)throw Error(`MCP tool "${Q}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:Y,destructiveHint:Y?!1:KV.has(Q),openWorldHint:BV.has(Q)}}function LV(Q){return{...Q,annotations:{...Q.annotations,...DV(Q.name)}}}var eY={status:["is","is_not"],phone:["is_not_empty","is_empty"],smsStatus:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"],commerceProduct:["is","is_not","at_least","less_than_count"]},FV=Object.entries(eY).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),a5={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","phone","smsStatus","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct","commerceProduct"],description:"Filter field. Use `phone` with is_not_empty/is_empty to check whether a subscriber has a phone number, and `smsStatus` (is/is_not one of `subscribed`, `unsubscribed`, `not_subscribed`) for SMS marketing consent. Use `event` for custom subscriber events, `segment` for saved segment membership, `stripeProduct`/`stripeCurrentProduct`/`stripeTrialProduct` for Stripe product-based segments, and `commerceProduct` for products purchased through commerce orders - the value is `provider:productId` (provider one of `shopify`, `woocommerce`, `api`; product ids are provider-scoped), optionally with an order-count threshold (`provider:productId:count`) for at_least/less_than_count; a bare product id matches the id on any provider. Engagement fields (`emailSent`, `emailDelivered`, `emailOpened`, `emailClicked`, `emailBounced`, `emailComplained`) accept a time range as the value or a specific campaign via `campaign:<campaign_id>`."},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${FV}.`},value:{type:"string",description:"Filter value. For custom attribute empty checks, use `attributeName:` such as `last_logged_in:`. Event examples: `saas.purchase:30d`, `saas.purchase:all`, or `saas.purchase:5:30d` for thresholds. Segment values are segment IDs. Stripe product examples: `prod_123` for bought/didn't buy/current/trialing, `prod_123:3` for payment thresholds, `prod_123:is_canceled` for products set to cancel, `prod_123:cancels_at:2026-05-26`, `prod_123:end_at:2026-05-26`, or `prod_123:start_at:7 days ago` for product-scoped dates. Engagement examples: `7d`, `30d`, `90d`, `180d`, `all` for rolling time windows, or `campaign:<campaign_id>` to scope to a specific sent campaign (use `list_campaigns` to find IDs)."}},required:["field","operator","value"],additionalProperties:!1},s5={type:"object",properties:{kind:{type:"string",enum:["group"]},id:{type:"string",description:"Stable group ID. Any string works; one will be generated if omitted."},joinOperator:{type:"string",enum:["and","or"],description:"How children in this group combine."},children:{type:"array",minItems:1,items:{type:"object",description:'Either a filter leaf (`kind: "filter"`) or another group (`kind: "group"`).'}}},required:["kind","joinOperator","children"],additionalProperties:!0};function QX(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(typeof Y!=="object"||Y===null)return Y;let X=Y;if(typeof X.id==="string"&&X.id.trim()!=="")return X;return{...X,id:crypto.randomUUID()}})}function YX(Q){if(typeof Q!=="object"||Q===null)return Q;let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=QX([Y]);return Array.isArray(X)?X[0]:Y}if(Y.kind!=="group")return Q;return{...Y,id:typeof Y.id==="string"&&Y.id.trim()!==""?Y.id:crypto.randomUUID(),children:Array.isArray(Y.children)?Y.children.map(YX):[]}}function qV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function OV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function e5(Q){if(Q==="all")return!0;let Y=Q.match(/^(\d+)d$/);if(!Y?.[1])return!1;let X=Number.parseInt(Y[1],10);return Number.isInteger(X)&&X>0}function MV(Q,Y){let X=Y.split(":");if(Q==="at_least"||Q==="less_than_count"){if(X.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let $=X.slice(0,-2).join(":").trim(),J=X.at(-2),z=X.at(-1),H=J===void 0?Number.NaN:Number.parseInt(J,10);return $&&Number.isInteger(H)&&H>0&&z!==void 0&&e5(z)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(X.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=X.slice(0,-1).join(":").trim(),G=X.at(-1);return W&&G!==void 0&&e5(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function VV(Q){let Y=Q.indexOf(":");if(Y===-1)return{productId:Q,subfilter:null,rawValue:null};let X=Q.substring(0,Y),W=Q.substring(Y+1),G=W.indexOf(":");if(G===-1)return{productId:X,subfilter:W,rawValue:null};return{productId:X,subfilter:W.substring(0,G),rawValue:W.substring(G+1)}}function ZV(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function NV(Q){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(Q)}function wV(Q,Y){if(Y==="cancels_at"||Y==="cancel_at"||Y==="cancellation_at")return!0;if(Q==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(Y);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(Y)}function PV(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function bV(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let z=X.indexOf(":");if(z===-1)return null;let H=X.substring(0,z).trim(),U=Number.parseInt(X.substring(z+1).trim(),10);return H&&Number.isInteger(U)&&U>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(Q!=="stripeCurrentProduct"&&Q!=="stripeTrialProduct")return null;let{productId:W,subfilter:G,rawValue:$}=VV(X);if(!W.trim())return"Stripe product filters must include a product ID.";if(!G)return Y==="is"||Y==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let J=ZV(G);if(NV(J))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!wV(Q,J))return`Unsupported Stripe product subfilter "${G}".`;if(!PV(Y))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return $?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var jV=new Set(["shopify","woocommerce","api"]);function IV(Q,Y){let X=Y.trim(),W=X.indexOf(":");if(W!==-1&&jV.has(X.substring(0,W).trim()))X=X.substring(W+1).trim();if(!X)return'Purchased Product filters must include a product ID, like "shopify:42".';if(Q!=="at_least"&&Q!=="less_than_count")return null;let G=X.lastIndexOf(":");if(G===-1)return null;let $=X.substring(0,G).trim(),J=Number.parseInt(X.substring(G+1).trim(),10);return $&&Number.isInteger(J)&&J>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function GX(Q){if(typeof Q!=="object"||Q===null)return"Segment filters must be objects.";let Y=Q,X=Y.field,W=Y.operator,G=Y.value;if(typeof X!=="string"||!(X in eY))return`Unsupported segment filter field "${String(X)}".`;if(typeof W!=="string")return`Segment filter "${X}" must include an operator.`;let $=eY[X];if(!$.includes(W))return`Operator "${W}" is not supported for ${X} filters. Use one of: ${$.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${X}" must include a value.`;if(X==="attribute"&&typeof G==="string"){if(!qV(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!OV(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let J=MV(W,G);if(J)return J}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let J=bV(X,W,G);if(J)return J}if(X==="commerceProduct"&&typeof G==="string"){let J=IV(W,G);if(J)return J}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map((z)=>z.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function $X(Q){if(typeof Q!=="object"||Q===null)return[];let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=GX(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap($X);return[]}function P1(Q,Y,X){if(Y.html!==void 0&&Y.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`, not both.`);if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error(`\`blocks\` must be an array when calling \`${Q}\`.`);if(X?.requireContent&&Y.html===void 0&&Y.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`.`)}function wQ(Q,Y){if(Y.labels===void 0)return;if(!Array.isArray(Y.labels))throw Error(`\`labels\` must be an array when calling \`${Q}\`.`);if(Y.labels.some((X)=>typeof X!=="string"||X.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${Q}\`.`)}function EV(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!Y&&!X)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=GX(G);return $?[$]:[]}):$X(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function TV(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(Q.name===void 0&&Q.filterJoinOperator===void 0&&!Y&&!X)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=GX(G);return $?[$]:[]}):X?$X(Q.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var pY=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection"];function iY(Q,Y,X){if(Y[X]!==void 0&&!z0(Y[X]))throw Error(`\`${X}\` must be an object when calling \`${Q}\`.`)}function QH(Q,Y,X){if(Y[X]!==void 0&&!Array.isArray(Y[X]))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`)}function SV(Q){let Y=new Set(["companyId",...pY]),X=Object.keys(Q).filter((G)=>!Y.has(G));if(X.length>0)throw Error(`\`update_company\` accepts only company product-info fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);let W={};for(let G of pY)if(Q[G]!==void 0)W[G]=Q[G];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${pY.map((G)=>`\`${G}\``).join(", ")} when calling \`update_company\`.`);for(let G of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection"])if(Q[G]!==void 0&&typeof Q[G]!=="string")throw Error(`\`${G}\` must be a string when calling \`update_company\`.`);if(iY("update_company",Q,"brandColors"),iY("update_company",Q,"socialLinks"),iY("update_company",Q,"pricing"),QH("update_company",Q,"valueProps"),QH("update_company",Q,"testimonials"),typeof Q.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(Q.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");return W}function RV(Q){if(Q.clearEnrollmentFieldPath===!0&&Q.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(Q.clearSendingWindow===!0&&Q.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(Q.clearBccEmails===!0&&Q.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(Q.branch!==void 0&&Q.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");let Y={...Q};if(delete Y.clearEnrollmentFieldPath,delete Y.clearSendingWindow,delete Y.clearBccEmails,Q.clearEnrollmentFieldPath===!0)Y.enrollmentFieldPath=null;if(Q.clearSendingWindow===!0)Y.sendingWindow=null;if(Q.clearBccEmails===!0)Y.bccEmails=null;return Y}function CV(Q){let Y=Q.type==="sms",X;if(Y){let G=N(Q,"text"),$=Array.isArray(Q.blocks)&&Q.blocks.length>0;if(G===void 0&&!$)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");X={type:"sms"};for(let J of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(Q[J]!==void 0)X[J]=Q[J]}else{P1("insert_sequence_step",Q,{requireContent:!0}),X={subject:R("insert_sequence_step",Q,"subject")};for(let G of["name","previewText","html","blocks","delay","delayMs","waitUntil"])if(Q[G]!==void 0)X[G]=Q[G]}let W={steps:[X]};if(Q.afterNodeId!==void 0)W.afterNodeId=Q.afterNodeId;return{...Q.confirmStructuralChange!==void 0&&{confirmStructuralChange:Q.confirmStructuralChange},insertSteps:W}}function kV(Q){let Y=N(Q,"subscriberId"),X=Q.fieldValues,W=X===void 0?void 0:Array.isArray(X)?X:void 0;if(X!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let G=W?.map((z)=>typeof z==="string"?z.trim():"").filter((z)=>z.length>0)??[];if(W?.some((z)=>typeof z!=="string")||W!==void 0&&G.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(Y!==void 0===G.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let $=N(Q,"fieldPath"),J=N(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...$!==void 0&&{fieldPath:$},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...J!==void 0&&{reason:J}}}function vV(Q){P1("create_campaign",Q),wQ("create_campaign",Q);let Y=N(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0,G=Q.templateId!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(Y&&(X||W||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!Y&&N(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function xV(Q){if(N(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!z0(Q.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(Q.sendTimeOptimization!==void 0){if(typeof Q.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(Q.spreadOverHours!==void 0){if(typeof Q.spreadOverHours!=="number"||!Number.isInteger(Q.spreadOverHours)||Q.spreadOverHours<1||Q.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(Q.recurringInterval!==void 0&&Q.recurringInterval!=="weekly"&&Q.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function nY(Q,Y,X){let W=new Set(["companyId","landingPageId","name","slug","content"]),G=Object.keys(Y).filter(($)=>!W.has($));if(G.length>0)throw Error(`\`${Q}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map(($)=>`\`${$}\``).join(", ")}.`);if(X.requireUpdate&&Y.name===void 0&&Y.slug===void 0&&Y.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${Q}\`.`);return{...Y.name!==void 0&&{name:Y.name},...Y.slug!==void 0&&{slug:Y.slug},...Y.content!==void 0&&{content:Y.content}}}function _V(Q){let Y=new Set(["companyId","domain","verify"]),X=Object.keys(Q).filter((W)=>!Y.has(W));if(X.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${X.length===1?"":"s"}: ${X.map((W)=>`\`${W}\``).join(", ")}.`);if(Q.domain===void 0&&Q.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...Q.domain!==void 0&&{domain:Q.domain},...typeof Q.verify==="boolean"&&{verify:Q.verify}}}function gV(Q){P1("create_transactional_email",Q);let Y=N(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(Y&&(X||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!Y&&!X&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!Y&&N(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var rY={type:"object",description:"A step to create inside a sequence path. Use type:'delay' for a standalone delay, type:'email' for an email, type:'create_discount' for a discount action, or type:'condition' for a condition gate.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","condition","webhook"],description:"Sequence path step type. Omit for email steps; use delay for standalone waits."},nodeType:{type:"string",enum:["logic_delay","action_email","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","logic_condition","action_webhook"],description:"Advanced sequence path node type. Prefer type unless creating a non-email action."},config:{type:"object",description:"Config for advanced nodeType steps such as tag/list/webhook/wait-for-event/condition actions.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:tY,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},delay:sY,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:aY,name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use stripe to dynamically create a Stripe coupon plus promotion code, or shopify to dynamically create a Shopify Admin discount code."},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"}},additionalProperties:!1};function yV(Q){if(!Q||typeof Q!=="object")return null;let Y=Q;if(Y.success!==!1)return null;if(typeof Y.error==="string")return Error(Y.error);if(Y.error&&typeof Y.error==="object"&&typeof Y.error.message==="string")return Error(Y.error.message);if(typeof Y.message==="string")return Error(Y.message);return Error("The tool returned an unsuccessful response.")}function z0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function YH(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function uV(Q){let Y=new URLSearchParams;if(typeof Q.query==="string"&&Q.query.trim()!=="")Y.set("query",Q.query.trim());if(Array.isArray(Q.tags)&&Q.tags.length>0)Y.set("tags",Q.tags.filter((X)=>typeof X==="string"&&X.trim()!=="").join(","));if(typeof Q.list==="string"&&Q.list.trim()!=="")Y.set("list",Q.list.trim());if(typeof Q.listId==="string"&&Q.listId.trim()!=="")Y.set("listId",Q.listId.trim());if(typeof Q.listName==="string"&&Q.listName.trim()!=="")Y.set("listName",Q.listName.trim());if(typeof Q.segmentId==="string"&&Q.segmentId.trim()!=="")Y.set("segmentId",Q.segmentId);if(typeof Q.status==="string"&&Q.status.trim()!=="")Y.set("status",Q.status.trim());return Y.set("page",String(Q.page)),Y.set("limit",String(Q.pageSize)),Y}async function hV(Q,Y){let X=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,W=Math.min(100,Math.max(1,X??100)),G=[],$=1,J=0,z=0,H=0;while(!0){let A=uV({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:$,pageSize:W}),B=await D("GET",`/api/v1/subscribers?${A.toString()}`,void 0,Y);J=B.pagination?.total??B.subscribers.length,z=B.pagination?.totalPages??1,H+=1,G.push(...B.subscribers??[]);let K=X!==void 0&&G.length>=X,L=B.pagination?$>=B.pagination.totalPages:(B.subscribers??[]).length<W;if(K||L)break;$+=1}let U=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:U,pagination:{page:1,limit:W,total:J,totalPages:z,fetchedPages:H},returned:U.length,truncated:X!==void 0&&J>0&&U.length<J}}function fV(Q){let Y=typeof Q.email==="string"&&Q.email.trim()!==""?Q.email.trim():void 0,X=typeof Q.externalId==="string"&&Q.externalId.trim()!==""?Q.externalId.trim():void 0;return{...Y?{email:Y}:{},...X?{externalId:X}:{}}}function v1(Q,Y){let X=fV(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function XX(Q,Y){let X=new URLSearchParams;if(Y?.includeMachineEngagement)X.set("includeMachineEngagement","true");let W=X.toString(),G=W?`?${W}`:"";if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}${G}`;return X.set("externalId",String(Q.externalId)),`/api/v1/subscribers/external?${X.toString()}`}function XH(Q){if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}/notes`;let Y=new URLSearchParams;return Y.set("externalId",String(Q.externalId)),`/api/v1/subscribers/external/notes?${Y.toString()}`}async function dY(Q,Y,X){return D("GET",XX(Q,X),void 0,Y)}function N(Q,Y){let X=Q[Y];if(typeof X!=="string")return;let W=X.trim();return W.length>0?W:void 0}function R(Q,Y,X){let W=N(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function m0(Q,Y,X,W){let G=N(Y,X);if(G===void 0)return;if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function oY(Q,Y,X,W){let G=R(Q,Y,X);if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function x1(Q,Y,X,W,G){let $=Y[X];if($===void 0)return;if(typeof $!=="number"||!Number.isInteger($)||$<W||$>G)throw Error(`\`${X}\` must be an integer between ${W} and ${G} when calling \`${Q}\`.`);return $}function lV(Q,Y){let X=[],W=m0(Q,Y,"eventType",cY);if(W)X.push(W);if(Y.eventTypes!==void 0){if(!Array.isArray(Y.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${Q}\`.`);Y.eventTypes.forEach((G,$)=>{if(typeof G!=="string")throw Error(`\`eventTypes\` item ${$+1} must be a string when calling \`${Q}\`.`);let J=G.trim();if(!cY.includes(J))throw Error(`\`eventTypes\` item ${$+1} must be one of ${cY.join(", ")} when calling \`${Q}\`.`);X.push(J)})}return[...new Set(X)]}function WH(Q,Y){let X=new URLSearchParams,W=lV(Q,Y);if(W.length>0)X.set("eventTypes",W.join(","));let G=m0(Q,Y,"period",["1h","24h","7d","30d","90d"]);if(G)X.set("period",G);let $=N(Y,"start");if($)X.set("start",$);let J=N(Y,"end");if(J)X.set("end",J);let z=x1(Q,Y,"page",1,1e6);if(z!==void 0)X.set("page",String(z));let H=x1(Q,Y,"limit",1,500);if(H!==void 0)X.set("limit",String(H));if(Y.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");return X}function GH(Q,Y){if(Y.events===void 0)return;if(!Array.isArray(Y.events))throw Error(`\`events\` must be an array when calling \`${Q}\`.`);let X=Y.events.map((W,G)=>{if(typeof W!=="string"||!bQ.includes(W))throw Error(`\`events\` item ${G+1} must be one of ${bQ.join(", ")} when calling \`${Q}\`.`);return W});if(X.length===0)throw Error(`\`events\` must include at least one event type when calling \`${Q}\`.`);return X}function $H(Q,Y){if(!Array.isArray(Y.emails))throw Error(`\`emails\` must be an array when calling \`${Q}\`.`);let X=[];if(Y.emails.forEach((W,G)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${Q}\`.`);let $=W.trim();if($.length>0)X.push($)}),X.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${Q}\`.`);if(X.length>d5)throw Error(`\`emails\` must include no more than ${d5} email addresses when calling \`${Q}\`. Split larger batches into multiple calls.`);return X}function JH(Q,Y,X,W){let G=Y[X];if(G===void 0)return;if(!Array.isArray(G))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`);let $=[];if(G.forEach((J,z)=>{if(typeof J!=="string")throw Error(`\`${X}\` item ${z+1} must be a string when calling \`${Q}\`.`);let H=J.trim();if(H.length>0)$.push(H)}),$.length===0)throw Error(`\`${X}\` must include at least one ${W} when calling \`${Q}\`.`);return $}function mV(Q){let X=JH("enroll_subscribers_in_sequence",Q,"emails","email address"),W=JH("enroll_subscribers_in_sequence",Q,"subscriberIds","subscriber ID"),G=(X?.length??0)+(W?.length??0);if(G===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(G>o5)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${o5} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let $=N(Q,"targetNodeId");return{...X!==void 0&&{emails:X},...W!==void 0&&{subscriberIds:W},...$!==void 0&&{targetNodeId:$}}}var cV={pdf:"application/pdf",epub:"application/epub+zip",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",txt:"text/plain",csv:"text/csv"};function pV(Q){let Y=Q.split(".").pop()?.toLowerCase()??"";return cV[Y]??null}var iV=104857600;async function nV(Q,Y){if(!qX())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let X=pV(Q);if(!X)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=$V(Q).size;if(W>iV)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=GV(Q),$=await D("POST","/api/v1/products/delivery/upload-url",{filename:JV(Q),contentType:X,fileSizeBytes:W},Y),J=await fetch($.uploadUrl,{method:"PUT",headers:{"Content-Type":X},body:G});if(!J.ok)throw Error(`File upload failed (${J.status})`);return{url:$.publicUrl,fileName:$.fileName,fileSizeBytes:W,mimeType:X}}async function JX(Q){let Y=N(Q,"companyId");if(Y)return Y;let X=J1();if(X)return X;try{return(await D("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function rV(Q,Y){let X=await JX(Y);if(!X)throw Error(`A company is required when calling \`${Q}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return X}function Y4(Q,Y){if(!z0(Q)||!Y)return Q;return{...Q,url:Y}}function zH(Q,Y){if(!z0(Q))return Q;return{...Q,...Y.campaign!==void 0&&{url:Y.campaign},...Y.campaignPreview!==void 0&&{previewUrl:Y.campaignPreview}}}function e4(Q,Y,X){if(!Array.isArray(Q)||!Y)return Q;return Q.map((W)=>{if(!z0(W))return W;let G=N(W,"id");if(!G)return W;let $=N1({companyId:Y,...X==="campaign"&&{campaignId:G},...X==="landingPage"&&{landingPageId:G},...X==="sequence"&&{sequenceId:G},...X==="template"&&{emailId:G},...X==="transactional"&&{transactionalId:G}});if(X==="campaign")return zH(W,$.urls);let J=X==="sequence"?$.urls.sequence:X==="landingPage"?$.urls.landingPage:X==="template"?$.urls.email:$.urls.transactionalEmail;return Y4(W,J)})}function dV(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!z0(Y))return Y;let X=N(Y,"id");if(!X)return Y;let W=N1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var HH=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","update_sequence","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function oV(Q,Y,X){if(!z0(X)||!HH.has(Q))return X;let W=z0(X.company)?X.company:void 0,$=N(X,"selectedCompanyId")??N(X,"currentCompanyId")??N(X,"companyId")??(W?N(W,"id"):void 0)??(W?N(W,"companyId"):void 0)??await JX(Y);if(!$)return X;let J=z0(X.campaign)?X.campaign:void 0,z=z0(X.sequence)?X.sequence:void 0,H=z0(X.landingPage)?X.landingPage:void 0,U=z0(X.template)?X.template:void 0,A=z0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,B={companyId:$,campaignId:N(Y,"campaignId")??N(X,"campaignId")??(J?N(J,"id"):void 0),landingPageId:N(Y,"landingPageId")??N(X,"landingPageId")??(H?N(H,"id"):void 0),sequenceId:N(Y,"sequenceId")??N(X,"sequenceId")??(z?N(z,"id"):void 0),emailId:N(X,"templateId")??(U?N(U,"id"):void 0)??(A?N(A,"emailId"):void 0)??N(Y,"templateId"),transactionalId:N(Y,"transactionalId")??(A?N(A,"id"):void 0)??N(Y,"idOrSlug"),emailSendId:N(Y,"emailSendId")??N(X,"emailSendId")??(z0(X.emailSend)?N(X.emailSend,"id"):void 0),status:N(Y,"status")},K=N1(B),L=W?N1({companyId:$}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:dV(X.companies)},...Array.isArray(X.campaigns)&&{campaigns:e4(X.campaigns,$,"campaign")},...Array.isArray(X.landingPages)&&{landingPages:e4(X.landingPages,$,"landingPage")},...Array.isArray(X.sequences)&&{sequences:e4(X.sequences,$,"sequence")},...Array.isArray(X.templates)&&{templates:e4(X.templates,$,"template")},...Array.isArray(X.transactional)&&{transactional:e4(X.transactional,$,"transactional")},...W&&L!==void 0&&{company:{...W,url:L.urls.dashboard,settingsUrl:L.urls.settings}},...J&&K.urls.campaign!==void 0&&{campaign:zH(J,K.urls)},...z&&K.urls.sequence!==void 0&&{sequence:Y4(z,K.urls.sequence)},...H&&K.urls.landingPage!==void 0&&{landingPage:Y4(H,K.urls.landingPage)},...U&&K.urls.email!==void 0&&{template:Y4(U,K.urls.email)},...A&&K.urls.transactionalEmail!==void 0&&{transactional:Y4(A,K.urls.transactionalEmail)},...z0(X.emailSend)&&K.urls.emailSend!==void 0&&{emailSend:Y4(X.emailSend,K.urls.emailSend)},appUrls:K.urls}}var tV={type:"boolean",description:"Whether the Sequenzy operation succeeded."},aV={type:"string",description:"Human-readable status, confirmation, or next-step message."},sV={type:"string",description:"Additional context about the result."};function W0(Q){return{type:"object",description:Q,additionalProperties:!0}}function eV(Q){return{type:"array",description:Q,items:W0("One item in the returned collection.")}}function T(Q){return{type:"string",description:Q}}function b0(Q){return{type:"number",description:Q}}function G1(Q){return{type:"boolean",description:Q}}function V(Q){return W0(`The ${Q} record returned by Sequenzy.`)}function p(Q){return eV(`List of ${Q} records returned by Sequenzy.`)}var QZ={appUrls:W0("Dashboard URLs for relevant Sequenzy resources."),url:T("Primary dashboard URL for this result."),settingsUrl:T("Company settings URL when available.")},YZ={success:tV,message:aV,note:sV,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:W0("One returned item.")},value:W0("Fallback object wrapper used only when a tool returns a non-object value.")},XZ={get_account:{account:V("account"),companies:p("company"),currentCompanyId:T("Company ID selected by the authenticated API key, when available."),selectedCompanyId:T("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:T("Selected company ID."),companyName:T("Selected company name.")},get_app_urls:{dashboard:T("Company dashboard URL."),settings:T("Company settings URL."),campaign:T("Campaign editor URL."),landingPage:T("Landing page editor URL."),sequence:T("Sequence editor URL."),email:T("Email editor URL."),transactionalEmail:T("Transactional email URL."),emailSend:T("Sent email detail URL."),domain:T("Sending domain settings URL."),urls:W0("All generated URLs keyed by resource type.")},create_company:{company:V("company"),autoSelected:G1("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:V("company")},get_company:{company:V("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:W0("One sync rule.")},isDefault:G1("Whether the company still uses the platform default rules.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:W0("One sync rule.")},isDefault:G1("Whether the company now uses the platform default rules.")},get_shopify_automation_settings:{browseAbandonment:W0("Effective browse-abandonment settings (defaults applied)."),priceDrop:W0("Effective price-drop settings (defaults applied)."),shopDomain:T("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:W0("Effective browse-abandonment settings after the update."),priceDrop:W0("Effective price-drop settings after the update."),shopDomain:T("Connected Shopify store domain.")},create_api_key:{apiKey:W0("Created API key metadata: the newly created secret in `key`, plus `scopes` listing the assigned permission scopes (null when the key has full access)."),key:T("Newly created API key if the API response uses the short key field.")},list_websites:{websites:p("sender website")},add_website:{website:V("sender website")},check_website:{website:V("sender website"),ready:G1("Whether the sender website is ready."),status:T("Current processing or verification status.")},get_integration_guide:{guide:V("integration guide"),code:T("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:W0("One setup step.")}},add_subscriber:{subscriber:V("subscriber")},update_subscriber:{subscriber:V("subscriber")},remove_subscriber:{subscriber:V("subscriber"),hardDeleted:G1("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:V("subscriber")},list_subscriber_notes:{notes:p("subscriber note")},add_subscriber_note:{note:V("subscriber note")},delete_subscriber_note:{id:T("Deleted subscriber note ID."),deleted:G1("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:p("subscriber"),pagination:W0("Pagination metadata."),returned:b0("Number of subscribers returned."),truncated:G1("Whether the result was truncated by the requested limit.")},list_products:{products:p("product")},upsert_products:{products:p("product"),created:b0("Number of products created."),updated:b0("Number of products updated.")},delete_product:{productId:T("Deleted product ID.")},attach_product_file:{product:V("product"),delivery:V("digital delivery file")},remove_product_file:{product:V("product")},sync_products:{job:V("product sync job"),jobId:T("Queued product sync job ID.")},list_tags:{tags:p("tag")},create_tag:{tag:V("tag")},update_tag:{tag:V("tag")},delete_tag:{tagId:T("Deleted tag ID.")},list_lists:{lists:p("list")},create_list:{list:V("list")},update_list:{list:V("list")},delete_list:{listId:T("Deleted list ID.")},add_subscribers_to_list:{list:V("list"),added:b0("Number of subscribers added to the list."),skipped:b0("Number of subscribers skipped.")},remove_subscribers_from_list:{list:V("list"),removed:b0("Number of subscribers removed from the list."),skipped:b0("Number of subscribers skipped.")},list_segments:{segments:p("segment")},create_segment:{segment:V("segment")},update_segment:{segment:V("segment")},delete_segment:{segmentId:T("Deleted segment ID.")},get_segment_count:{count:b0("Number of subscribers matching the segment."),segmentId:T("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:p("audience sync")},list_ad_accounts:{adAccounts:p("ad account")},create_audience_sync:{audienceSync:V("audience sync")},update_audience_sync:{audienceSync:V("audience sync")},delete_audience_sync:{audienceSyncId:T("Deleted audience sync ID.")},sync_audience_now:{audienceSync:V("audience sync"),job:V("audience sync job"),jobId:T("Queued audience sync job ID.")},list_templates:{templates:p("email template")},get_template:{template:V("email template")},create_template:{template:V("email template")},update_template:{template:V("email template")},delete_template:{templateId:T("Deleted template ID.")},list_ab_tests:{abTests:p("A/B test")},get_ab_test:{abTest:V("A/B test")},get_ab_test_stats:{abTest:V("A/B test"),stats:V("A/B test statistics")},restart_ab_test:{abTest:V("A/B test")},update_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},create_ab_test:{abTest:V("A/B test")},add_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},delete_ab_test_variant:{abTest:V("A/B test"),variantId:T("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:T("Deleted A/B test ID.")},list_campaigns:{campaigns:p("campaign")},get_campaign:{campaign:V("campaign")},get_email_send:{emailSend:V("email send")},create_campaign:{campaign:V("campaign")},update_campaign:{campaign:V("campaign")},schedule_campaign:{campaign:V("campaign"),scheduledAt:T("Scheduled send timestamp.")},send_test_email:{emailSend:V("test email send"),recipient:T("Test email recipient.")},send_test_sms:{smsSendId:T("Created test SMS send ID."),toPhone:T("Normalized E.164 destination phone.")},cancel_campaign:{campaign:V("campaign")},pause_campaign:{campaign:V("campaign")},resume_campaign:{campaign:V("campaign")},delete_campaign:{campaignId:T("Deleted campaign ID.")},duplicate_campaign:{campaign:V("duplicated campaign")},resend_campaign_to_non_openers:{campaign:V("non-opener resend draft campaign"),estimatedNonOpenerCount:b0("Estimated number of subscribers who haven't opened the original campaign.")},list_landing_pages:{landingPages:p("landing page")},get_landing_page:{landingPage:V("landing page")},create_landing_page:{landingPage:V("landing page")},update_landing_page:{landingPage:V("landing page")},delete_landing_page:{landingPageId:T("Deleted landing page ID.")},publish_landing_page:{landingPage:V("landing page")},unpublish_landing_page:{landingPage:V("landing page")},connect_landing_page_domain:{landingPage:V("landing page"),domain:T("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:V("landing page"),domain:T("Landing page domain.")},list_sequences:{sequences:p("sequence")},get_sequence:{sequence:V("sequence")},create_sequence:{sequence:V("sequence")},update_sequence:{sequence:V("sequence")},insert_sequence_step:{sequence:V("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for the inserted step, including any delay node.",items:T("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:T("Inserted email template ID.")},insertedEmailCount:b0("Number of email steps inserted.")},enable_sequence:{sequence:V("sequence")},disable_sequence:{sequence:V("sequence")},pause_sequence_enrollments:{sequenceId:T("Sequence ID."),enrollmentPaused:G1("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:T("Sequence ID."),enrollmentPaused:G1("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:V("sequence"),enrollments:p("sequence enrollment"),enrolled:b0("Number of subscribers enrolled."),skipped:b0("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:V("sequence"),cancelled:b0("Number of enrollments cancelled."),skipped:b0("Number of enrollments skipped.")},delete_sequence:{sequenceId:T("Deleted sequence ID.")},list_transactional_emails:{transactional:p("transactional email")},get_transactional_email:{transactional:V("transactional email")},create_transactional_email:{transactional:V("transactional email")},update_transactional_email:{transactional:V("transactional email")},send_email:{emailSend:V("transactional email send"),transactional:V("transactional email")},get_stats:{stats:V("account or company statistics")},get_campaign_stats:{campaign:V("campaign"),stats:V("campaign statistics")},get_sequence_stats:{sequence:V("sequence"),stats:V("sequence statistics")},list_campaign_events:{events:p("campaign email event"),pagination:W0("Pagination metadata.")},list_sequence_events:{events:p("sequence email event"),pagination:W0("Pagination metadata.")},get_subscriber_activity:{activity:p("subscriber activity event"),subscribers:p("subscriber"),pagination:W0("Pagination metadata.")},list_team_members:{members:p("team member"),invitations:p("team invitation")},invite_team_member:{invitation:V("team invitation")},cancel_team_invitation:{invitationId:T("Cancelled invitation ID.")},list_conversations:{conversations:p("inbox conversation"),pagination:W0("Pagination metadata.")},get_conversation:{conversation:V("inbox conversation"),messages:p("conversation message")},reply_to_conversation:{conversation:V("inbox conversation"),message:V("conversation message")},update_conversation_status:{conversation:V("inbox conversation")},mark_conversation_read:{conversation:V("inbox conversation")},list_webhooks:{webhooks:p("outbound webhook")},create_webhook:{webhook:V("outbound webhook")},update_webhook:{webhook:V("outbound webhook")},delete_webhook:{webhookId:T("Deleted outbound webhook ID.")},test_webhook:{webhook:V("outbound webhook"),delivery:V("test webhook delivery")},list_webhook_deliveries:{deliveries:p("webhook delivery")},replay_webhook_delivery:{delivery:V("webhook delivery"),job:V("webhook replay job")},generate_email:{email:V("generated email"),html:T("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks.",items:W0("One generated email block.")},subject:T("Generated subject line."),previewText:T("Generated inbox preview text.")},generate_sequence:{sequence:V("generated sequence"),steps:p("generated sequence step")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:T("One generated subject line.")},variants:p("generated subject line variant")},generate_sms:{prompt:T("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:W0("One generated SMS message.")}},get_sms_settings:{sms:W0("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{}};function WZ(Q){let Y=XZ[Q];if(Y===void 0)throw Error(`MCP tool "${Q}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${Q}\` MCP tool.`,properties:{...YZ,...Y,...HH.has(Q)?QZ:{}},additionalProperties:!0}}function GZ(Q){return{...Q,outputSchema:WZ(Q.name)}}function $Z(Q){if(z0(Q))return Q;if(Array.isArray(Q))return{items:Q};return{value:Q}}var JZ=[{name:"get_account",description:`Get current account information including available companies. IMPORTANT: If you have access to multiple companies, you MUST either:
29
+ `)}L.write("payload.value = newResult;"),L.write("return payload;");let k=L.compile();return(S,y)=>k(K,S,y)},$,J=j1,z=!Y6.jitless,U=z&&vQ.value,A=Y.catchall,B;Q._zod.parse=(K,L)=>{B??(B=W.value);let O=K.value;if(!J(O))return K.issues.push({expected:"object",code:"invalid_type",input:O,inst:Q}),K;if(z&&U&&L?.async===!1&&L.jitless!==!0){if(!$)$=G(Y.shape);if(K=$(K,L),!A)return K;return LW([],O,K,L,B,Q)}return X(K,L)}});function R8(Q,Y,X,W){for(let $ of Q)if($.issues.length===0)return Y.value=$.value,Y;let G=Q.filter(($)=>!A1($));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map(($)=>$.issues.map((J)=>x0(J,W,T0())))}),Y}var iQ=q("$ZodUnion",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),n(Q._zod,"optout",()=>Y.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),n(Q._zod,"values",()=>{if(Y.options.every((G)=>G._zod.values))return new Set(Y.options.flatMap((G)=>Array.from(G._zod.values)));return}),n(Q._zod,"pattern",()=>{if(Y.options.every((G)=>G._zod.pattern)){let G=Y.options.map(($)=>$._zod.pattern);return new RegExp(`^(${G.map(($)=>z4($.source)).join("|")})$`)}return});let X=Y.options.length===1,W=Y.options[0]._zod.run;Q._zod.parse=(G,$)=>{if(X)return W(G,$);let J=!1,z=[];for(let H of Y.options){let U=H._zod.run({value:G.value,issues:[]},$);if(U instanceof Promise)z.push(U),J=!0;else{if(U.issues.length===0)return U;z.push(U)}}if(!J)return R8(z,G,Q,$);return Promise.all(z).then((H)=>{return R8(H,G,Q,$)})}}),qW=q("$ZodDiscriminatedUnion",(Q,Y)=>{iQ.init(Q,Y);let X=Q._zod.parse;n(Q._zod,"propValues",()=>{let G={};for(let $ of Y.options){let J=$._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf($)}"`);for(let[z,H]of Object.entries(J)){if(!G[z])G[z]=new Set;for(let U of H)G[z].add(U)}}return G});let W=g1(()=>{let G=Y.options,$=new Map;for(let J of G){let z=J._zod.propValues?.[Y.discriminator];if(!z||z.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(J)}"`);for(let H of z){if($.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);$.set(H,J)}}return $});Q._zod.parse=(G,$)=>{let J=G.value;if(!j1(J))return G.issues.push({code:"invalid_type",expected:"object",input:J,inst:Q}),G;let z=W.value.get(J?.[Y.discriminator]);if(z)return z._zod.run(G,$);if(Y.unionFallback)return X(G,$);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,input:J,path:[Y.discriminator],inst:Q}),G}}),OW=q("$ZodIntersection",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value,$=Y.left._zod.run({value:G,issues:[]},W),J=Y.right._zod.run({value:G,issues:[]},W);if($ instanceof Promise||J instanceof Promise)return Promise.all([$,J]).then(([H,U])=>{return C8(X,H,U)});return C8(X,$,J)}});function cQ(Q,Y){if(Q===Y)return{valid:!0,data:Q};if(Q instanceof Date&&Y instanceof Date&&+Q===+Y)return{valid:!0,data:Q};if(U1(Q)&&U1(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter(($)=>X.indexOf($)!==-1),G={...Q,...Y};for(let $ of W){let J=cQ(Q[$],Y[$]);if(!J.valid)return{valid:!1,mergeErrorPath:[$,...J.mergeErrorPath]};G[$]=J.data}return{valid:!0,data:G}}if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let W=0;W<Q.length;W++){let G=Q[W],$=Y[W],J=cQ(G,$);if(!J.valid)return{valid:!1,mergeErrorPath:[W,...J.mergeErrorPath]};X.push(J.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function C8(Q,Y,X){if(Y.issues.length)Q.issues.push(...Y.issues);if(X.issues.length)Q.issues.push(...X.issues);if(A1(Q))return Q;let W=cQ(Y.value,X.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return Q.value=W.data,Q}var MW=q("$ZodRecord",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!U1(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let $=[];if(Y.keyType._zod.values){let J=Y.keyType._zod.values;X.value={};for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let U=Y.valueType._zod.run({value:G[H],issues:[]},W);if(U instanceof Promise)$.push(U.then((A)=>{if(A.issues.length)X.issues.push(...a0(H,A.issues));X.value[H]=A.value}));else{if(U.issues.length)X.issues.push(...a0(H,U.issues));X.value[H]=U.value}}let z;for(let H in G)if(!J.has(H))z=z??[],z.push(H);if(z&&z.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:z})}else{X.value={};for(let J of Reflect.ownKeys(G)){if(J==="__proto__")continue;let z=Y.keyType._zod.run({value:J,issues:[]},W);if(z instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(z.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:z.issues.map((U)=>x0(U,W,T0())),input:J,path:[J],inst:Q}),X.value[z.value]=z.value;continue}let H=Y.valueType._zod.run({value:G[J],issues:[]},W);if(H instanceof Promise)$.push(H.then((U)=>{if(U.issues.length)X.issues.push(...a0(J,U.issues));X.value[z.value]=U.value}));else{if(H.issues.length)X.issues.push(...a0(J,H.issues));X.value[z.value]=H.value}}}if($.length)return Promise.all($).then(()=>X);return X}});var VW=q("$ZodEnum",(Q,Y)=>{o.init(Q,Y);let X=CQ(Y.entries),W=new Set(X);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${X.filter((G)=>xQ.has(typeof G)).map((G)=>typeof G==="string"?t0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,$)=>{let J=G.value;if(W.has(J))return G;return G.issues.push({code:"invalid_value",values:X,input:J,inst:Q}),G}}),ZW=q("$ZodLiteral",(Q,Y)=>{if(o.init(Q,Y),Y.values.length===0)throw Error("Cannot create literal schema with no valid values");Q._zod.values=new Set(Y.values),Q._zod.pattern=new RegExp(`^(${Y.values.map((X)=>typeof X==="string"?t0(X):X?t0(X.toString()):String(X)).join("|")})$`),Q._zod.parse=(X,W)=>{let G=X.value;if(Q._zod.values.has(G))return X;return X.issues.push({code:"invalid_value",values:Y.values,input:G,inst:Q}),X}});var NW=q("$ZodTransform",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new G4(Q.constructor.name);let G=Y.transform(X.value,X);if(W.async)return(G instanceof Promise?G:Promise.resolve(G)).then((J)=>{return X.value=J,X});if(G instanceof Promise)throw new o0;return X.value=G,X}});function k8(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var wW=q("$ZodOptional",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",n(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),n(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${z4(X.source)})?$`):void 0}),Q._zod.parse=(X,W)=>{if(Y.innerType._zod.optin==="optional"){let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>k8($,X.value));return k8(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),PW=q("$ZodNullable",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),n(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${z4(X.source)}|null)$`):void 0}),n(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,null]):void 0}),Q._zod.parse=(X,W)=>{if(X.value===null)return X;return Y.innerType._zod.run(X,W)}}),bW=q("$ZodDefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)return X.value=Y.defaultValue,X;let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>v8($,Y));return v8(G,Y)}});function v8(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var jW=q("$ZodPrefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)X.value=Y.defaultValue;return Y.innerType._zod.run(X,W)}}),IW=q("$ZodNonOptional",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"values",()=>{let X=Y.innerType._zod.values;return X?new Set([...X].filter((W)=>W!==void 0)):void 0}),Q._zod.parse=(X,W)=>{let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>x8($,Q));return x8(G,Q)}});function x8(Q,Y){if(!Q.issues.length&&Q.value===void 0)Q.issues.push({code:"invalid_type",expected:"nonoptional",input:Q.value,inst:Y});return Q}var EW=q("$ZodCatch",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>{if(X.value=$.value,$.issues.length)X.value=Y.catchValue({...X,error:{issues:$.issues.map((J)=>x0(J,W,T0()))},input:X.value}),X.issues=[];return X});if(X.value=G.value,G.issues.length)X.value=Y.catchValue({...X,error:{issues:G.issues.map(($)=>x0($,W,T0()))},input:X.value}),X.issues=[];return X}});var TW=q("$ZodPipe",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"values",()=>Y.in._zod.values),n(Q._zod,"optin",()=>Y.in._zod.optin),n(Q._zod,"optout",()=>Y.out._zod.optout),n(Q._zod,"propValues",()=>Y.in._zod.propValues),Q._zod.parse=(X,W)=>{if(W.direction==="backward"){let $=Y.out._zod.run(X,W);if($ instanceof Promise)return $.then((J)=>B6(J,Y.in,W));return B6($,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>B6($,Y.out,W));return B6(G,Y.out,W)}});function B6(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var SW=q("$ZodReadonly",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"propValues",()=>Y.innerType._zod.propValues),n(Q._zod,"values",()=>Y.innerType._zod.values),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(_8);return _8(G)}});function _8(Q){return Q.value=Object.freeze(Q.value),Q}var RW=q("$ZodCustom",(Q,Y)=>{U0.init(Q,Y),o.init(Q,Y),Q._zod.parse=(X,W)=>{return X},Q._zod.check=(X)=>{let W=X.value,G=Y.fn(W);if(G instanceof Promise)return G.then(($)=>g8($,X,W,Q));g8(G,X,W,Q);return}});function g8(Q,Y,X,W){if(!Q){let G={code:"custom",input:X,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)G.params=W._zod.def.params;Y.issues.push(y1(G))}}var H3=(Q)=>{let Y=typeof Q;switch(Y){case"number":return Number.isNaN(Q)?"NaN":"number";case"object":{if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Object.getPrototypeOf(Q)!==Object.prototype&&Q.constructor)return Q.constructor.name}}return Y},U3=()=>{let Q={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function Y(W){return Q[W]??null}let X={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${H3(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${$6(W.values[0])}`;return`Invalid option: expected one of ${X6(W.values,"|")}`;case"too_big":{let G=W.inclusive?"<=":"<",$=Y(W.origin);if($)return`Too big: expected ${W.origin??"value"} to have ${G}${W.maximum.toString()} ${$.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${G}${W.maximum.toString()}`}case"too_small":{let G=W.inclusive?">=":">",$=Y(W.origin);if($)return`Too small: expected ${W.origin} to have ${G}${W.minimum.toString()} ${$.unit}`;return`Too small: expected ${W.origin} to be ${G}${W.minimum.toString()}`}case"invalid_format":{let G=W;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${X[G.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${X6(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};function nQ(){return{localeError:U3()}}var SZ=Symbol("ZodOutput"),RZ=Symbol("ZodInput");class CW{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Q,...Y){let X=Y[0];if(this._map.set(Q,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.id,Q)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Q){let Y=this._map.get(Q);if(Y&&typeof Y==="object"&&"id"in Y)this._idmap.delete(Y.id);return this._map.delete(Q),this}get(Q){let Y=Q._zod.parent;if(Y){let X={...this.get(Y)??{}};delete X.id;let W={...X,...this._map.get(Q)};return Object.keys(W).length?W:void 0}return this._map.get(Q)}has(Q){return this._map.has(Q)}}function A3(){return new CW}var D4=A3();function kW(Q,Y){return new Q({type:"string",...E(Y)})}function vW(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...E(Y)})}function rQ(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...E(Y)})}function xW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...E(Y)})}function _W(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...E(Y)})}function gW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...E(Y)})}function yW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...E(Y)})}function uW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...E(Y)})}function hW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...E(Y)})}function fW(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...E(Y)})}function lW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...E(Y)})}function mW(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...E(Y)})}function cW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...E(Y)})}function pW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...E(Y)})}function iW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...E(Y)})}function nW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...E(Y)})}function rW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...E(Y)})}function dW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...E(Y)})}function oW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...E(Y)})}function tW(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...E(Y)})}function aW(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...E(Y)})}function sW(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...E(Y)})}function eW(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...E(Y)})}function QG(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...E(Y)})}function YG(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...E(Y)})}function XG(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...E(Y)})}function WG(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...E(Y)})}function GG(Q,Y){return new Q({type:"number",checks:[],...E(Y)})}function $G(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...E(Y)})}function JG(Q,Y){return new Q({type:"boolean",...E(Y)})}function zG(Q,Y){return new Q({type:"null",...E(Y)})}function HG(Q){return new Q({type:"unknown"})}function UG(Q,Y){return new Q({type:"never",...E(Y)})}function L6(Q,Y){return new fQ({check:"less_than",...E(Y),value:Q,inclusive:!1})}function L4(Q,Y){return new fQ({check:"less_than",...E(Y),value:Q,inclusive:!0})}function F6(Q,Y){return new lQ({check:"greater_than",...E(Y),value:Q,inclusive:!1})}function F4(Q,Y){return new lQ({check:"greater_than",...E(Y),value:Q,inclusive:!0})}function q6(Q,Y){return new F8({check:"multiple_of",...E(Y),value:Q})}function O6(Q,Y){return new O8({check:"max_length",...E(Y),maximum:Q})}function u1(Q,Y){return new M8({check:"min_length",...E(Y),minimum:Q})}function M6(Q,Y){return new V8({check:"length_equals",...E(Y),length:Q})}function dQ(Q,Y){return new Z8({check:"string_format",format:"regex",...E(Y),pattern:Q})}function oQ(Q){return new N8({check:"string_format",format:"lowercase",...E(Q)})}function tQ(Q){return new w8({check:"string_format",format:"uppercase",...E(Q)})}function aQ(Q,Y){return new P8({check:"string_format",format:"includes",...E(Y),includes:Q})}function sQ(Q,Y){return new b8({check:"string_format",format:"starts_with",...E(Y),prefix:Q})}function eQ(Q,Y){return new j8({check:"string_format",format:"ends_with",...E(Y),suffix:Q})}function I1(Q){return new I8({check:"overwrite",tx:Q})}function Q9(Q){return I1((Y)=>Y.normalize(Q))}function Y9(){return I1((Q)=>Q.trim())}function X9(){return I1((Q)=>Q.toLowerCase())}function W9(){return I1((Q)=>Q.toUpperCase())}function AG(Q,Y,X){return new Q({type:"array",element:Y,...E(X)})}function BG(Q,Y,X){let W=E(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function KG(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...E(X)})}function DG(Q){let Y=B3((X)=>{return X.addIssue=(W)=>{if(typeof W==="string")X.issues.push(y1(W,X.value,Y._zod.def));else{let G=W;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=X.value),G.inst??(G.inst=Y),G.continue??(G.continue=!Y._zod.def.abort),X.issues.push(y1(G))}},Q(X.value,X)});return Y}function B3(Q,Y){let X=new U0({check:"custom",...E(Y)});return X._zod.check=Q,X}function h1(Q){return!!Q._zod}function B1(Q,Y){if(h1(Q))return A4(Q,Y);return Q.safeParse(Y)}function V6(Q){if(!Q)return;let Y;if(h1(Q))Y=Q._zod?.def?.shape;else Y=Q.shape;if(!Y)return;if(typeof Y==="function")try{return Y()}catch{return}return Y}function LG(Q){if(h1(Q)){let $=Q._zod?.def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}}let X=Q._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let W=Q.value;if(W!==void 0)return W;return}var O4={};DX(O4,{time:()=>J9,duration:()=>z9,datetime:()=>G9,date:()=>$9,ZodISOTime:()=>OG,ZodISODuration:()=>MG,ZodISODateTime:()=>FG,ZodISODate:()=>qG});var FG=q("ZodISODateTime",(Q,Y)=>{d8.init(Q,Y),s.init(Q,Y)});function G9(Q){return QG(FG,Q)}var qG=q("ZodISODate",(Q,Y)=>{o8.init(Q,Y),s.init(Q,Y)});function $9(Q){return YG(qG,Q)}var OG=q("ZodISOTime",(Q,Y)=>{t8.init(Q,Y),s.init(Q,Y)});function J9(Q){return XG(OG,Q)}var MG=q("ZodISODuration",(Q,Y)=>{a8.init(Q,Y),s.init(Q,Y)});function z9(Q){return WG(MG,Q)}var VG=(Q,Y)=>{J6.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>RX(Q,X)},flatten:{value:(X)=>SX(Q,X)},addIssue:{value:(X)=>{Q.issues.push(X),Q.message=JSON.stringify(Q.issues,_1,2)}},addIssues:{value:(X)=>{Q.issues.push(...X),Q.message=JSON.stringify(Q.issues,_1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},FN=q("ZodError",VG),I0=q("ZodError",VG,{Parent:Error});var ZG=z6(I0),NG=H6(I0),wG=U4(I0),PG=B4(I0),bG=CX(I0),jG=kX(I0),IG=vX(I0),EG=xX(I0),TG=_X(I0),SG=gX(I0),RG=yX(I0),CG=uX(I0);var X0=q("ZodType",(Q,Y)=>{return o.init(Q,Y),Q.def=Y,Q.type=Y.type,Object.defineProperty(Q,"_def",{value:Y}),Q.check=(...X)=>{return Q.clone(m.mergeDefs(Y,{checks:[...Y.checks??[],...X.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},Q.clone=(X,W)=>v0(Q,X,W),Q.brand=()=>Q,Q.register=(X,W)=>{return X.add(Q,W),Q},Q.parse=(X,W)=>ZG(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>wG(Q,X,W),Q.parseAsync=async(X,W)=>NG(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>PG(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>bG(Q,X,W),Q.decode=(X,W)=>jG(Q,X,W),Q.encodeAsync=async(X,W)=>IG(Q,X,W),Q.decodeAsync=async(X,W)=>EG(Q,X,W),Q.safeEncode=(X,W)=>TG(Q,X,W),Q.safeDecode=(X,W)=>SG(Q,X,W),Q.safeEncodeAsync=async(X,W)=>RG(Q,X,W),Q.safeDecodeAsync=async(X,W)=>CG(Q,X,W),Q.refine=(X,W)=>Q.check(zU(X,W)),Q.superRefine=(X)=>Q.check(HU(X)),Q.overwrite=(X)=>Q.check(I1(X)),Q.optional=()=>Y0(Q),Q.nullable=()=>xG(Q),Q.nullish=()=>Y0(xG(Q)),Q.nonoptional=(X)=>YU(Q,X),Q.array=()=>u(Q),Q.or=(X)=>d([Q,X]),Q.and=(X)=>N6(Q,X),Q.transform=(X)=>U9(Q,hG(X)),Q.default=(X)=>s3(Q,X),Q.prefault=(X)=>QU(Q,X),Q.catch=(X)=>WU(Q,X),Q.pipe=(X)=>U9(Q,X),Q.readonly=()=>JU(Q),Q.describe=(X)=>{let W=Q.clone();return D4.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return D4.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return D4.get(Q);let W=Q.clone();return D4.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),_G=q("_ZodString",(Q,Y)=>{D6.init(Q,Y),X0.init(Q,Y);let X=Q._zod.bag;Q.format=X.format??null,Q.minLength=X.minimum??null,Q.maxLength=X.maximum??null,Q.regex=(...W)=>Q.check(dQ(...W)),Q.includes=(...W)=>Q.check(aQ(...W)),Q.startsWith=(...W)=>Q.check(sQ(...W)),Q.endsWith=(...W)=>Q.check(eQ(...W)),Q.min=(...W)=>Q.check(u1(...W)),Q.max=(...W)=>Q.check(O6(...W)),Q.length=(...W)=>Q.check(M6(...W)),Q.nonempty=(...W)=>Q.check(u1(1,...W)),Q.lowercase=(W)=>Q.check(oQ(W)),Q.uppercase=(W)=>Q.check(tQ(W)),Q.trim=()=>Q.check(Y9()),Q.normalize=(...W)=>Q.check(Q9(...W)),Q.toLowerCase=()=>Q.check(X9()),Q.toUpperCase=()=>Q.check(W9())}),Z3=q("ZodString",(Q,Y)=>{D6.init(Q,Y),_G.init(Q,Y),Q.email=(X)=>Q.check(vW(N3,X)),Q.url=(X)=>Q.check(uW(w3,X)),Q.jwt=(X)=>Q.check(eW(y3,X)),Q.emoji=(X)=>Q.check(hW(P3,X)),Q.guid=(X)=>Q.check(rQ(kG,X)),Q.uuid=(X)=>Q.check(xW(Z6,X)),Q.uuidv4=(X)=>Q.check(_W(Z6,X)),Q.uuidv6=(X)=>Q.check(gW(Z6,X)),Q.uuidv7=(X)=>Q.check(yW(Z6,X)),Q.nanoid=(X)=>Q.check(fW(b3,X)),Q.guid=(X)=>Q.check(rQ(kG,X)),Q.cuid=(X)=>Q.check(lW(j3,X)),Q.cuid2=(X)=>Q.check(mW(I3,X)),Q.ulid=(X)=>Q.check(cW(E3,X)),Q.base64=(X)=>Q.check(tW(x3,X)),Q.base64url=(X)=>Q.check(aW(_3,X)),Q.xid=(X)=>Q.check(pW(T3,X)),Q.ksuid=(X)=>Q.check(iW(S3,X)),Q.ipv4=(X)=>Q.check(nW(R3,X)),Q.ipv6=(X)=>Q.check(rW(C3,X)),Q.cidrv4=(X)=>Q.check(dW(k3,X)),Q.cidrv6=(X)=>Q.check(oW(v3,X)),Q.e164=(X)=>Q.check(sW(g3,X)),Q.datetime=(X)=>Q.check(G9(X)),Q.date=(X)=>Q.check($9(X)),Q.time=(X)=>Q.check(J9(X)),Q.duration=(X)=>Q.check(z9(X))});function F(Q){return kW(Z3,Q)}var s=q("ZodStringFormat",(Q,Y)=>{t.init(Q,Y),_G.init(Q,Y)}),N3=q("ZodEmail",(Q,Y)=>{h8.init(Q,Y),s.init(Q,Y)});var kG=q("ZodGUID",(Q,Y)=>{y8.init(Q,Y),s.init(Q,Y)});var Z6=q("ZodUUID",(Q,Y)=>{u8.init(Q,Y),s.init(Q,Y)});var w3=q("ZodURL",(Q,Y)=>{f8.init(Q,Y),s.init(Q,Y)});var P3=q("ZodEmoji",(Q,Y)=>{l8.init(Q,Y),s.init(Q,Y)});var b3=q("ZodNanoID",(Q,Y)=>{m8.init(Q,Y),s.init(Q,Y)});var j3=q("ZodCUID",(Q,Y)=>{c8.init(Q,Y),s.init(Q,Y)});var I3=q("ZodCUID2",(Q,Y)=>{p8.init(Q,Y),s.init(Q,Y)});var E3=q("ZodULID",(Q,Y)=>{i8.init(Q,Y),s.init(Q,Y)});var T3=q("ZodXID",(Q,Y)=>{n8.init(Q,Y),s.init(Q,Y)});var S3=q("ZodKSUID",(Q,Y)=>{r8.init(Q,Y),s.init(Q,Y)});var R3=q("ZodIPv4",(Q,Y)=>{s8.init(Q,Y),s.init(Q,Y)});var C3=q("ZodIPv6",(Q,Y)=>{e8.init(Q,Y),s.init(Q,Y)});var k3=q("ZodCIDRv4",(Q,Y)=>{QW.init(Q,Y),s.init(Q,Y)});var v3=q("ZodCIDRv6",(Q,Y)=>{YW.init(Q,Y),s.init(Q,Y)});var x3=q("ZodBase64",(Q,Y)=>{WW.init(Q,Y),s.init(Q,Y)});var _3=q("ZodBase64URL",(Q,Y)=>{GW.init(Q,Y),s.init(Q,Y)});var g3=q("ZodE164",(Q,Y)=>{$W.init(Q,Y),s.init(Q,Y)});var y3=q("ZodJWT",(Q,Y)=>{JW.init(Q,Y),s.init(Q,Y)});var gG=q("ZodNumber",(Q,Y)=>{pQ.init(Q,Y),X0.init(Q,Y),Q.gt=(W,G)=>Q.check(F6(W,G)),Q.gte=(W,G)=>Q.check(F4(W,G)),Q.min=(W,G)=>Q.check(F4(W,G)),Q.lt=(W,G)=>Q.check(L6(W,G)),Q.lte=(W,G)=>Q.check(L4(W,G)),Q.max=(W,G)=>Q.check(L4(W,G)),Q.int=(W)=>Q.check(vG(W)),Q.safe=(W)=>Q.check(vG(W)),Q.positive=(W)=>Q.check(F6(0,W)),Q.nonnegative=(W)=>Q.check(F4(0,W)),Q.negative=(W)=>Q.check(L6(0,W)),Q.nonpositive=(W)=>Q.check(L4(0,W)),Q.multipleOf=(W,G)=>Q.check(q6(W,G)),Q.step=(W,G)=>Q.check(q6(W,G)),Q.finite=()=>Q;let X=Q._zod.bag;Q.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Q.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Q.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Q.isFinite=!0,Q.format=X.format??null});function i(Q){return GG(gG,Q)}var u3=q("ZodNumberFormat",(Q,Y)=>{zW.init(Q,Y),gG.init(Q,Y)});function vG(Q){return $G(u3,Q)}var h3=q("ZodBoolean",(Q,Y)=>{HW.init(Q,Y),X0.init(Q,Y)});function H0(Q){return JG(h3,Q)}var f3=q("ZodNull",(Q,Y)=>{UW.init(Q,Y),X0.init(Q,Y)});function A9(Q){return zG(f3,Q)}var l3=q("ZodUnknown",(Q,Y)=>{AW.init(Q,Y),X0.init(Q,Y)});function e(){return HG(l3)}var m3=q("ZodNever",(Q,Y)=>{BW.init(Q,Y),X0.init(Q,Y)});function c3(Q){return UG(m3,Q)}var p3=q("ZodArray",(Q,Y)=>{KW.init(Q,Y),X0.init(Q,Y),Q.element=Y.element,Q.min=(X,W)=>Q.check(u1(X,W)),Q.nonempty=(X)=>Q.check(u1(1,X)),Q.max=(X,W)=>Q.check(O6(X,W)),Q.length=(X,W)=>Q.check(M6(X,W)),Q.unwrap=()=>Q.element});function u(Q,Y){return AG(p3,Q,Y)}var yG=q("ZodObject",(Q,Y)=>{FW.init(Q,Y),X0.init(Q,Y),m.defineLazy(Q,"shape",()=>{return Y.shape}),Q.keyof=()=>V0(Object.keys(Q._zod.def.shape)),Q.catchall=(X)=>Q.clone({...Q._zod.def,catchall:X}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:c3()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(X)=>{return m.extend(Q,X)},Q.safeExtend=(X)=>{return m.safeExtend(Q,X)},Q.merge=(X)=>m.merge(Q,X),Q.pick=(X)=>m.pick(Q,X),Q.omit=(X)=>m.omit(Q,X),Q.partial=(...X)=>m.partial(fG,Q,X[0]),Q.required=(...X)=>m.required(lG,Q,X[0])});function b(Q,Y){let X={type:"object",shape:Q??{},...m.normalizeParams(Y)};return new yG(X)}function q0(Q,Y){return new yG({type:"object",shape:Q,catchall:e(),...m.normalizeParams(Y)})}var uG=q("ZodUnion",(Q,Y)=>{iQ.init(Q,Y),X0.init(Q,Y),Q.options=Y.options});function d(Q,Y){return new uG({type:"union",options:Q,...m.normalizeParams(Y)})}var i3=q("ZodDiscriminatedUnion",(Q,Y)=>{uG.init(Q,Y),qW.init(Q,Y)});function B9(Q,Y,X){return new i3({type:"union",options:Y,discriminator:Q,...m.normalizeParams(X)})}var n3=q("ZodIntersection",(Q,Y)=>{OW.init(Q,Y),X0.init(Q,Y)});function N6(Q,Y){return new n3({type:"intersection",left:Q,right:Y})}var r3=q("ZodRecord",(Q,Y)=>{MW.init(Q,Y),X0.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function Q0(Q,Y,X){return new r3({type:"record",keyType:Q,valueType:Y,...m.normalizeParams(X)})}var H9=q("ZodEnum",(Q,Y)=>{VW.init(Q,Y),X0.init(Q,Y),Q.enum=Y.entries,Q.options=Object.values(Y.entries);let X=new Set(Object.keys(Y.entries));Q.extract=(W,G)=>{let $={};for(let J of W)if(X.has(J))$[J]=Y.entries[J];else throw Error(`Key ${J} not found in enum`);return new H9({...Y,checks:[],...m.normalizeParams(G),entries:$})},Q.exclude=(W,G)=>{let $={...Y.entries};for(let J of W)if(X.has(J))delete $[J];else throw Error(`Key ${J} not found in enum`);return new H9({...Y,checks:[],...m.normalizeParams(G),entries:$})}});function V0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new H9({type:"enum",entries:X,...m.normalizeParams(Y)})}var d3=q("ZodLiteral",(Q,Y)=>{ZW.init(Q,Y),X0.init(Q,Y),Q.values=new Set(Y.values),Object.defineProperty(Q,"value",{get(){if(Y.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return Y.values[0]}})});function j(Q,Y){return new d3({type:"literal",values:Array.isArray(Q)?Q:[Q],...m.normalizeParams(Y)})}var o3=q("ZodTransform",(Q,Y)=>{NW.init(Q,Y),X0.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new G4(Q.constructor.name);X.addIssue=($)=>{if(typeof $==="string")X.issues.push(m.issue($,X.value,Y));else{let J=$;if(J.fatal)J.continue=!1;J.code??(J.code="custom"),J.input??(J.input=X.value),J.inst??(J.inst=Q),X.issues.push(m.issue(J))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then(($)=>{return X.value=$,X});return X.value=G,X}});function hG(Q){return new o3({type:"transform",transform:Q})}var fG=q("ZodOptional",(Q,Y)=>{wW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function Y0(Q){return new fG({type:"optional",innerType:Q})}var t3=q("ZodNullable",(Q,Y)=>{PW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function xG(Q){return new t3({type:"nullable",innerType:Q})}var a3=q("ZodDefault",(Q,Y)=>{bW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function s3(Q,Y){return new a3({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var e3=q("ZodPrefault",(Q,Y)=>{jW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function QU(Q,Y){return new e3({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var lG=q("ZodNonOptional",(Q,Y)=>{IW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function YU(Q,Y){return new lG({type:"nonoptional",innerType:Q,...m.normalizeParams(Y)})}var XU=q("ZodCatch",(Q,Y)=>{EW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function WU(Q,Y){return new XU({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var GU=q("ZodPipe",(Q,Y)=>{TW.init(Q,Y),X0.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function U9(Q,Y){return new GU({type:"pipe",in:Q,out:Y})}var $U=q("ZodReadonly",(Q,Y)=>{SW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function JU(Q){return new $U({type:"readonly",innerType:Q})}var mG=q("ZodCustom",(Q,Y)=>{RW.init(Q,Y),X0.init(Q,Y)});function cG(Q,Y){return BG(mG,Q??(()=>!0),Y)}function zU(Q,Y={}){return KG(mG,Q,Y)}function HU(Q){return DG(Q)}function K9(Q,Y){return U9(hG(Q),Y)}T0(nQ());var D9="2025-11-25";var pG=[D9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],K1="io.modelcontextprotocol/related-task",P6="2.0",A0=cG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),iG=d([F(),i().int()]),nG=F(),Aw=q0({ttl:d([i(),A9()]).optional(),pollInterval:i().optional()}),UU=b({ttl:i().optional()}),AU=b({taskId:F()}),L9=q0({progressToken:iG.optional(),[K1]:AU.optional()}),E0=b({_meta:L9.optional()}),M4=E0.extend({task:UU.optional()}),rG=(Q)=>M4.safeParse(Q).success,B0=b({method:F(),params:E0.loose().optional()}),S0=b({_meta:L9.optional()}),R0=b({method:F(),params:S0.loose().optional()}),K0=q0({_meta:L9.optional()}),b6=d([F(),i().int()]),dG=b({jsonrpc:j(P6),id:b6,...B0.shape}).strict(),F9=(Q)=>dG.safeParse(Q).success,oG=b({jsonrpc:j(P6),...R0.shape}).strict(),tG=(Q)=>oG.safeParse(Q).success,q9=b({jsonrpc:j(P6),id:b6,result:K0}).strict(),V4=(Q)=>q9.safeParse(Q).success;var h;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(h||(h={}));var O9=b({jsonrpc:j(P6),id:b6.optional(),error:b({code:i().int(),message:F(),data:e().optional()})}).strict();var aG=(Q)=>O9.safeParse(Q).success;var sG=d([dG,oG,q9,O9]),Bw=d([q9,O9]),j6=K0.strict(),BU=S0.extend({requestId:b6.optional(),reason:F().optional()}),I6=R0.extend({method:j("notifications/cancelled"),params:BU}),KU=b({src:F(),mimeType:F().optional(),sizes:u(F()).optional(),theme:V0(["light","dark"]).optional()}),Z4=b({icons:u(KU).optional()}),f1=b({name:F(),title:F().optional()}),eG=f1.extend({...f1.shape,...Z4.shape,version:F(),websiteUrl:F().optional(),description:F().optional()}),DU=N6(b({applyDefaults:H0().optional()}),Q0(F(),e())),LU=K9((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},N6(b({form:DU.optional(),url:A0.optional()}),Q0(F(),e()).optional())),FU=q0({list:A0.optional(),cancel:A0.optional(),requests:q0({sampling:q0({createMessage:A0.optional()}).optional(),elicitation:q0({create:A0.optional()}).optional()}).optional()}),qU=q0({list:A0.optional(),cancel:A0.optional(),requests:q0({tools:q0({call:A0.optional()}).optional()}).optional()}),OU=b({experimental:Q0(F(),A0).optional(),sampling:b({context:A0.optional(),tools:A0.optional()}).optional(),elicitation:LU.optional(),roots:b({listChanged:H0().optional()}).optional(),tasks:FU.optional()}),MU=E0.extend({protocolVersion:F(),capabilities:OU,clientInfo:eG}),M9=B0.extend({method:j("initialize"),params:MU});var VU=b({experimental:Q0(F(),A0).optional(),logging:A0.optional(),completions:A0.optional(),prompts:b({listChanged:H0().optional()}).optional(),resources:b({subscribe:H0().optional(),listChanged:H0().optional()}).optional(),tools:b({listChanged:H0().optional()}).optional(),tasks:qU.optional()}),ZU=K0.extend({protocolVersion:F(),capabilities:VU,serverInfo:eG,instructions:F().optional()}),V9=R0.extend({method:j("notifications/initialized"),params:S0.optional()});var E6=B0.extend({method:j("ping"),params:E0.optional()}),NU=b({progress:i(),total:Y0(i()),message:Y0(F())}),wU=b({...S0.shape,...NU.shape,progressToken:iG}),T6=R0.extend({method:j("notifications/progress"),params:wU}),PU=E0.extend({cursor:nG.optional()}),N4=B0.extend({params:PU.optional()}),w4=K0.extend({nextCursor:nG.optional()}),bU=V0(["working","input_required","completed","failed","cancelled"]),P4=b({taskId:F(),status:bU,ttl:d([i(),A9()]),createdAt:F(),lastUpdatedAt:F(),pollInterval:Y0(i()),statusMessage:Y0(F())}),l1=K0.extend({task:P4}),jU=S0.merge(P4),b4=R0.extend({method:j("notifications/tasks/status"),params:jU}),S6=B0.extend({method:j("tasks/get"),params:E0.extend({taskId:F()})}),R6=K0.merge(P4),C6=B0.extend({method:j("tasks/result"),params:E0.extend({taskId:F()})}),Kw=K0.loose(),k6=N4.extend({method:j("tasks/list")}),v6=w4.extend({tasks:u(P4)}),x6=B0.extend({method:j("tasks/cancel"),params:E0.extend({taskId:F()})}),Q$=K0.merge(P4),Y$=b({uri:F(),mimeType:Y0(F()),_meta:Q0(F(),e()).optional()}),X$=Y$.extend({text:F()}),Z9=F().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),W$=Y$.extend({blob:Z9}),j4=V0(["user","assistant"]),m1=b({audience:u(j4).optional(),priority:i().min(0).max(1).optional(),lastModified:O4.datetime({offset:!0}).optional()}),G$=b({...f1.shape,...Z4.shape,uri:F(),description:Y0(F()),mimeType:Y0(F()),annotations:m1.optional(),_meta:Y0(q0({}))}),IU=b({...f1.shape,...Z4.shape,uriTemplate:F(),description:Y0(F()),mimeType:Y0(F()),annotations:m1.optional(),_meta:Y0(q0({}))}),N9=N4.extend({method:j("resources/list")}),EU=w4.extend({resources:u(G$)}),TU=N4.extend({method:j("resources/templates/list")}),SU=w4.extend({resourceTemplates:u(IU)}),w9=E0.extend({uri:F()}),RU=w9,P9=B0.extend({method:j("resources/read"),params:RU}),CU=K0.extend({contents:u(d([X$,W$]))}),kU=R0.extend({method:j("notifications/resources/list_changed"),params:S0.optional()}),vU=w9,xU=B0.extend({method:j("resources/subscribe"),params:vU}),_U=w9,gU=B0.extend({method:j("resources/unsubscribe"),params:_U}),yU=S0.extend({uri:F()}),uU=R0.extend({method:j("notifications/resources/updated"),params:yU}),hU=b({name:F(),description:Y0(F()),required:Y0(H0())}),fU=b({...f1.shape,...Z4.shape,description:Y0(F()),arguments:Y0(u(hU)),_meta:Y0(q0({}))}),lU=N4.extend({method:j("prompts/list")}),mU=w4.extend({prompts:u(fU)}),cU=E0.extend({name:F(),arguments:Q0(F(),F()).optional()}),pU=B0.extend({method:j("prompts/get"),params:cU}),b9=b({type:j("text"),text:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),j9=b({type:j("image"),data:Z9,mimeType:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),I9=b({type:j("audio"),data:Z9,mimeType:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),iU=b({type:j("tool_use"),name:F(),id:F(),input:Q0(F(),e()),_meta:Q0(F(),e()).optional()}),nU=b({type:j("resource"),resource:d([X$,W$]),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),rU=G$.extend({type:j("resource_link")}),E9=d([b9,j9,I9,rU,nU]),dU=b({role:j4,content:E9}),oU=K0.extend({description:F().optional(),messages:u(dU)}),tU=R0.extend({method:j("notifications/prompts/list_changed"),params:S0.optional()}),aU=b({title:F().optional(),readOnlyHint:H0().optional(),destructiveHint:H0().optional(),idempotentHint:H0().optional(),openWorldHint:H0().optional()}),sU=b({taskSupport:V0(["required","optional","forbidden"]).optional()}),$$=b({...f1.shape,...Z4.shape,description:F().optional(),inputSchema:b({type:j("object"),properties:Q0(F(),A0).optional(),required:u(F()).optional()}).catchall(e()),outputSchema:b({type:j("object"),properties:Q0(F(),A0).optional(),required:u(F()).optional()}).catchall(e()).optional(),annotations:aU.optional(),execution:sU.optional(),_meta:Q0(F(),e()).optional()}),T9=N4.extend({method:j("tools/list")}),eU=w4.extend({tools:u($$)}),_6=K0.extend({content:u(E9).default([]),structuredContent:Q0(F(),e()).optional(),isError:H0().optional()}),Dw=_6.or(K0.extend({toolResult:e()})),QA=M4.extend({name:F(),arguments:Q0(F(),e()).optional()}),I4=B0.extend({method:j("tools/call"),params:QA}),YA=R0.extend({method:j("notifications/tools/list_changed"),params:S0.optional()}),Lw=b({autoRefresh:H0().default(!0),debounceMs:i().int().nonnegative().default(300)}),E4=V0(["debug","info","notice","warning","error","critical","alert","emergency"]),XA=E0.extend({level:E4}),S9=B0.extend({method:j("logging/setLevel"),params:XA}),WA=S0.extend({level:E4,logger:F().optional(),data:e()}),GA=R0.extend({method:j("notifications/message"),params:WA}),$A=b({name:F().optional()}),JA=b({hints:u($A).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),zA=b({mode:V0(["auto","required","none"]).optional()}),HA=b({type:j("tool_result"),toolUseId:F().describe("The unique identifier for the corresponding tool call."),content:u(E9).default([]),structuredContent:b({}).loose().optional(),isError:H0().optional(),_meta:Q0(F(),e()).optional()}),UA=B9("type",[b9,j9,I9]),w6=B9("type",[b9,j9,I9,iU,HA]),AA=b({role:j4,content:d([w6,u(w6)]),_meta:Q0(F(),e()).optional()}),BA=M4.extend({messages:u(AA),modelPreferences:JA.optional(),systemPrompt:F().optional(),includeContext:V0(["none","thisServer","allServers"]).optional(),temperature:i().optional(),maxTokens:i().int(),stopSequences:u(F()).optional(),metadata:A0.optional(),tools:u($$).optional(),toolChoice:zA.optional()}),KA=B0.extend({method:j("sampling/createMessage"),params:BA}),R9=K0.extend({model:F(),stopReason:Y0(V0(["endTurn","stopSequence","maxTokens"]).or(F())),role:j4,content:UA}),C9=K0.extend({model:F(),stopReason:Y0(V0(["endTurn","stopSequence","maxTokens","toolUse"]).or(F())),role:j4,content:d([w6,u(w6)])}),DA=b({type:j("boolean"),title:F().optional(),description:F().optional(),default:H0().optional()}),LA=b({type:j("string"),title:F().optional(),description:F().optional(),minLength:i().optional(),maxLength:i().optional(),format:V0(["email","uri","date","date-time"]).optional(),default:F().optional()}),FA=b({type:V0(["number","integer"]),title:F().optional(),description:F().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),qA=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),default:F().optional()}),OA=b({type:j("string"),title:F().optional(),description:F().optional(),oneOf:u(b({const:F(),title:F()})),default:F().optional()}),MA=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),enumNames:u(F()).optional(),default:F().optional()}),VA=d([qA,OA]),ZA=b({type:j("array"),title:F().optional(),description:F().optional(),minItems:i().optional(),maxItems:i().optional(),items:b({type:j("string"),enum:u(F())}),default:u(F()).optional()}),NA=b({type:j("array"),title:F().optional(),description:F().optional(),minItems:i().optional(),maxItems:i().optional(),items:b({anyOf:u(b({const:F(),title:F()}))}),default:u(F()).optional()}),wA=d([ZA,NA]),PA=d([MA,VA,wA]),bA=d([PA,DA,LA,FA]),jA=M4.extend({mode:j("form").optional(),message:F(),requestedSchema:b({type:j("object"),properties:Q0(F(),bA),required:u(F()).optional()})}),IA=M4.extend({mode:j("url"),message:F(),elicitationId:F(),url:F().url()}),EA=d([jA,IA]),TA=B0.extend({method:j("elicitation/create"),params:EA}),SA=S0.extend({elicitationId:F()}),RA=R0.extend({method:j("notifications/elicitation/complete"),params:SA}),g6=K0.extend({action:V0(["accept","decline","cancel"]),content:K9((Q)=>Q===null?void 0:Q,Q0(F(),d([F(),i(),H0(),u(F())])).optional())}),CA=b({type:j("ref/resource"),uri:F()});var kA=b({type:j("ref/prompt"),name:F()}),vA=E0.extend({ref:d([kA,CA]),argument:b({name:F(),value:F()}),context:b({arguments:Q0(F(),F()).optional()}).optional()}),xA=B0.extend({method:j("completion/complete"),params:vA});var _A=K0.extend({completion:q0({values:u(F()).max(100),total:Y0(i().int()),hasMore:Y0(H0())})}),gA=b({uri:F().startsWith("file://"),name:F().optional(),_meta:Q0(F(),e()).optional()}),yA=B0.extend({method:j("roots/list"),params:E0.optional()}),k9=K0.extend({roots:u(gA)}),uA=R0.extend({method:j("notifications/roots/list_changed"),params:S0.optional()}),Fw=d([E6,M9,xA,S9,pU,lU,N9,TU,P9,xU,gU,I4,T9,S6,C6,k6,x6]),qw=d([I6,T6,V9,uA,b4]),Ow=d([j6,R9,C9,g6,k9,R6,v6,l1]),Mw=d([E6,KA,TA,yA,S6,C6,k6,x6]),Vw=d([I6,T6,GA,uU,kU,YA,tU,b4,RA]),Zw=d([j6,ZU,_A,oU,mU,EU,SU,CU,_6,eU,R6,v6,l1]);class _ extends Error{constructor(Q,Y,X){super(`MCP error ${Q}: ${Y}`);this.code=Q,this.data=X,this.name="McpError"}static fromError(Q,Y,X){if(Q===h.UrlElicitationRequired&&X){let W=X;if(W.elicitations)return new J$(W.elicitations,Y)}return new _(Q,Y,X)}}class J$ extends _{constructor(Q,Y=`URL elicitation${Q.length>1?"s":""} required`){super(h.UrlElicitationRequired,Y,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function D1(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var hA=Symbol("Let zodToJsonSchema decide on which parser to use");var ew=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function v9(Q){let X=V6(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=LG(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function x9(Q,Y){let X=B1(Q,Y);if(!X.success)throw X.error;return X.data}var iA=60000;class _9{constructor(Q){if(this._options=Q,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(I6,(Y)=>{this._oncancel(Y)}),this.setNotificationHandler(T6,(Y)=>{this._onprogress(Y)}),this.setRequestHandler(E6,(Y)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(S6,async(Y,X)=>{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(C6,async(Y,X)=>{let W=async()=>{let G=Y.params.taskId;if(this._taskMessageQueue){let J;while(J=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(J.type==="response"||J.type==="error"){let z=J.message,H=z.id,U=this._requestResolvers.get(H);if(U)if(this._requestResolvers.delete(H),J.type==="response")U(z);else{let A=z,B=new _(A.error.code,A.error.message,A.error.data);U(B)}else{let A=J.type==="response"?"Response":"Error";this._onerror(Error(`${A} handler missing for request ${H}`))}continue}await this._transport?.send(J.message,{relatedRequestId:X.requestId})}}let $=await this._taskStore.getTask(G,X.sessionId);if(!$)throw new _(h.InvalidParams,`Task not found: ${G}`);if(!D1($.status))return await this._waitForTaskUpdate(G,X.signal),await W();if(D1($.status)){let J=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...J,_meta:{...J._meta,[K1]:{taskId:G}}}}return await W()};return await W()}),this.setRequestHandler(k6,async(Y,X)=>{try{let{tasks:W,nextCursor:G}=await this._taskStore.listTasks(Y.params?.cursor,X.sessionId);return{tasks:W,nextCursor:G,_meta:{}}}catch(W){throw new _(h.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(x6,async(Y,X)=>{try{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,`Task not found: ${Y.params.taskId}`);if(D1(W.status))throw new _(h.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(Y.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Y.params.taskId);let G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new _(h.InvalidParams,`Task not found after cancellation: ${Y.params.taskId}`);return{_meta:{},...G}}catch(W){if(W instanceof _)throw W;throw new _(h.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,Y,X,W,G=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,Y),startTime:Date.now(),timeout:Y,maxTotalTimeout:X,resetTimeoutOnProgress:G,onTimeout:W})}_resetTimeout(Q){let Y=this._timeoutInfo.get(Q);if(!Y)return!1;let X=Date.now()-Y.startTime;if(Y.maxTotalTimeout&&X>=Y.maxTotalTimeout)throw this._timeoutInfo.delete(Q),_.fromError(h.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Y.maxTotalTimeout,totalElapsed:X});return clearTimeout(Y.timeoutId),Y.timeoutId=setTimeout(Y.onTimeout,Y.timeout),!0}_cleanupTimeout(Q){let Y=this._timeoutInfo.get(Q);if(Y)clearTimeout(Y.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let Y=this.transport?.onclose;this._transport.onclose=()=>{Y?.(),this._onclose()};let X=this.transport?.onerror;this._transport.onerror=(G)=>{X?.(G),this._onerror(G)};let W=this._transport?.onmessage;this._transport.onmessage=(G,$)=>{if(W?.(G,$),V4(G)||aG(G))this._onresponse(G);else if(F9(G))this._onrequest(G,$);else if(tG(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let Y=_.fromError(h.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of Q.values())X(Y)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let Y=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(Y===void 0)return;Promise.resolve().then(()=>Y(Q)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(Q,Y){let X=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,G=Q.params?._meta?.[K1]?.taskId;if(X===void 0){let U={jsonrpc:"2.0",id:Q.id,error:{code:h.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId).catch((A)=>this._onerror(Error(`Failed to enqueue error response: ${A}`)));else W?.send(U).catch((A)=>this._onerror(Error(`Failed to send an error response: ${A}`)));return}let $=new AbortController;this._requestHandlerAbortControllers.set(Q.id,$);let J=rG(Q.params)?Q.params.task:void 0,z=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:$.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(U)=>{let A={relatedRequestId:Q.id};if(G)A.relatedTask={taskId:G};await this.notification(U,A)},sendRequest:async(U,A,B)=>{let K={...B,relatedRequestId:Q.id};if(G&&!K.relatedTask)K.relatedTask={taskId:G};let L=K.relatedTask?.taskId??G;if(L&&z)await z.updateTaskStatus(L,"input_required");return await this.request(U,A,K)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:z,taskRequestedTtl:J?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(J)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(U)=>{if($.signal.aborted)return;let A={result:U,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)},async(U)=>{if($.signal.aborted)return;let A={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(U.code)?U.code:h.InternalError,message:U.message??"Internal error",...U.data!==void 0&&{data:U.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)}).catch((U)=>this._onerror(Error(`Failed to send response: ${U}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:Y,...X}=Q.params,W=Number(Y),G=this._progressHandlers.get(W);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let $=this._responseHandlers.get(W),J=this._timeoutInfo.get(W);if(J&&$&&J.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(z){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),$(z);return}G(X)}_onresponse(Q){let Y=Number(Q.id),X=this._requestResolvers.get(Y);if(X){if(this._requestResolvers.delete(Y),V4(Q))X(Q);else{let $=new _(Q.error.code,Q.error.message,Q.error.data);X($)}return}let W=this._responseHandlers.get(Y);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(Y),this._cleanupTimeout(Y);let G=!1;if(V4(Q)&&Q.result&&typeof Q.result==="object"){let $=Q.result;if($.task&&typeof $.task==="object"){let J=$.task;if(typeof J.taskId==="string")G=!0,this._taskProgressTokens.set(J.taskId,Y)}}if(!G)this._progressHandlers.delete(Y);if(V4(Q))W(Q);else{let $=_.fromError(Q.error.code,Q.error.message,Q.error.data);W($)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,Y,X){let{task:W}=X??{};if(!W){try{yield{type:"result",result:await this.request(Q,Y,X)}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}return}let G;try{let $=await this.request(Q,l1,X);if($.task)G=$.task.taskId,yield{type:"taskCreated",task:$.task};else throw new _(h.InternalError,"Task creation did not return a task");while(!0){let J=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:J},D1(J.status)){if(J.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(J.status==="failed")yield{type:"error",error:new _(h.InternalError,`Task ${G} failed`)};else if(J.status==="cancelled")yield{type:"error",error:new _(h.InternalError,`Task ${G} was cancelled`)};return}if(J.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let z=J.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,z)),X?.signal?.throwIfAborted()}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$,task:J,relatedTask:z}=X??{};return new Promise((H,U)=>{let A=(Z)=>{U(Z)};if(!this._transport){A(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),J)this.assertTaskCapability(Q.method)}catch(Z){A(Z);return}X?.signal?.throwIfAborted();let B=this._requestMessageId++,K={...Q,jsonrpc:"2.0",id:B};if(X?.onprogress)this._progressHandlers.set(B,X.onprogress),K.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:B}};if(J)K.params={...K.params,task:J};if(z)K.params={...K.params,_meta:{...K.params?._meta||{},[K1]:z}};let L=(Z)=>{this._responseHandlers.delete(B),this._progressHandlers.delete(B),this._cleanupTimeout(B),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:B,reason:String(Z)}},{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let k=Z instanceof _?Z:new _(h.RequestTimeout,String(Z));U(k)};this._responseHandlers.set(B,(Z)=>{if(X?.signal?.aborted)return;if(Z instanceof Error)return U(Z);try{let k=B1(Y,Z.result);if(!k.success)U(k.error);else H(k.data)}catch(k){U(k)}}),X?.signal?.addEventListener("abort",()=>{L(X?.signal?.reason)});let O=X?.timeout??iA,M=()=>L(_.fromError(h.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(B,O,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let w=z?.taskId;if(w){let Z=(k)=>{let S=this._responseHandlers.get(B);if(S)S(k);else this._onerror(Error(`Response handler missing for side-channeled request ${B}`))};this._requestResolvers.set(B,Z),this._enqueueTaskMessage(w,{type:"request",message:K,timestamp:Date.now()}).catch((k)=>{this._cleanupTimeout(B),U(k)})}else this._transport.send(K,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((Z)=>{this._cleanupTimeout(B),U(Z)})})}async getTask(Q,Y){return this.request({method:"tasks/get",params:Q},R6,Y)}async getTaskResult(Q,Y,X){return this.request({method:"tasks/result",params:Q},Y,X)}async listTasks(Q,Y){return this.request({method:"tasks/list",params:Q},v6,Y)}async cancelTask(Q,Y){return this.request({method:"tasks/cancel",params:Q},Q$,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let J={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[K1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:J,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!Y?.relatedRequestId&&!Y?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let J={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[K1]:Y.relatedTask}}};this._transport?.send(J,Y).catch((z)=>this._onerror(z))});return}let $={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)$={...$,params:{...$.params,_meta:{...$.params?._meta||{},[K1]:Y.relatedTask}}};await this._transport.send($,Y)}setRequestHandler(Q,Y){let X=v9(Q);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(W,G)=>{let $=x9(Q,W);return Promise.resolve(Y($,G))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,Y){let X=v9(Q);this._notificationHandlers.set(X,(W)=>{let G=x9(Q,W);return Promise.resolve(Y(G))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let Y=this._taskProgressTokens.get(Q);if(Y!==void 0)this._progressHandlers.delete(Y),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,Y,X){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,Y,X,W)}async _clearTaskQueue(Q,Y){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll(Q,Y);for(let W of X)if(W.type==="request"&&F9(W.message)){let G=W.message.id,$=this._requestResolvers.get(G);if($)$(new _(h.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,Y){let X=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)X=W.pollInterval}catch{}return new Promise((W,G)=>{if(Y.aborted){G(new _(h.InvalidRequest,"Request cancelled"));return}let $=setTimeout(W,X);Y.addEventListener("abort",()=>{clearTimeout($),G(new _(h.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,Y){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await X.createTask(W,Q.id,{method:Q.method,params:Q.params},Y)},getTask:async(W)=>{let G=await X.getTask(W,Y);if(!G)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(W,G,$)=>{await X.storeTaskResult(W,G,$,Y);let J=await X.getTask(W,Y);if(J){let z=b4.parse({method:"notifications/tasks/status",params:J});if(await this.notification(z),D1(J.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,$)=>{let J=await X.getTask(W,Y);if(!J)throw new _(h.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(D1(J.status))throw new _(h.InvalidParams,`Cannot update task "${W}" from terminal status "${J.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,$,Y);let z=await X.getTask(W,Y);if(z){let H=b4.parse({method:"notifications/tasks/status",params:z});if(await this.notification(H),D1(z.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function z$(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function H$(Q,Y){let X={...Q};for(let W in Y){let G=W,$=Y[G];if($===void 0)continue;let J=X[G];if(z$(J)&&z$($))X[G]={...J,...$};else X[G]=$}return X}var h5=KX(SY(),1),f5=KX(u5(),1);function QV(){let Q=new h5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return f5.default(Q),Q}class hY{constructor(Q){this._ajv=Q??QV()}getValidator(Q){let Y="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(X)=>{if(Y(X))return{valid:!0,data:X,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(Y.errors)}}}}class fY{constructor(Q){this._server=Q}requestStream(Q,Y,X){return this._server.requestStream(Q,Y,X)}async getTask(Q,Y){return this._server.getTask({taskId:Q},Y)}async getTaskResult(Q,Y,X){return this._server.getTaskResult({taskId:Q},Y,X)}async listTasks(Q,Y){return this._server.listTasks(Q?{cursor:Q}:void 0,Y)}async cancelTask(Q,Y){return this._server.cancelTask({taskId:Q},Y)}}function l5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"tools/call":if(!Q.tools?.call)throw Error(`${X} does not support task creation for tools/call (required for ${Y})`);break;default:break}}function m5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${X} does not support task creation for sampling/createMessage (required for ${Y})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${X} does not support task creation for elicitation/create (required for ${Y})`);break;default:break}}class lY extends _9{constructor(Q,Y){super(Y);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(E4.options.map((X,W)=>[X,W])),this.isMessageIgnored=(X,W)=>{let G=this._loggingLevels.get(W);return G?this.LOG_LEVEL_SEVERITY.get(X)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=Y?.capabilities??{},this._instructions=Y?.instructions,this._jsonSchemaValidator=Y?.jsonSchemaValidator??new hY,this.setRequestHandler(M9,(X)=>this._oninitialize(X)),this.setNotificationHandler(V9,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(S9,async(X,W)=>{let G=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:$}=X.params,J=E4.safeParse($);if(J.success)this._loggingLevels.set(G,J.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new fY(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=H$(this._capabilities,Q)}setRequestHandler(Q,Y){let W=V6(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let G;if(h1(W)){let J=W;G=J._zod?.def?.value??J.value}else{let J=W;G=J._def?.value??J.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let J=async(z,H)=>{let U=B1(I4,z);if(!U.success){let L=U.error instanceof Error?U.error.message:String(U.error);throw new _(h.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:A}=U.data,B=await Promise.resolve(Y(z,H));if(A.task){let L=B1(l1,B);if(!L.success){let O=L.error instanceof Error?L.error.message:String(L.error);throw new _(h.InvalidParams,`Invalid task creation result: ${O}`)}return L.data}let K=B1(_6,B);if(!K.success){let L=K.error instanceof Error?K.error.message:String(K.error);throw new _(h.InvalidParams,`Invalid tools/call result: ${L}`)}return K.data};return super.setRequestHandler(Q,J)}return super.setRequestHandler(Q,Y)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){m5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;l5(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let Y=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:pG.includes(Y)?Y:D9,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},j6)}async createMessage(Q,Y){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let X=Q.messages[Q.messages.length-1],W=Array.isArray(X.content)?X.content:[X.content],G=W.some((H)=>H.type==="tool_result"),$=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,J=$?Array.isArray($.content)?$.content:[$.content]:[],z=J.some((H)=>H.type==="tool_use");if(G){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!z)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(z){let H=new Set(J.filter((A)=>A.type==="tool_use").map((A)=>A.id)),U=new Set(W.filter((A)=>A.type==="tool_result").map((A)=>A.toolUseId));if(H.size!==U.size||![...H].every((A)=>U.has(A)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},C9,Y);return this.request({method:"sampling/createMessage",params:Q},R9,Y)}async elicitInput(Q,Y){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},g6,Y)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},G=await this.request({method:"elicitation/create",params:W},g6,Y);if(G.action==="accept"&&G.content&&W.requestedSchema)try{let J=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!J.valid)throw new _(h.InvalidParams,`Elicitation response content does not match requested schema: ${J.errorMessage}`)}catch($){if($ instanceof _)throw $;throw new _(h.InternalError,`Error validating elicitation response: ${$ instanceof Error?$.message:String($)}`)}return G}}}createElicitationCompletionNotifier(Q,Y){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},Y)}async listRoots(Q,Y){return this.request({method:"roots/list",params:Q},k9,Y)}async sendLoggingMessage(Q,Y){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,Y))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}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"})}}var c5={name:"@sequenzy/mcp",version:"0.0.94",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^7.0.2"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var mY=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],p5={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",landingPages:"/dashboard/company/{companyId}/landing-pages",landingPage:"/dashboard/company/{companyId}/landing-pages/{landingPageId}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function XV(Q){let X=(Q??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return X.length>0?X:"https://sequenzy.com"}function l0(Q){let Y=Q?.trim();return Y?Y:void 0}function r0(Q){return encodeURIComponent(Q)}function $0(Q,Y){return`${Q}${Y}`}function J0(Q,Y=""){return`/dashboard/company/${r0(Q)}${Y}`}function i5(Q,Y,X){return $0(Q,`${J0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function WV(Q,Y){let X=mY.map((W)=>[W,Y?i5(Q,Y,W):""]);return Object.fromEntries(X)}function N1(Q={},Y){let X=XV(Y),W=l0(Q.companyId),G={},$=WV(X,W);if(!W)return{appUrl:X,routeTemplates:p5,settingsTabValues:mY,urls:G,settingsUrls:$};G.dashboard=$0(X,J0(W)),G.campaigns=$0(X,J0(W,"/campaign")),G.landingPages=$0(X,J0(W,"/landing-pages")),G.sequences=$0(X,J0(W,"/sequences")),G.settings=$0(X,J0(W,"/settings")),G.emails=$0(X,J0(W,"/emails")),G.subscribers=$0(X,J0(W,"/subscribers")),G.sentEmails=$0(X,J0(W,"/sent-emails")),G.segments=$0(X,J0(W,"/segments")),G.metrics=$0(X,J0(W,"/metrics")),G.transactional=$0(X,J0(W,"/transactional"));let J=l0(Q.campaignId);if(J)G.campaign=$0(X,J0(W,`/campaign/${r0(J)}`)),G.campaignPreview=`${G.campaign}?step=review`;let z=l0(Q.landingPageId);if(z)G.landingPage=$0(X,J0(W,`/landing-pages/${r0(z)}`));let H=l0(Q.sequenceId);if(H)G.sequence=$0(X,J0(W,`/sequences/${r0(H)}`));let U=l0(Q.emailId)??l0(Q.templateId);if(U)G.email=$0(X,J0(W,`/emails/${r0(U)}`)),G.template=G.email;let A=l0(Q.transactionalId);if(A)G.transactionalEmail=$0(X,J0(W,`/transactional/${r0(A)}`));let B=l0(Q.emailSendId);if(B)G.emailSend=$0(X,J0(W,`/sent-emails/${r0(B)}`));let K=l0(Q.domainId);if(K)G.domain=$0(X,J0(W,`/settings/domain/${r0(K)}`)),G.domainVerify=`${G.domain}/verify`;let L=l0(Q.status);if(L)G.campaignList=$0(X,J0(W,`/campaign/list/${r0(L)}`)),G.sequenceList=$0(X,J0(W,`/sequences/list/${r0(L)}`));let O=l0(Q.settingsTab);if(O)G.settingsTab=i5(X,W,O);return{appUrl:X,routeTemplates:p5,settingsTabValues:mY,urls:G,settingsUrls:$}}var n5=[{uri:"sequenzy://dashboard",name:"Dashboard Overview",description:"Live overview stats for the last 7 days",mimeType:"application/json"},{uri:"sequenzy://company",name:"Current Company",description:"The currently selected company, including localization settings",mimeType:"application/json"},{uri:"sequenzy://campaigns/recent",name:"Recent Campaigns",description:"Last 10 campaigns with status and basic stats",mimeType:"application/json"},{uri:"sequenzy://subscribers/recent",name:"Recent Subscribers",description:"Most recently added subscribers",mimeType:"application/json"},{uri:"sequenzy://subscribers/engaged",name:"Engaged Subscribers",description:"Most active/engaged subscribers",mimeType:"application/json"},{uri:"sequenzy://sequences",name:"Sequences",description:"All email sequences with status",mimeType:"application/json"},{uri:"sequenzy://templates",name:"Templates",description:"All available email templates with localization status",mimeType:"application/json"},{uri:"sequenzy://segments",name:"Segments",description:"All defined segments with subscriber counts",mimeType:"application/json"},{uri:"sequenzy://tags",name:"Tags",description:"All tags with usage counts",mimeType:"application/json"},{uri:"sequenzy://health",name:"Deliverability Health",description:"Email deliverability metrics and health status",mimeType:"application/json"},{uri:"sequenzy://app-routes",name:"Dashboard URL Routes",description:"Route templates and settings tabs for building Sequenzy dashboard links",mimeType:"application/json"}];async function r5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await D("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await D("GET","/api/v1/account"),W=J1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await D("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await D("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await D("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await D("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await D("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await D("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await D("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await D("GET","/api/v1/tags");break;case"sequenzy://health":Y=await D("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=N1();break;default:throw Error(`Unknown resource: ${Q}`)}return{contents:[{uri:Q,mimeType:"application/json",text:JSON.stringify(Y,null,2)}]}}catch(Y){return{contents:[{uri:Q,mimeType:"text/plain",text:$1(Y)}]}}}import{readFileSync as GV,statSync as $V}from"node:fs";import{basename as JV}from"node:path";var WX=' Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in the transactional send `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" } where the text before the colon is a {{merge tag}} path (nested paths like "order.total" or "event.plan" work) and the text after it is the comparison value. `field` may also be "attribute" (same "name:value" form) or "email"/"firstName"/"lastName" (the value is the plain comparison string). Operators: is, is_not, contains, not_contains, gt, gte, lt, lte, is_empty, is_not_empty. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block.',s4=`Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. For provider-migrated HTML from another email platform, prefer the \`html\` field instead; Sequenzy stores it as one raw HTML block to preserve the original design. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.${WX}`,Q4=`Replacement Sequenzy email blocks. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`.${WX}`,tY=`Sequenzy email blocks. Provide blocks or html for email steps. For migrated provider HTML, prefer \`html\`; Sequenzy stores it as one raw HTML block and does not recreate it as native blocks. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Blocks can include repeat blocks over array variables such as items.${WX}`,NQ="Complete Sequenzy landing page content JSON. Use this when replacing the page structure. The content must be the editor-compatible landing page schema with version, template, seo, theme, and blocks. Landing pages must include exactly one footer block and at most one form block.",zV="Optional template key for default content, such as from-scratch, waitlist, lead-magnet, launch, demo-request, webinar, newsletter, product-hunt, pricing-offer, agency-lead-gen, or feature-announcement.",d5=500,o5=500,w1={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},cY=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay"],t5={type:"object",description:"Optional send window for every email step in the sequence. When set, email actions that become due outside the window wait until the next allowed local time. Omit days to allow every day.",properties:{enabled:{type:"boolean",description:"Set false to disable the sending window when creating a sequence. For updates, prefer clearSendingWindow."},timezone:{type:"string",description:"IANA timezone for the window, e.g. Europe/Kiev or America/New_York."},startTime:{type:"string",description:"Earliest local send time in 24-hour HH:mm format, e.g. 08:00."},endTime:{type:"string",description:"Latest local send cutoff in 24-hour HH:mm format, e.g. 20:00. Must be later than startTime."},days:{type:"array",description:"Allowed local days. Use full names or short names such as monday, tuesday, mon, tue. Omit for every day.",items:{type:"string"}}},additionalProperties:!1},HV={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},aY={type:"object",description:"Wait until a date from the trigger event before this step. Use this for renewal reminders, appointment follow-ups, trial-expiry nudges, and other subscriber-specific dates. The field value must be an ISO date string or Unix timestamp.",properties:{field:{type:"string",description:"Dot-path into the trigger event properties, e.g. renews_at or booking.startsAt."},untilDateField:{type:"string",description:"Alias for field."},offset:HV,days:{type:"number",description:"Offset days shorthand. Ignored when offset is provided."},hours:{type:"number",description:"Offset hours shorthand. Ignored when offset is provided."},minutes:{type:"number",description:"Offset minutes shorthand. Ignored when offset is provided."},direction:{type:"string",enum:["before","after"],description:"Whether the offset applies before or after the resolved date. Defaults to after."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"Alias for direction."},missingAction:{type:"string",enum:["continue","exit"],description:"What to do if the event field is missing or invalid. Defaults to continue."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"Alias for missingAction."}},additionalProperties:!1},sY={type:"object",description:"Fixed delay before this step. For a dynamic wait-until-date delay, either set mode:'until_date' plus untilDateField here, or use waitUntil.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"},mode:{type:"string",enum:["duration","until_date"],description:"Use duration for a fixed wait, or until_date to resolve a date from the trigger event."},untilDateField:{type:"string",description:"For mode:'until_date', dot-path into the trigger event properties."},field:{type:"string",description:"Alias for untilDateField."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"For mode:'until_date', whether days/hours/minutes are before or after the event date. Defaults to after."},direction:{type:"string",enum:["before","after"],description:"Alias for untilOffsetDirection."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"For mode:'until_date', what to do when the field is missing or invalid. Defaults to continue."},missingAction:{type:"string",enum:["continue","exit"],description:"Alias for untilMissingAction."}},additionalProperties:!1},PQ=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],bQ=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","sequence.finished","sequence.failed"],UV=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_websites","check_website","get_integration_guide","get_subscriber","list_subscriber_notes","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_email_send","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_transactional_emails","get_transactional_email","get_stats","get_campaign_stats","get_sequence_stats","list_campaign_events","list_sequence_events","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_sequence","generate_subject_lines","generate_sms","get_sms_settings"]),AV=new Set(["select_company","create_company","update_company","update_sync_rules","update_shopify_automation_settings","create_api_key","add_website","add_subscriber","update_subscriber","add_subscriber_note","remove_subscriber","delete_subscriber_note","upsert_products","delete_product","attach_product_file","remove_product_file","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","delete_template","restart_ab_test","update_ab_test_variant","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","send_test_sms","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_landing_page","update_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","update_sequence","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery","submit_feedback"]),BV=new Set(["send_test_email","send_test_sms","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","enable_sequence","resume_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery"]),KV=new Set(["remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","disable_sequence","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook"]);function DV(Q){let Y=UV.has(Q),X=AV.has(Q);if(Y===X)throw Error(`MCP tool "${Q}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:Y,destructiveHint:Y?!1:KV.has(Q),openWorldHint:BV.has(Q)}}function LV(Q){return{...Q,annotations:{...Q.annotations,...DV(Q.name)}}}var eY={status:["is","is_not"],phone:["is_not_empty","is_empty"],smsStatus:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"],commerceProduct:["is","is_not","at_least","less_than_count"]},FV=Object.entries(eY).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),a5={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","phone","smsStatus","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct","commerceProduct"],description:"Filter field. Use `phone` with is_not_empty/is_empty to check whether a subscriber has a phone number, and `smsStatus` (is/is_not one of `subscribed`, `unsubscribed`, `not_subscribed`) for SMS marketing consent. Use `event` for custom subscriber events, `segment` for saved segment membership, `stripeProduct`/`stripeCurrentProduct`/`stripeTrialProduct` for Stripe product-based segments, and `commerceProduct` for products purchased through commerce orders - the value is `provider:productId` (provider one of `shopify`, `woocommerce`, `api`; product ids are provider-scoped), optionally with an order-count threshold (`provider:productId:count`) for at_least/less_than_count; a bare product id matches the id on any provider. Engagement fields (`emailSent`, `emailDelivered`, `emailOpened`, `emailClicked`, `emailBounced`, `emailComplained`) accept a time range as the value or a specific campaign via `campaign:<campaign_id>`."},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${FV}.`},value:{type:"string",description:"Filter value. For custom attribute empty checks, use `attributeName:` such as `last_logged_in:`. Event examples: `saas.purchase:30d`, `saas.purchase:all`, or `saas.purchase:5:30d` for thresholds. Segment values are segment IDs. Stripe product examples: `prod_123` for bought/didn't buy/current/trialing, `prod_123:3` for payment thresholds, `prod_123:is_canceled` for products set to cancel, `prod_123:cancels_at:2026-05-26`, `prod_123:end_at:2026-05-26`, or `prod_123:start_at:7 days ago` for product-scoped dates. Engagement examples: `7d`, `30d`, `90d`, `180d`, `all` for rolling time windows, or `campaign:<campaign_id>` to scope to a specific sent campaign (use `list_campaigns` to find IDs)."}},required:["field","operator","value"],additionalProperties:!1},s5={type:"object",properties:{kind:{type:"string",enum:["group"]},id:{type:"string",description:"Stable group ID. Any string works; one will be generated if omitted."},joinOperator:{type:"string",enum:["and","or"],description:"How children in this group combine."},children:{type:"array",minItems:1,items:{type:"object",description:'Either a filter leaf (`kind: "filter"`) or another group (`kind: "group"`).'}}},required:["kind","joinOperator","children"],additionalProperties:!0};function QX(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(typeof Y!=="object"||Y===null)return Y;let X=Y;if(typeof X.id==="string"&&X.id.trim()!=="")return X;return{...X,id:crypto.randomUUID()}})}function YX(Q){if(typeof Q!=="object"||Q===null)return Q;let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=QX([Y]);return Array.isArray(X)?X[0]:Y}if(Y.kind!=="group")return Q;return{...Y,id:typeof Y.id==="string"&&Y.id.trim()!==""?Y.id:crypto.randomUUID(),children:Array.isArray(Y.children)?Y.children.map(YX):[]}}function qV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function OV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function e5(Q){if(Q==="all")return!0;let Y=Q.match(/^(\d+)d$/);if(!Y?.[1])return!1;let X=Number.parseInt(Y[1],10);return Number.isInteger(X)&&X>0}function MV(Q,Y){let X=Y.split(":");if(Q==="at_least"||Q==="less_than_count"){if(X.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let $=X.slice(0,-2).join(":").trim(),J=X.at(-2),z=X.at(-1),H=J===void 0?Number.NaN:Number.parseInt(J,10);return $&&Number.isInteger(H)&&H>0&&z!==void 0&&e5(z)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(X.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=X.slice(0,-1).join(":").trim(),G=X.at(-1);return W&&G!==void 0&&e5(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function VV(Q){let Y=Q.indexOf(":");if(Y===-1)return{productId:Q,subfilter:null,rawValue:null};let X=Q.substring(0,Y),W=Q.substring(Y+1),G=W.indexOf(":");if(G===-1)return{productId:X,subfilter:W,rawValue:null};return{productId:X,subfilter:W.substring(0,G),rawValue:W.substring(G+1)}}function ZV(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function NV(Q){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(Q)}function wV(Q,Y){if(Y==="cancels_at"||Y==="cancel_at"||Y==="cancellation_at")return!0;if(Q==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(Y);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(Y)}function PV(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function bV(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let z=X.indexOf(":");if(z===-1)return null;let H=X.substring(0,z).trim(),U=Number.parseInt(X.substring(z+1).trim(),10);return H&&Number.isInteger(U)&&U>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(Q!=="stripeCurrentProduct"&&Q!=="stripeTrialProduct")return null;let{productId:W,subfilter:G,rawValue:$}=VV(X);if(!W.trim())return"Stripe product filters must include a product ID.";if(!G)return Y==="is"||Y==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let J=ZV(G);if(NV(J))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!wV(Q,J))return`Unsupported Stripe product subfilter "${G}".`;if(!PV(Y))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return $?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var jV=new Set(["shopify","woocommerce","api"]);function IV(Q,Y){let X=Y.trim(),W=X.indexOf(":");if(W!==-1&&jV.has(X.substring(0,W).trim()))X=X.substring(W+1).trim();if(!X)return'Purchased Product filters must include a product ID, like "shopify:42".';if(Q!=="at_least"&&Q!=="less_than_count")return null;let G=X.lastIndexOf(":");if(G===-1)return null;let $=X.substring(0,G).trim(),J=Number.parseInt(X.substring(G+1).trim(),10);return $&&Number.isInteger(J)&&J>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function GX(Q){if(typeof Q!=="object"||Q===null)return"Segment filters must be objects.";let Y=Q,X=Y.field,W=Y.operator,G=Y.value;if(typeof X!=="string"||!(X in eY))return`Unsupported segment filter field "${String(X)}".`;if(typeof W!=="string")return`Segment filter "${X}" must include an operator.`;let $=eY[X];if(!$.includes(W))return`Operator "${W}" is not supported for ${X} filters. Use one of: ${$.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${X}" must include a value.`;if(X==="attribute"&&typeof G==="string"){if(!qV(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!OV(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let J=MV(W,G);if(J)return J}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let J=bV(X,W,G);if(J)return J}if(X==="commerceProduct"&&typeof G==="string"){let J=IV(W,G);if(J)return J}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map((z)=>z.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function $X(Q){if(typeof Q!=="object"||Q===null)return[];let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=GX(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap($X);return[]}function P1(Q,Y,X){if(Y.html!==void 0&&Y.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`, not both.`);if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error(`\`blocks\` must be an array when calling \`${Q}\`.`);if(X?.requireContent&&Y.html===void 0&&Y.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`.`)}function wQ(Q,Y){if(Y.labels===void 0)return;if(!Array.isArray(Y.labels))throw Error(`\`labels\` must be an array when calling \`${Q}\`.`);if(Y.labels.some((X)=>typeof X!=="string"||X.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${Q}\`.`)}function EV(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!Y&&!X)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=GX(G);return $?[$]:[]}):$X(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function TV(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(Q.name===void 0&&Q.filterJoinOperator===void 0&&!Y&&!X)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=GX(G);return $?[$]:[]}):X?$X(Q.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var pY=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection"];function iY(Q,Y,X){if(Y[X]!==void 0&&!z0(Y[X]))throw Error(`\`${X}\` must be an object when calling \`${Q}\`.`)}function QH(Q,Y,X){if(Y[X]!==void 0&&!Array.isArray(Y[X]))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`)}function SV(Q){let Y=new Set(["companyId",...pY]),X=Object.keys(Q).filter((G)=>!Y.has(G));if(X.length>0)throw Error(`\`update_company\` accepts only company product-info fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);let W={};for(let G of pY)if(Q[G]!==void 0)W[G]=Q[G];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${pY.map((G)=>`\`${G}\``).join(", ")} when calling \`update_company\`.`);for(let G of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection"])if(Q[G]!==void 0&&typeof Q[G]!=="string")throw Error(`\`${G}\` must be a string when calling \`update_company\`.`);if(iY("update_company",Q,"brandColors"),iY("update_company",Q,"socialLinks"),iY("update_company",Q,"pricing"),QH("update_company",Q,"valueProps"),QH("update_company",Q,"testimonials"),typeof Q.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(Q.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");return W}function RV(Q){if(Q.clearEnrollmentFieldPath===!0&&Q.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(Q.clearSendingWindow===!0&&Q.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(Q.clearBccEmails===!0&&Q.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(Q.branch!==void 0&&Q.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");let Y={...Q};if(delete Y.clearEnrollmentFieldPath,delete Y.clearSendingWindow,delete Y.clearBccEmails,Q.clearEnrollmentFieldPath===!0)Y.enrollmentFieldPath=null;if(Q.clearSendingWindow===!0)Y.sendingWindow=null;if(Q.clearBccEmails===!0)Y.bccEmails=null;return Y}function CV(Q){let Y=Q.type==="sms",X;if(Y){let G=N(Q,"text"),$=Array.isArray(Q.blocks)&&Q.blocks.length>0;if(G===void 0&&!$)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");X={type:"sms"};for(let J of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(Q[J]!==void 0)X[J]=Q[J]}else{P1("insert_sequence_step",Q,{requireContent:!0}),X={subject:R("insert_sequence_step",Q,"subject")};for(let G of["name","previewText","html","blocks","delay","delayMs","waitUntil"])if(Q[G]!==void 0)X[G]=Q[G]}let W={steps:[X]};if(Q.afterNodeId!==void 0)W.afterNodeId=Q.afterNodeId;return{...Q.confirmStructuralChange!==void 0&&{confirmStructuralChange:Q.confirmStructuralChange},insertSteps:W}}function kV(Q){let Y=N(Q,"subscriberId"),X=Q.fieldValues,W=X===void 0?void 0:Array.isArray(X)?X:void 0;if(X!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let G=W?.map((z)=>typeof z==="string"?z.trim():"").filter((z)=>z.length>0)??[];if(W?.some((z)=>typeof z!=="string")||W!==void 0&&G.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(Y!==void 0===G.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let $=N(Q,"fieldPath"),J=N(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...$!==void 0&&{fieldPath:$},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...J!==void 0&&{reason:J}}}function vV(Q){P1("create_campaign",Q),wQ("create_campaign",Q);let Y=N(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0,G=Q.templateId!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(Y&&(X||W||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!Y&&N(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function xV(Q){if(N(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!z0(Q.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(Q.sendTimeOptimization!==void 0){if(typeof Q.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(Q.spreadOverHours!==void 0){if(typeof Q.spreadOverHours!=="number"||!Number.isInteger(Q.spreadOverHours)||Q.spreadOverHours<1||Q.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(Q.recurringInterval!==void 0&&Q.recurringInterval!=="weekly"&&Q.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function nY(Q,Y,X){let W=new Set(["companyId","landingPageId","name","slug","content"]),G=Object.keys(Y).filter(($)=>!W.has($));if(G.length>0)throw Error(`\`${Q}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map(($)=>`\`${$}\``).join(", ")}.`);if(X.requireUpdate&&Y.name===void 0&&Y.slug===void 0&&Y.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${Q}\`.`);return{...Y.name!==void 0&&{name:Y.name},...Y.slug!==void 0&&{slug:Y.slug},...Y.content!==void 0&&{content:Y.content}}}function _V(Q){let Y=new Set(["companyId","domain","verify"]),X=Object.keys(Q).filter((W)=>!Y.has(W));if(X.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${X.length===1?"":"s"}: ${X.map((W)=>`\`${W}\``).join(", ")}.`);if(Q.domain===void 0&&Q.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...Q.domain!==void 0&&{domain:Q.domain},...typeof Q.verify==="boolean"&&{verify:Q.verify}}}function gV(Q){P1("create_transactional_email",Q);let Y=N(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(Y&&(X||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!Y&&!X&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!Y&&N(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var rY={type:"object",description:"A step to create inside a sequence path. Use type:'delay' for a standalone delay, type:'email' for an email, type:'create_discount' for a discount action, or type:'condition' for a condition gate.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","condition","webhook"],description:"Sequence path step type. Omit for email steps; use delay for standalone waits."},nodeType:{type:"string",enum:["logic_delay","action_email","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","logic_condition","action_webhook"],description:"Advanced sequence path node type. Prefer type unless creating a non-email action."},config:{type:"object",description:"Config for advanced nodeType steps such as tag/list/webhook/wait-for-event/condition actions.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:tY,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},delay:sY,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:aY,name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use stripe to dynamically create a Stripe coupon plus promotion code, or shopify to dynamically create a Shopify Admin discount code."},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"}},additionalProperties:!1};function yV(Q){if(!Q||typeof Q!=="object")return null;let Y=Q;if(Y.success!==!1)return null;if(typeof Y.error==="string")return Error(Y.error);if(Y.error&&typeof Y.error==="object"&&typeof Y.error.message==="string")return Error(Y.error.message);if(typeof Y.message==="string")return Error(Y.message);return Error("The tool returned an unsuccessful response.")}function z0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function YH(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function uV(Q){let Y=new URLSearchParams;if(typeof Q.query==="string"&&Q.query.trim()!=="")Y.set("query",Q.query.trim());if(Array.isArray(Q.tags)&&Q.tags.length>0)Y.set("tags",Q.tags.filter((X)=>typeof X==="string"&&X.trim()!=="").join(","));if(typeof Q.list==="string"&&Q.list.trim()!=="")Y.set("list",Q.list.trim());if(typeof Q.listId==="string"&&Q.listId.trim()!=="")Y.set("listId",Q.listId.trim());if(typeof Q.listName==="string"&&Q.listName.trim()!=="")Y.set("listName",Q.listName.trim());if(typeof Q.segmentId==="string"&&Q.segmentId.trim()!=="")Y.set("segmentId",Q.segmentId);if(typeof Q.status==="string"&&Q.status.trim()!=="")Y.set("status",Q.status.trim());return Y.set("page",String(Q.page)),Y.set("limit",String(Q.pageSize)),Y}async function hV(Q,Y){let X=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,W=Math.min(100,Math.max(1,X??100)),G=[],$=1,J=0,z=0,H=0;while(!0){let A=uV({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:$,pageSize:W}),B=await D("GET",`/api/v1/subscribers?${A.toString()}`,void 0,Y);J=B.pagination?.total??B.subscribers.length,z=B.pagination?.totalPages??1,H+=1,G.push(...B.subscribers??[]);let K=X!==void 0&&G.length>=X,L=B.pagination?$>=B.pagination.totalPages:(B.subscribers??[]).length<W;if(K||L)break;$+=1}let U=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:U,pagination:{page:1,limit:W,total:J,totalPages:z,fetchedPages:H},returned:U.length,truncated:X!==void 0&&J>0&&U.length<J}}function fV(Q){let Y=typeof Q.email==="string"&&Q.email.trim()!==""?Q.email.trim():void 0,X=typeof Q.externalId==="string"&&Q.externalId.trim()!==""?Q.externalId.trim():void 0;return{...Y?{email:Y}:{},...X?{externalId:X}:{}}}function v1(Q,Y){let X=fV(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function XX(Q,Y){let X=new URLSearchParams;if(Y?.includeMachineEngagement)X.set("includeMachineEngagement","true");let W=X.toString(),G=W?`?${W}`:"";if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}${G}`;return X.set("externalId",String(Q.externalId)),`/api/v1/subscribers/external?${X.toString()}`}function XH(Q){if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}/notes`;let Y=new URLSearchParams;return Y.set("externalId",String(Q.externalId)),`/api/v1/subscribers/external/notes?${Y.toString()}`}async function dY(Q,Y,X){return D("GET",XX(Q,X),void 0,Y)}function N(Q,Y){let X=Q[Y];if(typeof X!=="string")return;let W=X.trim();return W.length>0?W:void 0}function R(Q,Y,X){let W=N(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function m0(Q,Y,X,W){let G=N(Y,X);if(G===void 0)return;if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function oY(Q,Y,X,W){let G=R(Q,Y,X);if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function x1(Q,Y,X,W,G){let $=Y[X];if($===void 0)return;if(typeof $!=="number"||!Number.isInteger($)||$<W||$>G)throw Error(`\`${X}\` must be an integer between ${W} and ${G} when calling \`${Q}\`.`);return $}function lV(Q,Y){let X=[],W=m0(Q,Y,"eventType",cY);if(W)X.push(W);if(Y.eventTypes!==void 0){if(!Array.isArray(Y.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${Q}\`.`);Y.eventTypes.forEach((G,$)=>{if(typeof G!=="string")throw Error(`\`eventTypes\` item ${$+1} must be a string when calling \`${Q}\`.`);let J=G.trim();if(!cY.includes(J))throw Error(`\`eventTypes\` item ${$+1} must be one of ${cY.join(", ")} when calling \`${Q}\`.`);X.push(J)})}return[...new Set(X)]}function WH(Q,Y){let X=new URLSearchParams,W=lV(Q,Y);if(W.length>0)X.set("eventTypes",W.join(","));let G=m0(Q,Y,"period",["1h","24h","7d","30d","90d"]);if(G)X.set("period",G);let $=N(Y,"start");if($)X.set("start",$);let J=N(Y,"end");if(J)X.set("end",J);let z=x1(Q,Y,"page",1,1e6);if(z!==void 0)X.set("page",String(z));let H=x1(Q,Y,"limit",1,500);if(H!==void 0)X.set("limit",String(H));if(Y.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");return X}function GH(Q,Y){if(Y.events===void 0)return;if(!Array.isArray(Y.events))throw Error(`\`events\` must be an array when calling \`${Q}\`.`);let X=Y.events.map((W,G)=>{if(typeof W!=="string"||!bQ.includes(W))throw Error(`\`events\` item ${G+1} must be one of ${bQ.join(", ")} when calling \`${Q}\`.`);return W});if(X.length===0)throw Error(`\`events\` must include at least one event type when calling \`${Q}\`.`);return X}function $H(Q,Y){if(!Array.isArray(Y.emails))throw Error(`\`emails\` must be an array when calling \`${Q}\`.`);let X=[];if(Y.emails.forEach((W,G)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${Q}\`.`);let $=W.trim();if($.length>0)X.push($)}),X.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${Q}\`.`);if(X.length>d5)throw Error(`\`emails\` must include no more than ${d5} email addresses when calling \`${Q}\`. Split larger batches into multiple calls.`);return X}function JH(Q,Y,X,W){let G=Y[X];if(G===void 0)return;if(!Array.isArray(G))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`);let $=[];if(G.forEach((J,z)=>{if(typeof J!=="string")throw Error(`\`${X}\` item ${z+1} must be a string when calling \`${Q}\`.`);let H=J.trim();if(H.length>0)$.push(H)}),$.length===0)throw Error(`\`${X}\` must include at least one ${W} when calling \`${Q}\`.`);return $}function mV(Q){let X=JH("enroll_subscribers_in_sequence",Q,"emails","email address"),W=JH("enroll_subscribers_in_sequence",Q,"subscriberIds","subscriber ID"),G=(X?.length??0)+(W?.length??0);if(G===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(G>o5)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${o5} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let $=N(Q,"targetNodeId");return{...X!==void 0&&{emails:X},...W!==void 0&&{subscriberIds:W},...$!==void 0&&{targetNodeId:$}}}var cV={pdf:"application/pdf",epub:"application/epub+zip",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",txt:"text/plain",csv:"text/csv"};function pV(Q){let Y=Q.split(".").pop()?.toLowerCase()??"";return cV[Y]??null}var iV=104857600;async function nV(Q,Y){if(!qX())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let X=pV(Q);if(!X)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=$V(Q).size;if(W>iV)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=GV(Q),$=await D("POST","/api/v1/products/delivery/upload-url",{filename:JV(Q),contentType:X,fileSizeBytes:W},Y),J=await fetch($.uploadUrl,{method:"PUT",headers:{"Content-Type":X},body:G});if(!J.ok)throw Error(`File upload failed (${J.status})`);return{url:$.publicUrl,fileName:$.fileName,fileSizeBytes:W,mimeType:X}}async function JX(Q){let Y=N(Q,"companyId");if(Y)return Y;let X=J1();if(X)return X;try{return(await D("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function rV(Q,Y){let X=await JX(Y);if(!X)throw Error(`A company is required when calling \`${Q}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return X}function Y4(Q,Y){if(!z0(Q)||!Y)return Q;return{...Q,url:Y}}function zH(Q,Y){if(!z0(Q))return Q;return{...Q,...Y.campaign!==void 0&&{url:Y.campaign},...Y.campaignPreview!==void 0&&{previewUrl:Y.campaignPreview}}}function e4(Q,Y,X){if(!Array.isArray(Q)||!Y)return Q;return Q.map((W)=>{if(!z0(W))return W;let G=N(W,"id");if(!G)return W;let $=N1({companyId:Y,...X==="campaign"&&{campaignId:G},...X==="landingPage"&&{landingPageId:G},...X==="sequence"&&{sequenceId:G},...X==="template"&&{emailId:G},...X==="transactional"&&{transactionalId:G}});if(X==="campaign")return zH(W,$.urls);let J=X==="sequence"?$.urls.sequence:X==="landingPage"?$.urls.landingPage:X==="template"?$.urls.email:$.urls.transactionalEmail;return Y4(W,J)})}function dV(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!z0(Y))return Y;let X=N(Y,"id");if(!X)return Y;let W=N1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var HH=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","update_sequence","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function oV(Q,Y,X){if(!z0(X)||!HH.has(Q))return X;let W=z0(X.company)?X.company:void 0,$=N(X,"selectedCompanyId")??N(X,"currentCompanyId")??N(X,"companyId")??(W?N(W,"id"):void 0)??(W?N(W,"companyId"):void 0)??await JX(Y);if(!$)return X;let J=z0(X.campaign)?X.campaign:void 0,z=z0(X.sequence)?X.sequence:void 0,H=z0(X.landingPage)?X.landingPage:void 0,U=z0(X.template)?X.template:void 0,A=z0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,B={companyId:$,campaignId:N(Y,"campaignId")??N(X,"campaignId")??(J?N(J,"id"):void 0),landingPageId:N(Y,"landingPageId")??N(X,"landingPageId")??(H?N(H,"id"):void 0),sequenceId:N(Y,"sequenceId")??N(X,"sequenceId")??(z?N(z,"id"):void 0),emailId:N(X,"templateId")??(U?N(U,"id"):void 0)??(A?N(A,"emailId"):void 0)??N(Y,"templateId"),transactionalId:N(Y,"transactionalId")??(A?N(A,"id"):void 0)??N(Y,"idOrSlug"),emailSendId:N(Y,"emailSendId")??N(X,"emailSendId")??(z0(X.emailSend)?N(X.emailSend,"id"):void 0),status:N(Y,"status")},K=N1(B),L=W?N1({companyId:$}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:dV(X.companies)},...Array.isArray(X.campaigns)&&{campaigns:e4(X.campaigns,$,"campaign")},...Array.isArray(X.landingPages)&&{landingPages:e4(X.landingPages,$,"landingPage")},...Array.isArray(X.sequences)&&{sequences:e4(X.sequences,$,"sequence")},...Array.isArray(X.templates)&&{templates:e4(X.templates,$,"template")},...Array.isArray(X.transactional)&&{transactional:e4(X.transactional,$,"transactional")},...W&&L!==void 0&&{company:{...W,url:L.urls.dashboard,settingsUrl:L.urls.settings}},...J&&K.urls.campaign!==void 0&&{campaign:zH(J,K.urls)},...z&&K.urls.sequence!==void 0&&{sequence:Y4(z,K.urls.sequence)},...H&&K.urls.landingPage!==void 0&&{landingPage:Y4(H,K.urls.landingPage)},...U&&K.urls.email!==void 0&&{template:Y4(U,K.urls.email)},...A&&K.urls.transactionalEmail!==void 0&&{transactional:Y4(A,K.urls.transactionalEmail)},...z0(X.emailSend)&&K.urls.emailSend!==void 0&&{emailSend:Y4(X.emailSend,K.urls.emailSend)},appUrls:K.urls}}var tV={type:"boolean",description:"Whether the Sequenzy operation succeeded."},aV={type:"string",description:"Human-readable status, confirmation, or next-step message."},sV={type:"string",description:"Additional context about the result."};function W0(Q){return{type:"object",description:Q,additionalProperties:!0}}function eV(Q){return{type:"array",description:Q,items:W0("One item in the returned collection.")}}function T(Q){return{type:"string",description:Q}}function b0(Q){return{type:"number",description:Q}}function G1(Q){return{type:"boolean",description:Q}}function V(Q){return W0(`The ${Q} record returned by Sequenzy.`)}function p(Q){return eV(`List of ${Q} records returned by Sequenzy.`)}var QZ={appUrls:W0("Dashboard URLs for relevant Sequenzy resources."),url:T("Primary dashboard URL for this result."),settingsUrl:T("Company settings URL when available.")},YZ={success:tV,message:aV,note:sV,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:W0("One returned item.")},value:W0("Fallback object wrapper used only when a tool returns a non-object value.")},XZ={get_account:{account:V("account"),companies:p("company"),currentCompanyId:T("Company ID selected by the authenticated API key, when available."),selectedCompanyId:T("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:T("Selected company ID."),companyName:T("Selected company name.")},get_app_urls:{dashboard:T("Company dashboard URL."),settings:T("Company settings URL."),campaign:T("Campaign editor URL."),landingPage:T("Landing page editor URL."),sequence:T("Sequence editor URL."),email:T("Email editor URL."),transactionalEmail:T("Transactional email URL."),emailSend:T("Sent email detail URL."),domain:T("Sending domain settings URL."),urls:W0("All generated URLs keyed by resource type.")},create_company:{company:V("company"),autoSelected:G1("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:V("company")},get_company:{company:V("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:W0("One sync rule.")},isDefault:G1("Whether the company still uses the platform default rules.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:W0("One sync rule.")},isDefault:G1("Whether the company now uses the platform default rules.")},get_shopify_automation_settings:{browseAbandonment:W0("Effective browse-abandonment settings (defaults applied)."),priceDrop:W0("Effective price-drop settings (defaults applied)."),shopDomain:T("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:W0("Effective browse-abandonment settings after the update."),priceDrop:W0("Effective price-drop settings after the update."),shopDomain:T("Connected Shopify store domain.")},create_api_key:{apiKey:W0("Created API key metadata: the newly created secret in `key`, plus `scopes` listing the assigned permission scopes (null when the key has full access)."),key:T("Newly created API key if the API response uses the short key field.")},list_websites:{websites:p("sender website")},add_website:{website:V("sender website")},check_website:{website:V("sender website"),ready:G1("Whether the sender website is ready."),status:T("Current processing or verification status.")},get_integration_guide:{guide:V("integration guide"),code:T("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:W0("One setup step.")}},add_subscriber:{subscriber:V("subscriber")},update_subscriber:{subscriber:V("subscriber")},remove_subscriber:{subscriber:V("subscriber"),hardDeleted:G1("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:V("subscriber")},list_subscriber_notes:{notes:p("subscriber note")},add_subscriber_note:{note:V("subscriber note")},delete_subscriber_note:{id:T("Deleted subscriber note ID."),deleted:G1("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:p("subscriber"),pagination:W0("Pagination metadata."),returned:b0("Number of subscribers returned."),truncated:G1("Whether the result was truncated by the requested limit.")},list_products:{products:p("product")},upsert_products:{products:p("product"),created:b0("Number of products created."),updated:b0("Number of products updated.")},delete_product:{productId:T("Deleted product ID.")},attach_product_file:{product:V("product"),delivery:V("digital delivery file")},remove_product_file:{product:V("product")},sync_products:{job:V("product sync job"),jobId:T("Queued product sync job ID.")},list_tags:{tags:p("tag")},create_tag:{tag:V("tag")},update_tag:{tag:V("tag")},delete_tag:{tagId:T("Deleted tag ID.")},list_lists:{lists:p("list")},create_list:{list:V("list")},update_list:{list:V("list")},delete_list:{listId:T("Deleted list ID.")},add_subscribers_to_list:{list:V("list"),added:b0("Number of subscribers added to the list."),skipped:b0("Number of subscribers skipped.")},remove_subscribers_from_list:{list:V("list"),removed:b0("Number of subscribers removed from the list."),skipped:b0("Number of subscribers skipped.")},list_segments:{segments:p("segment")},create_segment:{segment:V("segment")},update_segment:{segment:V("segment")},delete_segment:{segmentId:T("Deleted segment ID.")},get_segment_count:{count:b0("Number of subscribers matching the segment."),segmentId:T("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:p("audience sync")},list_ad_accounts:{adAccounts:p("ad account")},create_audience_sync:{audienceSync:V("audience sync")},update_audience_sync:{audienceSync:V("audience sync")},delete_audience_sync:{audienceSyncId:T("Deleted audience sync ID.")},sync_audience_now:{audienceSync:V("audience sync"),job:V("audience sync job"),jobId:T("Queued audience sync job ID.")},list_templates:{templates:p("email template")},get_template:{template:V("email template")},create_template:{template:V("email template")},update_template:{template:V("email template")},delete_template:{templateId:T("Deleted template ID.")},list_ab_tests:{abTests:p("A/B test")},get_ab_test:{abTest:V("A/B test")},get_ab_test_stats:{abTest:V("A/B test"),stats:V("A/B test statistics")},restart_ab_test:{abTest:V("A/B test")},update_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},create_ab_test:{abTest:V("A/B test")},add_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},delete_ab_test_variant:{abTest:V("A/B test"),variantId:T("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:T("Deleted A/B test ID.")},list_campaigns:{campaigns:p("campaign")},get_campaign:{campaign:V("campaign")},get_email_send:{emailSend:V("email send")},create_campaign:{campaign:V("campaign")},update_campaign:{campaign:V("campaign")},schedule_campaign:{campaign:V("campaign"),scheduledAt:T("Scheduled send timestamp.")},send_test_email:{emailSend:V("test email send"),recipient:T("Test email recipient.")},send_test_sms:{smsSendId:T("Created test SMS send ID."),toPhone:T("Normalized E.164 destination phone.")},cancel_campaign:{campaign:V("campaign")},pause_campaign:{campaign:V("campaign")},resume_campaign:{campaign:V("campaign")},delete_campaign:{campaignId:T("Deleted campaign ID.")},duplicate_campaign:{campaign:V("duplicated campaign")},resend_campaign_to_non_openers:{campaign:V("non-opener resend draft campaign"),estimatedNonOpenerCount:b0("Estimated number of subscribers who haven't opened the original campaign.")},list_landing_pages:{landingPages:p("landing page")},get_landing_page:{landingPage:V("landing page")},create_landing_page:{landingPage:V("landing page")},update_landing_page:{landingPage:V("landing page")},delete_landing_page:{landingPageId:T("Deleted landing page ID.")},publish_landing_page:{landingPage:V("landing page")},unpublish_landing_page:{landingPage:V("landing page")},connect_landing_page_domain:{landingPage:V("landing page"),domain:T("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:V("landing page"),domain:T("Landing page domain.")},list_sequences:{sequences:p("sequence")},get_sequence:{sequence:V("sequence")},create_sequence:{sequence:V("sequence")},update_sequence:{sequence:V("sequence")},insert_sequence_step:{sequence:V("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for the inserted step, including any delay node.",items:T("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:T("Inserted email template ID.")},insertedEmailCount:b0("Number of email steps inserted.")},enable_sequence:{sequence:V("sequence")},disable_sequence:{sequence:V("sequence")},pause_sequence_enrollments:{sequenceId:T("Sequence ID."),enrollmentPaused:G1("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:T("Sequence ID."),enrollmentPaused:G1("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:V("sequence"),enrollments:p("sequence enrollment"),enrolled:b0("Number of subscribers enrolled."),skipped:b0("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:V("sequence"),cancelled:b0("Number of enrollments cancelled."),skipped:b0("Number of enrollments skipped.")},delete_sequence:{sequenceId:T("Deleted sequence ID.")},list_transactional_emails:{transactional:p("transactional email")},get_transactional_email:{transactional:V("transactional email")},create_transactional_email:{transactional:V("transactional email")},update_transactional_email:{transactional:V("transactional email")},send_email:{emailSend:V("transactional email send"),transactional:V("transactional email")},get_stats:{stats:V("account or company statistics")},get_campaign_stats:{campaign:V("campaign"),stats:V("campaign statistics")},get_sequence_stats:{sequence:V("sequence"),stats:V("sequence statistics")},list_campaign_events:{events:p("campaign email event"),pagination:W0("Pagination metadata.")},list_sequence_events:{events:p("sequence email event"),pagination:W0("Pagination metadata.")},get_subscriber_activity:{activity:p("subscriber activity event"),subscribers:p("subscriber"),pagination:W0("Pagination metadata.")},list_team_members:{members:p("team member"),invitations:p("team invitation")},invite_team_member:{invitation:V("team invitation")},cancel_team_invitation:{invitationId:T("Cancelled invitation ID.")},list_conversations:{conversations:p("inbox conversation"),pagination:W0("Pagination metadata.")},get_conversation:{conversation:V("inbox conversation"),messages:p("conversation message")},reply_to_conversation:{conversation:V("inbox conversation"),message:V("conversation message")},update_conversation_status:{conversation:V("inbox conversation")},mark_conversation_read:{conversation:V("inbox conversation")},list_webhooks:{webhooks:p("outbound webhook")},create_webhook:{webhook:V("outbound webhook")},update_webhook:{webhook:V("outbound webhook")},delete_webhook:{webhookId:T("Deleted outbound webhook ID.")},test_webhook:{webhook:V("outbound webhook"),delivery:V("test webhook delivery")},list_webhook_deliveries:{deliveries:p("webhook delivery")},replay_webhook_delivery:{delivery:V("webhook delivery"),job:V("webhook replay job")},generate_email:{email:V("generated email"),html:T("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks.",items:W0("One generated email block.")},subject:T("Generated subject line."),previewText:T("Generated inbox preview text.")},generate_sequence:{sequence:V("generated sequence"),steps:p("generated sequence step")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:T("One generated subject line.")},variants:p("generated subject line variant")},generate_sms:{prompt:T("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:W0("One generated SMS message.")}},get_sms_settings:{sms:W0("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{}};function WZ(Q){let Y=XZ[Q];if(Y===void 0)throw Error(`MCP tool "${Q}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${Q}\` MCP tool.`,properties:{...YZ,...Y,...HH.has(Q)?QZ:{}},additionalProperties:!0}}function GZ(Q){return{...Q,outputSchema:WZ(Q.name)}}function $Z(Q){if(z0(Q))return Q;if(Array.isArray(Q))return{items:Q};return{value:Q}}var JZ=[{name:"get_account",description:`Get current account information including available companies. IMPORTANT: If you have access to multiple companies, you MUST either:
30
30
  1. Call select_company first to choose which company to work with, OR
31
31
  2. Pass companyId explicitly in each tool call
32
32