@sequenzy/mcp 0.0.100 → 0.0.101

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 qH=Object.create;var{getPrototypeOf:OH,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(D,S,y)},$,z=j1,J=!Y6.jitless,A=J&&vQ.value,U=Y.catchall,K;Q._zod.parse=(D,L)=>{K??(K=W.value);let O=D.value;if(!z(O))return D.issues.push({expected:"object",code:"invalid_type",input:O,inst:Q}),D;if(J&&A&&L?.async===!1&&L.jitless!==!0){if(!$)$=G(Y.shape);if(D=$(D,L),!U)return D;return FW([],O,D,L,K,Q)}return X(D,L)}});function C8(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((z)=>x0(z,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(($)=>J4($.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 z=!1,J=[];for(let H of Y.options){let A=H._zod.run({value:G.value,issues:[]},$);if(A instanceof Promise)J.push(A),z=!0;else{if(A.issues.length===0)return A;J.push(A)}}if(!z)return C8(J,G,Q,$);return Promise.all(J).then((H)=>{return C8(H,G,Q,$)})}}),OW=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 z=$._zod.propValues;if(!z||Object.keys(z).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf($)}"`);for(let[J,H]of Object.entries(z)){if(!G[J])G[J]=new Set;for(let A of H)G[J].add(A)}}return G});let W=g1(()=>{let G=Y.options,$=new Map;for(let z of G){let J=z._zod.propValues?.[Y.discriminator];if(!J||J.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(z)}"`);for(let H of J){if($.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);$.set(H,z)}}return $});Q._zod.parse=(G,$)=>{let z=G.value;if(!j1(z))return G.issues.push({code:"invalid_type",expected:"object",input:z,inst:Q}),G;let J=W.value.get(z?.[Y.discriminator]);if(J)return J._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:z,path:[Y.discriminator],inst:Q}),G}}),MW=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),z=Y.right._zod.run({value:G,issues:[]},W);if($ instanceof Promise||z instanceof Promise)return Promise.all([$,z]).then(([H,A])=>{return k8(X,H,A)});return k8(X,$,z)}});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(H1(Q)&&H1(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter(($)=>X.indexOf($)!==-1),G={...Q,...Y};for(let $ of W){let z=cQ(Q[$],Y[$]);if(!z.valid)return{valid:!1,mergeErrorPath:[$,...z.mergeErrorPath]};G[$]=z.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],z=cQ(G,$);if(!z.valid)return{valid:!1,mergeErrorPath:[W,...z.mergeErrorPath]};X.push(z.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function k8(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 VW=q("$ZodRecord",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!H1(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let $=[];if(Y.keyType._zod.values){let z=Y.keyType._zod.values;X.value={};for(let H of z)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let A=Y.valueType._zod.run({value:G[H],issues:[]},W);if(A instanceof Promise)$.push(A.then((U)=>{if(U.issues.length)X.issues.push(...s0(H,U.issues));X.value[H]=U.value}));else{if(A.issues.length)X.issues.push(...s0(H,A.issues));X.value[H]=A.value}}let J;for(let H in G)if(!z.has(H))J=J??[],J.push(H);if(J&&J.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:J})}else{X.value={};for(let z of Reflect.ownKeys(G)){if(z==="__proto__")continue;let J=Y.keyType._zod.run({value:z,issues:[]},W);if(J instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(J.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:J.issues.map((A)=>x0(A,W,T0())),input:z,path:[z],inst:Q}),X.value[J.value]=J.value;continue}let H=Y.valueType._zod.run({value:G[z],issues:[]},W);if(H instanceof Promise)$.push(H.then((A)=>{if(A.issues.length)X.issues.push(...s0(z,A.issues));X.value[J.value]=A.value}));else{if(H.issues.length)X.issues.push(...s0(z,H.issues));X.value[J.value]=H.value}}}if($.length)return Promise.all($).then(()=>X);return X}});var ZW=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"?a0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,$)=>{let z=G.value;if(W.has(z))return G;return G.issues.push({code:"invalid_value",values:X,input:z,inst:Q}),G}}),NW=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"?a0(X):X?a0(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 wW=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((z)=>{return X.value=z,X});if(G instanceof Promise)throw new t0;return X.value=G,X}});function v8(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var PW=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(`^(${J4(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(($)=>v8($,X.value));return v8(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),bW=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(`^(${J4(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)}}),jW=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(($)=>x8($,Y));return x8(G,Y)}});function x8(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var IW=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)}}),EW=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(($)=>_8($,Q));return _8(G,Q)}});function _8(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 TW=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((z)=>x0(z,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 SW=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((z)=>K6(z,Y.in,W));return K6($,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>K6($,Y.out,W));return K6(G,Y.out,W)}});function K6(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var RW=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(g8);return g8(G)}});function g8(Q){return Q.value=Object.freeze(Q.value),Q}var CW=q("$ZodCustom",(Q,Y)=>{A0.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(($)=>y8($,X,W,Q));y8(G,X,W,Q);return}});function y8(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 UA=(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},KA=()=>{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 ${UA(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:KA()}}var kZ=Symbol("ZodOutput"),vZ=Symbol("ZodInput");class kW{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 DA(){return new kW}var B4=DA();function vW(Q,Y){return new Q({type:"string",...T(Y)})}function xW(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...T(Y)})}function rQ(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...T(Y)})}function _W(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...T(Y)})}function gW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...T(Y)})}function yW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...T(Y)})}function uW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...T(Y)})}function hW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...T(Y)})}function fW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...T(Y)})}function lW(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...T(Y)})}function mW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...T(Y)})}function cW(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...T(Y)})}function pW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...T(Y)})}function iW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...T(Y)})}function nW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...T(Y)})}function rW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...T(Y)})}function dW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...T(Y)})}function oW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...T(Y)})}function tW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...T(Y)})}function aW(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...T(Y)})}function sW(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...T(Y)})}function eW(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...T(Y)})}function QG(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...T(Y)})}function YG(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...T(Y)})}function XG(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...T(Y)})}function WG(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...T(Y)})}function GG(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...T(Y)})}function $G(Q,Y){return new Q({type:"number",checks:[],...T(Y)})}function zG(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...T(Y)})}function JG(Q,Y){return new Q({type:"boolean",...T(Y)})}function HG(Q,Y){return new Q({type:"null",...T(Y)})}function AG(Q){return new Q({type:"unknown"})}function UG(Q,Y){return new Q({type:"never",...T(Y)})}function L6(Q,Y){return new fQ({check:"less_than",...T(Y),value:Q,inclusive:!1})}function L4(Q,Y){return new fQ({check:"less_than",...T(Y),value:Q,inclusive:!0})}function F6(Q,Y){return new lQ({check:"greater_than",...T(Y),value:Q,inclusive:!1})}function F4(Q,Y){return new lQ({check:"greater_than",...T(Y),value:Q,inclusive:!0})}function q6(Q,Y){return new q8({check:"multiple_of",...T(Y),value:Q})}function O6(Q,Y){return new M8({check:"max_length",...T(Y),maximum:Q})}function u1(Q,Y){return new V8({check:"min_length",...T(Y),minimum:Q})}function M6(Q,Y){return new Z8({check:"length_equals",...T(Y),length:Q})}function dQ(Q,Y){return new N8({check:"string_format",format:"regex",...T(Y),pattern:Q})}function oQ(Q){return new w8({check:"string_format",format:"lowercase",...T(Q)})}function tQ(Q){return new P8({check:"string_format",format:"uppercase",...T(Q)})}function aQ(Q,Y){return new b8({check:"string_format",format:"includes",...T(Y),includes:Q})}function sQ(Q,Y){return new j8({check:"string_format",format:"starts_with",...T(Y),prefix:Q})}function eQ(Q,Y){return new I8({check:"string_format",format:"ends_with",...T(Y),suffix:Q})}function I1(Q){return new E8({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 KG(Q,Y,X){return new Q({type:"array",element:Y,...T(X)})}function DG(Q,Y,X){let W=T(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function BG(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...T(X)})}function LG(Q){let Y=BA((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 BA(Q,Y){let X=new A0({check:"custom",...T(Y)});return X._zod.check=Q,X}function h1(Q){return!!Q._zod}function U1(Q,Y){if(h1(Q))return U4(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 FG(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={};LX(O4,{time:()=>z9,duration:()=>J9,datetime:()=>G9,date:()=>$9,ZodISOTime:()=>MG,ZodISODuration:()=>VG,ZodISODateTime:()=>qG,ZodISODate:()=>OG});var qG=q("ZodISODateTime",(Q,Y)=>{o8.init(Q,Y),s.init(Q,Y)});function G9(Q){return YG(qG,Q)}var OG=q("ZodISODate",(Q,Y)=>{t8.init(Q,Y),s.init(Q,Y)});function $9(Q){return XG(OG,Q)}var MG=q("ZodISOTime",(Q,Y)=>{a8.init(Q,Y),s.init(Q,Y)});function z9(Q){return WG(MG,Q)}var VG=q("ZodISODuration",(Q,Y)=>{s8.init(Q,Y),s.init(Q,Y)});function J9(Q){return GG(VG,Q)}var ZG=(Q,Y)=>{z6.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>CX(Q,X)},flatten:{value:(X)=>RX(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}}})},MN=q("ZodError",ZG),I0=q("ZodError",ZG,{Parent:Error});var NG=J6(I0),wG=H6(I0),PG=A4(I0),bG=K4(I0),jG=kX(I0),IG=vX(I0),EG=xX(I0),TG=_X(I0),SG=gX(I0),RG=yX(I0),CG=uX(I0),kG=hX(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)=>NG(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>PG(Q,X,W),Q.parseAsync=async(X,W)=>wG(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>bG(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>jG(Q,X,W),Q.decode=(X,W)=>IG(Q,X,W),Q.encodeAsync=async(X,W)=>EG(Q,X,W),Q.decodeAsync=async(X,W)=>TG(Q,X,W),Q.safeEncode=(X,W)=>SG(Q,X,W),Q.safeDecode=(X,W)=>RG(Q,X,W),Q.safeEncodeAsync=async(X,W)=>CG(Q,X,W),Q.safeDecodeAsync=async(X,W)=>kG(Q,X,W),Q.refine=(X,W)=>Q.check(A3(X,W)),Q.superRefine=(X)=>Q.check(U3(X)),Q.overwrite=(X)=>Q.check(I1(X)),Q.optional=()=>Y0(Q),Q.nullable=()=>_G(Q),Q.nullish=()=>Y0(_G(Q)),Q.nonoptional=(X)=>W3(Q,X),Q.array=()=>u(Q),Q.or=(X)=>d([Q,X]),Q.and=(X)=>N6(Q,X),Q.transform=(X)=>A9(Q,fG(X)),Q.default=(X)=>Q3(Q,X),Q.prefault=(X)=>X3(Q,X),Q.catch=(X)=>$3(Q,X),Q.pipe=(X)=>A9(Q,X),Q.readonly=()=>H3(Q),Q.describe=(X)=>{let W=Q.clone();return B4.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return B4.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return B4.get(Q);let W=Q.clone();return B4.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),gG=q("_ZodString",(Q,Y)=>{B6.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())}),wA=q("ZodString",(Q,Y)=>{B6.init(Q,Y),gG.init(Q,Y),Q.email=(X)=>Q.check(xW(PA,X)),Q.url=(X)=>Q.check(hW(bA,X)),Q.jwt=(X)=>Q.check(QG(hA,X)),Q.emoji=(X)=>Q.check(fW(jA,X)),Q.guid=(X)=>Q.check(rQ(vG,X)),Q.uuid=(X)=>Q.check(_W(Z6,X)),Q.uuidv4=(X)=>Q.check(gW(Z6,X)),Q.uuidv6=(X)=>Q.check(yW(Z6,X)),Q.uuidv7=(X)=>Q.check(uW(Z6,X)),Q.nanoid=(X)=>Q.check(lW(IA,X)),Q.guid=(X)=>Q.check(rQ(vG,X)),Q.cuid=(X)=>Q.check(mW(EA,X)),Q.cuid2=(X)=>Q.check(cW(TA,X)),Q.ulid=(X)=>Q.check(pW(SA,X)),Q.base64=(X)=>Q.check(aW(gA,X)),Q.base64url=(X)=>Q.check(sW(yA,X)),Q.xid=(X)=>Q.check(iW(RA,X)),Q.ksuid=(X)=>Q.check(nW(CA,X)),Q.ipv4=(X)=>Q.check(rW(kA,X)),Q.ipv6=(X)=>Q.check(dW(vA,X)),Q.cidrv4=(X)=>Q.check(oW(xA,X)),Q.cidrv6=(X)=>Q.check(tW(_A,X)),Q.e164=(X)=>Q.check(eW(uA,X)),Q.datetime=(X)=>Q.check(G9(X)),Q.date=(X)=>Q.check($9(X)),Q.time=(X)=>Q.check(z9(X)),Q.duration=(X)=>Q.check(J9(X))});function F(Q){return vW(wA,Q)}var s=q("ZodStringFormat",(Q,Y)=>{t.init(Q,Y),gG.init(Q,Y)}),PA=q("ZodEmail",(Q,Y)=>{f8.init(Q,Y),s.init(Q,Y)});var vG=q("ZodGUID",(Q,Y)=>{u8.init(Q,Y),s.init(Q,Y)});var Z6=q("ZodUUID",(Q,Y)=>{h8.init(Q,Y),s.init(Q,Y)});var bA=q("ZodURL",(Q,Y)=>{l8.init(Q,Y),s.init(Q,Y)});var jA=q("ZodEmoji",(Q,Y)=>{m8.init(Q,Y),s.init(Q,Y)});var IA=q("ZodNanoID",(Q,Y)=>{c8.init(Q,Y),s.init(Q,Y)});var EA=q("ZodCUID",(Q,Y)=>{p8.init(Q,Y),s.init(Q,Y)});var TA=q("ZodCUID2",(Q,Y)=>{i8.init(Q,Y),s.init(Q,Y)});var SA=q("ZodULID",(Q,Y)=>{n8.init(Q,Y),s.init(Q,Y)});var RA=q("ZodXID",(Q,Y)=>{r8.init(Q,Y),s.init(Q,Y)});var CA=q("ZodKSUID",(Q,Y)=>{d8.init(Q,Y),s.init(Q,Y)});var kA=q("ZodIPv4",(Q,Y)=>{e8.init(Q,Y),s.init(Q,Y)});var vA=q("ZodIPv6",(Q,Y)=>{QW.init(Q,Y),s.init(Q,Y)});var xA=q("ZodCIDRv4",(Q,Y)=>{YW.init(Q,Y),s.init(Q,Y)});var _A=q("ZodCIDRv6",(Q,Y)=>{XW.init(Q,Y),s.init(Q,Y)});var gA=q("ZodBase64",(Q,Y)=>{GW.init(Q,Y),s.init(Q,Y)});var yA=q("ZodBase64URL",(Q,Y)=>{$W.init(Q,Y),s.init(Q,Y)});var uA=q("ZodE164",(Q,Y)=>{zW.init(Q,Y),s.init(Q,Y)});var hA=q("ZodJWT",(Q,Y)=>{JW.init(Q,Y),s.init(Q,Y)});var yG=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(xG(W)),Q.safe=(W)=>Q.check(xG(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 $G(yG,Q)}var fA=q("ZodNumberFormat",(Q,Y)=>{HW.init(Q,Y),yG.init(Q,Y)});function xG(Q){return zG(fA,Q)}var lA=q("ZodBoolean",(Q,Y)=>{AW.init(Q,Y),X0.init(Q,Y)});function H0(Q){return JG(lA,Q)}var mA=q("ZodNull",(Q,Y)=>{UW.init(Q,Y),X0.init(Q,Y)});function U9(Q){return HG(mA,Q)}var cA=q("ZodUnknown",(Q,Y)=>{KW.init(Q,Y),X0.init(Q,Y)});function e(){return AG(cA)}var pA=q("ZodNever",(Q,Y)=>{DW.init(Q,Y),X0.init(Q,Y)});function iA(Q){return UG(pA,Q)}var nA=q("ZodArray",(Q,Y)=>{BW.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 KG(nA,Q,Y)}var uG=q("ZodObject",(Q,Y)=>{qW.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:iA()}),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(lG,Q,X[0]),Q.required=(...X)=>m.required(mG,Q,X[0])});function b(Q,Y){let X={type:"object",shape:Q??{},...m.normalizeParams(Y)};return new uG(X)}function q0(Q,Y){return new uG({type:"object",shape:Q,catchall:e(),...m.normalizeParams(Y)})}var hG=q("ZodUnion",(Q,Y)=>{iQ.init(Q,Y),X0.init(Q,Y),Q.options=Y.options});function d(Q,Y){return new hG({type:"union",options:Q,...m.normalizeParams(Y)})}var rA=q("ZodDiscriminatedUnion",(Q,Y)=>{hG.init(Q,Y),OW.init(Q,Y)});function K9(Q,Y,X){return new rA({type:"union",options:Y,discriminator:Q,...m.normalizeParams(X)})}var dA=q("ZodIntersection",(Q,Y)=>{MW.init(Q,Y),X0.init(Q,Y)});function N6(Q,Y){return new dA({type:"intersection",left:Q,right:Y})}var oA=q("ZodRecord",(Q,Y)=>{VW.init(Q,Y),X0.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function Q0(Q,Y,X){return new oA({type:"record",keyType:Q,valueType:Y,...m.normalizeParams(X)})}var H9=q("ZodEnum",(Q,Y)=>{ZW.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 z of W)if(X.has(z))$[z]=Y.entries[z];else throw Error(`Key ${z} not found in enum`);return new H9({...Y,checks:[],...m.normalizeParams(G),entries:$})},Q.exclude=(W,G)=>{let $={...Y.entries};for(let z of W)if(X.has(z))delete $[z];else throw Error(`Key ${z} 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 tA=q("ZodLiteral",(Q,Y)=>{NW.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 tA({type:"literal",values:Array.isArray(Q)?Q:[Q],...m.normalizeParams(Y)})}var aA=q("ZodTransform",(Q,Y)=>{wW.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 z=$;if(z.fatal)z.continue=!1;z.code??(z.code="custom"),z.input??(z.input=X.value),z.inst??(z.inst=Q),X.issues.push(m.issue(z))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then(($)=>{return X.value=$,X});return X.value=G,X}});function fG(Q){return new aA({type:"transform",transform:Q})}var lG=q("ZodOptional",(Q,Y)=>{PW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function Y0(Q){return new lG({type:"optional",innerType:Q})}var sA=q("ZodNullable",(Q,Y)=>{bW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function _G(Q){return new sA({type:"nullable",innerType:Q})}var eA=q("ZodDefault",(Q,Y)=>{jW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function Q3(Q,Y){return new eA({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var Y3=q("ZodPrefault",(Q,Y)=>{IW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function X3(Q,Y){return new Y3({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var mG=q("ZodNonOptional",(Q,Y)=>{EW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function W3(Q,Y){return new mG({type:"nonoptional",innerType:Q,...m.normalizeParams(Y)})}var G3=q("ZodCatch",(Q,Y)=>{TW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function $3(Q,Y){return new G3({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var z3=q("ZodPipe",(Q,Y)=>{SW.init(Q,Y),X0.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function A9(Q,Y){return new z3({type:"pipe",in:Q,out:Y})}var J3=q("ZodReadonly",(Q,Y)=>{RW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function H3(Q){return new J3({type:"readonly",innerType:Q})}var cG=q("ZodCustom",(Q,Y)=>{CW.init(Q,Y),X0.init(Q,Y)});function pG(Q,Y){return DG(cG,Q??(()=>!0),Y)}function A3(Q,Y={}){return BG(cG,Q,Y)}function U3(Q){return LG(Q)}function D9(Q,Y){return A9(fG(Q),Y)}T0(nQ());var B9="2025-11-25";var iG=[B9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],K1="io.modelcontextprotocol/related-task",P6="2.0",U0=pG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),nG=d([F(),i().int()]),rG=F(),Bw=q0({ttl:d([i(),U9()]).optional(),pollInterval:i().optional()}),K3=b({ttl:i().optional()}),D3=b({taskId:F()}),L9=q0({progressToken:nG.optional(),[K1]:D3.optional()}),E0=b({_meta:L9.optional()}),M4=E0.extend({task:K3.optional()}),dG=(Q)=>M4.safeParse(Q).success,K0=b({method:F(),params:E0.loose().optional()}),S0=b({_meta:L9.optional()}),R0=b({method:F(),params:S0.loose().optional()}),D0=q0({_meta:L9.optional()}),b6=d([F(),i().int()]),oG=b({jsonrpc:j(P6),id:b6,...K0.shape}).strict(),F9=(Q)=>oG.safeParse(Q).success,tG=b({jsonrpc:j(P6),...R0.shape}).strict(),aG=(Q)=>tG.safeParse(Q).success,q9=b({jsonrpc:j(P6),id:b6,result:D0}).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 sG=(Q)=>O9.safeParse(Q).success;var eG=d([oG,tG,q9,O9]),Lw=d([q9,O9]),j6=D0.strict(),B3=S0.extend({requestId:b6.optional(),reason:F().optional()}),I6=R0.extend({method:j("notifications/cancelled"),params:B3}),L3=b({src:F(),mimeType:F().optional(),sizes:u(F()).optional(),theme:V0(["light","dark"]).optional()}),Z4=b({icons:u(L3).optional()}),f1=b({name:F(),title:F().optional()}),Q$=f1.extend({...f1.shape,...Z4.shape,version:F(),websiteUrl:F().optional(),description:F().optional()}),F3=N6(b({applyDefaults:H0().optional()}),Q0(F(),e())),q3=D9((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},N6(b({form:F3.optional(),url:U0.optional()}),Q0(F(),e()).optional())),O3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({sampling:q0({createMessage:U0.optional()}).optional(),elicitation:q0({create:U0.optional()}).optional()}).optional()}),M3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({tools:q0({call:U0.optional()}).optional()}).optional()}),V3=b({experimental:Q0(F(),U0).optional(),sampling:b({context:U0.optional(),tools:U0.optional()}).optional(),elicitation:q3.optional(),roots:b({listChanged:H0().optional()}).optional(),tasks:O3.optional()}),Z3=E0.extend({protocolVersion:F(),capabilities:V3,clientInfo:Q$}),M9=K0.extend({method:j("initialize"),params:Z3});var N3=b({experimental:Q0(F(),U0).optional(),logging:U0.optional(),completions:U0.optional(),prompts:b({listChanged:H0().optional()}).optional(),resources:b({subscribe:H0().optional(),listChanged:H0().optional()}).optional(),tools:b({listChanged:H0().optional()}).optional(),tasks:M3.optional()}),w3=D0.extend({protocolVersion:F(),capabilities:N3,serverInfo:Q$,instructions:F().optional()}),V9=R0.extend({method:j("notifications/initialized"),params:S0.optional()});var E6=K0.extend({method:j("ping"),params:E0.optional()}),P3=b({progress:i(),total:Y0(i()),message:Y0(F())}),b3=b({...S0.shape,...P3.shape,progressToken:nG}),T6=R0.extend({method:j("notifications/progress"),params:b3}),j3=E0.extend({cursor:rG.optional()}),N4=K0.extend({params:j3.optional()}),w4=D0.extend({nextCursor:rG.optional()}),I3=V0(["working","input_required","completed","failed","cancelled"]),P4=b({taskId:F(),status:I3,ttl:d([i(),U9()]),createdAt:F(),lastUpdatedAt:F(),pollInterval:Y0(i()),statusMessage:Y0(F())}),l1=D0.extend({task:P4}),E3=S0.merge(P4),b4=R0.extend({method:j("notifications/tasks/status"),params:E3}),S6=K0.extend({method:j("tasks/get"),params:E0.extend({taskId:F()})}),R6=D0.merge(P4),C6=K0.extend({method:j("tasks/result"),params:E0.extend({taskId:F()})}),Fw=D0.loose(),k6=N4.extend({method:j("tasks/list")}),v6=w4.extend({tasks:u(P4)}),x6=K0.extend({method:j("tasks/cancel"),params:E0.extend({taskId:F()})}),Y$=D0.merge(P4),X$=b({uri:F(),mimeType:Y0(F()),_meta:Q0(F(),e()).optional()}),W$=X$.extend({text:F()}),Z9=F().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),G$=X$.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()}),$$=b({...f1.shape,...Z4.shape,uri:F(),description:Y0(F()),mimeType:Y0(F()),annotations:m1.optional(),_meta:Y0(q0({}))}),T3=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")}),S3=w4.extend({resources:u($$)}),R3=N4.extend({method:j("resources/templates/list")}),C3=w4.extend({resourceTemplates:u(T3)}),w9=E0.extend({uri:F()}),k3=w9,P9=K0.extend({method:j("resources/read"),params:k3}),v3=D0.extend({contents:u(d([W$,G$]))}),x3=R0.extend({method:j("notifications/resources/list_changed"),params:S0.optional()}),_3=w9,g3=K0.extend({method:j("resources/subscribe"),params:_3}),y3=w9,u3=K0.extend({method:j("resources/unsubscribe"),params:y3}),h3=S0.extend({uri:F()}),f3=R0.extend({method:j("notifications/resources/updated"),params:h3}),l3=b({name:F(),description:Y0(F()),required:Y0(H0())}),m3=b({...f1.shape,...Z4.shape,description:Y0(F()),arguments:Y0(u(l3)),_meta:Y0(q0({}))}),c3=N4.extend({method:j("prompts/list")}),p3=w4.extend({prompts:u(m3)}),i3=E0.extend({name:F(),arguments:Q0(F(),F()).optional()}),n3=K0.extend({method:j("prompts/get"),params:i3}),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()}),r3=b({type:j("tool_use"),name:F(),id:F(),input:Q0(F(),e()),_meta:Q0(F(),e()).optional()}),d3=b({type:j("resource"),resource:d([W$,G$]),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),o3=$$.extend({type:j("resource_link")}),E9=d([b9,j9,I9,o3,d3]),t3=b({role:j4,content:E9}),a3=D0.extend({description:F().optional(),messages:u(t3)}),s3=R0.extend({method:j("notifications/prompts/list_changed"),params:S0.optional()}),e3=b({title:F().optional(),readOnlyHint:H0().optional(),destructiveHint:H0().optional(),idempotentHint:H0().optional(),openWorldHint:H0().optional()}),QU=b({taskSupport:V0(["required","optional","forbidden"]).optional()}),z$=b({...f1.shape,...Z4.shape,description:F().optional(),inputSchema:b({type:j("object"),properties:Q0(F(),U0).optional(),required:u(F()).optional()}).catchall(e()),outputSchema:b({type:j("object"),properties:Q0(F(),U0).optional(),required:u(F()).optional()}).catchall(e()).optional(),annotations:e3.optional(),execution:QU.optional(),_meta:Q0(F(),e()).optional()}),T9=N4.extend({method:j("tools/list")}),YU=w4.extend({tools:u(z$)}),_6=D0.extend({content:u(E9).default([]),structuredContent:Q0(F(),e()).optional(),isError:H0().optional()}),qw=_6.or(D0.extend({toolResult:e()})),XU=M4.extend({name:F(),arguments:Q0(F(),e()).optional()}),I4=K0.extend({method:j("tools/call"),params:XU}),WU=R0.extend({method:j("notifications/tools/list_changed"),params:S0.optional()}),Ow=b({autoRefresh:H0().default(!0),debounceMs:i().int().nonnegative().default(300)}),E4=V0(["debug","info","notice","warning","error","critical","alert","emergency"]),GU=E0.extend({level:E4}),S9=K0.extend({method:j("logging/setLevel"),params:GU}),$U=S0.extend({level:E4,logger:F().optional(),data:e()}),zU=R0.extend({method:j("notifications/message"),params:$U}),JU=b({name:F().optional()}),HU=b({hints:u(JU).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),AU=b({mode:V0(["auto","required","none"]).optional()}),UU=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()}),KU=K9("type",[b9,j9,I9]),w6=K9("type",[b9,j9,I9,r3,UU]),DU=b({role:j4,content:d([w6,u(w6)]),_meta:Q0(F(),e()).optional()}),BU=M4.extend({messages:u(DU),modelPreferences:HU.optional(),systemPrompt:F().optional(),includeContext:V0(["none","thisServer","allServers"]).optional(),temperature:i().optional(),maxTokens:i().int(),stopSequences:u(F()).optional(),metadata:U0.optional(),tools:u(z$).optional(),toolChoice:AU.optional()}),LU=K0.extend({method:j("sampling/createMessage"),params:BU}),R9=D0.extend({model:F(),stopReason:Y0(V0(["endTurn","stopSequence","maxTokens"]).or(F())),role:j4,content:KU}),C9=D0.extend({model:F(),stopReason:Y0(V0(["endTurn","stopSequence","maxTokens","toolUse"]).or(F())),role:j4,content:d([w6,u(w6)])}),FU=b({type:j("boolean"),title:F().optional(),description:F().optional(),default:H0().optional()}),qU=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()}),OU=b({type:V0(["number","integer"]),title:F().optional(),description:F().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),MU=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),default:F().optional()}),VU=b({type:j("string"),title:F().optional(),description:F().optional(),oneOf:u(b({const:F(),title:F()})),default:F().optional()}),ZU=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),enumNames:u(F()).optional(),default:F().optional()}),NU=d([MU,VU]),wU=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()}),PU=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()}),bU=d([wU,PU]),jU=d([ZU,NU,bU]),IU=d([jU,FU,qU,OU]),EU=M4.extend({mode:j("form").optional(),message:F(),requestedSchema:b({type:j("object"),properties:Q0(F(),IU),required:u(F()).optional()})}),TU=M4.extend({mode:j("url"),message:F(),elicitationId:F(),url:F().url()}),SU=d([EU,TU]),RU=K0.extend({method:j("elicitation/create"),params:SU}),CU=S0.extend({elicitationId:F()}),kU=R0.extend({method:j("notifications/elicitation/complete"),params:CU}),g6=D0.extend({action:V0(["accept","decline","cancel"]),content:D9((Q)=>Q===null?void 0:Q,Q0(F(),d([F(),i(),H0(),u(F())])).optional())}),vU=b({type:j("ref/resource"),uri:F()});var xU=b({type:j("ref/prompt"),name:F()}),_U=E0.extend({ref:d([xU,vU]),argument:b({name:F(),value:F()}),context:b({arguments:Q0(F(),F()).optional()}).optional()}),gU=K0.extend({method:j("completion/complete"),params:_U});var yU=D0.extend({completion:q0({values:u(F()).max(100),total:Y0(i().int()),hasMore:Y0(H0())})}),uU=b({uri:F().startsWith("file://"),name:F().optional(),_meta:Q0(F(),e()).optional()}),hU=K0.extend({method:j("roots/list"),params:E0.optional()}),k9=D0.extend({roots:u(uU)}),fU=R0.extend({method:j("notifications/roots/list_changed"),params:S0.optional()}),Mw=d([E6,M9,gU,S9,n3,c3,N9,R3,P9,g3,u3,I4,T9,S6,C6,k6,x6]),Vw=d([I6,T6,V9,fU,b4]),Zw=d([j6,R9,C9,g6,k9,R6,v6,l1]),Nw=d([E6,LU,RU,hU,S6,C6,k6,x6]),ww=d([I6,T6,zU,f3,x3,WU,s3,b4,kU]),Pw=d([j6,w3,yU,a3,p3,S3,C3,v3,_6,YU,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 lU=Symbol("Let zodToJsonSchema decide on which parser to use");var XP=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function v9(Q){let X=V6(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=FG(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function x9(Q,Y){let X=U1(Q,Y);if(!X.success)throw X.error;return X.data}var rU=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 z;while(z=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(z.type==="response"||z.type==="error"){let J=z.message,H=J.id,A=this._requestResolvers.get(H);if(A)if(this._requestResolvers.delete(H),z.type==="response")A(J);else{let U=J,K=new _(U.error.code,U.error.message,U.error.data);A(K)}else{let U=z.type==="response"?"Response":"Error";this._onerror(Error(`${U} handler missing for request ${H}`))}continue}await this._transport?.send(z.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 z=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...z,_meta:{...z._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)||sG(G))this._onresponse(G);else if(F9(G))this._onrequest(G,$);else if(aG(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 A={jsonrpc:"2.0",id:Q.id,error:{code:h.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId).catch((U)=>this._onerror(Error(`Failed to enqueue error response: ${U}`)));else W?.send(A).catch((U)=>this._onerror(Error(`Failed to send an error response: ${U}`)));return}let $=new AbortController;this._requestHandlerAbortControllers.set(Q.id,$);let z=dG(Q.params)?Q.params.task:void 0,J=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:$.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(A)=>{let U={relatedRequestId:Q.id};if(G)U.relatedTask={taskId:G};await this.notification(A,U)},sendRequest:async(A,U,K)=>{let D={...K,relatedRequestId:Q.id};if(G&&!D.relatedTask)D.relatedTask={taskId:G};let L=D.relatedTask?.taskId??G;if(L&&J)await J.updateTaskStatus(L,"input_required");return await this.request(A,U,D)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:J,taskRequestedTtl:z?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(z)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(A)=>{if($.signal.aborted)return;let U={result:A,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:U,timestamp:Date.now()},W?.sessionId);else await W?.send(U)},async(A)=>{if($.signal.aborted)return;let U={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(A.code)?A.code:h.InternalError,message:A.message??"Internal error",...A.data!==void 0&&{data:A.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId);else await W?.send(U)}).catch((A)=>this._onerror(Error(`Failed to send response: ${A}`))).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),z=this._timeoutInfo.get(W);if(z&&$&&z.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(J){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),$(J);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 z=$.task;if(typeof z.taskId==="string")G=!0,this._taskProgressTokens.set(z.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 z=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:z},D1(z.status)){if(z.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(z.status==="failed")yield{type:"error",error:new _(h.InternalError,`Task ${G} failed`)};else if(z.status==="cancelled")yield{type:"error",error:new _(h.InternalError,`Task ${G} was cancelled`)};return}if(z.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let J=z.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,J)),X?.signal?.throwIfAborted()}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$,task:z,relatedTask:J}=X??{};return new Promise((H,A)=>{let U=(Z)=>{A(Z)};if(!this._transport){U(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),z)this.assertTaskCapability(Q.method)}catch(Z){U(Z);return}X?.signal?.throwIfAborted();let K=this._requestMessageId++,D={...Q,jsonrpc:"2.0",id:K};if(X?.onprogress)this._progressHandlers.set(K,X.onprogress),D.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:K}};if(z)D.params={...D.params,task:z};if(J)D.params={...D.params,_meta:{...D.params?._meta||{},[K1]:J}};let L=(Z)=>{this._responseHandlers.delete(K),this._progressHandlers.delete(K),this._cleanupTimeout(K),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:K,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));A(k)};this._responseHandlers.set(K,(Z)=>{if(X?.signal?.aborted)return;if(Z instanceof Error)return A(Z);try{let k=U1(Y,Z.result);if(!k.success)A(k.error);else H(k.data)}catch(k){A(k)}}),X?.signal?.addEventListener("abort",()=>{L(X?.signal?.reason)});let O=X?.timeout??rU,M=()=>L(_.fromError(h.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(K,O,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let N=J?.taskId;if(N){let Z=(k)=>{let S=this._responseHandlers.get(K);if(S)S(k);else this._onerror(Error(`Response handler missing for side-channeled request ${K}`))};this._requestResolvers.set(K,Z),this._enqueueTaskMessage(N,{type:"request",message:D,timestamp:Date.now()}).catch((k)=>{this._cleanupTimeout(K),A(k)})}else this._transport.send(D,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((Z)=>{this._cleanupTimeout(K),A(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},Y$,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let z={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[K1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:z,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 z={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)z={...z,params:{...z.params,_meta:{...z.params?._meta||{},[K1]:Y.relatedTask}}};this._transport?.send(z,Y).catch((J)=>this._onerror(J))});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 z=await X.getTask(W,Y);if(z){let J=b4.parse({method:"notifications/tasks/status",params:z});if(await this.notification(J),D1(z.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,$)=>{let z=await X.getTask(W,Y);if(!z)throw new _(h.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(D1(z.status))throw new _(h.InvalidParams,`Cannot update task "${W}" from terminal status "${z.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,$,Y);let J=await X.getTask(W,Y);if(J){let H=b4.parse({method:"notifications/tasks/status",params:J});if(await this.notification(H),D1(J.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function H$(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function A$(Q,Y){let X={...Q};for(let W in Y){let G=W,$=Y[G];if($===void 0)continue;let z=X[G];if(H$(z)&&H$($))X[G]={...z,...$};else X[G]=$}return X}var f5=BX(SY(),1),l5=BX(h5(),1);function XV(){let Q=new f5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return l5.default(Q),Q}class hY{constructor(Q){this._ajv=Q??XV()}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 m5(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 c5(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,z=E4.safeParse($);if(z.success)this._loggingLevels.set(G,z.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=A$(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 z=W;G=z._zod?.def?.value??z.value}else{let z=W;G=z._def?.value??z.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let z=async(J,H)=>{let A=U1(I4,J);if(!A.success){let L=A.error instanceof Error?A.error.message:String(A.error);throw new _(h.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:U}=A.data,K=await Promise.resolve(Y(J,H));if(U.task){let L=U1(l1,K);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 D=U1(_6,K);if(!D.success){let L=D.error instanceof Error?D.error.message:String(D.error);throw new _(h.InvalidParams,`Invalid tools/call result: ${L}`)}return D.data};return super.setRequestHandler(Q,z)}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){c5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;m5(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:iG.includes(Y)?Y:B9,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,z=$?Array.isArray($.content)?$.content:[$.content]:[],J=z.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(!J)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(J){let H=new Set(z.filter((U)=>U.type==="tool_use").map((U)=>U.id)),A=new Set(W.filter((U)=>U.type==="tool_result").map((U)=>U.toolUseId));if(H.size!==A.size||![...H].every((U)=>A.has(U)))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 z=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!z.valid)throw new _(h.InvalidParams,`Elicitation response content does not match requested schema: ${z.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 p5={name:"@sequenzy/mcp",version:"0.0.100",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":"bunx --bun 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"],i5={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 GV(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 z0(Q,Y=""){return`/dashboard/company/${r0(Q)}${Y}`}function n5(Q,Y,X){return $0(Q,`${z0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function $V(Q,Y){let X=mY.map((W)=>[W,Y?n5(Q,Y,W):""]);return Object.fromEntries(X)}function Z1(Q={},Y){let X=GV(Y),W=l0(Q.companyId),G={},$=$V(X,W);if(!W)return{appUrl:X,routeTemplates:i5,settingsTabValues:mY,urls:G,settingsUrls:$};G.dashboard=$0(X,z0(W)),G.campaigns=$0(X,z0(W,"/campaign")),G.landingPages=$0(X,z0(W,"/landing-pages")),G.sequences=$0(X,z0(W,"/sequences")),G.settings=$0(X,z0(W,"/settings")),G.emails=$0(X,z0(W,"/emails")),G.subscribers=$0(X,z0(W,"/subscribers")),G.sentEmails=$0(X,z0(W,"/sent-emails")),G.segments=$0(X,z0(W,"/segments")),G.metrics=$0(X,z0(W,"/metrics")),G.transactional=$0(X,z0(W,"/transactional"));let z=l0(Q.campaignId);if(z)G.campaign=$0(X,z0(W,`/campaign/${r0(z)}`)),G.campaignPreview=`${G.campaign}?step=review`;let J=l0(Q.landingPageId);if(J)G.landingPage=$0(X,z0(W,`/landing-pages/${r0(J)}`));let H=l0(Q.sequenceId);if(H)G.sequence=$0(X,z0(W,`/sequences/${r0(H)}`));let A=l0(Q.emailId)??l0(Q.templateId);if(A)G.email=$0(X,z0(W,`/emails/${r0(A)}`)),G.template=G.email;let U=l0(Q.transactionalId);if(U)G.transactionalEmail=$0(X,z0(W,`/transactional/${r0(U)}`));let K=l0(Q.emailSendId);if(K)G.emailSend=$0(X,z0(W,`/sent-emails/${r0(K)}`));let D=l0(Q.domainId);if(D)G.domain=$0(X,z0(W,`/settings/domain/${r0(D)}`)),G.domainVerify=`${G.domain}/verify`;let L=l0(Q.status);if(L)G.campaignList=$0(X,z0(W,`/campaign/list/${r0(L)}`)),G.sequenceList=$0(X,z0(W,`/sequences/list/${r0(L)}`));let O=l0(Q.settingsTab);if(O)G.settingsTab=n5(X,W,O);return{appUrl:X,routeTemplates:i5,settingsTabValues:mY,urls:G,settingsUrls:$}}var r5=[{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 d5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await B("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await B("GET","/api/v1/account"),W=b1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await B("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await B("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await B("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await B("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await B("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await B("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await B("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await B("GET","/api/v1/tags");break;case"sequenzy://health":Y=await B("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=Z1();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 zV,statSync as JV}from"node:fs";import{basename as HV}from"node:path";var GX=' 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: [...] }.${GX}`,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\`.${GX}`,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.${GX}`,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.",AV="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.",o5=500,t5=500,N1={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"],a5={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},UV={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:UV,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},wQ=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],PQ=["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"],KV=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"]),DV=new Set(["select_company","create_company","update_company","update_sync_rules","update_shopify_automation_settings","create_api_key","add_sending_domain","add_website","verify_sending_domain","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","add_sending_domain","add_website","verify_sending_domain","enable_sequence","resume_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery"]),LV=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 FV(Q){let Y=KV.has(Q),X=DV.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:LV.has(Q),openWorldHint:BV.has(Q)}}function qV(Q){return{...Q,annotations:{...Q.annotations,...FV(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"]},OV=Object.entries(eY).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),s5={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: ${OV}.`},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},e5={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 MV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function VV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function QH(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 ZV(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(),z=X.at(-2),J=X.at(-1),H=z===void 0?Number.NaN:Number.parseInt(z,10);return $&&Number.isInteger(H)&&H>0&&J!==void 0&&QH(J)?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&&QH(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function NV(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 wV(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function PV(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 bV(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 jV(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function IV(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let J=X.indexOf(":");if(J===-1)return null;let H=X.substring(0,J).trim(),A=Number.parseInt(X.substring(J+1).trim(),10);return H&&Number.isInteger(A)&&A>=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:$}=NV(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 z=wV(G);if(PV(z))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!bV(Q,z))return`Unsupported Stripe product subfilter "${G}".`;if(!jV(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 EV=new Set(["shopify","woocommerce","api"]);function TV(Q,Y){let X=Y.trim(),W=X.indexOf(":");if(W!==-1&&EV.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(),z=Number.parseInt(X.substring(G+1).trim(),10);return $&&Number.isInteger(z)&&z>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function $X(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(!MV(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!VV(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let z=ZV(W,G);if(z)return z}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let z=IV(X,W,G);if(z)return z}if(X==="commerceProduct"&&typeof G==="string"){let z=TV(W,G);if(z)return z}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map((J)=>J.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function zX(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=$X(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap(zX);return[]}function w1(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 bQ(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 SV(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 $=$X(G);return $?[$]:[]}):zX(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function RV(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 $=$X(G);return $?[$]:[]}):X?zX(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","fromEmail","fromName","replyTo","replyToName"];function iY(Q,Y,X){if(Y[X]!==void 0&&!J0(Y[X]))throw Error(`\`${X}\` must be an object when calling \`${Q}\`.`)}function YH(Q,Y,X){if(Y[X]!==void 0&&!Array.isArray(Y[X]))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`)}function CV(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","fromEmail","fromName","replyTo","replyToName"])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"),YH("update_company",Q,"valueProps"),YH("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`.");for(let G of["fromEmail","replyTo"]){let $=Q[G];if(typeof $==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($.trim()))throw Error(`\`${G}\` must be a valid email address when calling \`update_company\`.`)}if(Q.fromName!==void 0&&Q.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_company`.");if(Q.replyToName!==void 0&&Q.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_company`.");return W}function kV(Q){if(Q.fromEmail!==void 0&&Q.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_sequence`, not both.");if(Q.replyTo!==void 0&&Q.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_sequence`, not both.");if(Q.fromName!==void 0&&Q.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_sequence`.");if(Q.replyToName!==void 0&&Q.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_sequence`.");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 vV(Q){let Y=Q.type==="sms",X;if(Y){let G=w(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 z of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(Q[z]!==void 0)X[z]=Q[z]}else{w1("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 xV(Q){let Y=w(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((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0)??[];if(W?.some((J)=>typeof J!=="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 $=w(Q,"fieldPath"),z=w(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...$!==void 0&&{fieldPath:$},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...z!==void 0&&{reason:z}}}function _V(Q){w1("create_campaign",Q),bQ("create_campaign",Q);let Y=w(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&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function gV(Q){w1("create_template",Q),bQ("create_template",Q);let Y=w(Q,"prompt")!==void 0,X=[Y,Q.html!==void 0,Q.blocks!==void 0].filter(Boolean).length;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_template`.");if(X!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function yV(Q){if(w(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!J0(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 uV(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 hV(Q){w1("create_transactional_email",Q);let Y=w(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&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var XX={type:"object",description:"Update Subscriber config. firstName, lastName, and customAttributeUpdates values may use trigger-event merge tags such as {{event.plan}}. Number and boolean values must be a literal or one standalone merge tag and are coerced after resolution.",properties:{label:{type:"string"},firstName:{type:["string","null"],description:"First name literal or merge tag; null clears the field."},lastName:{type:["string","null"],description:"Last name literal or merge tag; null clears the field."},status:{type:"string",enum:["active","unsubscribed","bounced"]},customAttributeUpdates:{type:"array",items:{type:"object",properties:{name:{type:"string"},value:{type:["string","number","boolean","null"],description:"Literal scalar, null to delete, or a standalone merge tag such as {{event.plan}}, {{event.amount}}, or {{event.active}}."},valueType:{type:"string",enum:["text","number","boolean"]}},required:["name","value"]}}},additionalProperties:!0},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","update_subscriber","condition","webhook"],description:"Sequence path step type. Omit for email steps; use delay for standalone waits or update_subscriber for action_update_attributes."},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:{...XX,description:"Config for advanced nodeType steps. For action_update_attributes, use the documented Update Subscriber fields and trigger-event merge tags; other node types accept their normal config fields.",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 fV(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 J0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function XH(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function lV(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 mV(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,z=0,J=0,H=0;while(!0){let U=lV({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:$,pageSize:W}),K=await B("GET",`/api/v1/subscribers?${U.toString()}`,void 0,Y);z=K.pagination?.total??K.subscribers.length,J=K.pagination?.totalPages??1,H+=1,G.push(...K.subscribers??[]);let D=X!==void 0&&G.length>=X,L=K.pagination?$>=K.pagination.totalPages:(K.subscribers??[]).length<W;if(D||L)break;$+=1}let A=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:A,pagination:{page:1,limit:W,total:z,totalPages:J,fetchedPages:H},returned:A.length,truncated:X!==void 0&&z>0&&A.length<z}}function cV(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=cV(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function WX(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 WH(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 B("GET",WX(Q,X),void 0,Y)}function w(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=w(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function m0(Q,Y,X,W){let G=w(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 pV(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 z=G.trim();if(!cY.includes(z))throw Error(`\`eventTypes\` item ${$+1} must be one of ${cY.join(", ")} when calling \`${Q}\`.`);X.push(z)})}return[...new Set(X)]}function GH(Q,Y){let X=new URLSearchParams,W=pV(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 $=w(Y,"start");if($)X.set("start",$);let z=w(Y,"end");if(z)X.set("end",z);let J=x1(Q,Y,"page",1,1e6);if(J!==void 0)X.set("page",String(J));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 $H(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"||!PQ.includes(W))throw Error(`\`events\` item ${G+1} must be one of ${PQ.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 zH(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>o5)throw Error(`\`emails\` must include no more than ${o5} 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((z,J)=>{if(typeof z!=="string")throw Error(`\`${X}\` item ${J+1} must be a string when calling \`${Q}\`.`);let H=z.trim();if(H.length>0)$.push(H)}),$.length===0)throw Error(`\`${X}\` must include at least one ${W} when calling \`${Q}\`.`);return $}function iV(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>t5)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${t5} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let $=w(Q,"targetNodeId");return{...X!==void 0&&{emails:X},...W!==void 0&&{subscriberIds:W},...$!==void 0&&{targetNodeId:$}}}var nV={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 rV(Q){let Y=Q.split(".").pop()?.toLowerCase()??"";return nV[Y]??null}var dV=104857600;async function oV(Q,Y){if(!OX())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=rV(Q);if(!X)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=JV(Q).size;if(W>dV)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=zV(Q),$=await B("POST","/api/v1/products/delivery/upload-url",{filename:HV(Q),contentType:X,fileSizeBytes:W},Y),z=await fetch($.uploadUrl,{method:"PUT",headers:{"Content-Type":X},body:G});if(!z.ok)throw Error(`File upload failed (${z.status})`);return{url:$.publicUrl,fileName:$.fileName,fileSizeBytes:W,mimeType:X}}async function JX(Q){let Y=w(Q,"companyId");if(Y)return Y;let X=b1();if(X)return X;try{return(await B("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function tV(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(!J0(Q)||!Y)return Q;return{...Q,url:Y}}function HH(Q,Y){if(!J0(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(!J0(W))return W;let G=w(W,"id");if(!G)return W;let $=Z1({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 HH(W,$.urls);let z=X==="sequence"?$.urls.sequence:X==="landingPage"?$.urls.landingPage:X==="template"?$.urls.email:$.urls.transactionalEmail;return Y4(W,z)})}function aV(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!J0(Y))return Y;let X=w(Y,"id");if(!X)return Y;let W=Z1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var AH=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 sV(Q,Y,X){if(!J0(X)||!AH.has(Q))return X;let W=J0(X.company)?X.company:void 0,$=w(X,"selectedCompanyId")??w(X,"currentCompanyId")??w(X,"companyId")??(W?w(W,"id"):void 0)??(W?w(W,"companyId"):void 0)??await JX(Y);if(!$)return X;let z=J0(X.campaign)?X.campaign:void 0,J=J0(X.sequence)?X.sequence:void 0,H=J0(X.landingPage)?X.landingPage:void 0,A=J0(X.template)?X.template:void 0,U=J0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,K={companyId:$,campaignId:w(Y,"campaignId")??w(X,"campaignId")??(z?w(z,"id"):void 0),landingPageId:w(Y,"landingPageId")??w(X,"landingPageId")??(H?w(H,"id"):void 0),sequenceId:w(Y,"sequenceId")??w(X,"sequenceId")??(J?w(J,"id"):void 0),emailId:w(X,"templateId")??(A?w(A,"id"):void 0)??(U?w(U,"emailId"):void 0)??w(Y,"templateId"),transactionalId:w(Y,"transactionalId")??(U?w(U,"id"):void 0)??w(Y,"idOrSlug"),emailSendId:w(Y,"emailSendId")??w(X,"emailSendId")??(J0(X.emailSend)?w(X.emailSend,"id"):void 0),status:w(Y,"status")},D=Z1(K),L=W?Z1({companyId:$}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:aV(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}},...z&&D.urls.campaign!==void 0&&{campaign:HH(z,D.urls)},...J&&D.urls.sequence!==void 0&&{sequence:Y4(J,D.urls.sequence)},...H&&D.urls.landingPage!==void 0&&{landingPage:Y4(H,D.urls.landingPage)},...A&&D.urls.email!==void 0&&{template:Y4(A,D.urls.email)},...U&&D.urls.transactionalEmail!==void 0&&{transactional:Y4(U,D.urls.transactionalEmail)},...J0(X.emailSend)&&D.urls.emailSend!==void 0&&{emailSend:Y4(X.emailSend,D.urls.emailSend)},appUrls:D.urls}}var eV={type:"boolean",description:"Whether the Sequenzy operation succeeded."},QZ={type:"string",description:"Human-readable status, confirmation, or next-step message."},YZ={type:"string",description:"Additional context about the result."};function W0(Q){return{type:"object",description:Q,additionalProperties:!0}}function XZ(Q){return{type:"array",description:Q,items:W0("One item in the returned collection.")}}function E(Q){return{type:"string",description:Q}}function b0(Q){return{type:"number",description:Q}}function d0(Q){return{type:"boolean",description:Q}}function V(Q){return W0(`The ${Q} record returned by Sequenzy.`)}function p(Q){return XZ(`List of ${Q} records returned by Sequenzy.`)}var WZ={appUrls:W0("Dashboard URLs for relevant Sequenzy resources."),url:E("Primary dashboard URL for this result."),settingsUrl:E("Company settings URL when available.")},GZ={success:eV,message:QZ,note:YZ,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.")},$Z={get_account:{account:V("account"),companies:p("company"),apiKeyPermissions:W0("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:E("Company ID selected by the authenticated API key, when available."),selectedCompanyId:E("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:E("Selected company ID."),companyName:E("Selected company name.")},get_app_urls:{dashboard:E("Company dashboard URL."),settings:E("Company settings URL."),campaign:E("Campaign editor URL."),landingPage:E("Landing page editor URL."),sequence:E("Sequence editor URL."),email:E("Email editor URL."),transactionalEmail:E("Transactional email URL."),emailSend:E("Sent email detail URL."),domain:E("Sending domain settings URL."),urls:W0("All generated URLs keyed by resource type.")},create_company:{company:V("company"),autoSelected:d0("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:d0("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:d0("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:E("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:E("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:E("Newly created API key if the API response uses the short key field.")},list_websites:{websites:p("sender website")},add_website:{website:V("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},add_sending_domain:{website:V("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},check_website:{website:V("sender website"),ready:d0("Whether the sender website is ready."),status:E("Current processing or verification status.")},verify_sending_domain:{website:V("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:d0("Whether the sending domain passed the fresh verification check."),message:E("Verification result summary.")},get_integration_guide:{guide:V("integration guide"),code:E("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:d0("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:E("Deleted subscriber note ID."),deleted:d0("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:p("subscriber"),pagination:W0("Pagination metadata."),returned:b0("Number of subscribers returned."),truncated:d0("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:E("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:E("Queued product sync job ID.")},list_tags:{tags:p("tag")},create_tag:{tag:V("tag")},update_tag:{tag:V("tag")},delete_tag:{tagId:E("Deleted tag ID.")},list_lists:{lists:p("list")},create_list:{list:V("list")},update_list:{list:V("list")},delete_list:{listId:E("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:E("Deleted segment ID.")},get_segment_count:{count:b0("Number of subscribers matching the segment."),segmentId:E("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:E("Deleted audience sync ID.")},sync_audience_now:{audienceSync:V("audience sync"),job:V("audience sync job"),jobId:E("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:E("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:E("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:E("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:E("Scheduled send timestamp.")},send_test_email:{emailSend:V("test email send"),recipient:E("Test email recipient.")},send_test_sms:{smsSendId:E("Created test SMS send ID."),toPhone:E("Normalized E.164 destination phone.")},cancel_campaign:{campaign:V("campaign")},pause_campaign:{campaign:V("campaign")},resume_campaign:{campaign:V("campaign")},delete_campaign:{campaignId:E("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:E("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:E("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:V("landing page"),domain:E("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:E("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:E("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:E("Sequence ID."),enrollmentPaused:d0("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:E("Sequence ID."),enrollmentPaused:d0("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:E("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:E("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:E("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:E("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:W0("One generated email block.")},subject:E("Generated subject line."),previewText:E("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:E("One generated subject line.")},variants:p("generated subject line variant")},generate_sms:{prompt:E("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 zZ(Q){let Y=$Z[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:{...GZ,...Y,...AH.has(Q)?WZ:{}},additionalProperties:!0}}function JZ(Q){return{...Q,outputSchema:zZ(Q.name)}}function HZ(Q){if(J0(Q))return Q;if(Array.isArray(Q))return{items:Q};return{value:Q}}var AZ=[{name:"get_account",description:`Get current account information including available companies, the current API key's permission scopes, and the API Keys management URL. Call this after a missing-scope error to inspect access and find the replacement-key settings. 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(D,S,y)},$,z=j1,J=!Y6.jitless,A=J&&vQ.value,U=Y.catchall,K;Q._zod.parse=(D,L)=>{K??(K=W.value);let O=D.value;if(!z(O))return D.issues.push({expected:"object",code:"invalid_type",input:O,inst:Q}),D;if(J&&A&&L?.async===!1&&L.jitless!==!0){if(!$)$=G(Y.shape);if(D=$(D,L),!U)return D;return FW([],O,D,L,K,Q)}return X(D,L)}});function C8(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((z)=>x0(z,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(($)=>J4($.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 z=!1,J=[];for(let H of Y.options){let A=H._zod.run({value:G.value,issues:[]},$);if(A instanceof Promise)J.push(A),z=!0;else{if(A.issues.length===0)return A;J.push(A)}}if(!z)return C8(J,G,Q,$);return Promise.all(J).then((H)=>{return C8(H,G,Q,$)})}}),OW=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 z=$._zod.propValues;if(!z||Object.keys(z).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf($)}"`);for(let[J,H]of Object.entries(z)){if(!G[J])G[J]=new Set;for(let A of H)G[J].add(A)}}return G});let W=g1(()=>{let G=Y.options,$=new Map;for(let z of G){let J=z._zod.propValues?.[Y.discriminator];if(!J||J.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(z)}"`);for(let H of J){if($.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);$.set(H,z)}}return $});Q._zod.parse=(G,$)=>{let z=G.value;if(!j1(z))return G.issues.push({code:"invalid_type",expected:"object",input:z,inst:Q}),G;let J=W.value.get(z?.[Y.discriminator]);if(J)return J._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:z,path:[Y.discriminator],inst:Q}),G}}),MW=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),z=Y.right._zod.run({value:G,issues:[]},W);if($ instanceof Promise||z instanceof Promise)return Promise.all([$,z]).then(([H,A])=>{return k8(X,H,A)});return k8(X,$,z)}});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(H1(Q)&&H1(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter(($)=>X.indexOf($)!==-1),G={...Q,...Y};for(let $ of W){let z=cQ(Q[$],Y[$]);if(!z.valid)return{valid:!1,mergeErrorPath:[$,...z.mergeErrorPath]};G[$]=z.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],z=cQ(G,$);if(!z.valid)return{valid:!1,mergeErrorPath:[W,...z.mergeErrorPath]};X.push(z.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function k8(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 VW=q("$ZodRecord",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!H1(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let $=[];if(Y.keyType._zod.values){let z=Y.keyType._zod.values;X.value={};for(let H of z)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let A=Y.valueType._zod.run({value:G[H],issues:[]},W);if(A instanceof Promise)$.push(A.then((U)=>{if(U.issues.length)X.issues.push(...s0(H,U.issues));X.value[H]=U.value}));else{if(A.issues.length)X.issues.push(...s0(H,A.issues));X.value[H]=A.value}}let J;for(let H in G)if(!z.has(H))J=J??[],J.push(H);if(J&&J.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:J})}else{X.value={};for(let z of Reflect.ownKeys(G)){if(z==="__proto__")continue;let J=Y.keyType._zod.run({value:z,issues:[]},W);if(J instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(J.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:J.issues.map((A)=>x0(A,W,T0())),input:z,path:[z],inst:Q}),X.value[J.value]=J.value;continue}let H=Y.valueType._zod.run({value:G[z],issues:[]},W);if(H instanceof Promise)$.push(H.then((A)=>{if(A.issues.length)X.issues.push(...s0(z,A.issues));X.value[J.value]=A.value}));else{if(H.issues.length)X.issues.push(...s0(z,H.issues));X.value[J.value]=H.value}}}if($.length)return Promise.all($).then(()=>X);return X}});var ZW=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"?a0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,$)=>{let z=G.value;if(W.has(z))return G;return G.issues.push({code:"invalid_value",values:X,input:z,inst:Q}),G}}),NW=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"?a0(X):X?a0(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 wW=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((z)=>{return X.value=z,X});if(G instanceof Promise)throw new t0;return X.value=G,X}});function v8(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var PW=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(`^(${J4(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(($)=>v8($,X.value));return v8(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),bW=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(`^(${J4(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)}}),jW=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(($)=>x8($,Y));return x8(G,Y)}});function x8(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var IW=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)}}),EW=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(($)=>_8($,Q));return _8(G,Q)}});function _8(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 TW=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((z)=>x0(z,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 SW=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((z)=>K6(z,Y.in,W));return K6($,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>K6($,Y.out,W));return K6(G,Y.out,W)}});function K6(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var RW=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(g8);return g8(G)}});function g8(Q){return Q.value=Object.freeze(Q.value),Q}var CW=q("$ZodCustom",(Q,Y)=>{A0.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(($)=>y8($,X,W,Q));y8(G,X,W,Q);return}});function y8(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 UA=(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},KA=()=>{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 ${UA(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:KA()}}var kZ=Symbol("ZodOutput"),vZ=Symbol("ZodInput");class kW{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 DA(){return new kW}var B4=DA();function vW(Q,Y){return new Q({type:"string",...T(Y)})}function xW(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...T(Y)})}function rQ(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...T(Y)})}function _W(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...T(Y)})}function gW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...T(Y)})}function yW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...T(Y)})}function uW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...T(Y)})}function hW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...T(Y)})}function fW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...T(Y)})}function lW(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...T(Y)})}function mW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...T(Y)})}function cW(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...T(Y)})}function pW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...T(Y)})}function iW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...T(Y)})}function nW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...T(Y)})}function rW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...T(Y)})}function dW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...T(Y)})}function oW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...T(Y)})}function tW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...T(Y)})}function aW(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...T(Y)})}function sW(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...T(Y)})}function eW(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...T(Y)})}function QG(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...T(Y)})}function YG(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...T(Y)})}function XG(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...T(Y)})}function WG(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...T(Y)})}function GG(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...T(Y)})}function $G(Q,Y){return new Q({type:"number",checks:[],...T(Y)})}function zG(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...T(Y)})}function JG(Q,Y){return new Q({type:"boolean",...T(Y)})}function HG(Q,Y){return new Q({type:"null",...T(Y)})}function AG(Q){return new Q({type:"unknown"})}function UG(Q,Y){return new Q({type:"never",...T(Y)})}function L6(Q,Y){return new fQ({check:"less_than",...T(Y),value:Q,inclusive:!1})}function L4(Q,Y){return new fQ({check:"less_than",...T(Y),value:Q,inclusive:!0})}function F6(Q,Y){return new lQ({check:"greater_than",...T(Y),value:Q,inclusive:!1})}function F4(Q,Y){return new lQ({check:"greater_than",...T(Y),value:Q,inclusive:!0})}function q6(Q,Y){return new q8({check:"multiple_of",...T(Y),value:Q})}function O6(Q,Y){return new M8({check:"max_length",...T(Y),maximum:Q})}function u1(Q,Y){return new V8({check:"min_length",...T(Y),minimum:Q})}function M6(Q,Y){return new Z8({check:"length_equals",...T(Y),length:Q})}function dQ(Q,Y){return new N8({check:"string_format",format:"regex",...T(Y),pattern:Q})}function oQ(Q){return new w8({check:"string_format",format:"lowercase",...T(Q)})}function tQ(Q){return new P8({check:"string_format",format:"uppercase",...T(Q)})}function aQ(Q,Y){return new b8({check:"string_format",format:"includes",...T(Y),includes:Q})}function sQ(Q,Y){return new j8({check:"string_format",format:"starts_with",...T(Y),prefix:Q})}function eQ(Q,Y){return new I8({check:"string_format",format:"ends_with",...T(Y),suffix:Q})}function I1(Q){return new E8({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 KG(Q,Y,X){return new Q({type:"array",element:Y,...T(X)})}function DG(Q,Y,X){let W=T(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function BG(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...T(X)})}function LG(Q){let Y=BA((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 BA(Q,Y){let X=new A0({check:"custom",...T(Y)});return X._zod.check=Q,X}function h1(Q){return!!Q._zod}function U1(Q,Y){if(h1(Q))return U4(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 FG(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={};LX(O4,{time:()=>z9,duration:()=>J9,datetime:()=>G9,date:()=>$9,ZodISOTime:()=>MG,ZodISODuration:()=>VG,ZodISODateTime:()=>qG,ZodISODate:()=>OG});var qG=q("ZodISODateTime",(Q,Y)=>{o8.init(Q,Y),s.init(Q,Y)});function G9(Q){return YG(qG,Q)}var OG=q("ZodISODate",(Q,Y)=>{t8.init(Q,Y),s.init(Q,Y)});function $9(Q){return XG(OG,Q)}var MG=q("ZodISOTime",(Q,Y)=>{a8.init(Q,Y),s.init(Q,Y)});function z9(Q){return WG(MG,Q)}var VG=q("ZodISODuration",(Q,Y)=>{s8.init(Q,Y),s.init(Q,Y)});function J9(Q){return GG(VG,Q)}var ZG=(Q,Y)=>{z6.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>CX(Q,X)},flatten:{value:(X)=>RX(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}}})},MN=q("ZodError",ZG),I0=q("ZodError",ZG,{Parent:Error});var NG=J6(I0),wG=H6(I0),PG=A4(I0),bG=K4(I0),jG=kX(I0),IG=vX(I0),EG=xX(I0),TG=_X(I0),SG=gX(I0),RG=yX(I0),CG=uX(I0),kG=hX(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)=>NG(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>PG(Q,X,W),Q.parseAsync=async(X,W)=>wG(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>bG(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>jG(Q,X,W),Q.decode=(X,W)=>IG(Q,X,W),Q.encodeAsync=async(X,W)=>EG(Q,X,W),Q.decodeAsync=async(X,W)=>TG(Q,X,W),Q.safeEncode=(X,W)=>SG(Q,X,W),Q.safeDecode=(X,W)=>RG(Q,X,W),Q.safeEncodeAsync=async(X,W)=>CG(Q,X,W),Q.safeDecodeAsync=async(X,W)=>kG(Q,X,W),Q.refine=(X,W)=>Q.check(A3(X,W)),Q.superRefine=(X)=>Q.check(U3(X)),Q.overwrite=(X)=>Q.check(I1(X)),Q.optional=()=>Y0(Q),Q.nullable=()=>_G(Q),Q.nullish=()=>Y0(_G(Q)),Q.nonoptional=(X)=>W3(Q,X),Q.array=()=>u(Q),Q.or=(X)=>d([Q,X]),Q.and=(X)=>N6(Q,X),Q.transform=(X)=>A9(Q,fG(X)),Q.default=(X)=>Q3(Q,X),Q.prefault=(X)=>X3(Q,X),Q.catch=(X)=>$3(Q,X),Q.pipe=(X)=>A9(Q,X),Q.readonly=()=>H3(Q),Q.describe=(X)=>{let W=Q.clone();return B4.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return B4.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return B4.get(Q);let W=Q.clone();return B4.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),gG=q("_ZodString",(Q,Y)=>{B6.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())}),wA=q("ZodString",(Q,Y)=>{B6.init(Q,Y),gG.init(Q,Y),Q.email=(X)=>Q.check(xW(PA,X)),Q.url=(X)=>Q.check(hW(bA,X)),Q.jwt=(X)=>Q.check(QG(hA,X)),Q.emoji=(X)=>Q.check(fW(jA,X)),Q.guid=(X)=>Q.check(rQ(vG,X)),Q.uuid=(X)=>Q.check(_W(Z6,X)),Q.uuidv4=(X)=>Q.check(gW(Z6,X)),Q.uuidv6=(X)=>Q.check(yW(Z6,X)),Q.uuidv7=(X)=>Q.check(uW(Z6,X)),Q.nanoid=(X)=>Q.check(lW(IA,X)),Q.guid=(X)=>Q.check(rQ(vG,X)),Q.cuid=(X)=>Q.check(mW(EA,X)),Q.cuid2=(X)=>Q.check(cW(TA,X)),Q.ulid=(X)=>Q.check(pW(SA,X)),Q.base64=(X)=>Q.check(aW(gA,X)),Q.base64url=(X)=>Q.check(sW(yA,X)),Q.xid=(X)=>Q.check(iW(RA,X)),Q.ksuid=(X)=>Q.check(nW(CA,X)),Q.ipv4=(X)=>Q.check(rW(kA,X)),Q.ipv6=(X)=>Q.check(dW(vA,X)),Q.cidrv4=(X)=>Q.check(oW(xA,X)),Q.cidrv6=(X)=>Q.check(tW(_A,X)),Q.e164=(X)=>Q.check(eW(uA,X)),Q.datetime=(X)=>Q.check(G9(X)),Q.date=(X)=>Q.check($9(X)),Q.time=(X)=>Q.check(z9(X)),Q.duration=(X)=>Q.check(J9(X))});function F(Q){return vW(wA,Q)}var s=q("ZodStringFormat",(Q,Y)=>{t.init(Q,Y),gG.init(Q,Y)}),PA=q("ZodEmail",(Q,Y)=>{f8.init(Q,Y),s.init(Q,Y)});var vG=q("ZodGUID",(Q,Y)=>{u8.init(Q,Y),s.init(Q,Y)});var Z6=q("ZodUUID",(Q,Y)=>{h8.init(Q,Y),s.init(Q,Y)});var bA=q("ZodURL",(Q,Y)=>{l8.init(Q,Y),s.init(Q,Y)});var jA=q("ZodEmoji",(Q,Y)=>{m8.init(Q,Y),s.init(Q,Y)});var IA=q("ZodNanoID",(Q,Y)=>{c8.init(Q,Y),s.init(Q,Y)});var EA=q("ZodCUID",(Q,Y)=>{p8.init(Q,Y),s.init(Q,Y)});var TA=q("ZodCUID2",(Q,Y)=>{i8.init(Q,Y),s.init(Q,Y)});var SA=q("ZodULID",(Q,Y)=>{n8.init(Q,Y),s.init(Q,Y)});var RA=q("ZodXID",(Q,Y)=>{r8.init(Q,Y),s.init(Q,Y)});var CA=q("ZodKSUID",(Q,Y)=>{d8.init(Q,Y),s.init(Q,Y)});var kA=q("ZodIPv4",(Q,Y)=>{e8.init(Q,Y),s.init(Q,Y)});var vA=q("ZodIPv6",(Q,Y)=>{QW.init(Q,Y),s.init(Q,Y)});var xA=q("ZodCIDRv4",(Q,Y)=>{YW.init(Q,Y),s.init(Q,Y)});var _A=q("ZodCIDRv6",(Q,Y)=>{XW.init(Q,Y),s.init(Q,Y)});var gA=q("ZodBase64",(Q,Y)=>{GW.init(Q,Y),s.init(Q,Y)});var yA=q("ZodBase64URL",(Q,Y)=>{$W.init(Q,Y),s.init(Q,Y)});var uA=q("ZodE164",(Q,Y)=>{zW.init(Q,Y),s.init(Q,Y)});var hA=q("ZodJWT",(Q,Y)=>{JW.init(Q,Y),s.init(Q,Y)});var yG=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(xG(W)),Q.safe=(W)=>Q.check(xG(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 $G(yG,Q)}var fA=q("ZodNumberFormat",(Q,Y)=>{HW.init(Q,Y),yG.init(Q,Y)});function xG(Q){return zG(fA,Q)}var lA=q("ZodBoolean",(Q,Y)=>{AW.init(Q,Y),X0.init(Q,Y)});function H0(Q){return JG(lA,Q)}var mA=q("ZodNull",(Q,Y)=>{UW.init(Q,Y),X0.init(Q,Y)});function U9(Q){return HG(mA,Q)}var cA=q("ZodUnknown",(Q,Y)=>{KW.init(Q,Y),X0.init(Q,Y)});function e(){return AG(cA)}var pA=q("ZodNever",(Q,Y)=>{DW.init(Q,Y),X0.init(Q,Y)});function iA(Q){return UG(pA,Q)}var nA=q("ZodArray",(Q,Y)=>{BW.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 KG(nA,Q,Y)}var uG=q("ZodObject",(Q,Y)=>{qW.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:iA()}),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(lG,Q,X[0]),Q.required=(...X)=>m.required(mG,Q,X[0])});function b(Q,Y){let X={type:"object",shape:Q??{},...m.normalizeParams(Y)};return new uG(X)}function q0(Q,Y){return new uG({type:"object",shape:Q,catchall:e(),...m.normalizeParams(Y)})}var hG=q("ZodUnion",(Q,Y)=>{iQ.init(Q,Y),X0.init(Q,Y),Q.options=Y.options});function d(Q,Y){return new hG({type:"union",options:Q,...m.normalizeParams(Y)})}var rA=q("ZodDiscriminatedUnion",(Q,Y)=>{hG.init(Q,Y),OW.init(Q,Y)});function K9(Q,Y,X){return new rA({type:"union",options:Y,discriminator:Q,...m.normalizeParams(X)})}var dA=q("ZodIntersection",(Q,Y)=>{MW.init(Q,Y),X0.init(Q,Y)});function N6(Q,Y){return new dA({type:"intersection",left:Q,right:Y})}var oA=q("ZodRecord",(Q,Y)=>{VW.init(Q,Y),X0.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function Q0(Q,Y,X){return new oA({type:"record",keyType:Q,valueType:Y,...m.normalizeParams(X)})}var H9=q("ZodEnum",(Q,Y)=>{ZW.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 z of W)if(X.has(z))$[z]=Y.entries[z];else throw Error(`Key ${z} not found in enum`);return new H9({...Y,checks:[],...m.normalizeParams(G),entries:$})},Q.exclude=(W,G)=>{let $={...Y.entries};for(let z of W)if(X.has(z))delete $[z];else throw Error(`Key ${z} 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 tA=q("ZodLiteral",(Q,Y)=>{NW.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 tA({type:"literal",values:Array.isArray(Q)?Q:[Q],...m.normalizeParams(Y)})}var aA=q("ZodTransform",(Q,Y)=>{wW.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 z=$;if(z.fatal)z.continue=!1;z.code??(z.code="custom"),z.input??(z.input=X.value),z.inst??(z.inst=Q),X.issues.push(m.issue(z))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then(($)=>{return X.value=$,X});return X.value=G,X}});function fG(Q){return new aA({type:"transform",transform:Q})}var lG=q("ZodOptional",(Q,Y)=>{PW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function Y0(Q){return new lG({type:"optional",innerType:Q})}var sA=q("ZodNullable",(Q,Y)=>{bW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function _G(Q){return new sA({type:"nullable",innerType:Q})}var eA=q("ZodDefault",(Q,Y)=>{jW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function Q3(Q,Y){return new eA({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var Y3=q("ZodPrefault",(Q,Y)=>{IW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function X3(Q,Y){return new Y3({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var mG=q("ZodNonOptional",(Q,Y)=>{EW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function W3(Q,Y){return new mG({type:"nonoptional",innerType:Q,...m.normalizeParams(Y)})}var G3=q("ZodCatch",(Q,Y)=>{TW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function $3(Q,Y){return new G3({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var z3=q("ZodPipe",(Q,Y)=>{SW.init(Q,Y),X0.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function A9(Q,Y){return new z3({type:"pipe",in:Q,out:Y})}var J3=q("ZodReadonly",(Q,Y)=>{RW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function H3(Q){return new J3({type:"readonly",innerType:Q})}var cG=q("ZodCustom",(Q,Y)=>{CW.init(Q,Y),X0.init(Q,Y)});function pG(Q,Y){return DG(cG,Q??(()=>!0),Y)}function A3(Q,Y={}){return BG(cG,Q,Y)}function U3(Q){return LG(Q)}function D9(Q,Y){return A9(fG(Q),Y)}T0(nQ());var B9="2025-11-25";var iG=[B9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],K1="io.modelcontextprotocol/related-task",P6="2.0",U0=pG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),nG=d([F(),i().int()]),rG=F(),Bw=q0({ttl:d([i(),U9()]).optional(),pollInterval:i().optional()}),K3=b({ttl:i().optional()}),D3=b({taskId:F()}),L9=q0({progressToken:nG.optional(),[K1]:D3.optional()}),E0=b({_meta:L9.optional()}),M4=E0.extend({task:K3.optional()}),dG=(Q)=>M4.safeParse(Q).success,K0=b({method:F(),params:E0.loose().optional()}),S0=b({_meta:L9.optional()}),R0=b({method:F(),params:S0.loose().optional()}),D0=q0({_meta:L9.optional()}),b6=d([F(),i().int()]),oG=b({jsonrpc:j(P6),id:b6,...K0.shape}).strict(),F9=(Q)=>oG.safeParse(Q).success,tG=b({jsonrpc:j(P6),...R0.shape}).strict(),aG=(Q)=>tG.safeParse(Q).success,q9=b({jsonrpc:j(P6),id:b6,result:D0}).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 sG=(Q)=>O9.safeParse(Q).success;var eG=d([oG,tG,q9,O9]),Lw=d([q9,O9]),j6=D0.strict(),B3=S0.extend({requestId:b6.optional(),reason:F().optional()}),I6=R0.extend({method:j("notifications/cancelled"),params:B3}),L3=b({src:F(),mimeType:F().optional(),sizes:u(F()).optional(),theme:V0(["light","dark"]).optional()}),Z4=b({icons:u(L3).optional()}),f1=b({name:F(),title:F().optional()}),Q$=f1.extend({...f1.shape,...Z4.shape,version:F(),websiteUrl:F().optional(),description:F().optional()}),F3=N6(b({applyDefaults:H0().optional()}),Q0(F(),e())),q3=D9((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},N6(b({form:F3.optional(),url:U0.optional()}),Q0(F(),e()).optional())),O3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({sampling:q0({createMessage:U0.optional()}).optional(),elicitation:q0({create:U0.optional()}).optional()}).optional()}),M3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({tools:q0({call:U0.optional()}).optional()}).optional()}),V3=b({experimental:Q0(F(),U0).optional(),sampling:b({context:U0.optional(),tools:U0.optional()}).optional(),elicitation:q3.optional(),roots:b({listChanged:H0().optional()}).optional(),tasks:O3.optional()}),Z3=E0.extend({protocolVersion:F(),capabilities:V3,clientInfo:Q$}),M9=K0.extend({method:j("initialize"),params:Z3});var N3=b({experimental:Q0(F(),U0).optional(),logging:U0.optional(),completions:U0.optional(),prompts:b({listChanged:H0().optional()}).optional(),resources:b({subscribe:H0().optional(),listChanged:H0().optional()}).optional(),tools:b({listChanged:H0().optional()}).optional(),tasks:M3.optional()}),w3=D0.extend({protocolVersion:F(),capabilities:N3,serverInfo:Q$,instructions:F().optional()}),V9=R0.extend({method:j("notifications/initialized"),params:S0.optional()});var E6=K0.extend({method:j("ping"),params:E0.optional()}),P3=b({progress:i(),total:Y0(i()),message:Y0(F())}),b3=b({...S0.shape,...P3.shape,progressToken:nG}),T6=R0.extend({method:j("notifications/progress"),params:b3}),j3=E0.extend({cursor:rG.optional()}),N4=K0.extend({params:j3.optional()}),w4=D0.extend({nextCursor:rG.optional()}),I3=V0(["working","input_required","completed","failed","cancelled"]),P4=b({taskId:F(),status:I3,ttl:d([i(),U9()]),createdAt:F(),lastUpdatedAt:F(),pollInterval:Y0(i()),statusMessage:Y0(F())}),l1=D0.extend({task:P4}),E3=S0.merge(P4),b4=R0.extend({method:j("notifications/tasks/status"),params:E3}),S6=K0.extend({method:j("tasks/get"),params:E0.extend({taskId:F()})}),R6=D0.merge(P4),C6=K0.extend({method:j("tasks/result"),params:E0.extend({taskId:F()})}),Fw=D0.loose(),k6=N4.extend({method:j("tasks/list")}),v6=w4.extend({tasks:u(P4)}),x6=K0.extend({method:j("tasks/cancel"),params:E0.extend({taskId:F()})}),Y$=D0.merge(P4),X$=b({uri:F(),mimeType:Y0(F()),_meta:Q0(F(),e()).optional()}),W$=X$.extend({text:F()}),Z9=F().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),G$=X$.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()}),$$=b({...f1.shape,...Z4.shape,uri:F(),description:Y0(F()),mimeType:Y0(F()),annotations:m1.optional(),_meta:Y0(q0({}))}),T3=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")}),S3=w4.extend({resources:u($$)}),R3=N4.extend({method:j("resources/templates/list")}),C3=w4.extend({resourceTemplates:u(T3)}),w9=E0.extend({uri:F()}),k3=w9,P9=K0.extend({method:j("resources/read"),params:k3}),v3=D0.extend({contents:u(d([W$,G$]))}),x3=R0.extend({method:j("notifications/resources/list_changed"),params:S0.optional()}),_3=w9,g3=K0.extend({method:j("resources/subscribe"),params:_3}),y3=w9,u3=K0.extend({method:j("resources/unsubscribe"),params:y3}),h3=S0.extend({uri:F()}),f3=R0.extend({method:j("notifications/resources/updated"),params:h3}),l3=b({name:F(),description:Y0(F()),required:Y0(H0())}),m3=b({...f1.shape,...Z4.shape,description:Y0(F()),arguments:Y0(u(l3)),_meta:Y0(q0({}))}),c3=N4.extend({method:j("prompts/list")}),p3=w4.extend({prompts:u(m3)}),i3=E0.extend({name:F(),arguments:Q0(F(),F()).optional()}),n3=K0.extend({method:j("prompts/get"),params:i3}),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()}),r3=b({type:j("tool_use"),name:F(),id:F(),input:Q0(F(),e()),_meta:Q0(F(),e()).optional()}),d3=b({type:j("resource"),resource:d([W$,G$]),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),o3=$$.extend({type:j("resource_link")}),E9=d([b9,j9,I9,o3,d3]),t3=b({role:j4,content:E9}),a3=D0.extend({description:F().optional(),messages:u(t3)}),s3=R0.extend({method:j("notifications/prompts/list_changed"),params:S0.optional()}),e3=b({title:F().optional(),readOnlyHint:H0().optional(),destructiveHint:H0().optional(),idempotentHint:H0().optional(),openWorldHint:H0().optional()}),QU=b({taskSupport:V0(["required","optional","forbidden"]).optional()}),z$=b({...f1.shape,...Z4.shape,description:F().optional(),inputSchema:b({type:j("object"),properties:Q0(F(),U0).optional(),required:u(F()).optional()}).catchall(e()),outputSchema:b({type:j("object"),properties:Q0(F(),U0).optional(),required:u(F()).optional()}).catchall(e()).optional(),annotations:e3.optional(),execution:QU.optional(),_meta:Q0(F(),e()).optional()}),T9=N4.extend({method:j("tools/list")}),YU=w4.extend({tools:u(z$)}),_6=D0.extend({content:u(E9).default([]),structuredContent:Q0(F(),e()).optional(),isError:H0().optional()}),qw=_6.or(D0.extend({toolResult:e()})),XU=M4.extend({name:F(),arguments:Q0(F(),e()).optional()}),I4=K0.extend({method:j("tools/call"),params:XU}),WU=R0.extend({method:j("notifications/tools/list_changed"),params:S0.optional()}),Ow=b({autoRefresh:H0().default(!0),debounceMs:i().int().nonnegative().default(300)}),E4=V0(["debug","info","notice","warning","error","critical","alert","emergency"]),GU=E0.extend({level:E4}),S9=K0.extend({method:j("logging/setLevel"),params:GU}),$U=S0.extend({level:E4,logger:F().optional(),data:e()}),zU=R0.extend({method:j("notifications/message"),params:$U}),JU=b({name:F().optional()}),HU=b({hints:u(JU).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),AU=b({mode:V0(["auto","required","none"]).optional()}),UU=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()}),KU=K9("type",[b9,j9,I9]),w6=K9("type",[b9,j9,I9,r3,UU]),DU=b({role:j4,content:d([w6,u(w6)]),_meta:Q0(F(),e()).optional()}),BU=M4.extend({messages:u(DU),modelPreferences:HU.optional(),systemPrompt:F().optional(),includeContext:V0(["none","thisServer","allServers"]).optional(),temperature:i().optional(),maxTokens:i().int(),stopSequences:u(F()).optional(),metadata:U0.optional(),tools:u(z$).optional(),toolChoice:AU.optional()}),LU=K0.extend({method:j("sampling/createMessage"),params:BU}),R9=D0.extend({model:F(),stopReason:Y0(V0(["endTurn","stopSequence","maxTokens"]).or(F())),role:j4,content:KU}),C9=D0.extend({model:F(),stopReason:Y0(V0(["endTurn","stopSequence","maxTokens","toolUse"]).or(F())),role:j4,content:d([w6,u(w6)])}),FU=b({type:j("boolean"),title:F().optional(),description:F().optional(),default:H0().optional()}),qU=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()}),OU=b({type:V0(["number","integer"]),title:F().optional(),description:F().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),MU=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),default:F().optional()}),VU=b({type:j("string"),title:F().optional(),description:F().optional(),oneOf:u(b({const:F(),title:F()})),default:F().optional()}),ZU=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),enumNames:u(F()).optional(),default:F().optional()}),NU=d([MU,VU]),wU=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()}),PU=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()}),bU=d([wU,PU]),jU=d([ZU,NU,bU]),IU=d([jU,FU,qU,OU]),EU=M4.extend({mode:j("form").optional(),message:F(),requestedSchema:b({type:j("object"),properties:Q0(F(),IU),required:u(F()).optional()})}),TU=M4.extend({mode:j("url"),message:F(),elicitationId:F(),url:F().url()}),SU=d([EU,TU]),RU=K0.extend({method:j("elicitation/create"),params:SU}),CU=S0.extend({elicitationId:F()}),kU=R0.extend({method:j("notifications/elicitation/complete"),params:CU}),g6=D0.extend({action:V0(["accept","decline","cancel"]),content:D9((Q)=>Q===null?void 0:Q,Q0(F(),d([F(),i(),H0(),u(F())])).optional())}),vU=b({type:j("ref/resource"),uri:F()});var xU=b({type:j("ref/prompt"),name:F()}),_U=E0.extend({ref:d([xU,vU]),argument:b({name:F(),value:F()}),context:b({arguments:Q0(F(),F()).optional()}).optional()}),gU=K0.extend({method:j("completion/complete"),params:_U});var yU=D0.extend({completion:q0({values:u(F()).max(100),total:Y0(i().int()),hasMore:Y0(H0())})}),uU=b({uri:F().startsWith("file://"),name:F().optional(),_meta:Q0(F(),e()).optional()}),hU=K0.extend({method:j("roots/list"),params:E0.optional()}),k9=D0.extend({roots:u(uU)}),fU=R0.extend({method:j("notifications/roots/list_changed"),params:S0.optional()}),Mw=d([E6,M9,gU,S9,n3,c3,N9,R3,P9,g3,u3,I4,T9,S6,C6,k6,x6]),Vw=d([I6,T6,V9,fU,b4]),Zw=d([j6,R9,C9,g6,k9,R6,v6,l1]),Nw=d([E6,LU,RU,hU,S6,C6,k6,x6]),ww=d([I6,T6,zU,f3,x3,WU,s3,b4,kU]),Pw=d([j6,w3,yU,a3,p3,S3,C3,v3,_6,YU,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 lU=Symbol("Let zodToJsonSchema decide on which parser to use");var XP=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function v9(Q){let X=V6(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=FG(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function x9(Q,Y){let X=U1(Q,Y);if(!X.success)throw X.error;return X.data}var rU=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 z;while(z=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(z.type==="response"||z.type==="error"){let J=z.message,H=J.id,A=this._requestResolvers.get(H);if(A)if(this._requestResolvers.delete(H),z.type==="response")A(J);else{let U=J,K=new _(U.error.code,U.error.message,U.error.data);A(K)}else{let U=z.type==="response"?"Response":"Error";this._onerror(Error(`${U} handler missing for request ${H}`))}continue}await this._transport?.send(z.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 z=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...z,_meta:{...z._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)||sG(G))this._onresponse(G);else if(F9(G))this._onrequest(G,$);else if(aG(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 A={jsonrpc:"2.0",id:Q.id,error:{code:h.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId).catch((U)=>this._onerror(Error(`Failed to enqueue error response: ${U}`)));else W?.send(A).catch((U)=>this._onerror(Error(`Failed to send an error response: ${U}`)));return}let $=new AbortController;this._requestHandlerAbortControllers.set(Q.id,$);let z=dG(Q.params)?Q.params.task:void 0,J=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:$.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(A)=>{let U={relatedRequestId:Q.id};if(G)U.relatedTask={taskId:G};await this.notification(A,U)},sendRequest:async(A,U,K)=>{let D={...K,relatedRequestId:Q.id};if(G&&!D.relatedTask)D.relatedTask={taskId:G};let L=D.relatedTask?.taskId??G;if(L&&J)await J.updateTaskStatus(L,"input_required");return await this.request(A,U,D)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:J,taskRequestedTtl:z?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(z)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(A)=>{if($.signal.aborted)return;let U={result:A,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:U,timestamp:Date.now()},W?.sessionId);else await W?.send(U)},async(A)=>{if($.signal.aborted)return;let U={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(A.code)?A.code:h.InternalError,message:A.message??"Internal error",...A.data!==void 0&&{data:A.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId);else await W?.send(U)}).catch((A)=>this._onerror(Error(`Failed to send response: ${A}`))).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),z=this._timeoutInfo.get(W);if(z&&$&&z.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(J){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),$(J);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 z=$.task;if(typeof z.taskId==="string")G=!0,this._taskProgressTokens.set(z.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 z=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:z},D1(z.status)){if(z.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(z.status==="failed")yield{type:"error",error:new _(h.InternalError,`Task ${G} failed`)};else if(z.status==="cancelled")yield{type:"error",error:new _(h.InternalError,`Task ${G} was cancelled`)};return}if(z.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let J=z.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,J)),X?.signal?.throwIfAborted()}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$,task:z,relatedTask:J}=X??{};return new Promise((H,A)=>{let U=(Z)=>{A(Z)};if(!this._transport){U(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),z)this.assertTaskCapability(Q.method)}catch(Z){U(Z);return}X?.signal?.throwIfAborted();let K=this._requestMessageId++,D={...Q,jsonrpc:"2.0",id:K};if(X?.onprogress)this._progressHandlers.set(K,X.onprogress),D.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:K}};if(z)D.params={...D.params,task:z};if(J)D.params={...D.params,_meta:{...D.params?._meta||{},[K1]:J}};let L=(Z)=>{this._responseHandlers.delete(K),this._progressHandlers.delete(K),this._cleanupTimeout(K),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:K,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));A(k)};this._responseHandlers.set(K,(Z)=>{if(X?.signal?.aborted)return;if(Z instanceof Error)return A(Z);try{let k=U1(Y,Z.result);if(!k.success)A(k.error);else H(k.data)}catch(k){A(k)}}),X?.signal?.addEventListener("abort",()=>{L(X?.signal?.reason)});let O=X?.timeout??rU,M=()=>L(_.fromError(h.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(K,O,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let N=J?.taskId;if(N){let Z=(k)=>{let S=this._responseHandlers.get(K);if(S)S(k);else this._onerror(Error(`Response handler missing for side-channeled request ${K}`))};this._requestResolvers.set(K,Z),this._enqueueTaskMessage(N,{type:"request",message:D,timestamp:Date.now()}).catch((k)=>{this._cleanupTimeout(K),A(k)})}else this._transport.send(D,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((Z)=>{this._cleanupTimeout(K),A(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},Y$,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let z={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[K1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:z,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 z={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)z={...z,params:{...z.params,_meta:{...z.params?._meta||{},[K1]:Y.relatedTask}}};this._transport?.send(z,Y).catch((J)=>this._onerror(J))});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 z=await X.getTask(W,Y);if(z){let J=b4.parse({method:"notifications/tasks/status",params:z});if(await this.notification(J),D1(z.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,$)=>{let z=await X.getTask(W,Y);if(!z)throw new _(h.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(D1(z.status))throw new _(h.InvalidParams,`Cannot update task "${W}" from terminal status "${z.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,$,Y);let J=await X.getTask(W,Y);if(J){let H=b4.parse({method:"notifications/tasks/status",params:J});if(await this.notification(H),D1(J.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function H$(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function A$(Q,Y){let X={...Q};for(let W in Y){let G=W,$=Y[G];if($===void 0)continue;let z=X[G];if(H$(z)&&H$($))X[G]={...z,...$};else X[G]=$}return X}var f5=BX(SY(),1),l5=BX(h5(),1);function XV(){let Q=new f5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return l5.default(Q),Q}class hY{constructor(Q){this._ajv=Q??XV()}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 m5(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 c5(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,z=E4.safeParse($);if(z.success)this._loggingLevels.set(G,z.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=A$(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 z=W;G=z._zod?.def?.value??z.value}else{let z=W;G=z._def?.value??z.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let z=async(J,H)=>{let A=U1(I4,J);if(!A.success){let L=A.error instanceof Error?A.error.message:String(A.error);throw new _(h.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:U}=A.data,K=await Promise.resolve(Y(J,H));if(U.task){let L=U1(l1,K);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 D=U1(_6,K);if(!D.success){let L=D.error instanceof Error?D.error.message:String(D.error);throw new _(h.InvalidParams,`Invalid tools/call result: ${L}`)}return D.data};return super.setRequestHandler(Q,z)}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){c5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;m5(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:iG.includes(Y)?Y:B9,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,z=$?Array.isArray($.content)?$.content:[$.content]:[],J=z.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(!J)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(J){let H=new Set(z.filter((U)=>U.type==="tool_use").map((U)=>U.id)),A=new Set(W.filter((U)=>U.type==="tool_result").map((U)=>U.toolUseId));if(H.size!==A.size||![...H].every((U)=>A.has(U)))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 z=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!z.valid)throw new _(h.InvalidParams,`Elicitation response content does not match requested schema: ${z.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 p5={name:"@sequenzy/mcp",version:"0.0.101",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":"bunx --bun 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"],i5={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 GV(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 z0(Q,Y=""){return`/dashboard/company/${r0(Q)}${Y}`}function n5(Q,Y,X){return $0(Q,`${z0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function $V(Q,Y){let X=mY.map((W)=>[W,Y?n5(Q,Y,W):""]);return Object.fromEntries(X)}function Z1(Q={},Y){let X=GV(Y),W=l0(Q.companyId),G={},$=$V(X,W);if(!W)return{appUrl:X,routeTemplates:i5,settingsTabValues:mY,urls:G,settingsUrls:$};G.dashboard=$0(X,z0(W)),G.campaigns=$0(X,z0(W,"/campaign")),G.landingPages=$0(X,z0(W,"/landing-pages")),G.sequences=$0(X,z0(W,"/sequences")),G.settings=$0(X,z0(W,"/settings")),G.emails=$0(X,z0(W,"/emails")),G.subscribers=$0(X,z0(W,"/subscribers")),G.sentEmails=$0(X,z0(W,"/sent-emails")),G.segments=$0(X,z0(W,"/segments")),G.metrics=$0(X,z0(W,"/metrics")),G.transactional=$0(X,z0(W,"/transactional"));let z=l0(Q.campaignId);if(z)G.campaign=$0(X,z0(W,`/campaign/${r0(z)}`)),G.campaignPreview=`${G.campaign}?step=review`;let J=l0(Q.landingPageId);if(J)G.landingPage=$0(X,z0(W,`/landing-pages/${r0(J)}`));let H=l0(Q.sequenceId);if(H)G.sequence=$0(X,z0(W,`/sequences/${r0(H)}`));let A=l0(Q.emailId)??l0(Q.templateId);if(A)G.email=$0(X,z0(W,`/emails/${r0(A)}`)),G.template=G.email;let U=l0(Q.transactionalId);if(U)G.transactionalEmail=$0(X,z0(W,`/transactional/${r0(U)}`));let K=l0(Q.emailSendId);if(K)G.emailSend=$0(X,z0(W,`/sent-emails/${r0(K)}`));let D=l0(Q.domainId);if(D)G.domain=$0(X,z0(W,`/settings/domain/${r0(D)}`)),G.domainVerify=`${G.domain}/verify`;let L=l0(Q.status);if(L)G.campaignList=$0(X,z0(W,`/campaign/list/${r0(L)}`)),G.sequenceList=$0(X,z0(W,`/sequences/list/${r0(L)}`));let O=l0(Q.settingsTab);if(O)G.settingsTab=n5(X,W,O);return{appUrl:X,routeTemplates:i5,settingsTabValues:mY,urls:G,settingsUrls:$}}var r5=[{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 d5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await B("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await B("GET","/api/v1/account"),W=b1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await B("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await B("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await B("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await B("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await B("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await B("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await B("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await B("GET","/api/v1/tags");break;case"sequenzy://health":Y=await B("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=Z1();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 zV,statSync as JV}from"node:fs";import{basename as HV}from"node:path";var GX=' 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: [...] }.${GX}`,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\`.${GX}`,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.${GX}`,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.",AV="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.",o5=500,t5=500,N1={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"],a5={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},UV={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:UV,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},wQ=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],PQ=["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"],KV=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"]),DV=new Set(["select_company","create_company","update_company","update_sync_rules","update_shopify_automation_settings","create_api_key","add_sending_domain","add_website","verify_sending_domain","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","add_sending_domain","add_website","verify_sending_domain","enable_sequence","resume_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery"]),LV=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 FV(Q){let Y=KV.has(Q),X=DV.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:LV.has(Q),openWorldHint:BV.has(Q)}}function qV(Q){return{...Q,annotations:{...Q.annotations,...FV(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"]},OV=Object.entries(eY).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),s5={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, a specific campaign via `campaign:<campaign_id>`, or `count:timeRange` (e.g. `10:30d`, `10:all`) with at_least/less_than_count to segment by number of opens/clicks."},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: ${OV}.`},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, `campaign:<campaign_id>` to scope to a specific sent campaign (use `list_campaigns` to find IDs), or `count:timeRange` like `10:30d` / `10:all` with at_least/less_than_count operators (e.g. emailClicked at_least `10:all` = clicked 10 or more times ever)."}},required:["field","operator","value"],additionalProperties:!1},e5={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 MV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function VV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function QH(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 ZV(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(),z=X.at(-2),J=X.at(-1),H=z===void 0?Number.NaN:Number.parseInt(z,10);return $&&Number.isInteger(H)&&H>0&&J!==void 0&&QH(J)?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&&QH(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function NV(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 wV(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function PV(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 bV(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 jV(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function IV(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let J=X.indexOf(":");if(J===-1)return null;let H=X.substring(0,J).trim(),A=Number.parseInt(X.substring(J+1).trim(),10);return H&&Number.isInteger(A)&&A>=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:$}=NV(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 z=wV(G);if(PV(z))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!bV(Q,z))return`Unsupported Stripe product subfilter "${G}".`;if(!jV(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 EV=new Set(["shopify","woocommerce","api"]);function TV(Q,Y){let X=Y.trim(),W=X.indexOf(":");if(W!==-1&&EV.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(),z=Number.parseInt(X.substring(G+1).trim(),10);return $&&Number.isInteger(z)&&z>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function $X(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(!MV(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!VV(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let z=ZV(W,G);if(z)return z}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let z=IV(X,W,G);if(z)return z}if(X==="commerceProduct"&&typeof G==="string"){let z=TV(W,G);if(z)return z}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map((J)=>J.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function zX(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=$X(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap(zX);return[]}function w1(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 bQ(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 SV(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 $=$X(G);return $?[$]:[]}):zX(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function RV(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 $=$X(G);return $?[$]:[]}):X?zX(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","fromEmail","fromName","replyTo","replyToName"];function iY(Q,Y,X){if(Y[X]!==void 0&&!J0(Y[X]))throw Error(`\`${X}\` must be an object when calling \`${Q}\`.`)}function YH(Q,Y,X){if(Y[X]!==void 0&&!Array.isArray(Y[X]))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`)}function CV(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","fromEmail","fromName","replyTo","replyToName"])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"),YH("update_company",Q,"valueProps"),YH("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`.");for(let G of["fromEmail","replyTo"]){let $=Q[G];if(typeof $==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($.trim()))throw Error(`\`${G}\` must be a valid email address when calling \`update_company\`.`)}if(Q.fromName!==void 0&&Q.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_company`.");if(Q.replyToName!==void 0&&Q.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_company`.");return W}function kV(Q){if(Q.fromEmail!==void 0&&Q.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_sequence`, not both.");if(Q.replyTo!==void 0&&Q.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_sequence`, not both.");if(Q.fromName!==void 0&&Q.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_sequence`.");if(Q.replyToName!==void 0&&Q.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_sequence`.");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 vV(Q){let Y=Q.type==="sms",X;if(Y){let G=w(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 z of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(Q[z]!==void 0)X[z]=Q[z]}else{w1("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 xV(Q){let Y=w(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((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0)??[];if(W?.some((J)=>typeof J!=="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 $=w(Q,"fieldPath"),z=w(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...$!==void 0&&{fieldPath:$},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...z!==void 0&&{reason:z}}}function _V(Q){w1("create_campaign",Q),bQ("create_campaign",Q);let Y=w(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&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function gV(Q){w1("create_template",Q),bQ("create_template",Q);let Y=w(Q,"prompt")!==void 0,X=[Y,Q.html!==void 0,Q.blocks!==void 0].filter(Boolean).length;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_template`.");if(X!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function yV(Q){if(w(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!J0(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 uV(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 hV(Q){w1("create_transactional_email",Q);let Y=w(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&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var XX={type:"object",description:"Update Subscriber config. firstName, lastName, and customAttributeUpdates values may use trigger-event merge tags such as {{event.plan}}. Number and boolean values must be a literal or one standalone merge tag and are coerced after resolution.",properties:{label:{type:"string"},firstName:{type:["string","null"],description:"First name literal or merge tag; null clears the field."},lastName:{type:["string","null"],description:"Last name literal or merge tag; null clears the field."},status:{type:"string",enum:["active","unsubscribed","bounced"]},customAttributeUpdates:{type:"array",items:{type:"object",properties:{name:{type:"string"},value:{type:["string","number","boolean","null"],description:"Literal scalar, null to delete, or a standalone merge tag such as {{event.plan}}, {{event.amount}}, or {{event.active}}."},valueType:{type:"string",enum:["text","number","boolean"]}},required:["name","value"]}}},additionalProperties:!0},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","update_subscriber","condition","webhook"],description:"Sequence path step type. Omit for email steps; use delay for standalone waits or update_subscriber for action_update_attributes."},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:{...XX,description:"Config for advanced nodeType steps. For action_update_attributes, use the documented Update Subscriber fields and trigger-event merge tags; other node types accept their normal config fields.",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 fV(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 J0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function XH(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function lV(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 mV(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,z=0,J=0,H=0;while(!0){let U=lV({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:$,pageSize:W}),K=await B("GET",`/api/v1/subscribers?${U.toString()}`,void 0,Y);z=K.pagination?.total??K.subscribers.length,J=K.pagination?.totalPages??1,H+=1,G.push(...K.subscribers??[]);let D=X!==void 0&&G.length>=X,L=K.pagination?$>=K.pagination.totalPages:(K.subscribers??[]).length<W;if(D||L)break;$+=1}let A=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:A,pagination:{page:1,limit:W,total:z,totalPages:J,fetchedPages:H},returned:A.length,truncated:X!==void 0&&z>0&&A.length<z}}function cV(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=cV(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function WX(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 WH(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 B("GET",WX(Q,X),void 0,Y)}function w(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=w(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function m0(Q,Y,X,W){let G=w(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 pV(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 z=G.trim();if(!cY.includes(z))throw Error(`\`eventTypes\` item ${$+1} must be one of ${cY.join(", ")} when calling \`${Q}\`.`);X.push(z)})}return[...new Set(X)]}function GH(Q,Y){let X=new URLSearchParams,W=pV(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 $=w(Y,"start");if($)X.set("start",$);let z=w(Y,"end");if(z)X.set("end",z);let J=x1(Q,Y,"page",1,1e6);if(J!==void 0)X.set("page",String(J));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 $H(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"||!PQ.includes(W))throw Error(`\`events\` item ${G+1} must be one of ${PQ.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 zH(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>o5)throw Error(`\`emails\` must include no more than ${o5} 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((z,J)=>{if(typeof z!=="string")throw Error(`\`${X}\` item ${J+1} must be a string when calling \`${Q}\`.`);let H=z.trim();if(H.length>0)$.push(H)}),$.length===0)throw Error(`\`${X}\` must include at least one ${W} when calling \`${Q}\`.`);return $}function iV(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>t5)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${t5} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let $=w(Q,"targetNodeId");return{...X!==void 0&&{emails:X},...W!==void 0&&{subscriberIds:W},...$!==void 0&&{targetNodeId:$}}}var nV={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 rV(Q){let Y=Q.split(".").pop()?.toLowerCase()??"";return nV[Y]??null}var dV=104857600;async function oV(Q,Y){if(!OX())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=rV(Q);if(!X)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=JV(Q).size;if(W>dV)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=zV(Q),$=await B("POST","/api/v1/products/delivery/upload-url",{filename:HV(Q),contentType:X,fileSizeBytes:W},Y),z=await fetch($.uploadUrl,{method:"PUT",headers:{"Content-Type":X},body:G});if(!z.ok)throw Error(`File upload failed (${z.status})`);return{url:$.publicUrl,fileName:$.fileName,fileSizeBytes:W,mimeType:X}}async function JX(Q){let Y=w(Q,"companyId");if(Y)return Y;let X=b1();if(X)return X;try{return(await B("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function tV(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(!J0(Q)||!Y)return Q;return{...Q,url:Y}}function HH(Q,Y){if(!J0(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(!J0(W))return W;let G=w(W,"id");if(!G)return W;let $=Z1({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 HH(W,$.urls);let z=X==="sequence"?$.urls.sequence:X==="landingPage"?$.urls.landingPage:X==="template"?$.urls.email:$.urls.transactionalEmail;return Y4(W,z)})}function aV(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!J0(Y))return Y;let X=w(Y,"id");if(!X)return Y;let W=Z1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var AH=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 sV(Q,Y,X){if(!J0(X)||!AH.has(Q))return X;let W=J0(X.company)?X.company:void 0,$=w(X,"selectedCompanyId")??w(X,"currentCompanyId")??w(X,"companyId")??(W?w(W,"id"):void 0)??(W?w(W,"companyId"):void 0)??await JX(Y);if(!$)return X;let z=J0(X.campaign)?X.campaign:void 0,J=J0(X.sequence)?X.sequence:void 0,H=J0(X.landingPage)?X.landingPage:void 0,A=J0(X.template)?X.template:void 0,U=J0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,K={companyId:$,campaignId:w(Y,"campaignId")??w(X,"campaignId")??(z?w(z,"id"):void 0),landingPageId:w(Y,"landingPageId")??w(X,"landingPageId")??(H?w(H,"id"):void 0),sequenceId:w(Y,"sequenceId")??w(X,"sequenceId")??(J?w(J,"id"):void 0),emailId:w(X,"templateId")??(A?w(A,"id"):void 0)??(U?w(U,"emailId"):void 0)??w(Y,"templateId"),transactionalId:w(Y,"transactionalId")??(U?w(U,"id"):void 0)??w(Y,"idOrSlug"),emailSendId:w(Y,"emailSendId")??w(X,"emailSendId")??(J0(X.emailSend)?w(X.emailSend,"id"):void 0),status:w(Y,"status")},D=Z1(K),L=W?Z1({companyId:$}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:aV(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}},...z&&D.urls.campaign!==void 0&&{campaign:HH(z,D.urls)},...J&&D.urls.sequence!==void 0&&{sequence:Y4(J,D.urls.sequence)},...H&&D.urls.landingPage!==void 0&&{landingPage:Y4(H,D.urls.landingPage)},...A&&D.urls.email!==void 0&&{template:Y4(A,D.urls.email)},...U&&D.urls.transactionalEmail!==void 0&&{transactional:Y4(U,D.urls.transactionalEmail)},...J0(X.emailSend)&&D.urls.emailSend!==void 0&&{emailSend:Y4(X.emailSend,D.urls.emailSend)},appUrls:D.urls}}var eV={type:"boolean",description:"Whether the Sequenzy operation succeeded."},QZ={type:"string",description:"Human-readable status, confirmation, or next-step message."},YZ={type:"string",description:"Additional context about the result."};function W0(Q){return{type:"object",description:Q,additionalProperties:!0}}function XZ(Q){return{type:"array",description:Q,items:W0("One item in the returned collection.")}}function E(Q){return{type:"string",description:Q}}function b0(Q){return{type:"number",description:Q}}function d0(Q){return{type:"boolean",description:Q}}function V(Q){return W0(`The ${Q} record returned by Sequenzy.`)}function p(Q){return XZ(`List of ${Q} records returned by Sequenzy.`)}var WZ={appUrls:W0("Dashboard URLs for relevant Sequenzy resources."),url:E("Primary dashboard URL for this result."),settingsUrl:E("Company settings URL when available.")},GZ={success:eV,message:QZ,note:YZ,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.")},$Z={get_account:{account:V("account"),companies:p("company"),apiKeyPermissions:W0("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:E("Company ID selected by the authenticated API key, when available."),selectedCompanyId:E("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:E("Selected company ID."),companyName:E("Selected company name.")},get_app_urls:{dashboard:E("Company dashboard URL."),settings:E("Company settings URL."),campaign:E("Campaign editor URL."),landingPage:E("Landing page editor URL."),sequence:E("Sequence editor URL."),email:E("Email editor URL."),transactionalEmail:E("Transactional email URL."),emailSend:E("Sent email detail URL."),domain:E("Sending domain settings URL."),urls:W0("All generated URLs keyed by resource type.")},create_company:{company:V("company"),autoSelected:d0("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:d0("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:d0("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:E("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:E("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:E("Newly created API key if the API response uses the short key field.")},list_websites:{websites:p("sender website")},add_website:{website:V("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},add_sending_domain:{website:V("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},check_website:{website:V("sender website"),ready:d0("Whether the sender website is ready."),status:E("Current processing or verification status.")},verify_sending_domain:{website:V("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:d0("Whether the sending domain passed the fresh verification check."),message:E("Verification result summary.")},get_integration_guide:{guide:V("integration guide"),code:E("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:d0("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:E("Deleted subscriber note ID."),deleted:d0("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:p("subscriber"),pagination:W0("Pagination metadata."),returned:b0("Number of subscribers returned."),truncated:d0("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:E("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:E("Queued product sync job ID.")},list_tags:{tags:p("tag")},create_tag:{tag:V("tag")},update_tag:{tag:V("tag")},delete_tag:{tagId:E("Deleted tag ID.")},list_lists:{lists:p("list")},create_list:{list:V("list")},update_list:{list:V("list")},delete_list:{listId:E("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:E("Deleted segment ID.")},get_segment_count:{count:b0("Number of subscribers matching the segment."),segmentId:E("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:E("Deleted audience sync ID.")},sync_audience_now:{audienceSync:V("audience sync"),job:V("audience sync job"),jobId:E("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:E("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:E("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:E("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:E("Scheduled send timestamp.")},send_test_email:{emailSend:V("test email send"),recipient:E("Test email recipient.")},send_test_sms:{smsSendId:E("Created test SMS send ID."),toPhone:E("Normalized E.164 destination phone.")},cancel_campaign:{campaign:V("campaign")},pause_campaign:{campaign:V("campaign")},resume_campaign:{campaign:V("campaign")},delete_campaign:{campaignId:E("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:E("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:E("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:V("landing page"),domain:E("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:E("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:E("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:E("Sequence ID."),enrollmentPaused:d0("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:E("Sequence ID."),enrollmentPaused:d0("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:E("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:E("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:E("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:E("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:W0("One generated email block.")},subject:E("Generated subject line."),previewText:E("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:E("One generated subject line.")},variants:p("generated subject line variant")},generate_sms:{prompt:E("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 zZ(Q){let Y=$Z[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:{...GZ,...Y,...AH.has(Q)?WZ:{}},additionalProperties:!0}}function JZ(Q){return{...Q,outputSchema:zZ(Q.name)}}function HZ(Q){if(J0(Q))return Q;if(Array.isArray(Q))return{items:Q};return{value:Q}}var AZ=[{name:"get_account",description:`Get current account information including available companies, the current API key's permission scopes, and the API Keys management URL. Call this after a missing-scope error to inspect access and find the replacement-key settings. 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