@sequenzy/mcp 0.0.109 → 0.0.110
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 +1 -1
- package/dist/server.js +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/index.js
CHANGED
|
@@ -26,7 +26,7 @@ var hz=Object.create;var{getPrototypeOf:fz,defineProperty:t$,getOwnPropertyNames
|
|
|
26
26
|
newResult[${R}] = ${h}.value;
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
`)}q.write("payload.value = newResult;"),q.write("return payload;");let k=q.compile();return(S,h)=>k(O,S,h)},G,X=Sw,Y=!O0.jitless,J=Y&&b4.value,D=w.catchall,z;b._zod.parse=(O,q)=>{z??(z=W.value);let B=O.value;if(!X(B))return O.issues.push({expected:"object",code:"invalid_type",input:B,inst:b}),O;if(Y&&J&&q?.async===!1&&q.jitless!==!0){if(!G)G=Q(w.shape);if(O=G(O,q),!D)return O;return f9([],B,O,q,z,b)}return $(O,q)}});function w9(b,w,$,W){for(let G of b)if(G.issues.length===0)return w.value=G.value,w;let Q=b.filter((G)=>!Fw(G));if(Q.length===1)return w.value=Q[0].value,Q[0];return w.issues.push({code:"invalid_union",input:w.value,inst:$,errors:b.map((G)=>G.issues.map((X)=>ub(X,W,Sb())))}),w}var A4=U("$ZodUnion",(b,w)=>{e.init(b,w),o(b._zod,"optin",()=>w.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),o(b._zod,"optout",()=>w.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),o(b._zod,"values",()=>{if(w.options.every((Q)=>Q._zod.values))return new Set(w.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),o(b._zod,"pattern",()=>{if(w.options.every((Q)=>Q._zod.pattern)){let Q=w.options.map((G)=>G._zod.pattern);return new RegExp(`^(${Q.map((G)=>L1(G.source)).join("|")})$`)}return});let $=w.options.length===1,W=w.options[0]._zod.run;b._zod.parse=(Q,G)=>{if($)return W(Q,G);let X=!1,Y=[];for(let H of w.options){let J=H._zod.run({value:Q.value,issues:[]},G);if(J instanceof Promise)Y.push(J),X=!0;else{if(J.issues.length===0)return J;Y.push(J)}}if(!X)return w9(Y,Q,b,G);return Promise.all(Y).then((H)=>{return w9(H,Q,b,G)})}}),g9=U("$ZodDiscriminatedUnion",(b,w)=>{A4.init(b,w);let $=b._zod.parse;o(b._zod,"propValues",()=>{let Q={};for(let G of w.options){let X=G._zod.propValues;if(!X||Object.keys(X).length===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(G)}"`);for(let[Y,H]of Object.entries(X)){if(!Q[Y])Q[Y]=new Set;for(let J of H)Q[Y].add(J)}}return Q});let W=fw(()=>{let Q=w.options,G=new Map;for(let X of Q){let Y=X._zod.propValues?.[w.discriminator];if(!Y||Y.size===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(X)}"`);for(let H of Y){if(G.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);G.set(H,X)}}return G});b._zod.parse=(Q,G)=>{let X=Q.value;if(!Sw(X))return Q.issues.push({code:"invalid_type",expected:"object",input:X,inst:b}),Q;let Y=W.value.get(X?.[w.discriminator]);if(Y)return Y._zod.run(Q,G);if(w.unionFallback)return $(Q,G);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:w.discriminator,input:X,path:[w.discriminator],inst:b}),Q}}),m9=U("$ZodIntersection",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value,G=w.left._zod.run({value:Q,issues:[]},W),X=w.right._zod.run({value:Q,issues:[]},W);if(G instanceof Promise||X instanceof Promise)return Promise.all([G,X]).then(([H,J])=>{return $9($,H,J)});return $9($,G,X)}});function D4(b,w){if(b===w)return{valid:!0,data:b};if(b instanceof Date&&w instanceof Date&&+b===+w)return{valid:!0,data:b};if(Bw(b)&&Bw(w)){let $=Object.keys(w),W=Object.keys(b).filter((G)=>$.indexOf(G)!==-1),Q={...b,...w};for(let G of W){let X=D4(b[G],w[G]);if(!X.valid)return{valid:!1,mergeErrorPath:[G,...X.mergeErrorPath]};Q[G]=X.data}return{valid:!0,data:Q}}if(Array.isArray(b)&&Array.isArray(w)){if(b.length!==w.length)return{valid:!1,mergeErrorPath:[]};let $=[];for(let W=0;W<b.length;W++){let Q=b[W],G=w[W],X=D4(Q,G);if(!X.valid)return{valid:!1,mergeErrorPath:[W,...X.mergeErrorPath]};$.push(X.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function $9(b,w,$){if(w.issues.length)b.issues.push(...w.issues);if($.issues.length)b.issues.push(...$.issues);if(Fw(b))return b;let W=D4(w.value,$.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return b.value=W.data,b}var n9=U("$ZodRecord",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value;if(!Bw(Q))return $.issues.push({expected:"record",code:"invalid_type",input:Q,inst:b}),$;let G=[];if(w.keyType._zod.values){let X=w.keyType._zod.values;$.value={};for(let H of X)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let J=w.valueType._zod.run({value:Q[H],issues:[]},W);if(J instanceof Promise)G.push(J.then((D)=>{if(D.issues.length)$.issues.push(...ww(H,D.issues));$.value[H]=D.value}));else{if(J.issues.length)$.issues.push(...ww(H,J.issues));$.value[H]=J.value}}let Y;for(let H in Q)if(!X.has(H))Y=Y??[],Y.push(H);if(Y&&Y.length>0)$.issues.push({code:"unrecognized_keys",input:Q,inst:b,keys:Y})}else{$.value={};for(let X of Reflect.ownKeys(Q)){if(X==="__proto__")continue;let Y=w.keyType._zod.run({value:X,issues:[]},W);if(Y instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(Y.issues.length){$.issues.push({code:"invalid_key",origin:"record",issues:Y.issues.map((J)=>ub(J,W,Sb())),input:X,path:[X],inst:b}),$.value[Y.value]=Y.value;continue}let H=w.valueType._zod.run({value:Q[X],issues:[]},W);if(H instanceof Promise)G.push(H.then((J)=>{if(J.issues.length)$.issues.push(...ww(X,J.issues));$.value[Y.value]=J.value}));else{if(H.issues.length)$.issues.push(...ww(X,H.issues));$.value[Y.value]=H.value}}}if(G.length)return Promise.all(G).then(()=>$);return $}});var l9=U("$ZodEnum",(b,w)=>{e.init(b,w);let $=s$(w.entries),W=new Set($);b._zod.values=W,b._zod.pattern=new RegExp(`^(${$.filter((Q)=>w4.has(typeof Q)).map((Q)=>typeof Q==="string"?bw(Q):Q.toString()).join("|")})$`),b._zod.parse=(Q,G)=>{let X=Q.value;if(W.has(X))return Q;return Q.issues.push({code:"invalid_value",values:$,input:X,inst:b}),Q}}),i9=U("$ZodLiteral",(b,w)=>{if(e.init(b,w),w.values.length===0)throw Error("Cannot create literal schema with no valid values");b._zod.values=new Set(w.values),b._zod.pattern=new RegExp(`^(${w.values.map(($)=>typeof $==="string"?bw($):$?bw($.toString()):String($)).join("|")})$`),b._zod.parse=($,W)=>{let Q=$.value;if(b._zod.values.has(Q))return $;return $.issues.push({code:"invalid_value",values:w.values,input:Q,inst:b}),$}});var p9=U("$ZodTransform",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{if(W.direction==="backward")throw new A1(b.constructor.name);let Q=w.transform($.value,$);if(W.async)return(Q instanceof Promise?Q:Promise.resolve(Q)).then((X)=>{return $.value=X,$});if(Q instanceof Promise)throw new ab;return $.value=Q,$}});function W9(b,w){if(b.issues.length&&w===void 0)return{issues:[],value:void 0};return b}var o9=U("$ZodOptional",(b,w)=>{e.init(b,w),b._zod.optin="optional",b._zod.optout="optional",o(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,void 0]):void 0}),o(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${L1($.source)})?$`):void 0}),b._zod.parse=($,W)=>{if(w.innerType._zod.optin==="optional"){let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>W9(G,$.value));return W9(Q,$.value)}if($.value===void 0)return $;return w.innerType._zod.run($,W)}}),d9=U("$ZodNullable",(b,w)=>{e.init(b,w),o(b._zod,"optin",()=>w.innerType._zod.optin),o(b._zod,"optout",()=>w.innerType._zod.optout),o(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${L1($.source)}|null)$`):void 0}),o(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,null]):void 0}),b._zod.parse=($,W)=>{if($.value===null)return $;return w.innerType._zod.run($,W)}}),t9=U("$ZodDefault",(b,w)=>{e.init(b,w),b._zod.optin="optional",o(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);if($.value===void 0)return $.value=w.defaultValue,$;let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>Q9(G,w));return Q9(Q,w)}});function Q9(b,w){if(b.value===void 0)b.value=w.defaultValue;return b}var r9=U("$ZodPrefault",(b,w)=>{e.init(b,w),b._zod.optin="optional",o(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);if($.value===void 0)$.value=w.defaultValue;return w.innerType._zod.run($,W)}}),e9=U("$ZodNonOptional",(b,w)=>{e.init(b,w),o(b._zod,"values",()=>{let $=w.innerType._zod.values;return $?new Set([...$].filter((W)=>W!==void 0)):void 0}),b._zod.parse=($,W)=>{let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>G9(G,b));return G9(Q,b)}});function G9(b,w){if(!b.issues.length&&b.value===void 0)b.issues.push({code:"invalid_type",expected:"nonoptional",input:b.value,inst:w});return b}var s9=U("$ZodCatch",(b,w)=>{e.init(b,w),o(b._zod,"optin",()=>w.innerType._zod.optin),o(b._zod,"optout",()=>w.innerType._zod.optout),o(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>{if($.value=G.value,G.issues.length)$.value=w.catchValue({...$,error:{issues:G.issues.map((X)=>ub(X,W,Sb()))},input:$.value}),$.issues=[];return $});if($.value=Q.value,Q.issues.length)$.value=w.catchValue({...$,error:{issues:Q.issues.map((G)=>ub(G,W,Sb()))},input:$.value}),$.issues=[];return $}});var a9=U("$ZodPipe",(b,w)=>{e.init(b,w),o(b._zod,"values",()=>w.in._zod.values),o(b._zod,"optin",()=>w.in._zod.optin),o(b._zod,"optout",()=>w.out._zod.optout),o(b._zod,"propValues",()=>w.in._zod.propValues),b._zod.parse=($,W)=>{if(W.direction==="backward"){let G=w.out._zod.run($,W);if(G instanceof Promise)return G.then((X)=>I0(X,w.in,W));return I0(G,w.in,W)}let Q=w.in._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>I0(G,w.out,W));return I0(Q,w.out,W)}});function I0(b,w,$){if(b.issues.length)return b.aborted=!0,b;return w._zod.run({value:b.value,issues:b.issues},$)}var b8=U("$ZodReadonly",(b,w)=>{e.init(b,w),o(b._zod,"propValues",()=>w.innerType._zod.propValues),o(b._zod,"values",()=>w.innerType._zod.values),o(b._zod,"optin",()=>w.innerType._zod.optin),o(b._zod,"optout",()=>w.innerType._zod.optout),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then(X9);return X9(Q)}});function X9(b){return b.value=Object.freeze(b.value),b}var w8=U("$ZodCustom",(b,w)=>{Jb.init(b,w),e.init(b,w),b._zod.parse=($,W)=>{return $},b._zod.check=($)=>{let W=$.value,Q=w.fn(W);if(Q instanceof Promise)return Q.then((G)=>Y9(G,$,W,b));Y9(Q,$,W,b);return}});function Y9(b,w,$,W){if(!b){let Q={code:"custom",input:$,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)Q.params=W._zod.def.params;w.issues.push(cw(Q))}}var S7=(b)=>{let w=typeof b;switch(w){case"number":return Number.isNaN(b)?"NaN":"number";case"object":{if(Array.isArray(b))return"array";if(b===null)return"null";if(Object.getPrototypeOf(b)!==Object.prototype&&b.constructor)return b.constructor.name}}return w},R7=()=>{let b={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 w(W){return b[W]??null}let $={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 ${S7(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${B0(W.values[0])}`;return`Invalid option: expected one of ${q0(W.values,"|")}`;case"too_big":{let Q=W.inclusive?"<=":"<",G=w(W.origin);if(G)return`Too big: expected ${W.origin??"value"} to have ${Q}${W.maximum.toString()} ${G.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${Q}${W.maximum.toString()}`}case"too_small":{let Q=W.inclusive?">=":">",G=w(W.origin);if(G)return`Too small: expected ${W.origin} to have ${Q}${W.minimum.toString()} ${G.unit}`;return`Too small: expected ${W.origin} to be ${Q}${W.minimum.toString()}`}case"invalid_format":{let Q=W;if(Q.format==="starts_with")return`Invalid string: must start with "${Q.prefix}"`;if(Q.format==="ends_with")return`Invalid string: must end with "${Q.suffix}"`;if(Q.format==="includes")return`Invalid string: must include "${Q.includes}"`;if(Q.format==="regex")return`Invalid string: must match pattern ${Q.pattern}`;return`Invalid ${$[Q.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":""}: ${q0(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 O4(){return{localeError:R7()}}var oM=Symbol("ZodOutput"),dM=Symbol("ZodInput");class $8{constructor(){this._map=new WeakMap,this._idmap=new Map}add(b,...w){let $=w[0];if(this._map.set(b,$),$&&typeof $==="object"&&"id"in $){if(this._idmap.has($.id))throw Error(`ID ${$.id} already exists in the registry`);this._idmap.set($.id,b)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(b){let w=this._map.get(b);if(w&&typeof w==="object"&&"id"in w)this._idmap.delete(w.id);return this._map.delete(b),this}get(b){let w=b._zod.parent;if(w){let $={...this.get(w)??{}};delete $.id;let W={...$,...this._map.get(b)};return Object.keys(W).length?W:void 0}return this._map.get(b)}has(b){return this._map.has(b)}}function k7(){return new $8}var M1=k7();function W8(b,w){return new b({type:"string",..._(w)})}function Q8(b,w){return new b({type:"string",format:"email",check:"string_format",abort:!1,..._(w)})}function q4(b,w){return new b({type:"string",format:"guid",check:"string_format",abort:!1,..._(w)})}function G8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,..._(w)})}function X8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",..._(w)})}function Y8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",..._(w)})}function H8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",..._(w)})}function J8(b,w){return new b({type:"string",format:"url",check:"string_format",abort:!1,..._(w)})}function D8(b,w){return new b({type:"string",format:"emoji",check:"string_format",abort:!1,..._(w)})}function z8(b,w){return new b({type:"string",format:"nanoid",check:"string_format",abort:!1,..._(w)})}function A8(b,w){return new b({type:"string",format:"cuid",check:"string_format",abort:!1,..._(w)})}function O8(b,w){return new b({type:"string",format:"cuid2",check:"string_format",abort:!1,..._(w)})}function q8(b,w){return new b({type:"string",format:"ulid",check:"string_format",abort:!1,..._(w)})}function L8(b,w){return new b({type:"string",format:"xid",check:"string_format",abort:!1,..._(w)})}function U8(b,w){return new b({type:"string",format:"ksuid",check:"string_format",abort:!1,..._(w)})}function B8(b,w){return new b({type:"string",format:"ipv4",check:"string_format",abort:!1,..._(w)})}function F8(b,w){return new b({type:"string",format:"ipv6",check:"string_format",abort:!1,..._(w)})}function K8(b,w){return new b({type:"string",format:"cidrv4",check:"string_format",abort:!1,..._(w)})}function P8(b,w){return new b({type:"string",format:"cidrv6",check:"string_format",abort:!1,..._(w)})}function M8(b,w){return new b({type:"string",format:"base64",check:"string_format",abort:!1,..._(w)})}function Z8(b,w){return new b({type:"string",format:"base64url",check:"string_format",abort:!1,..._(w)})}function I8(b,w){return new b({type:"string",format:"e164",check:"string_format",abort:!1,..._(w)})}function j8(b,w){return new b({type:"string",format:"jwt",check:"string_format",abort:!1,..._(w)})}function V8(b,w){return new b({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,..._(w)})}function N8(b,w){return new b({type:"string",format:"date",check:"string_format",..._(w)})}function E8(b,w){return new b({type:"string",format:"time",check:"string_format",precision:null,..._(w)})}function T8(b,w){return new b({type:"string",format:"duration",check:"string_format",..._(w)})}function _8(b,w){return new b({type:"number",checks:[],..._(w)})}function S8(b,w){return new b({type:"number",check:"number_format",abort:!1,format:"safeint",..._(w)})}function R8(b,w){return new b({type:"boolean",..._(w)})}function k8(b,w){return new b({type:"null",..._(w)})}function v8(b){return new b({type:"unknown"})}function C8(b,w){return new b({type:"never",..._(w)})}function N0(b,w){return new Y4({check:"less_than",..._(w),value:b,inclusive:!1})}function Z1(b,w){return new Y4({check:"less_than",..._(w),value:b,inclusive:!0})}function E0(b,w){return new H4({check:"greater_than",..._(w),value:b,inclusive:!1})}function I1(b,w){return new H4({check:"greater_than",..._(w),value:b,inclusive:!0})}function T0(b,w){return new cQ({check:"multiple_of",..._(w),value:b})}function _0(b,w){return new mQ({check:"max_length",..._(w),maximum:b})}function gw(b,w){return new nQ({check:"min_length",..._(w),minimum:b})}function S0(b,w){return new lQ({check:"length_equals",..._(w),length:b})}function L4(b,w){return new iQ({check:"string_format",format:"regex",..._(w),pattern:b})}function U4(b){return new pQ({check:"string_format",format:"lowercase",..._(b)})}function B4(b){return new oQ({check:"string_format",format:"uppercase",..._(b)})}function F4(b,w){return new dQ({check:"string_format",format:"includes",..._(w),includes:b})}function K4(b,w){return new tQ({check:"string_format",format:"starts_with",..._(w),prefix:b})}function P4(b,w){return new rQ({check:"string_format",format:"ends_with",..._(w),suffix:b})}function Rw(b){return new eQ({check:"overwrite",tx:b})}function M4(b){return Rw((w)=>w.normalize(b))}function Z4(){return Rw((b)=>b.trim())}function I4(){return Rw((b)=>b.toLowerCase())}function j4(){return Rw((b)=>b.toUpperCase())}function x8(b,w,$){return new b({type:"array",element:w,..._($)})}function u8(b,w,$){let W=_($);return W.abort??(W.abort=!0),new b({type:"custom",check:"custom",fn:w,...W})}function y8(b,w,$){return new b({type:"custom",check:"custom",fn:w,..._($)})}function h8(b){let w=v7(($)=>{return $.addIssue=(W)=>{if(typeof W==="string")$.issues.push(cw(W,$.value,w._zod.def));else{let Q=W;if(Q.fatal)Q.continue=!1;Q.code??(Q.code="custom"),Q.input??(Q.input=$.value),Q.inst??(Q.inst=w),Q.continue??(Q.continue=!w._zod.def.abort),$.issues.push(cw(Q))}},b($.value,$)});return w}function v7(b,w){let $=new Jb({check:"custom",..._(w)});return $._zod.check=b,$}function mw(b){return!!b._zod}function Kw(b,w){if(mw(b))return F1(b,w);return b.safeParse(w)}function R0(b){if(!b)return;let w;if(mw(b))w=b._zod?.def?.shape;else w=b.shape;if(!w)return;if(typeof w==="function")try{return w()}catch{return}return w}function f8(b){if(mw(b)){let G=b._zod?.def;if(G){if(G.value!==void 0)return G.value;if(Array.isArray(G.values)&&G.values.length>0)return G.values[0]}}let $=b._def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}let W=b.value;if(W!==void 0)return W;return}var V1={};xW(V1,{time:()=>E4,duration:()=>T4,datetime:()=>V4,date:()=>N4,ZodISOTime:()=>m8,ZodISODuration:()=>n8,ZodISODateTime:()=>c8,ZodISODate:()=>g8});var c8=U("ZodISODateTime",(b,w)=>{K9.init(b,w),bb.init(b,w)});function V4(b){return V8(c8,b)}var g8=U("ZodISODate",(b,w)=>{P9.init(b,w),bb.init(b,w)});function N4(b){return N8(g8,b)}var m8=U("ZodISOTime",(b,w)=>{M9.init(b,w),bb.init(b,w)});function E4(b){return E8(m8,b)}var n8=U("ZodISODuration",(b,w)=>{Z9.init(b,w),bb.init(b,w)});function T4(b){return T8(n8,b)}var l8=(b,w)=>{F0.init(b,w),b.name="ZodError",Object.defineProperties(b,{format:{value:($)=>wQ(b,$)},flatten:{value:($)=>bQ(b,$)},addIssue:{value:($)=>{b.issues.push($),b.message=JSON.stringify(b.issues,hw,2)}},addIssues:{value:($)=>{b.issues.push(...$),b.message=JSON.stringify(b.issues,hw,2)}},isEmpty:{get(){return b.issues.length===0}}})},vZ=U("ZodError",l8),Eb=U("ZodError",l8,{Parent:Error});var i8=K0(Eb),p8=P0(Eb),o8=B1(Eb),d8=K1(Eb),t8=$Q(Eb),r8=WQ(Eb),e8=QQ(Eb),s8=GQ(Eb),a8=XQ(Eb),bG=YQ(Eb),wG=HQ(Eb),$G=JQ(Eb);var Qb=U("ZodType",(b,w)=>{return e.init(b,w),b.def=w,b.type=w.type,Object.defineProperty(b,"_def",{value:w}),b.check=(...$)=>{return b.clone(n.mergeDefs(w,{checks:[...w.checks??[],...$.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},b.clone=($,W)=>xb(b,$,W),b.brand=()=>b,b.register=($,W)=>{return $.add(b,W),b},b.parse=($,W)=>i8(b,$,W,{callee:b.parse}),b.safeParse=($,W)=>o8(b,$,W),b.parseAsync=async($,W)=>p8(b,$,W,{callee:b.parseAsync}),b.safeParseAsync=async($,W)=>d8(b,$,W),b.spa=b.safeParseAsync,b.encode=($,W)=>t8(b,$,W),b.decode=($,W)=>r8(b,$,W),b.encodeAsync=async($,W)=>e8(b,$,W),b.decodeAsync=async($,W)=>s8(b,$,W),b.safeEncode=($,W)=>a8(b,$,W),b.safeDecode=($,W)=>bG(b,$,W),b.safeEncodeAsync=async($,W)=>wG(b,$,W),b.safeDecodeAsync=async($,W)=>$G(b,$,W),b.refine=($,W)=>b.check(_5($,W)),b.superRefine=($)=>b.check(S5($)),b.overwrite=($)=>b.check(Rw($)),b.optional=()=>Wb(b),b.nullable=()=>GG(b),b.nullish=()=>Wb(GG(b)),b.nonoptional=($)=>I5(b,$),b.array=()=>f(b),b.or=($)=>r([b,$]),b.and=($)=>v0(b,$),b.transform=($)=>S4(b,DG($)),b.default=($)=>P5(b,$),b.prefault=($)=>Z5(b,$),b.catch=($)=>V5(b,$),b.pipe=($)=>S4(b,$),b.readonly=()=>T5(b),b.describe=($)=>{let W=b.clone();return M1.add(W,{description:$}),W},Object.defineProperty(b,"description",{get(){return M1.get(b)?.description},configurable:!0}),b.meta=(...$)=>{if($.length===0)return M1.get(b);let W=b.clone();return M1.add(W,$[0]),W},b.isOptional=()=>b.safeParse(void 0).success,b.isNullable=()=>b.safeParse(null).success,b}),XG=U("_ZodString",(b,w)=>{V0.init(b,w),Qb.init(b,w);let $=b._zod.bag;b.format=$.format??null,b.minLength=$.minimum??null,b.maxLength=$.maximum??null,b.regex=(...W)=>b.check(L4(...W)),b.includes=(...W)=>b.check(F4(...W)),b.startsWith=(...W)=>b.check(K4(...W)),b.endsWith=(...W)=>b.check(P4(...W)),b.min=(...W)=>b.check(gw(...W)),b.max=(...W)=>b.check(_0(...W)),b.length=(...W)=>b.check(S0(...W)),b.nonempty=(...W)=>b.check(gw(1,...W)),b.lowercase=(W)=>b.check(U4(W)),b.uppercase=(W)=>b.check(B4(W)),b.trim=()=>b.check(Z4()),b.normalize=(...W)=>b.check(M4(...W)),b.toLowerCase=()=>b.check(I4()),b.toUpperCase=()=>b.check(j4())}),m7=U("ZodString",(b,w)=>{V0.init(b,w),XG.init(b,w),b.email=($)=>b.check(Q8(n7,$)),b.url=($)=>b.check(J8(l7,$)),b.jwt=($)=>b.check(j8(G5,$)),b.emoji=($)=>b.check(D8(i7,$)),b.guid=($)=>b.check(q4(WG,$)),b.uuid=($)=>b.check(G8(k0,$)),b.uuidv4=($)=>b.check(X8(k0,$)),b.uuidv6=($)=>b.check(Y8(k0,$)),b.uuidv7=($)=>b.check(H8(k0,$)),b.nanoid=($)=>b.check(z8(p7,$)),b.guid=($)=>b.check(q4(WG,$)),b.cuid=($)=>b.check(A8(o7,$)),b.cuid2=($)=>b.check(O8(d7,$)),b.ulid=($)=>b.check(q8(t7,$)),b.base64=($)=>b.check(M8($5,$)),b.base64url=($)=>b.check(Z8(W5,$)),b.xid=($)=>b.check(L8(r7,$)),b.ksuid=($)=>b.check(U8(e7,$)),b.ipv4=($)=>b.check(B8(s7,$)),b.ipv6=($)=>b.check(F8(a7,$)),b.cidrv4=($)=>b.check(K8(b5,$)),b.cidrv6=($)=>b.check(P8(w5,$)),b.e164=($)=>b.check(I8(Q5,$)),b.datetime=($)=>b.check(V4($)),b.date=($)=>b.check(N4($)),b.time=($)=>b.check(E4($)),b.duration=($)=>b.check(T4($))});function L(b){return W8(m7,b)}var bb=U("ZodStringFormat",(b,w)=>{s.init(b,w),XG.init(b,w)}),n7=U("ZodEmail",(b,w)=>{D9.init(b,w),bb.init(b,w)});var WG=U("ZodGUID",(b,w)=>{H9.init(b,w),bb.init(b,w)});var k0=U("ZodUUID",(b,w)=>{J9.init(b,w),bb.init(b,w)});var l7=U("ZodURL",(b,w)=>{z9.init(b,w),bb.init(b,w)});var i7=U("ZodEmoji",(b,w)=>{A9.init(b,w),bb.init(b,w)});var p7=U("ZodNanoID",(b,w)=>{O9.init(b,w),bb.init(b,w)});var o7=U("ZodCUID",(b,w)=>{q9.init(b,w),bb.init(b,w)});var d7=U("ZodCUID2",(b,w)=>{L9.init(b,w),bb.init(b,w)});var t7=U("ZodULID",(b,w)=>{U9.init(b,w),bb.init(b,w)});var r7=U("ZodXID",(b,w)=>{B9.init(b,w),bb.init(b,w)});var e7=U("ZodKSUID",(b,w)=>{F9.init(b,w),bb.init(b,w)});var s7=U("ZodIPv4",(b,w)=>{I9.init(b,w),bb.init(b,w)});var a7=U("ZodIPv6",(b,w)=>{j9.init(b,w),bb.init(b,w)});var b5=U("ZodCIDRv4",(b,w)=>{V9.init(b,w),bb.init(b,w)});var w5=U("ZodCIDRv6",(b,w)=>{N9.init(b,w),bb.init(b,w)});var $5=U("ZodBase64",(b,w)=>{T9.init(b,w),bb.init(b,w)});var W5=U("ZodBase64URL",(b,w)=>{_9.init(b,w),bb.init(b,w)});var Q5=U("ZodE164",(b,w)=>{S9.init(b,w),bb.init(b,w)});var G5=U("ZodJWT",(b,w)=>{R9.init(b,w),bb.init(b,w)});var YG=U("ZodNumber",(b,w)=>{z4.init(b,w),Qb.init(b,w),b.gt=(W,Q)=>b.check(E0(W,Q)),b.gte=(W,Q)=>b.check(I1(W,Q)),b.min=(W,Q)=>b.check(I1(W,Q)),b.lt=(W,Q)=>b.check(N0(W,Q)),b.lte=(W,Q)=>b.check(Z1(W,Q)),b.max=(W,Q)=>b.check(Z1(W,Q)),b.int=(W)=>b.check(QG(W)),b.safe=(W)=>b.check(QG(W)),b.positive=(W)=>b.check(E0(0,W)),b.nonnegative=(W)=>b.check(I1(0,W)),b.negative=(W)=>b.check(N0(0,W)),b.nonpositive=(W)=>b.check(Z1(0,W)),b.multipleOf=(W,Q)=>b.check(T0(W,Q)),b.step=(W,Q)=>b.check(T0(W,Q)),b.finite=()=>b;let $=b._zod.bag;b.minValue=Math.max($.minimum??Number.NEGATIVE_INFINITY,$.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,b.maxValue=Math.min($.maximum??Number.POSITIVE_INFINITY,$.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,b.isInt=($.format??"").includes("int")||Number.isSafeInteger($.multipleOf??0.5),b.isFinite=!0,b.format=$.format??null});function p(b){return _8(YG,b)}var X5=U("ZodNumberFormat",(b,w)=>{k9.init(b,w),YG.init(b,w)});function QG(b){return S8(X5,b)}var Y5=U("ZodBoolean",(b,w)=>{v9.init(b,w),Qb.init(b,w)});function Hb(b){return R8(Y5,b)}var H5=U("ZodNull",(b,w)=>{C9.init(b,w),Qb.init(b,w)});function R4(b){return k8(H5,b)}var J5=U("ZodUnknown",(b,w)=>{x9.init(b,w),Qb.init(b,w)});function wb(){return v8(J5)}var D5=U("ZodNever",(b,w)=>{u9.init(b,w),Qb.init(b,w)});function z5(b){return C8(D5,b)}var A5=U("ZodArray",(b,w)=>{y9.init(b,w),Qb.init(b,w),b.element=w.element,b.min=($,W)=>b.check(gw($,W)),b.nonempty=($)=>b.check(gw(1,$)),b.max=($,W)=>b.check(_0($,W)),b.length=($,W)=>b.check(S0($,W)),b.unwrap=()=>b.element});function f(b,w){return x8(A5,b,w)}var HG=U("ZodObject",(b,w)=>{c9.init(b,w),Qb.init(b,w),n.defineLazy(b,"shape",()=>{return w.shape}),b.keyof=()=>Pb(Object.keys(b._zod.def.shape)),b.catchall=($)=>b.clone({...b._zod.def,catchall:$}),b.passthrough=()=>b.clone({...b._zod.def,catchall:wb()}),b.loose=()=>b.clone({...b._zod.def,catchall:wb()}),b.strict=()=>b.clone({...b._zod.def,catchall:z5()}),b.strip=()=>b.clone({...b._zod.def,catchall:void 0}),b.extend=($)=>{return n.extend(b,$)},b.safeExtend=($)=>{return n.safeExtend(b,$)},b.merge=($)=>n.merge(b,$),b.pick=($)=>n.pick(b,$),b.omit=($)=>n.omit(b,$),b.partial=(...$)=>n.partial(zG,b,$[0]),b.required=(...$)=>n.required(AG,b,$[0])});function V(b,w){let $={type:"object",shape:b??{},...n.normalizeParams(w)};return new HG($)}function Ub(b,w){return new HG({type:"object",shape:b,catchall:wb(),...n.normalizeParams(w)})}var JG=U("ZodUnion",(b,w)=>{A4.init(b,w),Qb.init(b,w),b.options=w.options});function r(b,w){return new JG({type:"union",options:b,...n.normalizeParams(w)})}var O5=U("ZodDiscriminatedUnion",(b,w)=>{JG.init(b,w),g9.init(b,w)});function k4(b,w,$){return new O5({type:"union",options:w,discriminator:b,...n.normalizeParams($)})}var q5=U("ZodIntersection",(b,w)=>{m9.init(b,w),Qb.init(b,w)});function v0(b,w){return new q5({type:"intersection",left:b,right:w})}var L5=U("ZodRecord",(b,w)=>{n9.init(b,w),Qb.init(b,w),b.keyType=w.keyType,b.valueType=w.valueType});function $b(b,w,$){return new L5({type:"record",keyType:b,valueType:w,...n.normalizeParams($)})}var _4=U("ZodEnum",(b,w)=>{l9.init(b,w),Qb.init(b,w),b.enum=w.entries,b.options=Object.values(w.entries);let $=new Set(Object.keys(w.entries));b.extract=(W,Q)=>{let G={};for(let X of W)if($.has(X))G[X]=w.entries[X];else throw Error(`Key ${X} not found in enum`);return new _4({...w,checks:[],...n.normalizeParams(Q),entries:G})},b.exclude=(W,Q)=>{let G={...w.entries};for(let X of W)if($.has(X))delete G[X];else throw Error(`Key ${X} not found in enum`);return new _4({...w,checks:[],...n.normalizeParams(Q),entries:G})}});function Pb(b,w){let $=Array.isArray(b)?Object.fromEntries(b.map((W)=>[W,W])):b;return new _4({type:"enum",entries:$,...n.normalizeParams(w)})}var U5=U("ZodLiteral",(b,w)=>{i9.init(b,w),Qb.init(b,w),b.values=new Set(w.values),Object.defineProperty(b,"value",{get(){if(w.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return w.values[0]}})});function N(b,w){return new U5({type:"literal",values:Array.isArray(b)?b:[b],...n.normalizeParams(w)})}var B5=U("ZodTransform",(b,w)=>{p9.init(b,w),Qb.init(b,w),b._zod.parse=($,W)=>{if(W.direction==="backward")throw new A1(b.constructor.name);$.addIssue=(G)=>{if(typeof G==="string")$.issues.push(n.issue(G,$.value,w));else{let X=G;if(X.fatal)X.continue=!1;X.code??(X.code="custom"),X.input??(X.input=$.value),X.inst??(X.inst=b),$.issues.push(n.issue(X))}};let Q=w.transform($.value,$);if(Q instanceof Promise)return Q.then((G)=>{return $.value=G,$});return $.value=Q,$}});function DG(b){return new B5({type:"transform",transform:b})}var zG=U("ZodOptional",(b,w)=>{o9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function Wb(b){return new zG({type:"optional",innerType:b})}var F5=U("ZodNullable",(b,w)=>{d9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function GG(b){return new F5({type:"nullable",innerType:b})}var K5=U("ZodDefault",(b,w)=>{t9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeDefault=b.unwrap});function P5(b,w){return new K5({type:"default",innerType:b,get defaultValue(){return typeof w==="function"?w():n.shallowClone(w)}})}var M5=U("ZodPrefault",(b,w)=>{r9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function Z5(b,w){return new M5({type:"prefault",innerType:b,get defaultValue(){return typeof w==="function"?w():n.shallowClone(w)}})}var AG=U("ZodNonOptional",(b,w)=>{e9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function I5(b,w){return new AG({type:"nonoptional",innerType:b,...n.normalizeParams(w)})}var j5=U("ZodCatch",(b,w)=>{s9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeCatch=b.unwrap});function V5(b,w){return new j5({type:"catch",innerType:b,catchValue:typeof w==="function"?w:()=>w})}var N5=U("ZodPipe",(b,w)=>{a9.init(b,w),Qb.init(b,w),b.in=w.in,b.out=w.out});function S4(b,w){return new N5({type:"pipe",in:b,out:w})}var E5=U("ZodReadonly",(b,w)=>{b8.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function T5(b){return new E5({type:"readonly",innerType:b})}var OG=U("ZodCustom",(b,w)=>{w8.init(b,w),Qb.init(b,w)});function qG(b,w){return u8(OG,b??(()=>!0),w)}function _5(b,w={}){return y8(OG,b,w)}function S5(b){return h8(b)}function v4(b,w){return S4(DG(b),w)}Sb(O4());var C4="2025-11-25";var LG=[C4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Pw="io.modelcontextprotocol/related-task",x0="2.0",Db=qG((b)=>b!==null&&(typeof b==="object"||typeof b==="function")),UG=r([L(),p().int()]),BG=L(),TI=Ub({ttl:r([p(),R4()]).optional(),pollInterval:p().optional()}),R5=V({ttl:p().optional()}),k5=V({taskId:L()}),x4=Ub({progressToken:UG.optional(),[Pw]:k5.optional()}),Tb=V({_meta:x4.optional()}),N1=Tb.extend({task:R5.optional()}),FG=(b)=>N1.safeParse(b).success,zb=V({method:L(),params:Tb.loose().optional()}),Rb=V({_meta:x4.optional()}),kb=V({method:L(),params:Rb.loose().optional()}),Ab=Ub({_meta:x4.optional()}),u0=r([L(),p().int()]),KG=V({jsonrpc:N(x0),id:u0,...zb.shape}).strict(),u4=(b)=>KG.safeParse(b).success,PG=V({jsonrpc:N(x0),...kb.shape}).strict(),MG=(b)=>PG.safeParse(b).success,y4=V({jsonrpc:N(x0),id:u0,result:Ab}).strict(),E1=(b)=>y4.safeParse(b).success;var c;(function(b){b[b.ConnectionClosed=-32000]="ConnectionClosed",b[b.RequestTimeout=-32001]="RequestTimeout",b[b.ParseError=-32700]="ParseError",b[b.InvalidRequest=-32600]="InvalidRequest",b[b.MethodNotFound=-32601]="MethodNotFound",b[b.InvalidParams=-32602]="InvalidParams",b[b.InternalError=-32603]="InternalError",b[b.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(c||(c={}));var h4=V({jsonrpc:N(x0),id:u0.optional(),error:V({code:p().int(),message:L(),data:wb().optional()})}).strict();var ZG=(b)=>h4.safeParse(b).success;var IG=r([KG,PG,y4,h4]),_I=r([y4,h4]),y0=Ab.strict(),v5=Rb.extend({requestId:u0.optional(),reason:L().optional()}),h0=kb.extend({method:N("notifications/cancelled"),params:v5}),C5=V({src:L(),mimeType:L().optional(),sizes:f(L()).optional(),theme:Pb(["light","dark"]).optional()}),T1=V({icons:f(C5).optional()}),nw=V({name:L(),title:L().optional()}),jG=nw.extend({...nw.shape,...T1.shape,version:L(),websiteUrl:L().optional(),description:L().optional()}),x5=v0(V({applyDefaults:Hb().optional()}),$b(L(),wb())),u5=v4((b)=>{if(b&&typeof b==="object"&&!Array.isArray(b)){if(Object.keys(b).length===0)return{form:{}}}return b},v0(V({form:x5.optional(),url:Db.optional()}),$b(L(),wb()).optional())),y5=Ub({list:Db.optional(),cancel:Db.optional(),requests:Ub({sampling:Ub({createMessage:Db.optional()}).optional(),elicitation:Ub({create:Db.optional()}).optional()}).optional()}),h5=Ub({list:Db.optional(),cancel:Db.optional(),requests:Ub({tools:Ub({call:Db.optional()}).optional()}).optional()}),f5=V({experimental:$b(L(),Db).optional(),sampling:V({context:Db.optional(),tools:Db.optional()}).optional(),elicitation:u5.optional(),roots:V({listChanged:Hb().optional()}).optional(),tasks:y5.optional()}),c5=Tb.extend({protocolVersion:L(),capabilities:f5,clientInfo:jG}),f4=zb.extend({method:N("initialize"),params:c5});var g5=V({experimental:$b(L(),Db).optional(),logging:Db.optional(),completions:Db.optional(),prompts:V({listChanged:Hb().optional()}).optional(),resources:V({subscribe:Hb().optional(),listChanged:Hb().optional()}).optional(),tools:V({listChanged:Hb().optional()}).optional(),tasks:h5.optional()}),m5=Ab.extend({protocolVersion:L(),capabilities:g5,serverInfo:jG,instructions:L().optional()}),c4=kb.extend({method:N("notifications/initialized"),params:Rb.optional()});var f0=zb.extend({method:N("ping"),params:Tb.optional()}),n5=V({progress:p(),total:Wb(p()),message:Wb(L())}),l5=V({...Rb.shape,...n5.shape,progressToken:UG}),c0=kb.extend({method:N("notifications/progress"),params:l5}),i5=Tb.extend({cursor:BG.optional()}),_1=zb.extend({params:i5.optional()}),S1=Ab.extend({nextCursor:BG.optional()}),p5=Pb(["working","input_required","completed","failed","cancelled"]),R1=V({taskId:L(),status:p5,ttl:r([p(),R4()]),createdAt:L(),lastUpdatedAt:L(),pollInterval:Wb(p()),statusMessage:Wb(L())}),lw=Ab.extend({task:R1}),o5=Rb.merge(R1),k1=kb.extend({method:N("notifications/tasks/status"),params:o5}),g0=zb.extend({method:N("tasks/get"),params:Tb.extend({taskId:L()})}),m0=Ab.merge(R1),n0=zb.extend({method:N("tasks/result"),params:Tb.extend({taskId:L()})}),SI=Ab.loose(),l0=_1.extend({method:N("tasks/list")}),i0=S1.extend({tasks:f(R1)}),p0=zb.extend({method:N("tasks/cancel"),params:Tb.extend({taskId:L()})}),VG=Ab.merge(R1),NG=V({uri:L(),mimeType:Wb(L()),_meta:$b(L(),wb()).optional()}),EG=NG.extend({text:L()}),g4=L().refine((b)=>{try{return atob(b),!0}catch{return!1}},{message:"Invalid Base64 string"}),TG=NG.extend({blob:g4}),v1=Pb(["user","assistant"]),iw=V({audience:f(v1).optional(),priority:p().min(0).max(1).optional(),lastModified:V1.datetime({offset:!0}).optional()}),_G=V({...nw.shape,...T1.shape,uri:L(),description:Wb(L()),mimeType:Wb(L()),annotations:iw.optional(),_meta:Wb(Ub({}))}),d5=V({...nw.shape,...T1.shape,uriTemplate:L(),description:Wb(L()),mimeType:Wb(L()),annotations:iw.optional(),_meta:Wb(Ub({}))}),m4=_1.extend({method:N("resources/list")}),t5=S1.extend({resources:f(_G)}),r5=_1.extend({method:N("resources/templates/list")}),e5=S1.extend({resourceTemplates:f(d5)}),n4=Tb.extend({uri:L()}),s5=n4,l4=zb.extend({method:N("resources/read"),params:s5}),a5=Ab.extend({contents:f(r([EG,TG]))}),bA=kb.extend({method:N("notifications/resources/list_changed"),params:Rb.optional()}),wA=n4,$A=zb.extend({method:N("resources/subscribe"),params:wA}),WA=n4,QA=zb.extend({method:N("resources/unsubscribe"),params:WA}),GA=Rb.extend({uri:L()}),XA=kb.extend({method:N("notifications/resources/updated"),params:GA}),YA=V({name:L(),description:Wb(L()),required:Wb(Hb())}),HA=V({...nw.shape,...T1.shape,description:Wb(L()),arguments:Wb(f(YA)),_meta:Wb(Ub({}))}),JA=_1.extend({method:N("prompts/list")}),DA=S1.extend({prompts:f(HA)}),zA=Tb.extend({name:L(),arguments:$b(L(),L()).optional()}),AA=zb.extend({method:N("prompts/get"),params:zA}),i4=V({type:N("text"),text:L(),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),p4=V({type:N("image"),data:g4,mimeType:L(),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),o4=V({type:N("audio"),data:g4,mimeType:L(),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),OA=V({type:N("tool_use"),name:L(),id:L(),input:$b(L(),wb()),_meta:$b(L(),wb()).optional()}),qA=V({type:N("resource"),resource:r([EG,TG]),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),LA=_G.extend({type:N("resource_link")}),d4=r([i4,p4,o4,LA,qA]),UA=V({role:v1,content:d4}),BA=Ab.extend({description:L().optional(),messages:f(UA)}),FA=kb.extend({method:N("notifications/prompts/list_changed"),params:Rb.optional()}),KA=V({title:L().optional(),readOnlyHint:Hb().optional(),destructiveHint:Hb().optional(),idempotentHint:Hb().optional(),openWorldHint:Hb().optional()}),PA=V({taskSupport:Pb(["required","optional","forbidden"]).optional()}),SG=V({...nw.shape,...T1.shape,description:L().optional(),inputSchema:V({type:N("object"),properties:$b(L(),Db).optional(),required:f(L()).optional()}).catchall(wb()),outputSchema:V({type:N("object"),properties:$b(L(),Db).optional(),required:f(L()).optional()}).catchall(wb()).optional(),annotations:KA.optional(),execution:PA.optional(),_meta:$b(L(),wb()).optional()}),t4=_1.extend({method:N("tools/list")}),MA=S1.extend({tools:f(SG)}),o0=Ab.extend({content:f(d4).default([]),structuredContent:$b(L(),wb()).optional(),isError:Hb().optional()}),RI=o0.or(Ab.extend({toolResult:wb()})),ZA=N1.extend({name:L(),arguments:$b(L(),wb()).optional()}),C1=zb.extend({method:N("tools/call"),params:ZA}),IA=kb.extend({method:N("notifications/tools/list_changed"),params:Rb.optional()}),kI=V({autoRefresh:Hb().default(!0),debounceMs:p().int().nonnegative().default(300)}),x1=Pb(["debug","info","notice","warning","error","critical","alert","emergency"]),jA=Tb.extend({level:x1}),r4=zb.extend({method:N("logging/setLevel"),params:jA}),VA=Rb.extend({level:x1,logger:L().optional(),data:wb()}),NA=kb.extend({method:N("notifications/message"),params:VA}),EA=V({name:L().optional()}),TA=V({hints:f(EA).optional(),costPriority:p().min(0).max(1).optional(),speedPriority:p().min(0).max(1).optional(),intelligencePriority:p().min(0).max(1).optional()}),_A=V({mode:Pb(["auto","required","none"]).optional()}),SA=V({type:N("tool_result"),toolUseId:L().describe("The unique identifier for the corresponding tool call."),content:f(d4).default([]),structuredContent:V({}).loose().optional(),isError:Hb().optional(),_meta:$b(L(),wb()).optional()}),RA=k4("type",[i4,p4,o4]),C0=k4("type",[i4,p4,o4,OA,SA]),kA=V({role:v1,content:r([C0,f(C0)]),_meta:$b(L(),wb()).optional()}),vA=N1.extend({messages:f(kA),modelPreferences:TA.optional(),systemPrompt:L().optional(),includeContext:Pb(["none","thisServer","allServers"]).optional(),temperature:p().optional(),maxTokens:p().int(),stopSequences:f(L()).optional(),metadata:Db.optional(),tools:f(SG).optional(),toolChoice:_A.optional()}),CA=zb.extend({method:N("sampling/createMessage"),params:vA}),e4=Ab.extend({model:L(),stopReason:Wb(Pb(["endTurn","stopSequence","maxTokens"]).or(L())),role:v1,content:RA}),s4=Ab.extend({model:L(),stopReason:Wb(Pb(["endTurn","stopSequence","maxTokens","toolUse"]).or(L())),role:v1,content:r([C0,f(C0)])}),xA=V({type:N("boolean"),title:L().optional(),description:L().optional(),default:Hb().optional()}),uA=V({type:N("string"),title:L().optional(),description:L().optional(),minLength:p().optional(),maxLength:p().optional(),format:Pb(["email","uri","date","date-time"]).optional(),default:L().optional()}),yA=V({type:Pb(["number","integer"]),title:L().optional(),description:L().optional(),minimum:p().optional(),maximum:p().optional(),default:p().optional()}),hA=V({type:N("string"),title:L().optional(),description:L().optional(),enum:f(L()),default:L().optional()}),fA=V({type:N("string"),title:L().optional(),description:L().optional(),oneOf:f(V({const:L(),title:L()})),default:L().optional()}),cA=V({type:N("string"),title:L().optional(),description:L().optional(),enum:f(L()),enumNames:f(L()).optional(),default:L().optional()}),gA=r([hA,fA]),mA=V({type:N("array"),title:L().optional(),description:L().optional(),minItems:p().optional(),maxItems:p().optional(),items:V({type:N("string"),enum:f(L())}),default:f(L()).optional()}),nA=V({type:N("array"),title:L().optional(),description:L().optional(),minItems:p().optional(),maxItems:p().optional(),items:V({anyOf:f(V({const:L(),title:L()}))}),default:f(L()).optional()}),lA=r([mA,nA]),iA=r([cA,gA,lA]),pA=r([iA,xA,uA,yA]),oA=N1.extend({mode:N("form").optional(),message:L(),requestedSchema:V({type:N("object"),properties:$b(L(),pA),required:f(L()).optional()})}),dA=N1.extend({mode:N("url"),message:L(),elicitationId:L(),url:L().url()}),tA=r([oA,dA]),rA=zb.extend({method:N("elicitation/create"),params:tA}),eA=Rb.extend({elicitationId:L()}),sA=kb.extend({method:N("notifications/elicitation/complete"),params:eA}),d0=Ab.extend({action:Pb(["accept","decline","cancel"]),content:v4((b)=>b===null?void 0:b,$b(L(),r([L(),p(),Hb(),f(L())])).optional())}),aA=V({type:N("ref/resource"),uri:L()});var bO=V({type:N("ref/prompt"),name:L()}),wO=Tb.extend({ref:r([bO,aA]),argument:V({name:L(),value:L()}),context:V({arguments:$b(L(),L()).optional()}).optional()}),$O=zb.extend({method:N("completion/complete"),params:wO});var WO=Ab.extend({completion:Ub({values:f(L()).max(100),total:Wb(p().int()),hasMore:Wb(Hb())})}),QO=V({uri:L().startsWith("file://"),name:L().optional(),_meta:$b(L(),wb()).optional()}),GO=zb.extend({method:N("roots/list"),params:Tb.optional()}),a4=Ab.extend({roots:f(QO)}),XO=kb.extend({method:N("notifications/roots/list_changed"),params:Rb.optional()}),vI=r([f0,f4,$O,r4,AA,JA,m4,r5,l4,$A,QA,C1,t4,g0,n0,l0,p0]),CI=r([h0,c0,c4,XO,k1]),xI=r([y0,e4,s4,d0,a4,m0,i0,lw]),uI=r([f0,CA,rA,GO,g0,n0,l0,p0]),yI=r([h0,c0,NA,XA,bA,IA,FA,k1,sA]),hI=r([y0,m5,WO,BA,DA,t5,e5,a5,o0,MA,m0,i0,lw]);class x extends Error{constructor(b,w,$){super(`MCP error ${b}: ${w}`);this.code=b,this.data=$,this.name="McpError"}static fromError(b,w,$){if(b===c.UrlElicitationRequired&&$){let W=$;if(W.elicitations)return new RG(W.elicitations,w)}return new x(b,w,$)}}class RG extends x{constructor(b,w=`URL elicitation${b.length>1?"s":""} required`){super(c.UrlElicitationRequired,w,{elicitations:b})}get elicitations(){return this.data?.elicitations??[]}}function Mw(b){return b==="completed"||b==="failed"||b==="cancelled"}var YO=Symbol("Let zodToJsonSchema decide on which parser to use");var Bj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function b6(b){let $=R0(b)?.method;if(!$)throw Error("Schema is missing a method literal");let W=f8($);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function w6(b,w){let $=Kw(b,w);if(!$.success)throw $.error;return $.data}var OO=60000;class $6{constructor(b){if(this._options=b,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(h0,(w)=>{this._oncancel(w)}),this.setNotificationHandler(c0,(w)=>{this._onprogress(w)}),this.setRequestHandler(f0,(w)=>({})),this._taskStore=b?.taskStore,this._taskMessageQueue=b?.taskMessageQueue,this._taskStore)this.setRequestHandler(g0,async(w,$)=>{let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new x(c.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(n0,async(w,$)=>{let W=async()=>{let Q=w.params.taskId;if(this._taskMessageQueue){let X;while(X=await this._taskMessageQueue.dequeue(Q,$.sessionId)){if(X.type==="response"||X.type==="error"){let Y=X.message,H=Y.id,J=this._requestResolvers.get(H);if(J)if(this._requestResolvers.delete(H),X.type==="response")J(Y);else{let D=Y,z=new x(D.error.code,D.error.message,D.error.data);J(z)}else{let D=X.type==="response"?"Response":"Error";this._onerror(Error(`${D} handler missing for request ${H}`))}continue}await this._transport?.send(X.message,{relatedRequestId:$.requestId})}}let G=await this._taskStore.getTask(Q,$.sessionId);if(!G)throw new x(c.InvalidParams,`Task not found: ${Q}`);if(!Mw(G.status))return await this._waitForTaskUpdate(Q,$.signal),await W();if(Mw(G.status)){let X=await this._taskStore.getTaskResult(Q,$.sessionId);return this._clearTaskQueue(Q),{...X,_meta:{...X._meta,[Pw]:{taskId:Q}}}}return await W()};return await W()}),this.setRequestHandler(l0,async(w,$)=>{try{let{tasks:W,nextCursor:Q}=await this._taskStore.listTasks(w.params?.cursor,$.sessionId);return{tasks:W,nextCursor:Q,_meta:{}}}catch(W){throw new x(c.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(p0,async(w,$)=>{try{let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new x(c.InvalidParams,`Task not found: ${w.params.taskId}`);if(Mw(W.status))throw new x(c.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(w.params.taskId,"cancelled","Client cancelled task execution.",$.sessionId),this._clearTaskQueue(w.params.taskId);let Q=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!Q)throw new x(c.InvalidParams,`Task not found after cancellation: ${w.params.taskId}`);return{_meta:{},...Q}}catch(W){if(W instanceof x)throw W;throw new x(c.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(b){if(!b.params.requestId)return;this._requestHandlerAbortControllers.get(b.params.requestId)?.abort(b.params.reason)}_setupTimeout(b,w,$,W,Q=!1){this._timeoutInfo.set(b,{timeoutId:setTimeout(W,w),startTime:Date.now(),timeout:w,maxTotalTimeout:$,resetTimeoutOnProgress:Q,onTimeout:W})}_resetTimeout(b){let w=this._timeoutInfo.get(b);if(!w)return!1;let $=Date.now()-w.startTime;if(w.maxTotalTimeout&&$>=w.maxTotalTimeout)throw this._timeoutInfo.delete(b),x.fromError(c.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:w.maxTotalTimeout,totalElapsed:$});return clearTimeout(w.timeoutId),w.timeoutId=setTimeout(w.onTimeout,w.timeout),!0}_cleanupTimeout(b){let w=this._timeoutInfo.get(b);if(w)clearTimeout(w.timeoutId),this._timeoutInfo.delete(b)}async connect(b){this._transport=b;let w=this.transport?.onclose;this._transport.onclose=()=>{w?.(),this._onclose()};let $=this.transport?.onerror;this._transport.onerror=(Q)=>{$?.(Q),this._onerror(Q)};let W=this._transport?.onmessage;this._transport.onmessage=(Q,G)=>{if(W?.(Q,G),E1(Q)||ZG(Q))this._onresponse(Q);else if(u4(Q))this._onrequest(Q,G);else if(MG(Q))this._onnotification(Q);else this._onerror(Error(`Unknown message type: ${JSON.stringify(Q)}`))},await this._transport.start()}_onclose(){let b=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let w=x.fromError(c.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let $ of b.values())$(w)}_onerror(b){this.onerror?.(b)}_onnotification(b){let w=this._notificationHandlers.get(b.method)??this.fallbackNotificationHandler;if(w===void 0)return;Promise.resolve().then(()=>w(b)).catch(($)=>this._onerror(Error(`Uncaught error in notification handler: ${$}`)))}_onrequest(b,w){let $=this._requestHandlers.get(b.method)??this.fallbackRequestHandler,W=this._transport,Q=b.params?._meta?.[Pw]?.taskId;if($===void 0){let J={jsonrpc:"2.0",id:b.id,error:{code:c.MethodNotFound,message:"Method not found"}};if(Q&&this._taskMessageQueue)this._enqueueTaskMessage(Q,{type:"error",message:J,timestamp:Date.now()},W?.sessionId).catch((D)=>this._onerror(Error(`Failed to enqueue error response: ${D}`)));else W?.send(J).catch((D)=>this._onerror(Error(`Failed to send an error response: ${D}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set(b.id,G);let X=FG(b.params)?b.params.task:void 0,Y=this._taskStore?this.requestTaskStore(b,W?.sessionId):void 0,H={signal:G.signal,sessionId:W?.sessionId,_meta:b.params?._meta,sendNotification:async(J)=>{let D={relatedRequestId:b.id};if(Q)D.relatedTask={taskId:Q};await this.notification(J,D)},sendRequest:async(J,D,z)=>{let O={...z,relatedRequestId:b.id};if(Q&&!O.relatedTask)O.relatedTask={taskId:Q};let q=O.relatedTask?.taskId??Q;if(q&&Y)await Y.updateTaskStatus(q,"input_required");return await this.request(J,D,O)},authInfo:w?.authInfo,requestId:b.id,requestInfo:w?.requestInfo,taskId:Q,taskStore:Y,taskRequestedTtl:X?.ttl,closeSSEStream:w?.closeSSEStream,closeStandaloneSSEStream:w?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(X)this.assertTaskHandlerCapability(b.method)}).then(()=>$(b,H)).then(async(J)=>{if(G.signal.aborted)return;let D={result:J,jsonrpc:"2.0",id:b.id};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"response",message:D,timestamp:Date.now()},W?.sessionId);else await W?.send(D)},async(J)=>{if(G.signal.aborted)return;let D={jsonrpc:"2.0",id:b.id,error:{code:Number.isSafeInteger(J.code)?J.code:c.InternalError,message:J.message??"Internal error",...J.data!==void 0&&{data:J.data}}};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"error",message:D,timestamp:Date.now()},W?.sessionId);else await W?.send(D)}).catch((J)=>this._onerror(Error(`Failed to send response: ${J}`))).finally(()=>{this._requestHandlerAbortControllers.delete(b.id)})}_onprogress(b){let{progressToken:w,...$}=b.params,W=Number(w),Q=this._progressHandlers.get(W);if(!Q){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(b)}`));return}let G=this._responseHandlers.get(W),X=this._timeoutInfo.get(W);if(X&&G&&X.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(Y){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),G(Y);return}Q($)}_onresponse(b){let w=Number(b.id),$=this._requestResolvers.get(w);if($){if(this._requestResolvers.delete(w),E1(b))$(b);else{let G=new x(b.error.code,b.error.message,b.error.data);$(G)}return}let W=this._responseHandlers.get(w);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(b)}`));return}this._responseHandlers.delete(w),this._cleanupTimeout(w);let Q=!1;if(E1(b)&&b.result&&typeof b.result==="object"){let G=b.result;if(G.task&&typeof G.task==="object"){let X=G.task;if(typeof X.taskId==="string")Q=!0,this._taskProgressTokens.set(X.taskId,w)}}if(!Q)this._progressHandlers.delete(w);if(E1(b))W(b);else{let G=x.fromError(b.error.code,b.error.message,b.error.data);W(G)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(b,w,$){let{task:W}=$??{};if(!W){try{yield{type:"result",result:await this.request(b,w,$)}}catch(G){yield{type:"error",error:G instanceof x?G:new x(c.InternalError,String(G))}}return}let Q;try{let G=await this.request(b,lw,$);if(G.task)Q=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new x(c.InternalError,"Task creation did not return a task");while(!0){let X=await this.getTask({taskId:Q},$);if(yield{type:"taskStatus",task:X},Mw(X.status)){if(X.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:Q},w,$)};else if(X.status==="failed")yield{type:"error",error:new x(c.InternalError,`Task ${Q} failed`)};else if(X.status==="cancelled")yield{type:"error",error:new x(c.InternalError,`Task ${Q} was cancelled`)};return}if(X.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:Q},w,$)};return}let Y=X.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,Y)),$?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof x?G:new x(c.InternalError,String(G))}}}request(b,w,$){let{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G,task:X,relatedTask:Y}=$??{};return new Promise((H,J)=>{let D=(M)=>{J(M)};if(!this._transport){D(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(b.method),X)this.assertTaskCapability(b.method)}catch(M){D(M);return}$?.signal?.throwIfAborted();let z=this._requestMessageId++,O={...b,jsonrpc:"2.0",id:z};if($?.onprogress)this._progressHandlers.set(z,$.onprogress),O.params={...b.params,_meta:{...b.params?._meta||{},progressToken:z}};if(X)O.params={...O.params,task:X};if(Y)O.params={...O.params,_meta:{...O.params?._meta||{},[Pw]:Y}};let q=(M)=>{this._responseHandlers.delete(z),this._progressHandlers.delete(z),this._cleanupTimeout(z),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:z,reason:String(M)}},{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let k=M instanceof x?M:new x(c.RequestTimeout,String(M));J(k)};this._responseHandlers.set(z,(M)=>{if($?.signal?.aborted)return;if(M instanceof Error)return J(M);try{let k=Kw(w,M.result);if(!k.success)J(k.error);else H(k.data)}catch(k){J(k)}}),$?.signal?.addEventListener("abort",()=>{q($?.signal?.reason)});let B=$?.timeout??OO,K=()=>q(x.fromError(c.RequestTimeout,"Request timed out",{timeout:B}));this._setupTimeout(z,B,$?.maxTotalTimeout,K,$?.resetTimeoutOnProgress??!1);let Z=Y?.taskId;if(Z){let M=(k)=>{let S=this._responseHandlers.get(z);if(S)S(k);else this._onerror(Error(`Response handler missing for side-channeled request ${z}`))};this._requestResolvers.set(z,M),this._enqueueTaskMessage(Z,{type:"request",message:O,timestamp:Date.now()}).catch((k)=>{this._cleanupTimeout(z),J(k)})}else this._transport.send(O,{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G}).catch((M)=>{this._cleanupTimeout(z),J(M)})})}async getTask(b,w){return this.request({method:"tasks/get",params:b},m0,w)}async getTaskResult(b,w,$){return this.request({method:"tasks/result",params:b},w,$)}async listTasks(b,w){return this.request({method:"tasks/list",params:b},i0,w)}async cancelTask(b,w){return this.request({method:"tasks/cancel",params:b},VG,w)}async notification(b,w){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(b.method);let $=w?.relatedTask?.taskId;if($){let X={...b,jsonrpc:"2.0",params:{...b.params,_meta:{...b.params?._meta||{},[Pw]:w.relatedTask}}};await this._enqueueTaskMessage($,{type:"notification",message:X,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(b.method)&&!b.params&&!w?.relatedRequestId&&!w?.relatedTask){if(this._pendingDebouncedNotifications.has(b.method))return;this._pendingDebouncedNotifications.add(b.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(b.method),!this._transport)return;let X={...b,jsonrpc:"2.0"};if(w?.relatedTask)X={...X,params:{...X.params,_meta:{...X.params?._meta||{},[Pw]:w.relatedTask}}};this._transport?.send(X,w).catch((Y)=>this._onerror(Y))});return}let G={...b,jsonrpc:"2.0"};if(w?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[Pw]:w.relatedTask}}};await this._transport.send(G,w)}setRequestHandler(b,w){let $=b6(b);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(W,Q)=>{let G=w6(b,W);return Promise.resolve(w(G,Q))})}removeRequestHandler(b){this._requestHandlers.delete(b)}assertCanSetRequestHandler(b){if(this._requestHandlers.has(b))throw Error(`A request handler for ${b} already exists, which would be overridden`)}setNotificationHandler(b,w){let $=b6(b);this._notificationHandlers.set($,(W)=>{let Q=w6(b,W);return Promise.resolve(w(Q))})}removeNotificationHandler(b){this._notificationHandlers.delete(b)}_cleanupTaskProgressHandler(b){let w=this._taskProgressTokens.get(b);if(w!==void 0)this._progressHandlers.delete(w),this._taskProgressTokens.delete(b)}async _enqueueTaskMessage(b,w,$){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(b,w,$,W)}async _clearTaskQueue(b,w){if(this._taskMessageQueue){let $=await this._taskMessageQueue.dequeueAll(b,w);for(let W of $)if(W.type==="request"&&u4(W.message)){let Q=W.message.id,G=this._requestResolvers.get(Q);if(G)G(new x(c.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(Q);else this._onerror(Error(`Resolver missing for request ${Q} during task ${b} cleanup`))}}}async _waitForTaskUpdate(b,w){let $=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(b);if(W?.pollInterval)$=W.pollInterval}catch{}return new Promise((W,Q)=>{if(w.aborted){Q(new x(c.InvalidRequest,"Request cancelled"));return}let G=setTimeout(W,$);w.addEventListener("abort",()=>{clearTimeout(G),Q(new x(c.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(b,w){let $=this._taskStore;if(!$)throw Error("No task store configured");return{createTask:async(W)=>{if(!b)throw Error("No request provided");return await $.createTask(W,b.id,{method:b.method,params:b.params},w)},getTask:async(W)=>{let Q=await $.getTask(W,w);if(!Q)throw new x(c.InvalidParams,"Failed to retrieve task: Task not found");return Q},storeTaskResult:async(W,Q,G)=>{await $.storeTaskResult(W,Q,G,w);let X=await $.getTask(W,w);if(X){let Y=k1.parse({method:"notifications/tasks/status",params:X});if(await this.notification(Y),Mw(X.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return $.getTaskResult(W,w)},updateTaskStatus:async(W,Q,G)=>{let X=await $.getTask(W,w);if(!X)throw new x(c.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(Mw(X.status))throw new x(c.InvalidParams,`Cannot update task "${W}" from terminal status "${X.status}" to "${Q}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await $.updateTaskStatus(W,Q,G,w);let Y=await $.getTask(W,w);if(Y){let H=k1.parse({method:"notifications/tasks/status",params:Y});if(await this.notification(H),Mw(Y.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return $.listTasks(W,w)}}}}function kG(b){return b!==null&&typeof b==="object"&&!Array.isArray(b)}function vG(b,w){let $={...b};for(let W in w){let Q=W,G=w[Q];if(G===void 0)continue;let X=$[Q];if(kG(X)&&kG(G))$[Q]={...X,...G};else $[Q]=G}return $}var DD=CW(r6(),1),zD=CW(JD(),1);function ZP(){let b=new DD.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return zD.default(b),b}class XW{constructor(b){this._ajv=b??ZP()}getValidator(b){let w="$id"in b&&typeof b.$id==="string"?this._ajv.getSchema(b.$id)??this._ajv.compile(b):this._ajv.compile(b);return($)=>{if(w($))return{valid:!0,data:$,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(w.errors)}}}}class YW{constructor(b){this._server=b}requestStream(b,w,$){return this._server.requestStream(b,w,$)}async getTask(b,w){return this._server.getTask({taskId:b},w)}async getTaskResult(b,w,$){return this._server.getTaskResult({taskId:b},w,$)}async listTasks(b,w){return this._server.listTasks(b?{cursor:b}:void 0,w)}async cancelTask(b,w){return this._server.cancelTask({taskId:b},w)}}function AD(b,w,$){if(!b)throw Error(`${$} does not support task creation (required for ${w})`);switch(w){case"tools/call":if(!b.tools?.call)throw Error(`${$} does not support task creation for tools/call (required for ${w})`);break;default:break}}function OD(b,w,$){if(!b)throw Error(`${$} does not support task creation (required for ${w})`);switch(w){case"sampling/createMessage":if(!b.sampling?.createMessage)throw Error(`${$} does not support task creation for sampling/createMessage (required for ${w})`);break;case"elicitation/create":if(!b.elicitation?.create)throw Error(`${$} does not support task creation for elicitation/create (required for ${w})`);break;default:break}}class HW extends $6{constructor(b,w){super(w);if(this._serverInfo=b,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(x1.options.map(($,W)=>[$,W])),this.isMessageIgnored=($,W)=>{let Q=this._loggingLevels.get(W);return Q?this.LOG_LEVEL_SEVERITY.get($)<this.LOG_LEVEL_SEVERITY.get(Q):!1},this._capabilities=w?.capabilities??{},this._instructions=w?.instructions,this._jsonSchemaValidator=w?.jsonSchemaValidator??new XW,this.setRequestHandler(f4,($)=>this._oninitialize($)),this.setNotificationHandler(c4,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(r4,async($,W)=>{let Q=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:G}=$.params,X=x1.safeParse(G);if(X.success)this._loggingLevels.set(Q,X.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new YW(this)};return this._experimental}registerCapabilities(b){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=vG(this._capabilities,b)}setRequestHandler(b,w){let W=R0(b)?.method;if(!W)throw Error("Schema is missing a method literal");let Q;if(mw(W)){let X=W;Q=X._zod?.def?.value??X.value}else{let X=W;Q=X._def?.value??X.value}if(typeof Q!=="string")throw Error("Schema method literal must be a string");if(Q==="tools/call"){let X=async(Y,H)=>{let J=Kw(C1,Y);if(!J.success){let q=J.error instanceof Error?J.error.message:String(J.error);throw new x(c.InvalidParams,`Invalid tools/call request: ${q}`)}let{params:D}=J.data,z=await Promise.resolve(w(Y,H));if(D.task){let q=Kw(lw,z);if(!q.success){let B=q.error instanceof Error?q.error.message:String(q.error);throw new x(c.InvalidParams,`Invalid task creation result: ${B}`)}return q.data}let O=Kw(o0,z);if(!O.success){let q=O.error instanceof Error?O.error.message:String(O.error);throw new x(c.InvalidParams,`Invalid tools/call result: ${q}`)}return O.data};return super.setRequestHandler(b,X)}return super.setRequestHandler(b,w)}assertCapabilityForMethod(b){switch(b){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${b})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${b})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${b})`);break;case"ping":break}}assertNotificationCapability(b){switch(b){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);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 ${b})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${b})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${b})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${b})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(b){if(!this._capabilities)return;switch(b){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${b})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${b})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${b})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${b})`);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 ${b})`);break;case"ping":case"initialize":break}}assertTaskCapability(b){OD(this._clientCapabilities?.tasks?.requests,b,"Client")}assertTaskHandlerCapability(b){if(!this._capabilities)return;AD(this._capabilities.tasks?.requests,b,"Server")}async _oninitialize(b){let w=b.params.protocolVersion;return this._clientCapabilities=b.params.capabilities,this._clientVersion=b.params.clientInfo,{protocolVersion:LG.includes(w)?w:C4,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"},y0)}async createMessage(b,w){if(b.tools||b.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(b.messages.length>0){let $=b.messages[b.messages.length-1],W=Array.isArray($.content)?$.content:[$.content],Q=W.some((H)=>H.type==="tool_result"),G=b.messages.length>1?b.messages[b.messages.length-2]:void 0,X=G?Array.isArray(G.content)?G.content:[G.content]:[],Y=X.some((H)=>H.type==="tool_use");if(Q){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!Y)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(Y){let H=new Set(X.filter((D)=>D.type==="tool_use").map((D)=>D.id)),J=new Set(W.filter((D)=>D.type==="tool_result").map((D)=>D.toolUseId));if(H.size!==J.size||![...H].every((D)=>J.has(D)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(b.tools)return this.request({method:"sampling/createMessage",params:b},s4,w);return this.request({method:"sampling/createMessage",params:b},e4,w)}async elicitInput(b,w){switch(b.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=b;return this.request({method:"elicitation/create",params:W},d0,w)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=b.mode==="form"?b:{...b,mode:"form"},Q=await this.request({method:"elicitation/create",params:W},d0,w);if(Q.action==="accept"&&Q.content&&W.requestedSchema)try{let X=this._jsonSchemaValidator.getValidator(W.requestedSchema)(Q.content);if(!X.valid)throw new x(c.InvalidParams,`Elicitation response content does not match requested schema: ${X.errorMessage}`)}catch(G){if(G instanceof x)throw G;throw new x(c.InternalError,`Error validating elicitation response: ${G instanceof Error?G.message:String(G)}`)}return Q}}}createElicitationCompletionNotifier(b,w){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:b}},w)}async listRoots(b,w){return this.request({method:"roots/list",params:b},a4,w)}async sendLoggingMessage(b,w){if(this._capabilities.logging){if(!this.isMessageIgnored(b.level,w))return this.notification({method:"notifications/message",params:b})}}async sendResourceUpdated(b){return this.notification({method:"notifications/resources/updated",params:b})}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 qD={name:"@sequenzy/mcp",version:"0.0.109",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 JW=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],LD={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 jP(b){let $=(b??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return $.length>0?$:"https://sequenzy.com"}function nb(b){let w=b?.trim();return w?w:void 0}function rb(b){return encodeURIComponent(b)}function Xb(b,w){return`${b}${w}`}function Yb(b,w=""){return`/dashboard/company/${rb(b)}${w}`}function UD(b,w,$){return Xb(b,`${Yb(w,"/settings")}?tab=${encodeURIComponent($)}`)}function VP(b,w){let $=JW.map((W)=>[W,w?UD(b,w,W):""]);return Object.fromEntries($)}function Hw(b={},w){let $=jP(w),W=nb(b.companyId),Q={},G=VP($,W);if(!W)return{appUrl:$,routeTemplates:LD,settingsTabValues:JW,urls:Q,settingsUrls:G};Q.dashboard=Xb($,Yb(W)),Q.campaigns=Xb($,Yb(W,"/campaign")),Q.landingPages=Xb($,Yb(W,"/landing-pages")),Q.sequences=Xb($,Yb(W,"/sequences")),Q.settings=Xb($,Yb(W,"/settings")),Q.emails=Xb($,Yb(W,"/emails")),Q.subscribers=Xb($,Yb(W,"/subscribers")),Q.sentEmails=Xb($,Yb(W,"/sent-emails")),Q.segments=Xb($,Yb(W,"/segments")),Q.metrics=Xb($,Yb(W,"/metrics")),Q.transactional=Xb($,Yb(W,"/transactional"));let X=nb(b.campaignId);if(X)Q.campaign=Xb($,Yb(W,`/campaign/${rb(X)}`)),Q.campaignPreview=`${Q.campaign}?step=review`;let Y=nb(b.landingPageId);if(Y)Q.landingPage=Xb($,Yb(W,`/landing-pages/${rb(Y)}`));let H=nb(b.sequenceId);if(H)Q.sequence=Xb($,Yb(W,`/sequences/${rb(H)}`));let J=nb(b.emailId)??nb(b.templateId);if(J)Q.email=Xb($,Yb(W,`/emails/${rb(J)}`)),Q.template=Q.email;let D=nb(b.transactionalId);if(D)Q.transactionalEmail=Xb($,Yb(W,`/transactional/${rb(D)}`));let z=nb(b.emailSendId);if(z)Q.emailSend=Xb($,Yb(W,`/sent-emails/${rb(z)}`));let O=nb(b.domainId);if(O)Q.domain=Xb($,Yb(W,`/settings/domain/${rb(O)}`)),Q.domainVerify=`${Q.domain}/verify`;let q=nb(b.status);if(q)Q.campaignList=Xb($,Yb(W,`/campaign/list/${rb(q)}`)),Q.sequenceList=Xb($,Yb(W,`/sequences/list/${rb(q)}`));let B=nb(b.settingsTab);if(B)Q.settingsTab=UD($,W,B);return{appUrl:$,routeTemplates:LD,settingsTabValues:JW,urls:Q,settingsUrls:G}}var BD=[{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 FD(b){try{let w;switch(b){case"sequenzy://dashboard":w=await A("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let $=await A("GET","/api/v1/account"),W=qw()??$.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");w=await A("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":w=await A("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":w=await A("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":w=await A("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":w=await A("GET","/api/v1/sequences");break;case"sequenzy://templates":w=await A("GET","/api/v1/templates");break;case"sequenzy://segments":w=await A("GET","/api/v1/segments");break;case"sequenzy://tags":w=await A("GET","/api/v1/tags");break;case"sequenzy://health":w=await A("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":w=Hw();break;default:throw Error(`Unknown resource: ${b}`)}return{contents:[{uri:b,mimeType:"application/json",text:JSON.stringify(w,null,2)}]}}catch(w){return{contents:[{uri:b,mimeType:"text/plain",text:Ow(w)}]}}}function y(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}function F(b,w){let $=b[w];if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function j(b,w,$){let W=F(w,$);if(W===void 0)throw Error(`\`${$}\` is required when calling \`${b}\`.`);return W}var _w='For exact historical Poll/NPS respondents, use field `pollResponse`, operator `is`, and a JSON value shaped like {"v":1,"campaignId":"camp_123","blockId":"poll_1","match":{"kind":"answer","value":"loved"}}. For NPS buckets, use match {"kind":"npsBucket","bucket":"promoters"}; bucket may be `promoters`, `passives`, or `detractors`.',Jw='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: [...] }. 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. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',Dw='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`. 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. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',W1='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. 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. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',X0="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.",KD="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.",DW=500,zW=500,lb={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},v$=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay"],C$={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},NP={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},Q1={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:NP,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},G1={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},AW={type:"object",description:"Type-aware patch for the existing node. Start from get_sequence.sequence.nodes[].config. For logic_delay, set exactly one of delay ({ days, hours, minutes }), delayMs, or waitUntil; optional label is also accepted. For action_email, use name/label, subject, previewText, html/htmlContent or blocks, isTransactional, and sender/reply identity fields. For action_sms, use text, blocks, imageUrls, label, or ineligibleAction. Other node types accept their editable config keys. Managed IDs, nodeType conversion, and branch path IDs/count are not editable here; use edit_sequence_graph for topology. Webhook header patches are merged, and redacted values from get_sequence must be omitted or replaced with a real new value.",additionalProperties:!0},x$={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:AW,expectedUpdatedAt:{type:"string",description:"Required optimistic-concurrency value from get_sequence.sequence.nodes[].updatedAt. The update is rejected if that node or its linked email content changed after it was read."}},required:["nodeId","changes","expectedUpdatedAt"],additionalProperties:!1},X1=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],Y1=["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","poll.answered"];var EP=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"]),TP=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","upload_image_asset","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","set_template_localization","sync_template_localizations","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","update_sequence_node","update_sequence_nodes","edit_sequence_graph","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"]),_P=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"]),SP=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","edit_sequence_graph","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook"]);function RP(b){let w=EP.has(b),$=TP.has(b);if(w===$)throw Error(`MCP tool "${b}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:w,destructiveHint:w?!1:SP.has(b),openWorldHint:_P.has(b)}}function PD(b){return{...b,annotations:{...b.annotations,...RP(b.name)}}}var OW={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"],pollResponse:["is"],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"]},kP=Object.entries(OW).map(([b,w])=>`${b}: ${w.join(", ")}`).join("; "),qW={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","pollResponse","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. ${_w}`},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: ${kP}.`},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). ${_w}`}},required:["field","operator","value"],additionalProperties:!1},LW={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 u$(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(typeof w!=="object"||w===null)return w;let $=w;if(typeof $.id==="string"&&$.id.trim()!=="")return $;return{...$,id:crypto.randomUUID()}})}function y$(b){if(typeof b!=="object"||b===null)return b;let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=u$([w]);return Array.isArray($)?$[0]:w}if(w.kind!=="group")return b;return{...w,id:typeof w.id==="string"&&w.id.trim()!==""?w.id:crypto.randomUUID(),children:Array.isArray(w.children)?w.children.map(y$):[]}}function vP(b){let w=b.indexOf(":");return w!==-1&&b.substring(0,w).trim().length>0}function CP(b){let w=b.indexOf(":");return w!==-1&&b.substring(w+1).trim().length>0}function MD(b){if(b==="all")return!0;let w=b.match(/^(\d+)d$/);if(!w?.[1])return!1;let $=Number.parseInt(w[1],10);return Number.isInteger($)&&$>0}function xP(b,w){let $=w.split(":");if(b==="at_least"||b==="less_than_count"){if($.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let G=$.slice(0,-2).join(":").trim(),X=$.at(-2),Y=$.at(-1),H=X===void 0?Number.NaN:Number.parseInt(X,10);return G&&Number.isInteger(H)&&H>0&&Y!==void 0&&MD(Y)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if($.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=$.slice(0,-1).join(":").trim(),Q=$.at(-1);return W&&Q!==void 0&&MD(Q)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function uP(b){let w=b.indexOf(":");if(w===-1)return{productId:b,subfilter:null,rawValue:null};let $=b.substring(0,w),W=b.substring(w+1),Q=W.indexOf(":");if(Q===-1)return{productId:$,subfilter:W,rawValue:null};return{productId:$,subfilter:W.substring(0,Q),rawValue:W.substring(Q+1)}}function yP(b){return b.trim().toLowerCase().replace(/[-\s]+/g,"_")}function hP(b){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(b)}function fP(b,w){if(w==="cancels_at"||w==="cancel_at"||w==="cancellation_at")return!0;if(b==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(w);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(w)}function cP(b){return["is","is_not","gte","lte","gt","lt"].includes(b)}function gP(b,w,$){if(b==="stripeProduct"){if(w!=="at_least"&&w!=="less_than_count")return null;let Y=$.indexOf(":");if(Y===-1)return null;let H=$.substring(0,Y).trim(),J=Number.parseInt($.substring(Y+1).trim(),10);return H&&Number.isInteger(J)&&J>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(b!=="stripeCurrentProduct"&&b!=="stripeTrialProduct")return null;let{productId:W,subfilter:Q,rawValue:G}=uP($);if(!W.trim())return"Stripe product filters must include a product ID.";if(!Q)return w==="is"||w==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let X=yP(Q);if(hP(X))return w==="is"||w==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!fP(b,X))return`Unsupported Stripe product subfilter "${Q}".`;if(!cP(w))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return G?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var mP=new Set(["shopify","woocommerce","api"]);function nP(b,w){let $=w.trim(),W=$.indexOf(":");if(W!==-1&&mP.has($.substring(0,W).trim()))$=$.substring(W+1).trim();if(!$)return'Purchased Product filters must include a product ID, like "shopify:42".';if(b!=="at_least"&&b!=="less_than_count")return null;let Q=$.lastIndexOf(":");if(Q===-1)return null;let G=$.substring(0,Q).trim(),X=Number.parseInt($.substring(Q+1).trim(),10);return G&&Number.isInteger(X)&&X>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function lP(b){let w;try{w=JSON.parse(b)}catch{return`Poll response filters must use valid JSON. ${_w}`}if(!y(w)||w.v!==1||typeof w.campaignId!=="string"||!w.campaignId.trim()||typeof w.blockId!=="string"||!w.blockId.trim()||!y(w.match))return`Poll response filter context is invalid. ${_w}`;let $=w.match;if($.kind==="answer"&&typeof $.value==="string"&&$.value.length>0)return null;if($.kind==="npsBucket"&&($.bucket==="promoters"||$.bucket==="passives"||$.bucket==="detractors"))return null;return`Poll response filter match is invalid. ${_w}`}function h$(b){if(typeof b!=="object"||b===null)return"Segment filters must be objects.";let w=b,$=w.field,W=w.operator,Q=w.value;if(typeof $!=="string"||!($ in OW))return`Unsupported segment filter field "${String($)}".`;if(typeof W!=="string")return`Segment filter "${$}" must include an operator.`;let G=OW[$];if(!G.includes(W))return`Operator "${W}" is not supported for ${$} filters. Use one of: ${G.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof Q!=="string"||Q.trim().length===0))return`Segment filter "${$}" must include a value.`;if($==="attribute"&&typeof Q==="string"){if(!vP(Q))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!CP(Q))return'Attribute filters must include a value after "attributeName:".'}if($==="event"&&typeof Q==="string"){let X=xP(W,Q);if(X)return X}if($==="pollResponse"&&typeof Q==="string"){let X=lP(Q);if(X)return X}if(($==="stripeProduct"||$==="stripeCurrentProduct"||$==="stripeTrialProduct")&&typeof Q==="string"){let X=gP($,W,Q);if(X)return X}if($==="commerceProduct"&&typeof Q==="string"){let X=nP(W,Q);if(X)return X}if($==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof Q==="string"&&Q.split(",").map((Y)=>Y.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function f$(b){if(typeof b!=="object"||b===null)return[];let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=h$(w);return $?[$]:[]}if(Array.isArray(w.children))return w.children.flatMap(f$);return[]}function _b(b,w,$){if(w.html!==void 0&&w.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`, not both.`);if(w.blocks!==void 0&&!Array.isArray(w.blocks))throw Error(`\`blocks\` must be an array when calling \`${b}\`.`);if($?.requireContent&&w.html===void 0&&w.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`.`)}function H1(b,w){if(w.labels===void 0)return;if(!Array.isArray(w.labels))throw Error(`\`labels\` must be an array when calling \`${b}\`.`);if(w.labels.some(($)=>typeof $!=="string"||$.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${b}\`.`)}function jD(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!w&&!$)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=w?b.filters.flatMap((Q)=>{let G=h$(Q);return G?[G]:[]}):f$(b.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function VD(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(b.name===void 0&&b.filterJoinOperator===void 0&&!w&&!$)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=w?b.filters.flatMap((Q)=>{let G=h$(Q);return G?[G]:[]}):$?f$(b.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var UW=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"];function BW(b,w,$){if(w[$]!==void 0&&!y(w[$]))throw Error(`\`${$}\` must be an object when calling \`${b}\`.`)}function ZD(b,w,$){if(w[$]!==void 0&&!Array.isArray(w[$]))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`)}function ND(b){let w=new Set(["companyId",...UW]),$=Object.keys(b).filter((Q)=>!w.has(Q));if($.length>0)throw Error(`\`update_company\` accepts only company product-info fields. Unsupported field${$.length===1?"":"s"}: ${$.map((Q)=>`\`${Q}\``).join(", ")}.`);let W={};for(let Q of UW)if(b[Q]!==void 0)W[Q]=b[Q];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${UW.map((Q)=>`\`${Q}\``).join(", ")} when calling \`update_company\`.`);for(let Q of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"])if(b[Q]!==void 0&&typeof b[Q]!=="string")throw Error(`\`${Q}\` must be a string when calling \`update_company\`.`);if(BW("update_company",b,"brandColors"),BW("update_company",b,"socialLinks"),BW("update_company",b,"pricing"),ZD("update_company",b,"valueProps"),ZD("update_company",b,"testimonials"),typeof b.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(b.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let Q of["fromEmail","replyTo"]){let G=b[Q];if(typeof G==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(G.trim()))throw Error(`\`${Q}\` must be a valid email address when calling \`update_company\`.`)}if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_company`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_company`.");return W}var ED=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function iP(b){return ED.some((w)=>b[w]!==void 0)}function pP(b){if(typeof b.nodeType==="string")return b.nodeType==="action_email";return b.type===void 0||b.type==="email"}function c$(b,w,$){for(let W of ED){let Q=$[W];if(Q!==void 0&&typeof Q!=="string")throw Error(`\`${W}\` must be a string for ${w} when calling \`${b}\`.`)}if($.senderProfileId!==void 0&&$.fromEmail!==void 0)throw Error(`Provide either \`senderProfileId\` or \`fromEmail\` for ${w} when calling \`${b}\`, not both.`);if($.replyProfileId!==void 0&&$.replyTo!==void 0)throw Error(`Provide either \`replyProfileId\` or \`replyTo\` for ${w} when calling \`${b}\`, not both.`);if($.replyToName!==void 0&&$.replyTo===void 0)throw Error(`\`replyToName\` requires \`replyTo\` for ${w} when calling \`${b}\`.`)}function KW(b,w,$){if(iP($)&&!pP($))throw Error(`Sender identity fields are only supported for email steps at ${w} when calling \`${b}\`.`);c$(b,w,$)}function ID(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(y(W))c$(b,`${w}[${Q}]`,W)})}function FW(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(y(W))KW(b,`${w}[${Q}]`,W)})}function oP(b){if(ID("update_sequence","emails",b.emails),ID("update_sequence","steps",b.steps),y(b.insertSteps))FW("update_sequence","insertSteps.steps",b.insertSteps.steps);if(!y(b.branch))return;if(Array.isArray(b.branch.branches))b.branch.branches.forEach(($,W)=>{if(y($))FW("update_sequence",`branch.branches[${W}].steps`,$.steps)});FW("update_sequence","branch.elseSteps",b.branch.elseSteps)}function TD(b){if(b.fromEmail!==void 0&&b.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_sequence`, not both.");if(b.replyTo!==void 0&&b.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_sequence`, not both.");if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_sequence`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_sequence`.");if(b.clearEnrollmentFieldPath===!0&&b.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(b.clearSendingWindow===!0&&b.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(b.clearBccEmails===!0&&b.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(b.branch!==void 0&&b.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");oP(b);let w={...b};if(delete w.clearEnrollmentFieldPath,delete w.clearSendingWindow,delete w.clearBccEmails,b.clearEnrollmentFieldPath===!0)w.enrollmentFieldPath=null;if(b.clearSendingWindow===!0)w.sendingWindow=null;if(b.clearBccEmails===!0)w.bccEmails=null;return w}function _D(b,w,$){let W=j(b,w,"nodeId");if(!y(w.changes)||Object.keys(w.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${$} when calling \`${b}\`.`);let Q=j(b,w,"expectedUpdatedAt");return{nodeId:W,changes:w.changes,expectedUpdatedAt:Q}}function SD(b){let w=_D("update_sequence_node",b,"the node update");return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:[w]}}function RD(b){if(!Array.isArray(b.updates)||b.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let w=new Set,$=b.updates.map((W,Q)=>{if(!y(W))throw Error(`\`updates[${Q}]\` must be an object when calling \`update_sequence_nodes\`.`);let G=_D("update_sequence_nodes",W,`updates[${Q}]`),X=String(G.nodeId);if(w.has(X))throw Error(`\`updates[${Q}]\` targets duplicate nodeId '${X}' when calling \`update_sequence_nodes\`.`);return w.add(X),G});return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:$}}function kD(b){let w=j("edit_sequence_graph",b,"action"),$=j("edit_sequence_graph",b,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(w))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let Q=F(b,"nodeId"),G=F(b,"afterNodeId"),X=F(b,"beforeNodeId"),Y=b.edges;if(w!=="replace_edges"&&!Q)throw Error(`\`nodeId\` is required for ${w} when calling \`edit_sequence_graph\`.`);if(w==="replace_edges"&&Q)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let H=w==="move_node"||w==="duplicate_node";if(H&&(G?1:0)+(X?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${w} when calling \`edit_sequence_graph\`.`);if(!H&&(G||X))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${w} when calling \`edit_sequence_graph\`.`);if((w==="replace_edges"||w==="delete_node"&&Y!==void 0)&&(!Array.isArray(Y)||Y.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${w} when calling \`edit_sequence_graph\`.`);if((w==="move_node"||w==="duplicate_node")&&Y!==void 0)throw Error(`\`edges\` is not used with ${w} when calling \`edit_sequence_graph\`.`);let J=Array.isArray(Y)?Y.map((D,z)=>{if(!y(D))throw Error(`\`edges\` item ${z+1} must be an object when calling \`edit_sequence_graph\`.`);let O=j("edit_sequence_graph",D,"sourceNodeId"),q=j("edit_sequence_graph",D,"targetNodeId");if(D.condition!==void 0&&D.condition!==null&&!y(D.condition))throw Error(`\`edges\` item ${z+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:O,targetNodeId:q,...y(D.condition)?{condition:D.condition}:{}}}):void 0;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},graphEdit:{action:w,expectedRevision:$,...Q?{nodeId:Q}:{},...G?{afterNodeId:G}:{},...X?{beforeNodeId:X}:{},...J?{edges:J}:{}}}}function vD(b){let w=b.type==="sms",$;if(w){KW("insert_sequence_step","SMS step",b);let Q=F(b,"text"),G=Array.isArray(b.blocks)&&b.blocks.length>0;if(Q===void 0&&!G)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");$={type:"sms"};for(let X of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(b[X]!==void 0)$[X]=b[X]}else{_b("insert_sequence_step",b,{requireContent:!0}),c$("insert_sequence_step","email step",b),$={subject:j("insert_sequence_step",b,"subject")};for(let Q of["name","previewText","html","blocks","delay","delayMs","waitUntil","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"])if(b[Q]!==void 0)$[Q]=b[Q]}let W={steps:[$]};if(b.afterNodeId!==void 0)W.afterNodeId=b.afterNodeId;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},insertSteps:W}}function CD(b){let w=F(b,"subscriberId"),$=b.fieldValues,W=$===void 0?void 0:Array.isArray($)?$:void 0;if($!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let Q=W?.map((Y)=>typeof Y==="string"?Y.trim():"").filter((Y)=>Y.length>0)??[];if(W?.some((Y)=>typeof Y!=="string")||W!==void 0&&Q.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(w!==void 0===Q.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let G=F(b,"fieldPath"),X=F(b,"reason");return{...w!==void 0&&{subscriberId:w},...G!==void 0&&{fieldPath:G},...Q.length>0&&{fieldValues:Q},...typeof b.dryRun==="boolean"&&{dryRun:b.dryRun},...X!==void 0&&{reason:X}}}function xD(b){_b("create_campaign",b),H1("create_campaign",b);let w=F(b,"prompt")!==void 0,$=b.html!==void 0,W=b.blocks!==void 0,Q=b.templateId!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(w&&($||W||Q))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!w&&F(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function uD(b){_b("create_template",b),H1("create_template",b);let w=F(b,"prompt")!==void 0,$=[w,b.html!==void 0,b.blocks!==void 0].filter(Boolean).length;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_template`.");if($!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!w&&F(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function yD(b){if(F(b,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(b.targetLists!==void 0&&!y(b.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(b.sendTimeOptimization!==void 0){if(typeof b.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(b.spreadOverHours!==void 0){if(typeof b.spreadOverHours!=="number"||!Number.isInteger(b.spreadOverHours)||b.spreadOverHours<1||b.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(b.recurringInterval!==void 0&&b.recurringInterval!=="weekly"&&b.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function g$(b,w,$){let W=new Set(["companyId","landingPageId","name","slug","content"]),Q=Object.keys(w).filter((G)=>!W.has(G));if(Q.length>0)throw Error(`\`${b}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${Q.length===1?"":"s"}: ${Q.map((G)=>`\`${G}\``).join(", ")}.`);if($.requireUpdate&&w.name===void 0&&w.slug===void 0&&w.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${b}\`.`);return{...w.name!==void 0&&{name:w.name},...w.slug!==void 0&&{slug:w.slug},...w.content!==void 0&&{content:w.content}}}function hD(b){let w=new Set(["companyId","domain","verify"]),$=Object.keys(b).filter((W)=>!w.has(W));if($.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${$.length===1?"":"s"}: ${$.map((W)=>`\`${W}\``).join(", ")}.`);if(b.domain===void 0&&b.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...b.domain!==void 0&&{domain:b.domain},...typeof b.verify==="boolean"&&{verify:b.verify}}}function fD(b){_b("create_transactional_email",b);let w=F(b,"prompt")!==void 0,$=b.html!==void 0,W=b.blocks!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(w&&($||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!w&&!$&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!w&&F(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var Y0={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},PW={senderProfileId:{type:"string",description:"Sender profile for this step's From identity. Mutually exclusive with fromEmail."},fromEmail:{type:"string",description:"From address for this step. Its domain must be configured and verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this step. Alone it only changes the visible name; with fromEmail it also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this step's Reply-To. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Reply-To address for this step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."}},m$={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:{...Y0,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:W1,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:G1,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:Q1,name:{type:"string",description:"Email template name for email steps."},senderProfileId:{type:"string",description:"Sender profile for this email step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"From address for this email step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this email step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this email step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},replyTo:{type:"string",description:"Reply-To address for this email step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},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 cD(b){if(!b||typeof b!=="object")return null;let w=b;if(w.success!==!1)return null;if(typeof w.error==="string")return Error(w.error);if(w.error&&typeof w.error==="object"&&typeof w.error.message==="string")return Error(w.error.message);if(typeof w.message==="string")return Error(w.message);return Error("The tool returned an unsuccessful response.")}function MW(b){return b.trim().toLowerCase().replace(/\s+/g,"-")}function dP(b){let w=new URLSearchParams;if(typeof b.query==="string"&&b.query.trim()!=="")w.set("query",b.query.trim());if(Array.isArray(b.tags)&&b.tags.length>0)w.set("tags",b.tags.filter(($)=>typeof $==="string"&&$.trim()!=="").join(","));if(typeof b.list==="string"&&b.list.trim()!=="")w.set("list",b.list.trim());if(typeof b.listId==="string"&&b.listId.trim()!=="")w.set("listId",b.listId.trim());if(typeof b.listName==="string"&&b.listName.trim()!=="")w.set("listName",b.listName.trim());if(typeof b.segmentId==="string"&&b.segmentId.trim()!=="")w.set("segmentId",b.segmentId);if(typeof b.status==="string"&&b.status.trim()!=="")w.set("status",b.status.trim());return w.set("page",String(b.page)),w.set("limit",String(b.pageSize)),w}async function mD(b,w){let $=typeof b.limit==="number"&&Number.isFinite(b.limit)?Math.max(1,Math.trunc(b.limit)):void 0,W=Math.min(100,Math.max(1,$??100)),Q=[],G=1,X=0,Y=0,H=0;while(!0){let D=dP({query:b.query,tags:b.tags,list:b.list,listId:b.listId,listName:b.listName,segmentId:b.segmentId,status:b.status,page:G,pageSize:W}),z=await A("GET",`/api/v1/subscribers?${D.toString()}`,void 0,w);X=z.pagination?.total??z.subscribers.length,Y=z.pagination?.totalPages??1,H+=1,Q.push(...z.subscribers??[]);let O=$!==void 0&&Q.length>=$,q=z.pagination?G>=z.pagination.totalPages:(z.subscribers??[]).length<W;if(O||q)break;G+=1}let J=$!==void 0?Q.slice(0,$):Q;return{success:!0,subscribers:J,pagination:{page:1,limit:W,total:X,totalPages:Y,fetchedPages:H},returned:J.length,truncated:$!==void 0&&X>0&&J.length<X}}function tP(b){let w=typeof b.email==="string"&&b.email.trim()!==""?b.email.trim():void 0,$=typeof b.externalId==="string"&&b.externalId.trim()!==""?b.externalId.trim():void 0;return{...w?{email:w}:{},...$?{externalId:$}:{}}}function Aw(b,w){let $=tP(w);if(!$.email&&!$.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${b}\`.`);return $}function n$(b,w){let $=new URLSearchParams;if(w?.includeMachineEngagement)$.set("includeMachineEngagement","true");let W=$.toString(),Q=W?`?${W}`:"";if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}${Q}`;return $.set("externalId",String(b.externalId)),`/api/v1/subscribers/external?${$.toString()}`}function ZW(b){if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}/notes`;let w=new URLSearchParams;return w.set("externalId",String(b.externalId)),`/api/v1/subscribers/external/notes?${w.toString()}`}async function H0(b,w,$){return A("GET",n$(b,$),void 0,w)}function Vb(b,w,$,W){let Q=F(w,$);if(Q===void 0)return;if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${b}\`.`);return Q}function J0(b,w,$,W){let Q=j(b,w,$);if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${b}\`.`);return Q}function zw(b,w,$,W,Q){let G=w[$];if(G===void 0)return;if(typeof G!=="number"||!Number.isInteger(G)||G<W||G>Q)throw Error(`\`${$}\` must be an integer between ${W} and ${Q} when calling \`${b}\`.`);return G}function rP(b,w){let $=[],W=Vb(b,w,"eventType",v$);if(W)$.push(W);if(w.eventTypes!==void 0){if(!Array.isArray(w.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${b}\`.`);w.eventTypes.forEach((Q,G)=>{if(typeof Q!=="string")throw Error(`\`eventTypes\` item ${G+1} must be a string when calling \`${b}\`.`);let X=Q.trim();if(!v$.includes(X))throw Error(`\`eventTypes\` item ${G+1} must be one of ${v$.join(", ")} when calling \`${b}\`.`);$.push(X)})}return[...new Set($)]}function IW(b,w){let $=new URLSearchParams,W=rP(b,w);if(W.length>0)$.set("eventTypes",W.join(","));let Q=Vb(b,w,"period",["1h","24h","7d","30d","90d"]);if(Q)$.set("period",Q);let G=F(w,"start");if(G)$.set("start",G);let X=F(w,"end");if(X)$.set("end",X);let Y=zw(b,w,"page",1,1e6);if(Y!==void 0)$.set("page",String(Y));let H=zw(b,w,"limit",1,500);if(H!==void 0)$.set("limit",String(H));if(w.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");return $}function jW(b,w){if(w.events===void 0)return;if(!Array.isArray(w.events))throw Error(`\`events\` must be an array when calling \`${b}\`.`);let $=w.events.map((W,Q)=>{if(typeof W!=="string"||!Y1.includes(W))throw Error(`\`events\` item ${Q+1} must be one of ${Y1.join(", ")} when calling \`${b}\`.`);return W});if($.length===0)throw Error(`\`events\` must include at least one event type when calling \`${b}\`.`);return $}function VW(b,w){if(!Array.isArray(w.emails))throw Error(`\`emails\` must be an array when calling \`${b}\`.`);let $=[];if(w.emails.forEach((W,Q)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${Q+1} must be a string when calling \`${b}\`.`);let G=W.trim();if(G.length>0)$.push(G)}),$.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${b}\`.`);if($.length>DW)throw Error(`\`emails\` must include no more than ${DW} email addresses when calling \`${b}\`. Split larger batches into multiple calls.`);return $}function gD(b,w,$,W){let Q=w[$];if(Q===void 0)return;if(!Array.isArray(Q))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`);let G=[];if(Q.forEach((X,Y)=>{if(typeof X!=="string")throw Error(`\`${$}\` item ${Y+1} must be a string when calling \`${b}\`.`);let H=X.trim();if(H.length>0)G.push(H)}),G.length===0)throw Error(`\`${$}\` must include at least one ${W} when calling \`${b}\`.`);return G}function nD(b){let $=gD("enroll_subscribers_in_sequence",b,"emails","email address"),W=gD("enroll_subscribers_in_sequence",b,"subscriberIds","subscriber ID"),Q=($?.length??0)+(W?.length??0);if(Q===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(Q>zW)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${zW} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let G=F(b,"targetNodeId");return{...$!==void 0&&{emails:$},...W!==void 0&&{subscriberIds:W},...G!==void 0&&{targetNodeId:G}}}import{readFileSync as eP,statSync as sP}from"node:fs";import{basename as aP}from"node:path";var bM={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 wM(b){let w=b.split(".").pop()?.toLowerCase()??"";return bM[w]??null}var $M=104857600;async function lD(b,w){if(!z0())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 $=wM(b);if(!$)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=sP(b).size;if(W>$M)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let Q=eP(b),G=await A("POST","/api/v1/products/delivery/upload-url",{filename:aP(b),contentType:$,fileSizeBytes:W},w),X=await fetch(G.uploadUrl,{method:"PUT",headers:{"Content-Type":$},body:Q});if(!X.ok)throw Error(`File upload failed (${X.status})`);return{url:G.publicUrl,fileName:G.fileName,fileSizeBytes:W,mimeType:$}}async function l$(b){let w=F(b,"companyId");if(w)return w;let $=qw();if($)return $;try{return(await A("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function iD(b,w){let $=await l$(w);if(!$)throw Error(`A company is required when calling \`${b}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return $}function J1(b,w){if(!y(b)||!w)return b;return{...b,url:w}}function pD(b,w){if(!y(b))return b;return{...b,...w.campaign!==void 0&&{url:w.campaign},...w.campaignPreview!==void 0&&{previewUrl:w.campaignPreview}}}function D0(b,w,$){if(!Array.isArray(b)||!w)return b;return b.map((W)=>{if(!y(W))return W;let Q=F(W,"id");if(!Q)return W;let G=Hw({companyId:w,...$==="campaign"&&{campaignId:Q},...$==="landingPage"&&{landingPageId:Q},...$==="sequence"&&{sequenceId:Q},...$==="template"&&{emailId:Q},...$==="transactional"&&{transactionalId:Q}});if($==="campaign")return pD(W,G.urls);let X=$==="sequence"?G.urls.sequence:$==="landingPage"?G.urls.landingPage:$==="template"?G.urls.email:G.urls.transactionalEmail;return J1(W,X)})}function WM(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(!y(w))return w;let $=F(w,"id");if(!$)return w;let W=Hw({companyId:$});return{...w,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var NW=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","update_sequence_node","update_sequence_nodes","edit_sequence_graph","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","set_template_localization","sync_template_localizations","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function oD(b,w,$){if(!y($)||!NW.has(b))return $;let W=y($.company)?$.company:void 0,G=F($,"selectedCompanyId")??F($,"currentCompanyId")??F($,"companyId")??(W?F(W,"id"):void 0)??(W?F(W,"companyId"):void 0)??await l$(w);if(!G)return $;let X=y($.campaign)?$.campaign:void 0,Y=y($.sequence)?$.sequence:void 0,H=y($.landingPage)?$.landingPage:void 0,J=y($.template)?$.template:void 0,D=y($.transactional)&&!Array.isArray($.transactional)?$.transactional:void 0,z={companyId:G,campaignId:F(w,"campaignId")??F($,"campaignId")??(X?F(X,"id"):void 0),landingPageId:F(w,"landingPageId")??F($,"landingPageId")??(H?F(H,"id"):void 0),sequenceId:F(w,"sequenceId")??F($,"sequenceId")??(Y?F(Y,"id"):void 0),emailId:F($,"templateId")??(J?F(J,"id"):void 0)??(D?F(D,"emailId"):void 0)??F(w,"templateId"),transactionalId:F(w,"transactionalId")??(D?F(D,"id"):void 0)??F(w,"idOrSlug"),emailSendId:F(w,"emailSendId")??F($,"emailSendId")??(y($.emailSend)?F($.emailSend,"id"):void 0),status:F(w,"status")},O=Hw(z),q=W?Hw({companyId:G}):void 0;return{...$,...Array.isArray($.companies)&&{companies:WM($.companies)},...Array.isArray($.campaigns)&&{campaigns:D0($.campaigns,G,"campaign")},...Array.isArray($.landingPages)&&{landingPages:D0($.landingPages,G,"landingPage")},...Array.isArray($.sequences)&&{sequences:D0($.sequences,G,"sequence")},...Array.isArray($.templates)&&{templates:D0($.templates,G,"template")},...Array.isArray($.transactional)&&{transactional:D0($.transactional,G,"transactional")},...W&&q!==void 0&&{company:{...W,url:q.urls.dashboard,settingsUrl:q.urls.settings}},...X&&O.urls.campaign!==void 0&&{campaign:pD(X,O.urls)},...Y&&O.urls.sequence!==void 0&&{sequence:J1(Y,O.urls.sequence)},...H&&O.urls.landingPage!==void 0&&{landingPage:J1(H,O.urls.landingPage)},...J&&O.urls.email!==void 0&&{template:J1(J,O.urls.email)},...D&&O.urls.transactionalEmail!==void 0&&{transactional:J1(D,O.urls.transactionalEmail)},...y($.emailSend)&&O.urls.emailSend!==void 0&&{emailSend:J1($.emailSend,O.urls.emailSend)},appUrls:O.urls}}import{readFileSync as QM,statSync as GM}from"node:fs";import{basename as XM,extname as tD}from"node:path";var TW=5242880,YM=Math.ceil(TW/3)*4,HM=Math.ceil(YM*1.05)+256,rD={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},JM=new Set(Object.values(rD));function EW(b){return b?.split(";")[0]?.trim().toLowerCase()||void 0}function DM(b){return rD[tD(b).toLowerCase()]}function zM(b){let w=tD(b);return(w?b.slice(0,-w.length):b).replace(/[-_]+/g," ").trim()||"Image"}function AM(b){if(b.length>HM)throw Error("Image assets must be 5MB or smaller.")}function OM(b){let w=0,$=0;for(let Q=0;Q<b.length;Q+=1){let G=b.charCodeAt(Q);if(G===9||G===10||G===11||G===12||G===13||G===32)continue;w+=1,$=G===61?$+1:0}if(Math.floor(w*3/4)-Math.min($,2)>TW)throw Error("Image assets must be 5MB or smaller.")}function qM(b){AM(b);let w=b.trim(),$=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(w),W=$?.[2]??w;OM(W);let Q=W.replace(/\s+/g,"");if(Q.length===0||Q.length%4===1||!/^[A-Za-z0-9+/]*={0,2}$/.test(Q))throw Error("`imageBase64` must contain valid base64 image bytes.");return{bytes:Buffer.from(Q,"base64"),...$?.[1]?{dataUrlContentType:EW($[1])}:{}}}function dD(b){if(b<=0)throw Error("The image file is empty.");if(b>TW)throw Error("Image assets must be 5MB or smaller.")}function LM(b){let w=DM(b.filename)??EW(b.explicitContentType)??EW(b.dataUrlContentType);if(!w||!JM.has(w))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return w}function UM(b){let w,$,W;if(b.filePath!==void 0){if(!z0())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. For a remote MCP connection, pass `imageBase64` and `filename` instead.");let G=GM(b.filePath).size;dD(G),w=QM(b.filePath),$=b.filename??XM(b.filePath)}else{if(!b.imageBase64)throw Error("Provide either `filePath` or `imageBase64` when uploading an image asset.");if(!b.filename)throw Error("`filename` is required with `imageBase64` when uploading an image asset.");let G=qM(b.imageBase64);w=G.bytes,W=G.dataUrlContentType,$=b.filename,dD(w.byteLength)}let Q=LM({filename:$,explicitContentType:b.contentType,dataUrlContentType:W});return{bytes:w,filename:$,contentType:Q,altText:b.altText??zM($)}}async function eD(b){let w=UM(b),$=w.bytes.byteLength,W=await A("POST","/api/v1/media/upload-url",{filename:w.filename,contentType:w.contentType,fileSizeBytes:$},b.companyId);return await lW(W.uploadUrl,w.bytes,w.contentType,b.companyId),(await A("POST","/api/v1/media/complete-upload",{key:W.key,filename:W.fileName,contentType:w.contentType,fileSizeBytes:$,...b.sourceWidth!==void 0&&{width:b.sourceWidth},...b.sourceHeight!==void 0&&{height:b.sourceHeight},altText:w.altText},b.companyId)).asset}var BM={type:"boolean",description:"Whether the Sequenzy operation succeeded."},FM={type:"string",description:"Human-readable status, confirmation, or next-step message."},KM={type:"string",description:"Additional context about the result."};function t(b){return{type:"object",description:b,additionalProperties:!0}}function PM(b){return{type:"array",description:b,items:t("One item in the returned collection.")}}function T(b){return{type:"string",description:b}}function Kb(b){return{type:"number",description:b}}function eb(b){return{type:"boolean",description:b}}function P(b){return t(`The ${b} record returned by Sequenzy.`)}function i(b){return PM(`List of ${b} records returned by Sequenzy.`)}var MM={appUrls:t("Dashboard URLs for relevant Sequenzy resources."),url:T("Primary dashboard URL for this result."),settingsUrl:T("Company settings URL when available.")},ZM={success:BM,message:FM,note:KM,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:t("One returned item.")},value:t("Fallback object wrapper used only when a tool returns a non-object value.")},IM={get_account:{account:P("account"),companies:i("company"),apiKeyPermissions:t("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:T("Company ID selected by the authenticated API key, when available."),selectedCompanyId:T("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:T("Selected company ID."),companyName:T("Selected company name.")},get_app_urls:{dashboard:T("Company dashboard URL."),settings:T("Company settings URL."),campaign:T("Campaign editor URL."),landingPage:T("Landing page editor URL."),sequence:T("Sequence editor URL."),email:T("Email editor URL."),transactionalEmail:T("Transactional email URL."),emailSend:T("Sent email detail URL."),domain:T("Sending domain settings URL."),urls:t("All generated URLs keyed by resource type.")},create_company:{company:P("company"),autoSelected:eb("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:P("company")},get_company:{company:P("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:t("One sync rule.")},isDefault:eb("Whether the company still uses the platform default rules.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:t("One sync rule.")},isDefault:eb("Whether the company now uses the platform default rules.")},get_shopify_automation_settings:{browseAbandonment:t("Effective browse-abandonment settings (defaults applied)."),priceDrop:t("Effective price-drop settings (defaults applied)."),shopDomain:T("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:t("Effective browse-abandonment settings after the update."),priceDrop:t("Effective price-drop settings after the update."),shopDomain:T("Connected Shopify store domain.")},create_api_key:{apiKey:t("Created API key metadata: the newly created secret in `key`, plus `scopes` listing the assigned permission scopes (null when the key has full access)."),key:T("Newly created API key if the API response uses the short key field.")},list_websites:{websites:i("sender website")},add_website:{website:P("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},add_sending_domain:{website:P("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},check_website:{website:P("sender website"),ready:eb("Whether the sender website is ready."),status:T("Current processing or verification status.")},verify_sending_domain:{website:P("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:eb("Whether the sending domain passed the fresh verification check."),message:T("Verification result summary.")},get_integration_guide:{guide:P("integration guide"),code:T("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:t("One setup step.")}},add_subscriber:{subscriber:P("subscriber")},update_subscriber:{subscriber:P("subscriber")},remove_subscriber:{subscriber:P("subscriber"),hardDeleted:eb("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:P("subscriber")},list_subscriber_notes:{notes:i("subscriber note")},add_subscriber_note:{note:P("subscriber note")},delete_subscriber_note:{id:T("Deleted subscriber note ID."),deleted:eb("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:i("subscriber"),pagination:t("Pagination metadata."),returned:Kb("Number of subscribers returned."),truncated:eb("Whether the result was truncated by the requested limit.")},list_products:{products:i("product")},upsert_products:{products:i("product"),created:Kb("Number of products created."),updated:Kb("Number of products updated.")},delete_product:{productId:T("Deleted product ID.")},attach_product_file:{product:P("product"),delivery:P("digital delivery file")},remove_product_file:{product:P("product")},upload_image_asset:{asset:P("hosted image asset"),imageBlock:t("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:P("product sync job"),jobId:T("Queued product sync job ID.")},list_tags:{tags:i("tag")},create_tag:{tag:P("tag")},update_tag:{tag:P("tag")},delete_tag:{tagId:T("Deleted tag ID.")},list_lists:{lists:i("list")},create_list:{list:P("list")},update_list:{list:P("list")},delete_list:{listId:T("Deleted list ID.")},add_subscribers_to_list:{list:P("list"),added:Kb("Number of subscribers added to the list."),skipped:Kb("Number of subscribers skipped.")},remove_subscribers_from_list:{list:P("list"),removed:Kb("Number of subscribers removed from the list."),skipped:Kb("Number of subscribers skipped.")},list_segments:{segments:i("segment")},create_segment:{segment:P("segment")},update_segment:{segment:P("segment")},delete_segment:{segmentId:T("Deleted segment ID.")},get_segment_count:{count:Kb("Number of subscribers matching the segment."),segmentId:T("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:i("audience sync")},list_ad_accounts:{adAccounts:i("ad account")},create_audience_sync:{audienceSync:P("audience sync")},update_audience_sync:{audienceSync:P("audience sync")},delete_audience_sync:{audienceSyncId:T("Deleted audience sync ID.")},sync_audience_now:{audienceSync:P("audience sync"),job:P("audience sync job"),jobId:T("Queued audience sync job ID.")},list_templates:{templates:i("email template")},get_template:{template:P("email template")},create_template:{template:P("email template")},update_template:{template:P("email template")},set_template_localization:{templateId:T("Localized template ID."),localization:P("template localization")},sync_template_localizations:{templateId:T("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:T("One queued locale code.")},queuedVariantCount:Kb("Number of localized variants queued for translation.")},delete_template:{templateId:T("Deleted template ID.")},list_ab_tests:{abTests:i("A/B test")},get_ab_test:{abTest:P("A/B test")},get_ab_test_stats:{abTest:P("A/B test"),stats:P("A/B test statistics")},restart_ab_test:{abTest:P("A/B test")},update_ab_test_variant:{abTest:P("A/B test"),variant:P("A/B test variant")},create_ab_test:{abTest:P("A/B test")},add_ab_test_variant:{abTest:P("A/B test"),variant:P("A/B test variant")},delete_ab_test_variant:{abTest:P("A/B test"),variantId:T("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:T("Deleted A/B test ID.")},list_campaigns:{campaigns:i("campaign")},get_campaign:{campaign:P("campaign")},get_email_send:{emailSend:P("email send")},create_campaign:{campaign:P("campaign")},update_campaign:{campaign:P("campaign")},schedule_campaign:{campaign:P("campaign"),scheduledAt:T("Scheduled send timestamp.")},send_test_email:{emailSend:P("test email send"),recipient:T("Test email recipient.")},send_test_sms:{smsSendId:T("Created test SMS send ID."),toPhone:T("Normalized E.164 destination phone.")},cancel_campaign:{campaign:P("campaign")},pause_campaign:{campaign:P("campaign")},resume_campaign:{campaign:P("campaign")},delete_campaign:{campaignId:T("Deleted campaign ID.")},duplicate_campaign:{campaign:P("duplicated campaign")},resend_campaign_to_non_openers:{campaign:P("non-opener resend draft campaign"),estimatedNonOpenerCount:Kb("Estimated number of subscribers who haven't opened the original campaign.")},list_landing_pages:{landingPages:i("landing page")},get_landing_page:{landingPage:P("landing page")},create_landing_page:{landingPage:P("landing page")},update_landing_page:{landingPage:P("landing page")},delete_landing_page:{landingPageId:T("Deleted landing page ID.")},publish_landing_page:{landingPage:P("landing page")},unpublish_landing_page:{landingPage:P("landing page")},connect_landing_page_domain:{landingPage:P("landing page"),domain:T("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:P("landing page"),domain:T("Landing page domain.")},list_sequences:{sequences:i("sequence")},get_sequence:{sequence:P("sequence")},create_sequence:{sequence:P("sequence"),eventTrackingCode:T("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:t("Custom-event endpoint, payload contract, example payload, documentation URL, and get_integration_guide arguments."),requiredEvents:{type:"array",description:"Event names the application or an integration must send.",items:T("One required event name.")}},update_sequence:{sequence:P("sequence")},update_sequence_node:{sequence:P("sequence")},update_sequence_nodes:{sequence:P("sequence")},edit_sequence_graph:{sequence:P("sequence")},insert_sequence_step:{sequence:P("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for the inserted step, including any delay node.",items:T("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:T("Inserted email template ID.")},insertedEmailCount:Kb("Number of email steps inserted.")},enable_sequence:{sequence:P("sequence")},disable_sequence:{sequence:P("sequence")},pause_sequence_enrollments:{sequenceId:T("Sequence ID."),enrollmentPaused:eb("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:T("Sequence ID."),enrollmentPaused:eb("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:P("sequence"),enrollments:i("sequence enrollment"),enrolled:Kb("Number of subscribers enrolled."),skipped:Kb("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:P("sequence"),cancelled:Kb("Number of enrollments cancelled."),skipped:Kb("Number of enrollments skipped.")},delete_sequence:{sequenceId:T("Deleted sequence ID.")},list_transactional_emails:{transactional:i("transactional email")},get_transactional_email:{transactional:P("transactional email")},create_transactional_email:{transactional:P("transactional email")},update_transactional_email:{transactional:P("transactional email")},send_email:{emailSend:P("transactional email send"),transactional:P("transactional email")},get_stats:{stats:P("account or company statistics")},get_campaign_stats:{campaign:P("campaign"),stats:P("campaign statistics"),clickedLinks:{type:"array",description:"Per-link click breakdown, most clicked first (top 20). Each entry has url, clicks, and percentage (that link's share of every recorded link click). Present only when the campaign has tracked link clicks.",items:t("One clicked link with url/clicks/share.")},polls:{type:"array",description:`Poll and NPS summaries. Each subscriber counts once per campaign poll block using their latest answer to that block; NPS entries include score, average, and promoter/passive/detractor counts. To list the exact historical respondents behind a count, use the summary blockId and the get_campaign_stats campaignId with create_segment. ${_w} A summary's attributeKey identifies the subscriber attribute that stores their current/latest response and may be overwritten by a later poll that reuses the key.`,items:t("One poll or NPS results summary.")}},get_sequence_stats:{sequence:P("sequence"),stats:P("sequence statistics")},list_campaign_events:{events:i("campaign email event"),pagination:t("Pagination metadata.")},list_sequence_events:{events:i("sequence email event"),pagination:t("Pagination metadata.")},get_subscriber_activity:{activity:i("subscriber activity event"),subscribers:i("subscriber"),pagination:t("Pagination metadata.")},list_team_members:{members:i("team member"),invitations:i("team invitation")},invite_team_member:{invitation:P("team invitation")},cancel_team_invitation:{invitationId:T("Cancelled invitation ID.")},list_conversations:{conversations:i("inbox conversation"),pagination:t("Pagination metadata.")},get_conversation:{conversation:P("inbox conversation"),messages:i("conversation message")},reply_to_conversation:{conversation:P("inbox conversation"),message:P("conversation message")},update_conversation_status:{conversation:P("inbox conversation")},mark_conversation_read:{conversation:P("inbox conversation")},list_webhooks:{webhooks:i("outbound webhook")},create_webhook:{webhook:P("outbound webhook")},update_webhook:{webhook:P("outbound webhook")},delete_webhook:{webhookId:T("Deleted outbound webhook ID.")},test_webhook:{webhook:P("outbound webhook"),delivery:P("test webhook delivery")},list_webhook_deliveries:{deliveries:i("webhook delivery")},replay_webhook_delivery:{delivery:P("webhook delivery"),job:P("webhook replay job")},generate_email:{email:P("generated email"),html:T("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:t("One generated email block.")},subject:T("Generated subject line."),previewText:T("Generated inbox preview text.")},generate_sequence:{sequence:P("generated sequence"),steps:i("generated sequence step")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:T("One generated subject line.")},variants:i("generated subject line variant")},generate_sms:{prompt:T("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:t("One generated SMS message.")}},get_sms_settings:{sms:t("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{}};function jM(b){let w=IM[b];if(w===void 0)throw Error(`MCP tool "${b}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${b}\` MCP tool.`,properties:{...ZM,...w,...NW.has(b)?MM:{}},additionalProperties:!0}}function sD(b){return{...b,outputSchema:jM(b.name)}}function aD(b){if(y(b))return b;if(Array.isArray(b))return{items:b};return{value:b}}var bz=[{name:"list_ab_tests",description:"List A/B tests and their variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Optional sequence ID to filter automation A/B tests."}}}},{name:"get_ab_test",description:"Get A/B test details, variants, and per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"}},required:["abTestId"]}},{name:"get_ab_test_stats",description:"Get A/B test aggregate stats and per-variant stats. Supports period or custom start/end ranges.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},period:{type:"string",description:"Optional period: 1h, 24h, 7d, 30d, or 90d."},start:{type:"string",description:"Custom range start as ISO 8601. Requires end."},end:{type:"string",description:"Custom range end as ISO 8601. Requires start."},includeMachineEngagement:lb},required:["abTestId"]}},{name:"restart_ab_test",description:"Run another sequence A/B test after a winner is selected. By default the winner becomes the new control; pass sourceVariantId to use another variant as the control email.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to restart"},sourceVariantId:{type:"string",description:"Optional variant ID to use as the new control email. Defaults to the selected winner."},testType:{type:"string",description:"Optional test type: subject or content."},winnerThreshold:{type:"number",description:"Optional number of subscribers before selecting a winner. Must be from 10 to 1000."},variantCount:{type:"number",description:"Optional total variants including the control. Must be from 2 to 4."}},required:["abTestId"],additionalProperties:!1}},{name:"update_ab_test_variant",description:"Update a draft A/B test variant. Provide at least one of subject, previewText, html, or blocks. Use either html or blocks, not both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID"},subject:{type:"string",description:"Variant subject line"},previewText:{type:"string",description:"Variant preview text. Pass an empty string to clear it."},html:{type:"string",description:"Replacement HTML body. Mutually exclusive with blocks."},blocks:{type:"array",description:`${Dw} Mutually exclusive with html.`,items:{type:"object"}}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"create_ab_test",description:"Create a campaign A/B test. Control variant A is created automatically from the campaign's current email; optionally provide extra variants. The campaign must be in draft or rejected status, and each campaign can only have one A/B test.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Draft campaign ID to create the A/B test for."},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Percentage of the audience used for the test phase, from 5 to 50. Defaults to 20."},testDurationMinutes:{type:"number",description:"Test phase duration in minutes before the winner is selected, from 15 to 1440. Defaults to 240."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Defaults to open_rate."},variants:{type:"array",description:"Optional extra variants to create in addition to control variant A.",items:{type:"object",properties:{subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:Dw,items:{type:"object"}}},required:["subject"]}}},required:["campaignId"]}},{name:"add_ab_test_variant",description:"Add a variant to a draft campaign A/B test. Variants cannot be added after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:Dw,items:{type:"object"}}},required:["abTestId","subject"]}},{name:"delete_ab_test_variant",description:"Permanently delete a variant from a draft campaign A/B test. This cannot be undone. Variant A is the control and cannot be deleted, and the test must keep at least the minimum number of variants. Variants cannot be removed after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID to delete."}},required:["abTestId","variantId"]}},{name:"delete_ab_test",description:"Permanently delete a campaign A/B test and all of its variants. This cannot be undone. Running tests (testing or winner_selected) cannot be deleted, and the linked campaign must be in draft or rejected status.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to delete."}},required:["abTestId"]}}];var wz=[{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
|
+
`)}q.write("payload.value = newResult;"),q.write("return payload;");let k=q.compile();return(S,h)=>k(O,S,h)},G,X=Sw,Y=!O0.jitless,J=Y&&b4.value,D=w.catchall,z;b._zod.parse=(O,q)=>{z??(z=W.value);let B=O.value;if(!X(B))return O.issues.push({expected:"object",code:"invalid_type",input:B,inst:b}),O;if(Y&&J&&q?.async===!1&&q.jitless!==!0){if(!G)G=Q(w.shape);if(O=G(O,q),!D)return O;return f9([],B,O,q,z,b)}return $(O,q)}});function w9(b,w,$,W){for(let G of b)if(G.issues.length===0)return w.value=G.value,w;let Q=b.filter((G)=>!Fw(G));if(Q.length===1)return w.value=Q[0].value,Q[0];return w.issues.push({code:"invalid_union",input:w.value,inst:$,errors:b.map((G)=>G.issues.map((X)=>ub(X,W,Sb())))}),w}var A4=U("$ZodUnion",(b,w)=>{e.init(b,w),o(b._zod,"optin",()=>w.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),o(b._zod,"optout",()=>w.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),o(b._zod,"values",()=>{if(w.options.every((Q)=>Q._zod.values))return new Set(w.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),o(b._zod,"pattern",()=>{if(w.options.every((Q)=>Q._zod.pattern)){let Q=w.options.map((G)=>G._zod.pattern);return new RegExp(`^(${Q.map((G)=>L1(G.source)).join("|")})$`)}return});let $=w.options.length===1,W=w.options[0]._zod.run;b._zod.parse=(Q,G)=>{if($)return W(Q,G);let X=!1,Y=[];for(let H of w.options){let J=H._zod.run({value:Q.value,issues:[]},G);if(J instanceof Promise)Y.push(J),X=!0;else{if(J.issues.length===0)return J;Y.push(J)}}if(!X)return w9(Y,Q,b,G);return Promise.all(Y).then((H)=>{return w9(H,Q,b,G)})}}),g9=U("$ZodDiscriminatedUnion",(b,w)=>{A4.init(b,w);let $=b._zod.parse;o(b._zod,"propValues",()=>{let Q={};for(let G of w.options){let X=G._zod.propValues;if(!X||Object.keys(X).length===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(G)}"`);for(let[Y,H]of Object.entries(X)){if(!Q[Y])Q[Y]=new Set;for(let J of H)Q[Y].add(J)}}return Q});let W=fw(()=>{let Q=w.options,G=new Map;for(let X of Q){let Y=X._zod.propValues?.[w.discriminator];if(!Y||Y.size===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(X)}"`);for(let H of Y){if(G.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);G.set(H,X)}}return G});b._zod.parse=(Q,G)=>{let X=Q.value;if(!Sw(X))return Q.issues.push({code:"invalid_type",expected:"object",input:X,inst:b}),Q;let Y=W.value.get(X?.[w.discriminator]);if(Y)return Y._zod.run(Q,G);if(w.unionFallback)return $(Q,G);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:w.discriminator,input:X,path:[w.discriminator],inst:b}),Q}}),m9=U("$ZodIntersection",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value,G=w.left._zod.run({value:Q,issues:[]},W),X=w.right._zod.run({value:Q,issues:[]},W);if(G instanceof Promise||X instanceof Promise)return Promise.all([G,X]).then(([H,J])=>{return $9($,H,J)});return $9($,G,X)}});function D4(b,w){if(b===w)return{valid:!0,data:b};if(b instanceof Date&&w instanceof Date&&+b===+w)return{valid:!0,data:b};if(Bw(b)&&Bw(w)){let $=Object.keys(w),W=Object.keys(b).filter((G)=>$.indexOf(G)!==-1),Q={...b,...w};for(let G of W){let X=D4(b[G],w[G]);if(!X.valid)return{valid:!1,mergeErrorPath:[G,...X.mergeErrorPath]};Q[G]=X.data}return{valid:!0,data:Q}}if(Array.isArray(b)&&Array.isArray(w)){if(b.length!==w.length)return{valid:!1,mergeErrorPath:[]};let $=[];for(let W=0;W<b.length;W++){let Q=b[W],G=w[W],X=D4(Q,G);if(!X.valid)return{valid:!1,mergeErrorPath:[W,...X.mergeErrorPath]};$.push(X.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function $9(b,w,$){if(w.issues.length)b.issues.push(...w.issues);if($.issues.length)b.issues.push(...$.issues);if(Fw(b))return b;let W=D4(w.value,$.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return b.value=W.data,b}var n9=U("$ZodRecord",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value;if(!Bw(Q))return $.issues.push({expected:"record",code:"invalid_type",input:Q,inst:b}),$;let G=[];if(w.keyType._zod.values){let X=w.keyType._zod.values;$.value={};for(let H of X)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let J=w.valueType._zod.run({value:Q[H],issues:[]},W);if(J instanceof Promise)G.push(J.then((D)=>{if(D.issues.length)$.issues.push(...ww(H,D.issues));$.value[H]=D.value}));else{if(J.issues.length)$.issues.push(...ww(H,J.issues));$.value[H]=J.value}}let Y;for(let H in Q)if(!X.has(H))Y=Y??[],Y.push(H);if(Y&&Y.length>0)$.issues.push({code:"unrecognized_keys",input:Q,inst:b,keys:Y})}else{$.value={};for(let X of Reflect.ownKeys(Q)){if(X==="__proto__")continue;let Y=w.keyType._zod.run({value:X,issues:[]},W);if(Y instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(Y.issues.length){$.issues.push({code:"invalid_key",origin:"record",issues:Y.issues.map((J)=>ub(J,W,Sb())),input:X,path:[X],inst:b}),$.value[Y.value]=Y.value;continue}let H=w.valueType._zod.run({value:Q[X],issues:[]},W);if(H instanceof Promise)G.push(H.then((J)=>{if(J.issues.length)$.issues.push(...ww(X,J.issues));$.value[Y.value]=J.value}));else{if(H.issues.length)$.issues.push(...ww(X,H.issues));$.value[Y.value]=H.value}}}if(G.length)return Promise.all(G).then(()=>$);return $}});var l9=U("$ZodEnum",(b,w)=>{e.init(b,w);let $=s$(w.entries),W=new Set($);b._zod.values=W,b._zod.pattern=new RegExp(`^(${$.filter((Q)=>w4.has(typeof Q)).map((Q)=>typeof Q==="string"?bw(Q):Q.toString()).join("|")})$`),b._zod.parse=(Q,G)=>{let X=Q.value;if(W.has(X))return Q;return Q.issues.push({code:"invalid_value",values:$,input:X,inst:b}),Q}}),i9=U("$ZodLiteral",(b,w)=>{if(e.init(b,w),w.values.length===0)throw Error("Cannot create literal schema with no valid values");b._zod.values=new Set(w.values),b._zod.pattern=new RegExp(`^(${w.values.map(($)=>typeof $==="string"?bw($):$?bw($.toString()):String($)).join("|")})$`),b._zod.parse=($,W)=>{let Q=$.value;if(b._zod.values.has(Q))return $;return $.issues.push({code:"invalid_value",values:w.values,input:Q,inst:b}),$}});var p9=U("$ZodTransform",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{if(W.direction==="backward")throw new A1(b.constructor.name);let Q=w.transform($.value,$);if(W.async)return(Q instanceof Promise?Q:Promise.resolve(Q)).then((X)=>{return $.value=X,$});if(Q instanceof Promise)throw new ab;return $.value=Q,$}});function W9(b,w){if(b.issues.length&&w===void 0)return{issues:[],value:void 0};return b}var o9=U("$ZodOptional",(b,w)=>{e.init(b,w),b._zod.optin="optional",b._zod.optout="optional",o(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,void 0]):void 0}),o(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${L1($.source)})?$`):void 0}),b._zod.parse=($,W)=>{if(w.innerType._zod.optin==="optional"){let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>W9(G,$.value));return W9(Q,$.value)}if($.value===void 0)return $;return w.innerType._zod.run($,W)}}),d9=U("$ZodNullable",(b,w)=>{e.init(b,w),o(b._zod,"optin",()=>w.innerType._zod.optin),o(b._zod,"optout",()=>w.innerType._zod.optout),o(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${L1($.source)}|null)$`):void 0}),o(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,null]):void 0}),b._zod.parse=($,W)=>{if($.value===null)return $;return w.innerType._zod.run($,W)}}),t9=U("$ZodDefault",(b,w)=>{e.init(b,w),b._zod.optin="optional",o(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);if($.value===void 0)return $.value=w.defaultValue,$;let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>Q9(G,w));return Q9(Q,w)}});function Q9(b,w){if(b.value===void 0)b.value=w.defaultValue;return b}var r9=U("$ZodPrefault",(b,w)=>{e.init(b,w),b._zod.optin="optional",o(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);if($.value===void 0)$.value=w.defaultValue;return w.innerType._zod.run($,W)}}),e9=U("$ZodNonOptional",(b,w)=>{e.init(b,w),o(b._zod,"values",()=>{let $=w.innerType._zod.values;return $?new Set([...$].filter((W)=>W!==void 0)):void 0}),b._zod.parse=($,W)=>{let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>G9(G,b));return G9(Q,b)}});function G9(b,w){if(!b.issues.length&&b.value===void 0)b.issues.push({code:"invalid_type",expected:"nonoptional",input:b.value,inst:w});return b}var s9=U("$ZodCatch",(b,w)=>{e.init(b,w),o(b._zod,"optin",()=>w.innerType._zod.optin),o(b._zod,"optout",()=>w.innerType._zod.optout),o(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>{if($.value=G.value,G.issues.length)$.value=w.catchValue({...$,error:{issues:G.issues.map((X)=>ub(X,W,Sb()))},input:$.value}),$.issues=[];return $});if($.value=Q.value,Q.issues.length)$.value=w.catchValue({...$,error:{issues:Q.issues.map((G)=>ub(G,W,Sb()))},input:$.value}),$.issues=[];return $}});var a9=U("$ZodPipe",(b,w)=>{e.init(b,w),o(b._zod,"values",()=>w.in._zod.values),o(b._zod,"optin",()=>w.in._zod.optin),o(b._zod,"optout",()=>w.out._zod.optout),o(b._zod,"propValues",()=>w.in._zod.propValues),b._zod.parse=($,W)=>{if(W.direction==="backward"){let G=w.out._zod.run($,W);if(G instanceof Promise)return G.then((X)=>I0(X,w.in,W));return I0(G,w.in,W)}let Q=w.in._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>I0(G,w.out,W));return I0(Q,w.out,W)}});function I0(b,w,$){if(b.issues.length)return b.aborted=!0,b;return w._zod.run({value:b.value,issues:b.issues},$)}var b8=U("$ZodReadonly",(b,w)=>{e.init(b,w),o(b._zod,"propValues",()=>w.innerType._zod.propValues),o(b._zod,"values",()=>w.innerType._zod.values),o(b._zod,"optin",()=>w.innerType._zod.optin),o(b._zod,"optout",()=>w.innerType._zod.optout),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then(X9);return X9(Q)}});function X9(b){return b.value=Object.freeze(b.value),b}var w8=U("$ZodCustom",(b,w)=>{Jb.init(b,w),e.init(b,w),b._zod.parse=($,W)=>{return $},b._zod.check=($)=>{let W=$.value,Q=w.fn(W);if(Q instanceof Promise)return Q.then((G)=>Y9(G,$,W,b));Y9(Q,$,W,b);return}});function Y9(b,w,$,W){if(!b){let Q={code:"custom",input:$,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)Q.params=W._zod.def.params;w.issues.push(cw(Q))}}var S7=(b)=>{let w=typeof b;switch(w){case"number":return Number.isNaN(b)?"NaN":"number";case"object":{if(Array.isArray(b))return"array";if(b===null)return"null";if(Object.getPrototypeOf(b)!==Object.prototype&&b.constructor)return b.constructor.name}}return w},R7=()=>{let b={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 w(W){return b[W]??null}let $={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 ${S7(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${B0(W.values[0])}`;return`Invalid option: expected one of ${q0(W.values,"|")}`;case"too_big":{let Q=W.inclusive?"<=":"<",G=w(W.origin);if(G)return`Too big: expected ${W.origin??"value"} to have ${Q}${W.maximum.toString()} ${G.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${Q}${W.maximum.toString()}`}case"too_small":{let Q=W.inclusive?">=":">",G=w(W.origin);if(G)return`Too small: expected ${W.origin} to have ${Q}${W.minimum.toString()} ${G.unit}`;return`Too small: expected ${W.origin} to be ${Q}${W.minimum.toString()}`}case"invalid_format":{let Q=W;if(Q.format==="starts_with")return`Invalid string: must start with "${Q.prefix}"`;if(Q.format==="ends_with")return`Invalid string: must end with "${Q.suffix}"`;if(Q.format==="includes")return`Invalid string: must include "${Q.includes}"`;if(Q.format==="regex")return`Invalid string: must match pattern ${Q.pattern}`;return`Invalid ${$[Q.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":""}: ${q0(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 O4(){return{localeError:R7()}}var oM=Symbol("ZodOutput"),dM=Symbol("ZodInput");class $8{constructor(){this._map=new WeakMap,this._idmap=new Map}add(b,...w){let $=w[0];if(this._map.set(b,$),$&&typeof $==="object"&&"id"in $){if(this._idmap.has($.id))throw Error(`ID ${$.id} already exists in the registry`);this._idmap.set($.id,b)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(b){let w=this._map.get(b);if(w&&typeof w==="object"&&"id"in w)this._idmap.delete(w.id);return this._map.delete(b),this}get(b){let w=b._zod.parent;if(w){let $={...this.get(w)??{}};delete $.id;let W={...$,...this._map.get(b)};return Object.keys(W).length?W:void 0}return this._map.get(b)}has(b){return this._map.has(b)}}function k7(){return new $8}var M1=k7();function W8(b,w){return new b({type:"string",..._(w)})}function Q8(b,w){return new b({type:"string",format:"email",check:"string_format",abort:!1,..._(w)})}function q4(b,w){return new b({type:"string",format:"guid",check:"string_format",abort:!1,..._(w)})}function G8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,..._(w)})}function X8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",..._(w)})}function Y8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",..._(w)})}function H8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",..._(w)})}function J8(b,w){return new b({type:"string",format:"url",check:"string_format",abort:!1,..._(w)})}function D8(b,w){return new b({type:"string",format:"emoji",check:"string_format",abort:!1,..._(w)})}function z8(b,w){return new b({type:"string",format:"nanoid",check:"string_format",abort:!1,..._(w)})}function A8(b,w){return new b({type:"string",format:"cuid",check:"string_format",abort:!1,..._(w)})}function O8(b,w){return new b({type:"string",format:"cuid2",check:"string_format",abort:!1,..._(w)})}function q8(b,w){return new b({type:"string",format:"ulid",check:"string_format",abort:!1,..._(w)})}function L8(b,w){return new b({type:"string",format:"xid",check:"string_format",abort:!1,..._(w)})}function U8(b,w){return new b({type:"string",format:"ksuid",check:"string_format",abort:!1,..._(w)})}function B8(b,w){return new b({type:"string",format:"ipv4",check:"string_format",abort:!1,..._(w)})}function F8(b,w){return new b({type:"string",format:"ipv6",check:"string_format",abort:!1,..._(w)})}function K8(b,w){return new b({type:"string",format:"cidrv4",check:"string_format",abort:!1,..._(w)})}function P8(b,w){return new b({type:"string",format:"cidrv6",check:"string_format",abort:!1,..._(w)})}function M8(b,w){return new b({type:"string",format:"base64",check:"string_format",abort:!1,..._(w)})}function Z8(b,w){return new b({type:"string",format:"base64url",check:"string_format",abort:!1,..._(w)})}function I8(b,w){return new b({type:"string",format:"e164",check:"string_format",abort:!1,..._(w)})}function j8(b,w){return new b({type:"string",format:"jwt",check:"string_format",abort:!1,..._(w)})}function V8(b,w){return new b({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,..._(w)})}function N8(b,w){return new b({type:"string",format:"date",check:"string_format",..._(w)})}function E8(b,w){return new b({type:"string",format:"time",check:"string_format",precision:null,..._(w)})}function T8(b,w){return new b({type:"string",format:"duration",check:"string_format",..._(w)})}function _8(b,w){return new b({type:"number",checks:[],..._(w)})}function S8(b,w){return new b({type:"number",check:"number_format",abort:!1,format:"safeint",..._(w)})}function R8(b,w){return new b({type:"boolean",..._(w)})}function k8(b,w){return new b({type:"null",..._(w)})}function v8(b){return new b({type:"unknown"})}function C8(b,w){return new b({type:"never",..._(w)})}function N0(b,w){return new Y4({check:"less_than",..._(w),value:b,inclusive:!1})}function Z1(b,w){return new Y4({check:"less_than",..._(w),value:b,inclusive:!0})}function E0(b,w){return new H4({check:"greater_than",..._(w),value:b,inclusive:!1})}function I1(b,w){return new H4({check:"greater_than",..._(w),value:b,inclusive:!0})}function T0(b,w){return new cQ({check:"multiple_of",..._(w),value:b})}function _0(b,w){return new mQ({check:"max_length",..._(w),maximum:b})}function gw(b,w){return new nQ({check:"min_length",..._(w),minimum:b})}function S0(b,w){return new lQ({check:"length_equals",..._(w),length:b})}function L4(b,w){return new iQ({check:"string_format",format:"regex",..._(w),pattern:b})}function U4(b){return new pQ({check:"string_format",format:"lowercase",..._(b)})}function B4(b){return new oQ({check:"string_format",format:"uppercase",..._(b)})}function F4(b,w){return new dQ({check:"string_format",format:"includes",..._(w),includes:b})}function K4(b,w){return new tQ({check:"string_format",format:"starts_with",..._(w),prefix:b})}function P4(b,w){return new rQ({check:"string_format",format:"ends_with",..._(w),suffix:b})}function Rw(b){return new eQ({check:"overwrite",tx:b})}function M4(b){return Rw((w)=>w.normalize(b))}function Z4(){return Rw((b)=>b.trim())}function I4(){return Rw((b)=>b.toLowerCase())}function j4(){return Rw((b)=>b.toUpperCase())}function x8(b,w,$){return new b({type:"array",element:w,..._($)})}function u8(b,w,$){let W=_($);return W.abort??(W.abort=!0),new b({type:"custom",check:"custom",fn:w,...W})}function y8(b,w,$){return new b({type:"custom",check:"custom",fn:w,..._($)})}function h8(b){let w=v7(($)=>{return $.addIssue=(W)=>{if(typeof W==="string")$.issues.push(cw(W,$.value,w._zod.def));else{let Q=W;if(Q.fatal)Q.continue=!1;Q.code??(Q.code="custom"),Q.input??(Q.input=$.value),Q.inst??(Q.inst=w),Q.continue??(Q.continue=!w._zod.def.abort),$.issues.push(cw(Q))}},b($.value,$)});return w}function v7(b,w){let $=new Jb({check:"custom",..._(w)});return $._zod.check=b,$}function mw(b){return!!b._zod}function Kw(b,w){if(mw(b))return F1(b,w);return b.safeParse(w)}function R0(b){if(!b)return;let w;if(mw(b))w=b._zod?.def?.shape;else w=b.shape;if(!w)return;if(typeof w==="function")try{return w()}catch{return}return w}function f8(b){if(mw(b)){let G=b._zod?.def;if(G){if(G.value!==void 0)return G.value;if(Array.isArray(G.values)&&G.values.length>0)return G.values[0]}}let $=b._def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}let W=b.value;if(W!==void 0)return W;return}var V1={};xW(V1,{time:()=>E4,duration:()=>T4,datetime:()=>V4,date:()=>N4,ZodISOTime:()=>m8,ZodISODuration:()=>n8,ZodISODateTime:()=>c8,ZodISODate:()=>g8});var c8=U("ZodISODateTime",(b,w)=>{K9.init(b,w),bb.init(b,w)});function V4(b){return V8(c8,b)}var g8=U("ZodISODate",(b,w)=>{P9.init(b,w),bb.init(b,w)});function N4(b){return N8(g8,b)}var m8=U("ZodISOTime",(b,w)=>{M9.init(b,w),bb.init(b,w)});function E4(b){return E8(m8,b)}var n8=U("ZodISODuration",(b,w)=>{Z9.init(b,w),bb.init(b,w)});function T4(b){return T8(n8,b)}var l8=(b,w)=>{F0.init(b,w),b.name="ZodError",Object.defineProperties(b,{format:{value:($)=>wQ(b,$)},flatten:{value:($)=>bQ(b,$)},addIssue:{value:($)=>{b.issues.push($),b.message=JSON.stringify(b.issues,hw,2)}},addIssues:{value:($)=>{b.issues.push(...$),b.message=JSON.stringify(b.issues,hw,2)}},isEmpty:{get(){return b.issues.length===0}}})},vZ=U("ZodError",l8),Eb=U("ZodError",l8,{Parent:Error});var i8=K0(Eb),p8=P0(Eb),o8=B1(Eb),d8=K1(Eb),t8=$Q(Eb),r8=WQ(Eb),e8=QQ(Eb),s8=GQ(Eb),a8=XQ(Eb),bG=YQ(Eb),wG=HQ(Eb),$G=JQ(Eb);var Qb=U("ZodType",(b,w)=>{return e.init(b,w),b.def=w,b.type=w.type,Object.defineProperty(b,"_def",{value:w}),b.check=(...$)=>{return b.clone(n.mergeDefs(w,{checks:[...w.checks??[],...$.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},b.clone=($,W)=>xb(b,$,W),b.brand=()=>b,b.register=($,W)=>{return $.add(b,W),b},b.parse=($,W)=>i8(b,$,W,{callee:b.parse}),b.safeParse=($,W)=>o8(b,$,W),b.parseAsync=async($,W)=>p8(b,$,W,{callee:b.parseAsync}),b.safeParseAsync=async($,W)=>d8(b,$,W),b.spa=b.safeParseAsync,b.encode=($,W)=>t8(b,$,W),b.decode=($,W)=>r8(b,$,W),b.encodeAsync=async($,W)=>e8(b,$,W),b.decodeAsync=async($,W)=>s8(b,$,W),b.safeEncode=($,W)=>a8(b,$,W),b.safeDecode=($,W)=>bG(b,$,W),b.safeEncodeAsync=async($,W)=>wG(b,$,W),b.safeDecodeAsync=async($,W)=>$G(b,$,W),b.refine=($,W)=>b.check(_5($,W)),b.superRefine=($)=>b.check(S5($)),b.overwrite=($)=>b.check(Rw($)),b.optional=()=>Wb(b),b.nullable=()=>GG(b),b.nullish=()=>Wb(GG(b)),b.nonoptional=($)=>I5(b,$),b.array=()=>f(b),b.or=($)=>r([b,$]),b.and=($)=>v0(b,$),b.transform=($)=>S4(b,DG($)),b.default=($)=>P5(b,$),b.prefault=($)=>Z5(b,$),b.catch=($)=>V5(b,$),b.pipe=($)=>S4(b,$),b.readonly=()=>T5(b),b.describe=($)=>{let W=b.clone();return M1.add(W,{description:$}),W},Object.defineProperty(b,"description",{get(){return M1.get(b)?.description},configurable:!0}),b.meta=(...$)=>{if($.length===0)return M1.get(b);let W=b.clone();return M1.add(W,$[0]),W},b.isOptional=()=>b.safeParse(void 0).success,b.isNullable=()=>b.safeParse(null).success,b}),XG=U("_ZodString",(b,w)=>{V0.init(b,w),Qb.init(b,w);let $=b._zod.bag;b.format=$.format??null,b.minLength=$.minimum??null,b.maxLength=$.maximum??null,b.regex=(...W)=>b.check(L4(...W)),b.includes=(...W)=>b.check(F4(...W)),b.startsWith=(...W)=>b.check(K4(...W)),b.endsWith=(...W)=>b.check(P4(...W)),b.min=(...W)=>b.check(gw(...W)),b.max=(...W)=>b.check(_0(...W)),b.length=(...W)=>b.check(S0(...W)),b.nonempty=(...W)=>b.check(gw(1,...W)),b.lowercase=(W)=>b.check(U4(W)),b.uppercase=(W)=>b.check(B4(W)),b.trim=()=>b.check(Z4()),b.normalize=(...W)=>b.check(M4(...W)),b.toLowerCase=()=>b.check(I4()),b.toUpperCase=()=>b.check(j4())}),m7=U("ZodString",(b,w)=>{V0.init(b,w),XG.init(b,w),b.email=($)=>b.check(Q8(n7,$)),b.url=($)=>b.check(J8(l7,$)),b.jwt=($)=>b.check(j8(G5,$)),b.emoji=($)=>b.check(D8(i7,$)),b.guid=($)=>b.check(q4(WG,$)),b.uuid=($)=>b.check(G8(k0,$)),b.uuidv4=($)=>b.check(X8(k0,$)),b.uuidv6=($)=>b.check(Y8(k0,$)),b.uuidv7=($)=>b.check(H8(k0,$)),b.nanoid=($)=>b.check(z8(p7,$)),b.guid=($)=>b.check(q4(WG,$)),b.cuid=($)=>b.check(A8(o7,$)),b.cuid2=($)=>b.check(O8(d7,$)),b.ulid=($)=>b.check(q8(t7,$)),b.base64=($)=>b.check(M8($5,$)),b.base64url=($)=>b.check(Z8(W5,$)),b.xid=($)=>b.check(L8(r7,$)),b.ksuid=($)=>b.check(U8(e7,$)),b.ipv4=($)=>b.check(B8(s7,$)),b.ipv6=($)=>b.check(F8(a7,$)),b.cidrv4=($)=>b.check(K8(b5,$)),b.cidrv6=($)=>b.check(P8(w5,$)),b.e164=($)=>b.check(I8(Q5,$)),b.datetime=($)=>b.check(V4($)),b.date=($)=>b.check(N4($)),b.time=($)=>b.check(E4($)),b.duration=($)=>b.check(T4($))});function L(b){return W8(m7,b)}var bb=U("ZodStringFormat",(b,w)=>{s.init(b,w),XG.init(b,w)}),n7=U("ZodEmail",(b,w)=>{D9.init(b,w),bb.init(b,w)});var WG=U("ZodGUID",(b,w)=>{H9.init(b,w),bb.init(b,w)});var k0=U("ZodUUID",(b,w)=>{J9.init(b,w),bb.init(b,w)});var l7=U("ZodURL",(b,w)=>{z9.init(b,w),bb.init(b,w)});var i7=U("ZodEmoji",(b,w)=>{A9.init(b,w),bb.init(b,w)});var p7=U("ZodNanoID",(b,w)=>{O9.init(b,w),bb.init(b,w)});var o7=U("ZodCUID",(b,w)=>{q9.init(b,w),bb.init(b,w)});var d7=U("ZodCUID2",(b,w)=>{L9.init(b,w),bb.init(b,w)});var t7=U("ZodULID",(b,w)=>{U9.init(b,w),bb.init(b,w)});var r7=U("ZodXID",(b,w)=>{B9.init(b,w),bb.init(b,w)});var e7=U("ZodKSUID",(b,w)=>{F9.init(b,w),bb.init(b,w)});var s7=U("ZodIPv4",(b,w)=>{I9.init(b,w),bb.init(b,w)});var a7=U("ZodIPv6",(b,w)=>{j9.init(b,w),bb.init(b,w)});var b5=U("ZodCIDRv4",(b,w)=>{V9.init(b,w),bb.init(b,w)});var w5=U("ZodCIDRv6",(b,w)=>{N9.init(b,w),bb.init(b,w)});var $5=U("ZodBase64",(b,w)=>{T9.init(b,w),bb.init(b,w)});var W5=U("ZodBase64URL",(b,w)=>{_9.init(b,w),bb.init(b,w)});var Q5=U("ZodE164",(b,w)=>{S9.init(b,w),bb.init(b,w)});var G5=U("ZodJWT",(b,w)=>{R9.init(b,w),bb.init(b,w)});var YG=U("ZodNumber",(b,w)=>{z4.init(b,w),Qb.init(b,w),b.gt=(W,Q)=>b.check(E0(W,Q)),b.gte=(W,Q)=>b.check(I1(W,Q)),b.min=(W,Q)=>b.check(I1(W,Q)),b.lt=(W,Q)=>b.check(N0(W,Q)),b.lte=(W,Q)=>b.check(Z1(W,Q)),b.max=(W,Q)=>b.check(Z1(W,Q)),b.int=(W)=>b.check(QG(W)),b.safe=(W)=>b.check(QG(W)),b.positive=(W)=>b.check(E0(0,W)),b.nonnegative=(W)=>b.check(I1(0,W)),b.negative=(W)=>b.check(N0(0,W)),b.nonpositive=(W)=>b.check(Z1(0,W)),b.multipleOf=(W,Q)=>b.check(T0(W,Q)),b.step=(W,Q)=>b.check(T0(W,Q)),b.finite=()=>b;let $=b._zod.bag;b.minValue=Math.max($.minimum??Number.NEGATIVE_INFINITY,$.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,b.maxValue=Math.min($.maximum??Number.POSITIVE_INFINITY,$.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,b.isInt=($.format??"").includes("int")||Number.isSafeInteger($.multipleOf??0.5),b.isFinite=!0,b.format=$.format??null});function p(b){return _8(YG,b)}var X5=U("ZodNumberFormat",(b,w)=>{k9.init(b,w),YG.init(b,w)});function QG(b){return S8(X5,b)}var Y5=U("ZodBoolean",(b,w)=>{v9.init(b,w),Qb.init(b,w)});function Hb(b){return R8(Y5,b)}var H5=U("ZodNull",(b,w)=>{C9.init(b,w),Qb.init(b,w)});function R4(b){return k8(H5,b)}var J5=U("ZodUnknown",(b,w)=>{x9.init(b,w),Qb.init(b,w)});function wb(){return v8(J5)}var D5=U("ZodNever",(b,w)=>{u9.init(b,w),Qb.init(b,w)});function z5(b){return C8(D5,b)}var A5=U("ZodArray",(b,w)=>{y9.init(b,w),Qb.init(b,w),b.element=w.element,b.min=($,W)=>b.check(gw($,W)),b.nonempty=($)=>b.check(gw(1,$)),b.max=($,W)=>b.check(_0($,W)),b.length=($,W)=>b.check(S0($,W)),b.unwrap=()=>b.element});function f(b,w){return x8(A5,b,w)}var HG=U("ZodObject",(b,w)=>{c9.init(b,w),Qb.init(b,w),n.defineLazy(b,"shape",()=>{return w.shape}),b.keyof=()=>Pb(Object.keys(b._zod.def.shape)),b.catchall=($)=>b.clone({...b._zod.def,catchall:$}),b.passthrough=()=>b.clone({...b._zod.def,catchall:wb()}),b.loose=()=>b.clone({...b._zod.def,catchall:wb()}),b.strict=()=>b.clone({...b._zod.def,catchall:z5()}),b.strip=()=>b.clone({...b._zod.def,catchall:void 0}),b.extend=($)=>{return n.extend(b,$)},b.safeExtend=($)=>{return n.safeExtend(b,$)},b.merge=($)=>n.merge(b,$),b.pick=($)=>n.pick(b,$),b.omit=($)=>n.omit(b,$),b.partial=(...$)=>n.partial(zG,b,$[0]),b.required=(...$)=>n.required(AG,b,$[0])});function V(b,w){let $={type:"object",shape:b??{},...n.normalizeParams(w)};return new HG($)}function Ub(b,w){return new HG({type:"object",shape:b,catchall:wb(),...n.normalizeParams(w)})}var JG=U("ZodUnion",(b,w)=>{A4.init(b,w),Qb.init(b,w),b.options=w.options});function r(b,w){return new JG({type:"union",options:b,...n.normalizeParams(w)})}var O5=U("ZodDiscriminatedUnion",(b,w)=>{JG.init(b,w),g9.init(b,w)});function k4(b,w,$){return new O5({type:"union",options:w,discriminator:b,...n.normalizeParams($)})}var q5=U("ZodIntersection",(b,w)=>{m9.init(b,w),Qb.init(b,w)});function v0(b,w){return new q5({type:"intersection",left:b,right:w})}var L5=U("ZodRecord",(b,w)=>{n9.init(b,w),Qb.init(b,w),b.keyType=w.keyType,b.valueType=w.valueType});function $b(b,w,$){return new L5({type:"record",keyType:b,valueType:w,...n.normalizeParams($)})}var _4=U("ZodEnum",(b,w)=>{l9.init(b,w),Qb.init(b,w),b.enum=w.entries,b.options=Object.values(w.entries);let $=new Set(Object.keys(w.entries));b.extract=(W,Q)=>{let G={};for(let X of W)if($.has(X))G[X]=w.entries[X];else throw Error(`Key ${X} not found in enum`);return new _4({...w,checks:[],...n.normalizeParams(Q),entries:G})},b.exclude=(W,Q)=>{let G={...w.entries};for(let X of W)if($.has(X))delete G[X];else throw Error(`Key ${X} not found in enum`);return new _4({...w,checks:[],...n.normalizeParams(Q),entries:G})}});function Pb(b,w){let $=Array.isArray(b)?Object.fromEntries(b.map((W)=>[W,W])):b;return new _4({type:"enum",entries:$,...n.normalizeParams(w)})}var U5=U("ZodLiteral",(b,w)=>{i9.init(b,w),Qb.init(b,w),b.values=new Set(w.values),Object.defineProperty(b,"value",{get(){if(w.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return w.values[0]}})});function N(b,w){return new U5({type:"literal",values:Array.isArray(b)?b:[b],...n.normalizeParams(w)})}var B5=U("ZodTransform",(b,w)=>{p9.init(b,w),Qb.init(b,w),b._zod.parse=($,W)=>{if(W.direction==="backward")throw new A1(b.constructor.name);$.addIssue=(G)=>{if(typeof G==="string")$.issues.push(n.issue(G,$.value,w));else{let X=G;if(X.fatal)X.continue=!1;X.code??(X.code="custom"),X.input??(X.input=$.value),X.inst??(X.inst=b),$.issues.push(n.issue(X))}};let Q=w.transform($.value,$);if(Q instanceof Promise)return Q.then((G)=>{return $.value=G,$});return $.value=Q,$}});function DG(b){return new B5({type:"transform",transform:b})}var zG=U("ZodOptional",(b,w)=>{o9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function Wb(b){return new zG({type:"optional",innerType:b})}var F5=U("ZodNullable",(b,w)=>{d9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function GG(b){return new F5({type:"nullable",innerType:b})}var K5=U("ZodDefault",(b,w)=>{t9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeDefault=b.unwrap});function P5(b,w){return new K5({type:"default",innerType:b,get defaultValue(){return typeof w==="function"?w():n.shallowClone(w)}})}var M5=U("ZodPrefault",(b,w)=>{r9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function Z5(b,w){return new M5({type:"prefault",innerType:b,get defaultValue(){return typeof w==="function"?w():n.shallowClone(w)}})}var AG=U("ZodNonOptional",(b,w)=>{e9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function I5(b,w){return new AG({type:"nonoptional",innerType:b,...n.normalizeParams(w)})}var j5=U("ZodCatch",(b,w)=>{s9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeCatch=b.unwrap});function V5(b,w){return new j5({type:"catch",innerType:b,catchValue:typeof w==="function"?w:()=>w})}var N5=U("ZodPipe",(b,w)=>{a9.init(b,w),Qb.init(b,w),b.in=w.in,b.out=w.out});function S4(b,w){return new N5({type:"pipe",in:b,out:w})}var E5=U("ZodReadonly",(b,w)=>{b8.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function T5(b){return new E5({type:"readonly",innerType:b})}var OG=U("ZodCustom",(b,w)=>{w8.init(b,w),Qb.init(b,w)});function qG(b,w){return u8(OG,b??(()=>!0),w)}function _5(b,w={}){return y8(OG,b,w)}function S5(b){return h8(b)}function v4(b,w){return S4(DG(b),w)}Sb(O4());var C4="2025-11-25";var LG=[C4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Pw="io.modelcontextprotocol/related-task",x0="2.0",Db=qG((b)=>b!==null&&(typeof b==="object"||typeof b==="function")),UG=r([L(),p().int()]),BG=L(),TI=Ub({ttl:r([p(),R4()]).optional(),pollInterval:p().optional()}),R5=V({ttl:p().optional()}),k5=V({taskId:L()}),x4=Ub({progressToken:UG.optional(),[Pw]:k5.optional()}),Tb=V({_meta:x4.optional()}),N1=Tb.extend({task:R5.optional()}),FG=(b)=>N1.safeParse(b).success,zb=V({method:L(),params:Tb.loose().optional()}),Rb=V({_meta:x4.optional()}),kb=V({method:L(),params:Rb.loose().optional()}),Ab=Ub({_meta:x4.optional()}),u0=r([L(),p().int()]),KG=V({jsonrpc:N(x0),id:u0,...zb.shape}).strict(),u4=(b)=>KG.safeParse(b).success,PG=V({jsonrpc:N(x0),...kb.shape}).strict(),MG=(b)=>PG.safeParse(b).success,y4=V({jsonrpc:N(x0),id:u0,result:Ab}).strict(),E1=(b)=>y4.safeParse(b).success;var c;(function(b){b[b.ConnectionClosed=-32000]="ConnectionClosed",b[b.RequestTimeout=-32001]="RequestTimeout",b[b.ParseError=-32700]="ParseError",b[b.InvalidRequest=-32600]="InvalidRequest",b[b.MethodNotFound=-32601]="MethodNotFound",b[b.InvalidParams=-32602]="InvalidParams",b[b.InternalError=-32603]="InternalError",b[b.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(c||(c={}));var h4=V({jsonrpc:N(x0),id:u0.optional(),error:V({code:p().int(),message:L(),data:wb().optional()})}).strict();var ZG=(b)=>h4.safeParse(b).success;var IG=r([KG,PG,y4,h4]),_I=r([y4,h4]),y0=Ab.strict(),v5=Rb.extend({requestId:u0.optional(),reason:L().optional()}),h0=kb.extend({method:N("notifications/cancelled"),params:v5}),C5=V({src:L(),mimeType:L().optional(),sizes:f(L()).optional(),theme:Pb(["light","dark"]).optional()}),T1=V({icons:f(C5).optional()}),nw=V({name:L(),title:L().optional()}),jG=nw.extend({...nw.shape,...T1.shape,version:L(),websiteUrl:L().optional(),description:L().optional()}),x5=v0(V({applyDefaults:Hb().optional()}),$b(L(),wb())),u5=v4((b)=>{if(b&&typeof b==="object"&&!Array.isArray(b)){if(Object.keys(b).length===0)return{form:{}}}return b},v0(V({form:x5.optional(),url:Db.optional()}),$b(L(),wb()).optional())),y5=Ub({list:Db.optional(),cancel:Db.optional(),requests:Ub({sampling:Ub({createMessage:Db.optional()}).optional(),elicitation:Ub({create:Db.optional()}).optional()}).optional()}),h5=Ub({list:Db.optional(),cancel:Db.optional(),requests:Ub({tools:Ub({call:Db.optional()}).optional()}).optional()}),f5=V({experimental:$b(L(),Db).optional(),sampling:V({context:Db.optional(),tools:Db.optional()}).optional(),elicitation:u5.optional(),roots:V({listChanged:Hb().optional()}).optional(),tasks:y5.optional()}),c5=Tb.extend({protocolVersion:L(),capabilities:f5,clientInfo:jG}),f4=zb.extend({method:N("initialize"),params:c5});var g5=V({experimental:$b(L(),Db).optional(),logging:Db.optional(),completions:Db.optional(),prompts:V({listChanged:Hb().optional()}).optional(),resources:V({subscribe:Hb().optional(),listChanged:Hb().optional()}).optional(),tools:V({listChanged:Hb().optional()}).optional(),tasks:h5.optional()}),m5=Ab.extend({protocolVersion:L(),capabilities:g5,serverInfo:jG,instructions:L().optional()}),c4=kb.extend({method:N("notifications/initialized"),params:Rb.optional()});var f0=zb.extend({method:N("ping"),params:Tb.optional()}),n5=V({progress:p(),total:Wb(p()),message:Wb(L())}),l5=V({...Rb.shape,...n5.shape,progressToken:UG}),c0=kb.extend({method:N("notifications/progress"),params:l5}),i5=Tb.extend({cursor:BG.optional()}),_1=zb.extend({params:i5.optional()}),S1=Ab.extend({nextCursor:BG.optional()}),p5=Pb(["working","input_required","completed","failed","cancelled"]),R1=V({taskId:L(),status:p5,ttl:r([p(),R4()]),createdAt:L(),lastUpdatedAt:L(),pollInterval:Wb(p()),statusMessage:Wb(L())}),lw=Ab.extend({task:R1}),o5=Rb.merge(R1),k1=kb.extend({method:N("notifications/tasks/status"),params:o5}),g0=zb.extend({method:N("tasks/get"),params:Tb.extend({taskId:L()})}),m0=Ab.merge(R1),n0=zb.extend({method:N("tasks/result"),params:Tb.extend({taskId:L()})}),SI=Ab.loose(),l0=_1.extend({method:N("tasks/list")}),i0=S1.extend({tasks:f(R1)}),p0=zb.extend({method:N("tasks/cancel"),params:Tb.extend({taskId:L()})}),VG=Ab.merge(R1),NG=V({uri:L(),mimeType:Wb(L()),_meta:$b(L(),wb()).optional()}),EG=NG.extend({text:L()}),g4=L().refine((b)=>{try{return atob(b),!0}catch{return!1}},{message:"Invalid Base64 string"}),TG=NG.extend({blob:g4}),v1=Pb(["user","assistant"]),iw=V({audience:f(v1).optional(),priority:p().min(0).max(1).optional(),lastModified:V1.datetime({offset:!0}).optional()}),_G=V({...nw.shape,...T1.shape,uri:L(),description:Wb(L()),mimeType:Wb(L()),annotations:iw.optional(),_meta:Wb(Ub({}))}),d5=V({...nw.shape,...T1.shape,uriTemplate:L(),description:Wb(L()),mimeType:Wb(L()),annotations:iw.optional(),_meta:Wb(Ub({}))}),m4=_1.extend({method:N("resources/list")}),t5=S1.extend({resources:f(_G)}),r5=_1.extend({method:N("resources/templates/list")}),e5=S1.extend({resourceTemplates:f(d5)}),n4=Tb.extend({uri:L()}),s5=n4,l4=zb.extend({method:N("resources/read"),params:s5}),a5=Ab.extend({contents:f(r([EG,TG]))}),bA=kb.extend({method:N("notifications/resources/list_changed"),params:Rb.optional()}),wA=n4,$A=zb.extend({method:N("resources/subscribe"),params:wA}),WA=n4,QA=zb.extend({method:N("resources/unsubscribe"),params:WA}),GA=Rb.extend({uri:L()}),XA=kb.extend({method:N("notifications/resources/updated"),params:GA}),YA=V({name:L(),description:Wb(L()),required:Wb(Hb())}),HA=V({...nw.shape,...T1.shape,description:Wb(L()),arguments:Wb(f(YA)),_meta:Wb(Ub({}))}),JA=_1.extend({method:N("prompts/list")}),DA=S1.extend({prompts:f(HA)}),zA=Tb.extend({name:L(),arguments:$b(L(),L()).optional()}),AA=zb.extend({method:N("prompts/get"),params:zA}),i4=V({type:N("text"),text:L(),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),p4=V({type:N("image"),data:g4,mimeType:L(),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),o4=V({type:N("audio"),data:g4,mimeType:L(),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),OA=V({type:N("tool_use"),name:L(),id:L(),input:$b(L(),wb()),_meta:$b(L(),wb()).optional()}),qA=V({type:N("resource"),resource:r([EG,TG]),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),LA=_G.extend({type:N("resource_link")}),d4=r([i4,p4,o4,LA,qA]),UA=V({role:v1,content:d4}),BA=Ab.extend({description:L().optional(),messages:f(UA)}),FA=kb.extend({method:N("notifications/prompts/list_changed"),params:Rb.optional()}),KA=V({title:L().optional(),readOnlyHint:Hb().optional(),destructiveHint:Hb().optional(),idempotentHint:Hb().optional(),openWorldHint:Hb().optional()}),PA=V({taskSupport:Pb(["required","optional","forbidden"]).optional()}),SG=V({...nw.shape,...T1.shape,description:L().optional(),inputSchema:V({type:N("object"),properties:$b(L(),Db).optional(),required:f(L()).optional()}).catchall(wb()),outputSchema:V({type:N("object"),properties:$b(L(),Db).optional(),required:f(L()).optional()}).catchall(wb()).optional(),annotations:KA.optional(),execution:PA.optional(),_meta:$b(L(),wb()).optional()}),t4=_1.extend({method:N("tools/list")}),MA=S1.extend({tools:f(SG)}),o0=Ab.extend({content:f(d4).default([]),structuredContent:$b(L(),wb()).optional(),isError:Hb().optional()}),RI=o0.or(Ab.extend({toolResult:wb()})),ZA=N1.extend({name:L(),arguments:$b(L(),wb()).optional()}),C1=zb.extend({method:N("tools/call"),params:ZA}),IA=kb.extend({method:N("notifications/tools/list_changed"),params:Rb.optional()}),kI=V({autoRefresh:Hb().default(!0),debounceMs:p().int().nonnegative().default(300)}),x1=Pb(["debug","info","notice","warning","error","critical","alert","emergency"]),jA=Tb.extend({level:x1}),r4=zb.extend({method:N("logging/setLevel"),params:jA}),VA=Rb.extend({level:x1,logger:L().optional(),data:wb()}),NA=kb.extend({method:N("notifications/message"),params:VA}),EA=V({name:L().optional()}),TA=V({hints:f(EA).optional(),costPriority:p().min(0).max(1).optional(),speedPriority:p().min(0).max(1).optional(),intelligencePriority:p().min(0).max(1).optional()}),_A=V({mode:Pb(["auto","required","none"]).optional()}),SA=V({type:N("tool_result"),toolUseId:L().describe("The unique identifier for the corresponding tool call."),content:f(d4).default([]),structuredContent:V({}).loose().optional(),isError:Hb().optional(),_meta:$b(L(),wb()).optional()}),RA=k4("type",[i4,p4,o4]),C0=k4("type",[i4,p4,o4,OA,SA]),kA=V({role:v1,content:r([C0,f(C0)]),_meta:$b(L(),wb()).optional()}),vA=N1.extend({messages:f(kA),modelPreferences:TA.optional(),systemPrompt:L().optional(),includeContext:Pb(["none","thisServer","allServers"]).optional(),temperature:p().optional(),maxTokens:p().int(),stopSequences:f(L()).optional(),metadata:Db.optional(),tools:f(SG).optional(),toolChoice:_A.optional()}),CA=zb.extend({method:N("sampling/createMessage"),params:vA}),e4=Ab.extend({model:L(),stopReason:Wb(Pb(["endTurn","stopSequence","maxTokens"]).or(L())),role:v1,content:RA}),s4=Ab.extend({model:L(),stopReason:Wb(Pb(["endTurn","stopSequence","maxTokens","toolUse"]).or(L())),role:v1,content:r([C0,f(C0)])}),xA=V({type:N("boolean"),title:L().optional(),description:L().optional(),default:Hb().optional()}),uA=V({type:N("string"),title:L().optional(),description:L().optional(),minLength:p().optional(),maxLength:p().optional(),format:Pb(["email","uri","date","date-time"]).optional(),default:L().optional()}),yA=V({type:Pb(["number","integer"]),title:L().optional(),description:L().optional(),minimum:p().optional(),maximum:p().optional(),default:p().optional()}),hA=V({type:N("string"),title:L().optional(),description:L().optional(),enum:f(L()),default:L().optional()}),fA=V({type:N("string"),title:L().optional(),description:L().optional(),oneOf:f(V({const:L(),title:L()})),default:L().optional()}),cA=V({type:N("string"),title:L().optional(),description:L().optional(),enum:f(L()),enumNames:f(L()).optional(),default:L().optional()}),gA=r([hA,fA]),mA=V({type:N("array"),title:L().optional(),description:L().optional(),minItems:p().optional(),maxItems:p().optional(),items:V({type:N("string"),enum:f(L())}),default:f(L()).optional()}),nA=V({type:N("array"),title:L().optional(),description:L().optional(),minItems:p().optional(),maxItems:p().optional(),items:V({anyOf:f(V({const:L(),title:L()}))}),default:f(L()).optional()}),lA=r([mA,nA]),iA=r([cA,gA,lA]),pA=r([iA,xA,uA,yA]),oA=N1.extend({mode:N("form").optional(),message:L(),requestedSchema:V({type:N("object"),properties:$b(L(),pA),required:f(L()).optional()})}),dA=N1.extend({mode:N("url"),message:L(),elicitationId:L(),url:L().url()}),tA=r([oA,dA]),rA=zb.extend({method:N("elicitation/create"),params:tA}),eA=Rb.extend({elicitationId:L()}),sA=kb.extend({method:N("notifications/elicitation/complete"),params:eA}),d0=Ab.extend({action:Pb(["accept","decline","cancel"]),content:v4((b)=>b===null?void 0:b,$b(L(),r([L(),p(),Hb(),f(L())])).optional())}),aA=V({type:N("ref/resource"),uri:L()});var bO=V({type:N("ref/prompt"),name:L()}),wO=Tb.extend({ref:r([bO,aA]),argument:V({name:L(),value:L()}),context:V({arguments:$b(L(),L()).optional()}).optional()}),$O=zb.extend({method:N("completion/complete"),params:wO});var WO=Ab.extend({completion:Ub({values:f(L()).max(100),total:Wb(p().int()),hasMore:Wb(Hb())})}),QO=V({uri:L().startsWith("file://"),name:L().optional(),_meta:$b(L(),wb()).optional()}),GO=zb.extend({method:N("roots/list"),params:Tb.optional()}),a4=Ab.extend({roots:f(QO)}),XO=kb.extend({method:N("notifications/roots/list_changed"),params:Rb.optional()}),vI=r([f0,f4,$O,r4,AA,JA,m4,r5,l4,$A,QA,C1,t4,g0,n0,l0,p0]),CI=r([h0,c0,c4,XO,k1]),xI=r([y0,e4,s4,d0,a4,m0,i0,lw]),uI=r([f0,CA,rA,GO,g0,n0,l0,p0]),yI=r([h0,c0,NA,XA,bA,IA,FA,k1,sA]),hI=r([y0,m5,WO,BA,DA,t5,e5,a5,o0,MA,m0,i0,lw]);class x extends Error{constructor(b,w,$){super(`MCP error ${b}: ${w}`);this.code=b,this.data=$,this.name="McpError"}static fromError(b,w,$){if(b===c.UrlElicitationRequired&&$){let W=$;if(W.elicitations)return new RG(W.elicitations,w)}return new x(b,w,$)}}class RG extends x{constructor(b,w=`URL elicitation${b.length>1?"s":""} required`){super(c.UrlElicitationRequired,w,{elicitations:b})}get elicitations(){return this.data?.elicitations??[]}}function Mw(b){return b==="completed"||b==="failed"||b==="cancelled"}var YO=Symbol("Let zodToJsonSchema decide on which parser to use");var Bj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function b6(b){let $=R0(b)?.method;if(!$)throw Error("Schema is missing a method literal");let W=f8($);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function w6(b,w){let $=Kw(b,w);if(!$.success)throw $.error;return $.data}var OO=60000;class $6{constructor(b){if(this._options=b,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(h0,(w)=>{this._oncancel(w)}),this.setNotificationHandler(c0,(w)=>{this._onprogress(w)}),this.setRequestHandler(f0,(w)=>({})),this._taskStore=b?.taskStore,this._taskMessageQueue=b?.taskMessageQueue,this._taskStore)this.setRequestHandler(g0,async(w,$)=>{let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new x(c.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(n0,async(w,$)=>{let W=async()=>{let Q=w.params.taskId;if(this._taskMessageQueue){let X;while(X=await this._taskMessageQueue.dequeue(Q,$.sessionId)){if(X.type==="response"||X.type==="error"){let Y=X.message,H=Y.id,J=this._requestResolvers.get(H);if(J)if(this._requestResolvers.delete(H),X.type==="response")J(Y);else{let D=Y,z=new x(D.error.code,D.error.message,D.error.data);J(z)}else{let D=X.type==="response"?"Response":"Error";this._onerror(Error(`${D} handler missing for request ${H}`))}continue}await this._transport?.send(X.message,{relatedRequestId:$.requestId})}}let G=await this._taskStore.getTask(Q,$.sessionId);if(!G)throw new x(c.InvalidParams,`Task not found: ${Q}`);if(!Mw(G.status))return await this._waitForTaskUpdate(Q,$.signal),await W();if(Mw(G.status)){let X=await this._taskStore.getTaskResult(Q,$.sessionId);return this._clearTaskQueue(Q),{...X,_meta:{...X._meta,[Pw]:{taskId:Q}}}}return await W()};return await W()}),this.setRequestHandler(l0,async(w,$)=>{try{let{tasks:W,nextCursor:Q}=await this._taskStore.listTasks(w.params?.cursor,$.sessionId);return{tasks:W,nextCursor:Q,_meta:{}}}catch(W){throw new x(c.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(p0,async(w,$)=>{try{let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new x(c.InvalidParams,`Task not found: ${w.params.taskId}`);if(Mw(W.status))throw new x(c.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(w.params.taskId,"cancelled","Client cancelled task execution.",$.sessionId),this._clearTaskQueue(w.params.taskId);let Q=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!Q)throw new x(c.InvalidParams,`Task not found after cancellation: ${w.params.taskId}`);return{_meta:{},...Q}}catch(W){if(W instanceof x)throw W;throw new x(c.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(b){if(!b.params.requestId)return;this._requestHandlerAbortControllers.get(b.params.requestId)?.abort(b.params.reason)}_setupTimeout(b,w,$,W,Q=!1){this._timeoutInfo.set(b,{timeoutId:setTimeout(W,w),startTime:Date.now(),timeout:w,maxTotalTimeout:$,resetTimeoutOnProgress:Q,onTimeout:W})}_resetTimeout(b){let w=this._timeoutInfo.get(b);if(!w)return!1;let $=Date.now()-w.startTime;if(w.maxTotalTimeout&&$>=w.maxTotalTimeout)throw this._timeoutInfo.delete(b),x.fromError(c.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:w.maxTotalTimeout,totalElapsed:$});return clearTimeout(w.timeoutId),w.timeoutId=setTimeout(w.onTimeout,w.timeout),!0}_cleanupTimeout(b){let w=this._timeoutInfo.get(b);if(w)clearTimeout(w.timeoutId),this._timeoutInfo.delete(b)}async connect(b){this._transport=b;let w=this.transport?.onclose;this._transport.onclose=()=>{w?.(),this._onclose()};let $=this.transport?.onerror;this._transport.onerror=(Q)=>{$?.(Q),this._onerror(Q)};let W=this._transport?.onmessage;this._transport.onmessage=(Q,G)=>{if(W?.(Q,G),E1(Q)||ZG(Q))this._onresponse(Q);else if(u4(Q))this._onrequest(Q,G);else if(MG(Q))this._onnotification(Q);else this._onerror(Error(`Unknown message type: ${JSON.stringify(Q)}`))},await this._transport.start()}_onclose(){let b=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let w=x.fromError(c.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let $ of b.values())$(w)}_onerror(b){this.onerror?.(b)}_onnotification(b){let w=this._notificationHandlers.get(b.method)??this.fallbackNotificationHandler;if(w===void 0)return;Promise.resolve().then(()=>w(b)).catch(($)=>this._onerror(Error(`Uncaught error in notification handler: ${$}`)))}_onrequest(b,w){let $=this._requestHandlers.get(b.method)??this.fallbackRequestHandler,W=this._transport,Q=b.params?._meta?.[Pw]?.taskId;if($===void 0){let J={jsonrpc:"2.0",id:b.id,error:{code:c.MethodNotFound,message:"Method not found"}};if(Q&&this._taskMessageQueue)this._enqueueTaskMessage(Q,{type:"error",message:J,timestamp:Date.now()},W?.sessionId).catch((D)=>this._onerror(Error(`Failed to enqueue error response: ${D}`)));else W?.send(J).catch((D)=>this._onerror(Error(`Failed to send an error response: ${D}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set(b.id,G);let X=FG(b.params)?b.params.task:void 0,Y=this._taskStore?this.requestTaskStore(b,W?.sessionId):void 0,H={signal:G.signal,sessionId:W?.sessionId,_meta:b.params?._meta,sendNotification:async(J)=>{let D={relatedRequestId:b.id};if(Q)D.relatedTask={taskId:Q};await this.notification(J,D)},sendRequest:async(J,D,z)=>{let O={...z,relatedRequestId:b.id};if(Q&&!O.relatedTask)O.relatedTask={taskId:Q};let q=O.relatedTask?.taskId??Q;if(q&&Y)await Y.updateTaskStatus(q,"input_required");return await this.request(J,D,O)},authInfo:w?.authInfo,requestId:b.id,requestInfo:w?.requestInfo,taskId:Q,taskStore:Y,taskRequestedTtl:X?.ttl,closeSSEStream:w?.closeSSEStream,closeStandaloneSSEStream:w?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(X)this.assertTaskHandlerCapability(b.method)}).then(()=>$(b,H)).then(async(J)=>{if(G.signal.aborted)return;let D={result:J,jsonrpc:"2.0",id:b.id};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"response",message:D,timestamp:Date.now()},W?.sessionId);else await W?.send(D)},async(J)=>{if(G.signal.aborted)return;let D={jsonrpc:"2.0",id:b.id,error:{code:Number.isSafeInteger(J.code)?J.code:c.InternalError,message:J.message??"Internal error",...J.data!==void 0&&{data:J.data}}};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"error",message:D,timestamp:Date.now()},W?.sessionId);else await W?.send(D)}).catch((J)=>this._onerror(Error(`Failed to send response: ${J}`))).finally(()=>{this._requestHandlerAbortControllers.delete(b.id)})}_onprogress(b){let{progressToken:w,...$}=b.params,W=Number(w),Q=this._progressHandlers.get(W);if(!Q){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(b)}`));return}let G=this._responseHandlers.get(W),X=this._timeoutInfo.get(W);if(X&&G&&X.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(Y){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),G(Y);return}Q($)}_onresponse(b){let w=Number(b.id),$=this._requestResolvers.get(w);if($){if(this._requestResolvers.delete(w),E1(b))$(b);else{let G=new x(b.error.code,b.error.message,b.error.data);$(G)}return}let W=this._responseHandlers.get(w);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(b)}`));return}this._responseHandlers.delete(w),this._cleanupTimeout(w);let Q=!1;if(E1(b)&&b.result&&typeof b.result==="object"){let G=b.result;if(G.task&&typeof G.task==="object"){let X=G.task;if(typeof X.taskId==="string")Q=!0,this._taskProgressTokens.set(X.taskId,w)}}if(!Q)this._progressHandlers.delete(w);if(E1(b))W(b);else{let G=x.fromError(b.error.code,b.error.message,b.error.data);W(G)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(b,w,$){let{task:W}=$??{};if(!W){try{yield{type:"result",result:await this.request(b,w,$)}}catch(G){yield{type:"error",error:G instanceof x?G:new x(c.InternalError,String(G))}}return}let Q;try{let G=await this.request(b,lw,$);if(G.task)Q=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new x(c.InternalError,"Task creation did not return a task");while(!0){let X=await this.getTask({taskId:Q},$);if(yield{type:"taskStatus",task:X},Mw(X.status)){if(X.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:Q},w,$)};else if(X.status==="failed")yield{type:"error",error:new x(c.InternalError,`Task ${Q} failed`)};else if(X.status==="cancelled")yield{type:"error",error:new x(c.InternalError,`Task ${Q} was cancelled`)};return}if(X.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:Q},w,$)};return}let Y=X.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,Y)),$?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof x?G:new x(c.InternalError,String(G))}}}request(b,w,$){let{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G,task:X,relatedTask:Y}=$??{};return new Promise((H,J)=>{let D=(M)=>{J(M)};if(!this._transport){D(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(b.method),X)this.assertTaskCapability(b.method)}catch(M){D(M);return}$?.signal?.throwIfAborted();let z=this._requestMessageId++,O={...b,jsonrpc:"2.0",id:z};if($?.onprogress)this._progressHandlers.set(z,$.onprogress),O.params={...b.params,_meta:{...b.params?._meta||{},progressToken:z}};if(X)O.params={...O.params,task:X};if(Y)O.params={...O.params,_meta:{...O.params?._meta||{},[Pw]:Y}};let q=(M)=>{this._responseHandlers.delete(z),this._progressHandlers.delete(z),this._cleanupTimeout(z),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:z,reason:String(M)}},{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let k=M instanceof x?M:new x(c.RequestTimeout,String(M));J(k)};this._responseHandlers.set(z,(M)=>{if($?.signal?.aborted)return;if(M instanceof Error)return J(M);try{let k=Kw(w,M.result);if(!k.success)J(k.error);else H(k.data)}catch(k){J(k)}}),$?.signal?.addEventListener("abort",()=>{q($?.signal?.reason)});let B=$?.timeout??OO,K=()=>q(x.fromError(c.RequestTimeout,"Request timed out",{timeout:B}));this._setupTimeout(z,B,$?.maxTotalTimeout,K,$?.resetTimeoutOnProgress??!1);let Z=Y?.taskId;if(Z){let M=(k)=>{let S=this._responseHandlers.get(z);if(S)S(k);else this._onerror(Error(`Response handler missing for side-channeled request ${z}`))};this._requestResolvers.set(z,M),this._enqueueTaskMessage(Z,{type:"request",message:O,timestamp:Date.now()}).catch((k)=>{this._cleanupTimeout(z),J(k)})}else this._transport.send(O,{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G}).catch((M)=>{this._cleanupTimeout(z),J(M)})})}async getTask(b,w){return this.request({method:"tasks/get",params:b},m0,w)}async getTaskResult(b,w,$){return this.request({method:"tasks/result",params:b},w,$)}async listTasks(b,w){return this.request({method:"tasks/list",params:b},i0,w)}async cancelTask(b,w){return this.request({method:"tasks/cancel",params:b},VG,w)}async notification(b,w){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(b.method);let $=w?.relatedTask?.taskId;if($){let X={...b,jsonrpc:"2.0",params:{...b.params,_meta:{...b.params?._meta||{},[Pw]:w.relatedTask}}};await this._enqueueTaskMessage($,{type:"notification",message:X,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(b.method)&&!b.params&&!w?.relatedRequestId&&!w?.relatedTask){if(this._pendingDebouncedNotifications.has(b.method))return;this._pendingDebouncedNotifications.add(b.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(b.method),!this._transport)return;let X={...b,jsonrpc:"2.0"};if(w?.relatedTask)X={...X,params:{...X.params,_meta:{...X.params?._meta||{},[Pw]:w.relatedTask}}};this._transport?.send(X,w).catch((Y)=>this._onerror(Y))});return}let G={...b,jsonrpc:"2.0"};if(w?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[Pw]:w.relatedTask}}};await this._transport.send(G,w)}setRequestHandler(b,w){let $=b6(b);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(W,Q)=>{let G=w6(b,W);return Promise.resolve(w(G,Q))})}removeRequestHandler(b){this._requestHandlers.delete(b)}assertCanSetRequestHandler(b){if(this._requestHandlers.has(b))throw Error(`A request handler for ${b} already exists, which would be overridden`)}setNotificationHandler(b,w){let $=b6(b);this._notificationHandlers.set($,(W)=>{let Q=w6(b,W);return Promise.resolve(w(Q))})}removeNotificationHandler(b){this._notificationHandlers.delete(b)}_cleanupTaskProgressHandler(b){let w=this._taskProgressTokens.get(b);if(w!==void 0)this._progressHandlers.delete(w),this._taskProgressTokens.delete(b)}async _enqueueTaskMessage(b,w,$){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(b,w,$,W)}async _clearTaskQueue(b,w){if(this._taskMessageQueue){let $=await this._taskMessageQueue.dequeueAll(b,w);for(let W of $)if(W.type==="request"&&u4(W.message)){let Q=W.message.id,G=this._requestResolvers.get(Q);if(G)G(new x(c.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(Q);else this._onerror(Error(`Resolver missing for request ${Q} during task ${b} cleanup`))}}}async _waitForTaskUpdate(b,w){let $=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(b);if(W?.pollInterval)$=W.pollInterval}catch{}return new Promise((W,Q)=>{if(w.aborted){Q(new x(c.InvalidRequest,"Request cancelled"));return}let G=setTimeout(W,$);w.addEventListener("abort",()=>{clearTimeout(G),Q(new x(c.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(b,w){let $=this._taskStore;if(!$)throw Error("No task store configured");return{createTask:async(W)=>{if(!b)throw Error("No request provided");return await $.createTask(W,b.id,{method:b.method,params:b.params},w)},getTask:async(W)=>{let Q=await $.getTask(W,w);if(!Q)throw new x(c.InvalidParams,"Failed to retrieve task: Task not found");return Q},storeTaskResult:async(W,Q,G)=>{await $.storeTaskResult(W,Q,G,w);let X=await $.getTask(W,w);if(X){let Y=k1.parse({method:"notifications/tasks/status",params:X});if(await this.notification(Y),Mw(X.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return $.getTaskResult(W,w)},updateTaskStatus:async(W,Q,G)=>{let X=await $.getTask(W,w);if(!X)throw new x(c.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(Mw(X.status))throw new x(c.InvalidParams,`Cannot update task "${W}" from terminal status "${X.status}" to "${Q}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await $.updateTaskStatus(W,Q,G,w);let Y=await $.getTask(W,w);if(Y){let H=k1.parse({method:"notifications/tasks/status",params:Y});if(await this.notification(H),Mw(Y.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return $.listTasks(W,w)}}}}function kG(b){return b!==null&&typeof b==="object"&&!Array.isArray(b)}function vG(b,w){let $={...b};for(let W in w){let Q=W,G=w[Q];if(G===void 0)continue;let X=$[Q];if(kG(X)&&kG(G))$[Q]={...X,...G};else $[Q]=G}return $}var DD=CW(r6(),1),zD=CW(JD(),1);function ZP(){let b=new DD.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return zD.default(b),b}class XW{constructor(b){this._ajv=b??ZP()}getValidator(b){let w="$id"in b&&typeof b.$id==="string"?this._ajv.getSchema(b.$id)??this._ajv.compile(b):this._ajv.compile(b);return($)=>{if(w($))return{valid:!0,data:$,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(w.errors)}}}}class YW{constructor(b){this._server=b}requestStream(b,w,$){return this._server.requestStream(b,w,$)}async getTask(b,w){return this._server.getTask({taskId:b},w)}async getTaskResult(b,w,$){return this._server.getTaskResult({taskId:b},w,$)}async listTasks(b,w){return this._server.listTasks(b?{cursor:b}:void 0,w)}async cancelTask(b,w){return this._server.cancelTask({taskId:b},w)}}function AD(b,w,$){if(!b)throw Error(`${$} does not support task creation (required for ${w})`);switch(w){case"tools/call":if(!b.tools?.call)throw Error(`${$} does not support task creation for tools/call (required for ${w})`);break;default:break}}function OD(b,w,$){if(!b)throw Error(`${$} does not support task creation (required for ${w})`);switch(w){case"sampling/createMessage":if(!b.sampling?.createMessage)throw Error(`${$} does not support task creation for sampling/createMessage (required for ${w})`);break;case"elicitation/create":if(!b.elicitation?.create)throw Error(`${$} does not support task creation for elicitation/create (required for ${w})`);break;default:break}}class HW extends $6{constructor(b,w){super(w);if(this._serverInfo=b,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(x1.options.map(($,W)=>[$,W])),this.isMessageIgnored=($,W)=>{let Q=this._loggingLevels.get(W);return Q?this.LOG_LEVEL_SEVERITY.get($)<this.LOG_LEVEL_SEVERITY.get(Q):!1},this._capabilities=w?.capabilities??{},this._instructions=w?.instructions,this._jsonSchemaValidator=w?.jsonSchemaValidator??new XW,this.setRequestHandler(f4,($)=>this._oninitialize($)),this.setNotificationHandler(c4,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(r4,async($,W)=>{let Q=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:G}=$.params,X=x1.safeParse(G);if(X.success)this._loggingLevels.set(Q,X.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new YW(this)};return this._experimental}registerCapabilities(b){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=vG(this._capabilities,b)}setRequestHandler(b,w){let W=R0(b)?.method;if(!W)throw Error("Schema is missing a method literal");let Q;if(mw(W)){let X=W;Q=X._zod?.def?.value??X.value}else{let X=W;Q=X._def?.value??X.value}if(typeof Q!=="string")throw Error("Schema method literal must be a string");if(Q==="tools/call"){let X=async(Y,H)=>{let J=Kw(C1,Y);if(!J.success){let q=J.error instanceof Error?J.error.message:String(J.error);throw new x(c.InvalidParams,`Invalid tools/call request: ${q}`)}let{params:D}=J.data,z=await Promise.resolve(w(Y,H));if(D.task){let q=Kw(lw,z);if(!q.success){let B=q.error instanceof Error?q.error.message:String(q.error);throw new x(c.InvalidParams,`Invalid task creation result: ${B}`)}return q.data}let O=Kw(o0,z);if(!O.success){let q=O.error instanceof Error?O.error.message:String(O.error);throw new x(c.InvalidParams,`Invalid tools/call result: ${q}`)}return O.data};return super.setRequestHandler(b,X)}return super.setRequestHandler(b,w)}assertCapabilityForMethod(b){switch(b){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${b})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${b})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${b})`);break;case"ping":break}}assertNotificationCapability(b){switch(b){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);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 ${b})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${b})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${b})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${b})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(b){if(!this._capabilities)return;switch(b){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${b})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${b})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${b})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${b})`);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 ${b})`);break;case"ping":case"initialize":break}}assertTaskCapability(b){OD(this._clientCapabilities?.tasks?.requests,b,"Client")}assertTaskHandlerCapability(b){if(!this._capabilities)return;AD(this._capabilities.tasks?.requests,b,"Server")}async _oninitialize(b){let w=b.params.protocolVersion;return this._clientCapabilities=b.params.capabilities,this._clientVersion=b.params.clientInfo,{protocolVersion:LG.includes(w)?w:C4,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"},y0)}async createMessage(b,w){if(b.tools||b.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(b.messages.length>0){let $=b.messages[b.messages.length-1],W=Array.isArray($.content)?$.content:[$.content],Q=W.some((H)=>H.type==="tool_result"),G=b.messages.length>1?b.messages[b.messages.length-2]:void 0,X=G?Array.isArray(G.content)?G.content:[G.content]:[],Y=X.some((H)=>H.type==="tool_use");if(Q){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!Y)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(Y){let H=new Set(X.filter((D)=>D.type==="tool_use").map((D)=>D.id)),J=new Set(W.filter((D)=>D.type==="tool_result").map((D)=>D.toolUseId));if(H.size!==J.size||![...H].every((D)=>J.has(D)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(b.tools)return this.request({method:"sampling/createMessage",params:b},s4,w);return this.request({method:"sampling/createMessage",params:b},e4,w)}async elicitInput(b,w){switch(b.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=b;return this.request({method:"elicitation/create",params:W},d0,w)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=b.mode==="form"?b:{...b,mode:"form"},Q=await this.request({method:"elicitation/create",params:W},d0,w);if(Q.action==="accept"&&Q.content&&W.requestedSchema)try{let X=this._jsonSchemaValidator.getValidator(W.requestedSchema)(Q.content);if(!X.valid)throw new x(c.InvalidParams,`Elicitation response content does not match requested schema: ${X.errorMessage}`)}catch(G){if(G instanceof x)throw G;throw new x(c.InternalError,`Error validating elicitation response: ${G instanceof Error?G.message:String(G)}`)}return Q}}}createElicitationCompletionNotifier(b,w){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:b}},w)}async listRoots(b,w){return this.request({method:"roots/list",params:b},a4,w)}async sendLoggingMessage(b,w){if(this._capabilities.logging){if(!this.isMessageIgnored(b.level,w))return this.notification({method:"notifications/message",params:b})}}async sendResourceUpdated(b){return this.notification({method:"notifications/resources/updated",params:b})}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 qD={name:"@sequenzy/mcp",version:"0.0.110",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 JW=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],LD={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 jP(b){let $=(b??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return $.length>0?$:"https://sequenzy.com"}function nb(b){let w=b?.trim();return w?w:void 0}function rb(b){return encodeURIComponent(b)}function Xb(b,w){return`${b}${w}`}function Yb(b,w=""){return`/dashboard/company/${rb(b)}${w}`}function UD(b,w,$){return Xb(b,`${Yb(w,"/settings")}?tab=${encodeURIComponent($)}`)}function VP(b,w){let $=JW.map((W)=>[W,w?UD(b,w,W):""]);return Object.fromEntries($)}function Hw(b={},w){let $=jP(w),W=nb(b.companyId),Q={},G=VP($,W);if(!W)return{appUrl:$,routeTemplates:LD,settingsTabValues:JW,urls:Q,settingsUrls:G};Q.dashboard=Xb($,Yb(W)),Q.campaigns=Xb($,Yb(W,"/campaign")),Q.landingPages=Xb($,Yb(W,"/landing-pages")),Q.sequences=Xb($,Yb(W,"/sequences")),Q.settings=Xb($,Yb(W,"/settings")),Q.emails=Xb($,Yb(W,"/emails")),Q.subscribers=Xb($,Yb(W,"/subscribers")),Q.sentEmails=Xb($,Yb(W,"/sent-emails")),Q.segments=Xb($,Yb(W,"/segments")),Q.metrics=Xb($,Yb(W,"/metrics")),Q.transactional=Xb($,Yb(W,"/transactional"));let X=nb(b.campaignId);if(X)Q.campaign=Xb($,Yb(W,`/campaign/${rb(X)}`)),Q.campaignPreview=`${Q.campaign}?step=review`;let Y=nb(b.landingPageId);if(Y)Q.landingPage=Xb($,Yb(W,`/landing-pages/${rb(Y)}`));let H=nb(b.sequenceId);if(H)Q.sequence=Xb($,Yb(W,`/sequences/${rb(H)}`));let J=nb(b.emailId)??nb(b.templateId);if(J)Q.email=Xb($,Yb(W,`/emails/${rb(J)}`)),Q.template=Q.email;let D=nb(b.transactionalId);if(D)Q.transactionalEmail=Xb($,Yb(W,`/transactional/${rb(D)}`));let z=nb(b.emailSendId);if(z)Q.emailSend=Xb($,Yb(W,`/sent-emails/${rb(z)}`));let O=nb(b.domainId);if(O)Q.domain=Xb($,Yb(W,`/settings/domain/${rb(O)}`)),Q.domainVerify=`${Q.domain}/verify`;let q=nb(b.status);if(q)Q.campaignList=Xb($,Yb(W,`/campaign/list/${rb(q)}`)),Q.sequenceList=Xb($,Yb(W,`/sequences/list/${rb(q)}`));let B=nb(b.settingsTab);if(B)Q.settingsTab=UD($,W,B);return{appUrl:$,routeTemplates:LD,settingsTabValues:JW,urls:Q,settingsUrls:G}}var BD=[{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 FD(b){try{let w;switch(b){case"sequenzy://dashboard":w=await A("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let $=await A("GET","/api/v1/account"),W=qw()??$.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");w=await A("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":w=await A("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":w=await A("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":w=await A("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":w=await A("GET","/api/v1/sequences");break;case"sequenzy://templates":w=await A("GET","/api/v1/templates");break;case"sequenzy://segments":w=await A("GET","/api/v1/segments");break;case"sequenzy://tags":w=await A("GET","/api/v1/tags");break;case"sequenzy://health":w=await A("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":w=Hw();break;default:throw Error(`Unknown resource: ${b}`)}return{contents:[{uri:b,mimeType:"application/json",text:JSON.stringify(w,null,2)}]}}catch(w){return{contents:[{uri:b,mimeType:"text/plain",text:Ow(w)}]}}}function y(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}function F(b,w){let $=b[w];if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function j(b,w,$){let W=F(w,$);if(W===void 0)throw Error(`\`${$}\` is required when calling \`${b}\`.`);return W}var _w='For exact historical Poll/NPS respondents, use field `pollResponse`, operator `is`, and a JSON value shaped like {"v":1,"campaignId":"camp_123","blockId":"poll_1","match":{"kind":"answer","value":"loved"}}. For NPS buckets, use match {"kind":"npsBucket","bucket":"promoters"}; bucket may be `promoters`, `passives`, or `detractors`.',Jw='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: [...] }. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',Dw='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`. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',W1='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. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',X0="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.",KD="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.",DW=500,zW=500,lb={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},v$=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay"],C$={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},NP={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},Q1={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:NP,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},G1={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},AW={type:"object",description:"Type-aware patch for the existing node. Start from get_sequence.sequence.nodes[].config. For logic_delay, set exactly one of delay ({ days, hours, minutes }), delayMs, or waitUntil; optional label is also accepted. For action_email, use name/label, subject, previewText, html/htmlContent or blocks, isTransactional, and sender/reply identity fields. For action_sms, use text, blocks, imageUrls, label, or ineligibleAction. Other node types accept their editable config keys. Managed IDs, nodeType conversion, and branch path IDs/count are not editable here; use edit_sequence_graph for topology. Webhook header patches are merged, and redacted values from get_sequence must be omitted or replaced with a real new value.",additionalProperties:!0},x$={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:AW,expectedUpdatedAt:{type:"string",description:"Required optimistic-concurrency value from get_sequence.sequence.nodes[].updatedAt. The update is rejected if that node or its linked email content changed after it was read."}},required:["nodeId","changes","expectedUpdatedAt"],additionalProperties:!1},X1=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],Y1=["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","poll.answered"];var EP=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"]),TP=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","upload_image_asset","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","set_template_localization","sync_template_localizations","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","update_sequence_node","update_sequence_nodes","edit_sequence_graph","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"]),_P=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"]),SP=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","edit_sequence_graph","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook"]);function RP(b){let w=EP.has(b),$=TP.has(b);if(w===$)throw Error(`MCP tool "${b}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:w,destructiveHint:w?!1:SP.has(b),openWorldHint:_P.has(b)}}function PD(b){return{...b,annotations:{...b.annotations,...RP(b.name)}}}var OW={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"],pollResponse:["is"],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"]},kP=Object.entries(OW).map(([b,w])=>`${b}: ${w.join(", ")}`).join("; "),qW={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","pollResponse","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. ${_w}`},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: ${kP}.`},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). ${_w}`}},required:["field","operator","value"],additionalProperties:!1},LW={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 u$(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(typeof w!=="object"||w===null)return w;let $=w;if(typeof $.id==="string"&&$.id.trim()!=="")return $;return{...$,id:crypto.randomUUID()}})}function y$(b){if(typeof b!=="object"||b===null)return b;let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=u$([w]);return Array.isArray($)?$[0]:w}if(w.kind!=="group")return b;return{...w,id:typeof w.id==="string"&&w.id.trim()!==""?w.id:crypto.randomUUID(),children:Array.isArray(w.children)?w.children.map(y$):[]}}function vP(b){let w=b.indexOf(":");return w!==-1&&b.substring(0,w).trim().length>0}function CP(b){let w=b.indexOf(":");return w!==-1&&b.substring(w+1).trim().length>0}function MD(b){if(b==="all")return!0;let w=b.match(/^(\d+)d$/);if(!w?.[1])return!1;let $=Number.parseInt(w[1],10);return Number.isInteger($)&&$>0}function xP(b,w){let $=w.split(":");if(b==="at_least"||b==="less_than_count"){if($.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let G=$.slice(0,-2).join(":").trim(),X=$.at(-2),Y=$.at(-1),H=X===void 0?Number.NaN:Number.parseInt(X,10);return G&&Number.isInteger(H)&&H>0&&Y!==void 0&&MD(Y)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if($.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=$.slice(0,-1).join(":").trim(),Q=$.at(-1);return W&&Q!==void 0&&MD(Q)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function uP(b){let w=b.indexOf(":");if(w===-1)return{productId:b,subfilter:null,rawValue:null};let $=b.substring(0,w),W=b.substring(w+1),Q=W.indexOf(":");if(Q===-1)return{productId:$,subfilter:W,rawValue:null};return{productId:$,subfilter:W.substring(0,Q),rawValue:W.substring(Q+1)}}function yP(b){return b.trim().toLowerCase().replace(/[-\s]+/g,"_")}function hP(b){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(b)}function fP(b,w){if(w==="cancels_at"||w==="cancel_at"||w==="cancellation_at")return!0;if(b==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(w);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(w)}function cP(b){return["is","is_not","gte","lte","gt","lt"].includes(b)}function gP(b,w,$){if(b==="stripeProduct"){if(w!=="at_least"&&w!=="less_than_count")return null;let Y=$.indexOf(":");if(Y===-1)return null;let H=$.substring(0,Y).trim(),J=Number.parseInt($.substring(Y+1).trim(),10);return H&&Number.isInteger(J)&&J>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(b!=="stripeCurrentProduct"&&b!=="stripeTrialProduct")return null;let{productId:W,subfilter:Q,rawValue:G}=uP($);if(!W.trim())return"Stripe product filters must include a product ID.";if(!Q)return w==="is"||w==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let X=yP(Q);if(hP(X))return w==="is"||w==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!fP(b,X))return`Unsupported Stripe product subfilter "${Q}".`;if(!cP(w))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return G?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var mP=new Set(["shopify","woocommerce","api"]);function nP(b,w){let $=w.trim(),W=$.indexOf(":");if(W!==-1&&mP.has($.substring(0,W).trim()))$=$.substring(W+1).trim();if(!$)return'Purchased Product filters must include a product ID, like "shopify:42".';if(b!=="at_least"&&b!=="less_than_count")return null;let Q=$.lastIndexOf(":");if(Q===-1)return null;let G=$.substring(0,Q).trim(),X=Number.parseInt($.substring(Q+1).trim(),10);return G&&Number.isInteger(X)&&X>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function lP(b){let w;try{w=JSON.parse(b)}catch{return`Poll response filters must use valid JSON. ${_w}`}if(!y(w)||w.v!==1||typeof w.campaignId!=="string"||!w.campaignId.trim()||typeof w.blockId!=="string"||!w.blockId.trim()||!y(w.match))return`Poll response filter context is invalid. ${_w}`;let $=w.match;if($.kind==="answer"&&typeof $.value==="string"&&$.value.length>0)return null;if($.kind==="npsBucket"&&($.bucket==="promoters"||$.bucket==="passives"||$.bucket==="detractors"))return null;return`Poll response filter match is invalid. ${_w}`}function h$(b){if(typeof b!=="object"||b===null)return"Segment filters must be objects.";let w=b,$=w.field,W=w.operator,Q=w.value;if(typeof $!=="string"||!($ in OW))return`Unsupported segment filter field "${String($)}".`;if(typeof W!=="string")return`Segment filter "${$}" must include an operator.`;let G=OW[$];if(!G.includes(W))return`Operator "${W}" is not supported for ${$} filters. Use one of: ${G.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof Q!=="string"||Q.trim().length===0))return`Segment filter "${$}" must include a value.`;if($==="attribute"&&typeof Q==="string"){if(!vP(Q))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!CP(Q))return'Attribute filters must include a value after "attributeName:".'}if($==="event"&&typeof Q==="string"){let X=xP(W,Q);if(X)return X}if($==="pollResponse"&&typeof Q==="string"){let X=lP(Q);if(X)return X}if(($==="stripeProduct"||$==="stripeCurrentProduct"||$==="stripeTrialProduct")&&typeof Q==="string"){let X=gP($,W,Q);if(X)return X}if($==="commerceProduct"&&typeof Q==="string"){let X=nP(W,Q);if(X)return X}if($==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof Q==="string"&&Q.split(",").map((Y)=>Y.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function f$(b){if(typeof b!=="object"||b===null)return[];let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=h$(w);return $?[$]:[]}if(Array.isArray(w.children))return w.children.flatMap(f$);return[]}function _b(b,w,$){if(w.html!==void 0&&w.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`, not both.`);if(w.blocks!==void 0&&!Array.isArray(w.blocks))throw Error(`\`blocks\` must be an array when calling \`${b}\`.`);if($?.requireContent&&w.html===void 0&&w.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`.`)}function H1(b,w){if(w.labels===void 0)return;if(!Array.isArray(w.labels))throw Error(`\`labels\` must be an array when calling \`${b}\`.`);if(w.labels.some(($)=>typeof $!=="string"||$.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${b}\`.`)}function jD(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!w&&!$)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=w?b.filters.flatMap((Q)=>{let G=h$(Q);return G?[G]:[]}):f$(b.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function VD(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(b.name===void 0&&b.filterJoinOperator===void 0&&!w&&!$)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=w?b.filters.flatMap((Q)=>{let G=h$(Q);return G?[G]:[]}):$?f$(b.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var UW=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"];function BW(b,w,$){if(w[$]!==void 0&&!y(w[$]))throw Error(`\`${$}\` must be an object when calling \`${b}\`.`)}function ZD(b,w,$){if(w[$]!==void 0&&!Array.isArray(w[$]))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`)}function ND(b){let w=new Set(["companyId",...UW]),$=Object.keys(b).filter((Q)=>!w.has(Q));if($.length>0)throw Error(`\`update_company\` accepts only company product-info fields. Unsupported field${$.length===1?"":"s"}: ${$.map((Q)=>`\`${Q}\``).join(", ")}.`);let W={};for(let Q of UW)if(b[Q]!==void 0)W[Q]=b[Q];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${UW.map((Q)=>`\`${Q}\``).join(", ")} when calling \`update_company\`.`);for(let Q of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"])if(b[Q]!==void 0&&typeof b[Q]!=="string")throw Error(`\`${Q}\` must be a string when calling \`update_company\`.`);if(BW("update_company",b,"brandColors"),BW("update_company",b,"socialLinks"),BW("update_company",b,"pricing"),ZD("update_company",b,"valueProps"),ZD("update_company",b,"testimonials"),typeof b.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(b.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let Q of["fromEmail","replyTo"]){let G=b[Q];if(typeof G==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(G.trim()))throw Error(`\`${Q}\` must be a valid email address when calling \`update_company\`.`)}if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_company`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_company`.");return W}var ED=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function iP(b){return ED.some((w)=>b[w]!==void 0)}function pP(b){if(typeof b.nodeType==="string")return b.nodeType==="action_email";return b.type===void 0||b.type==="email"}function c$(b,w,$){for(let W of ED){let Q=$[W];if(Q!==void 0&&typeof Q!=="string")throw Error(`\`${W}\` must be a string for ${w} when calling \`${b}\`.`)}if($.senderProfileId!==void 0&&$.fromEmail!==void 0)throw Error(`Provide either \`senderProfileId\` or \`fromEmail\` for ${w} when calling \`${b}\`, not both.`);if($.replyProfileId!==void 0&&$.replyTo!==void 0)throw Error(`Provide either \`replyProfileId\` or \`replyTo\` for ${w} when calling \`${b}\`, not both.`);if($.replyToName!==void 0&&$.replyTo===void 0)throw Error(`\`replyToName\` requires \`replyTo\` for ${w} when calling \`${b}\`.`)}function KW(b,w,$){if(iP($)&&!pP($))throw Error(`Sender identity fields are only supported for email steps at ${w} when calling \`${b}\`.`);c$(b,w,$)}function ID(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(y(W))c$(b,`${w}[${Q}]`,W)})}function FW(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(y(W))KW(b,`${w}[${Q}]`,W)})}function oP(b){if(ID("update_sequence","emails",b.emails),ID("update_sequence","steps",b.steps),y(b.insertSteps))FW("update_sequence","insertSteps.steps",b.insertSteps.steps);if(!y(b.branch))return;if(Array.isArray(b.branch.branches))b.branch.branches.forEach(($,W)=>{if(y($))FW("update_sequence",`branch.branches[${W}].steps`,$.steps)});FW("update_sequence","branch.elseSteps",b.branch.elseSteps)}function TD(b){if(b.fromEmail!==void 0&&b.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_sequence`, not both.");if(b.replyTo!==void 0&&b.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_sequence`, not both.");if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_sequence`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_sequence`.");if(b.clearEnrollmentFieldPath===!0&&b.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(b.clearSendingWindow===!0&&b.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(b.clearBccEmails===!0&&b.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(b.branch!==void 0&&b.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");oP(b);let w={...b};if(delete w.clearEnrollmentFieldPath,delete w.clearSendingWindow,delete w.clearBccEmails,b.clearEnrollmentFieldPath===!0)w.enrollmentFieldPath=null;if(b.clearSendingWindow===!0)w.sendingWindow=null;if(b.clearBccEmails===!0)w.bccEmails=null;return w}function _D(b,w,$){let W=j(b,w,"nodeId");if(!y(w.changes)||Object.keys(w.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${$} when calling \`${b}\`.`);let Q=j(b,w,"expectedUpdatedAt");return{nodeId:W,changes:w.changes,expectedUpdatedAt:Q}}function SD(b){let w=_D("update_sequence_node",b,"the node update");return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:[w]}}function RD(b){if(!Array.isArray(b.updates)||b.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let w=new Set,$=b.updates.map((W,Q)=>{if(!y(W))throw Error(`\`updates[${Q}]\` must be an object when calling \`update_sequence_nodes\`.`);let G=_D("update_sequence_nodes",W,`updates[${Q}]`),X=String(G.nodeId);if(w.has(X))throw Error(`\`updates[${Q}]\` targets duplicate nodeId '${X}' when calling \`update_sequence_nodes\`.`);return w.add(X),G});return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:$}}function kD(b){let w=j("edit_sequence_graph",b,"action"),$=j("edit_sequence_graph",b,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(w))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let Q=F(b,"nodeId"),G=F(b,"afterNodeId"),X=F(b,"beforeNodeId"),Y=b.edges;if(w!=="replace_edges"&&!Q)throw Error(`\`nodeId\` is required for ${w} when calling \`edit_sequence_graph\`.`);if(w==="replace_edges"&&Q)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let H=w==="move_node"||w==="duplicate_node";if(H&&(G?1:0)+(X?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${w} when calling \`edit_sequence_graph\`.`);if(!H&&(G||X))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${w} when calling \`edit_sequence_graph\`.`);if((w==="replace_edges"||w==="delete_node"&&Y!==void 0)&&(!Array.isArray(Y)||Y.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${w} when calling \`edit_sequence_graph\`.`);if((w==="move_node"||w==="duplicate_node")&&Y!==void 0)throw Error(`\`edges\` is not used with ${w} when calling \`edit_sequence_graph\`.`);let J=Array.isArray(Y)?Y.map((D,z)=>{if(!y(D))throw Error(`\`edges\` item ${z+1} must be an object when calling \`edit_sequence_graph\`.`);let O=j("edit_sequence_graph",D,"sourceNodeId"),q=j("edit_sequence_graph",D,"targetNodeId");if(D.condition!==void 0&&D.condition!==null&&!y(D.condition))throw Error(`\`edges\` item ${z+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:O,targetNodeId:q,...y(D.condition)?{condition:D.condition}:{}}}):void 0;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},graphEdit:{action:w,expectedRevision:$,...Q?{nodeId:Q}:{},...G?{afterNodeId:G}:{},...X?{beforeNodeId:X}:{},...J?{edges:J}:{}}}}function vD(b){let w=b.type==="sms",$;if(w){KW("insert_sequence_step","SMS step",b);let Q=F(b,"text"),G=Array.isArray(b.blocks)&&b.blocks.length>0;if(Q===void 0&&!G)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");$={type:"sms"};for(let X of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(b[X]!==void 0)$[X]=b[X]}else{_b("insert_sequence_step",b,{requireContent:!0}),c$("insert_sequence_step","email step",b),$={subject:j("insert_sequence_step",b,"subject")};for(let Q of["name","previewText","html","blocks","delay","delayMs","waitUntil","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"])if(b[Q]!==void 0)$[Q]=b[Q]}let W={steps:[$]};if(b.afterNodeId!==void 0)W.afterNodeId=b.afterNodeId;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},insertSteps:W}}function CD(b){let w=F(b,"subscriberId"),$=b.fieldValues,W=$===void 0?void 0:Array.isArray($)?$:void 0;if($!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let Q=W?.map((Y)=>typeof Y==="string"?Y.trim():"").filter((Y)=>Y.length>0)??[];if(W?.some((Y)=>typeof Y!=="string")||W!==void 0&&Q.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(w!==void 0===Q.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let G=F(b,"fieldPath"),X=F(b,"reason");return{...w!==void 0&&{subscriberId:w},...G!==void 0&&{fieldPath:G},...Q.length>0&&{fieldValues:Q},...typeof b.dryRun==="boolean"&&{dryRun:b.dryRun},...X!==void 0&&{reason:X}}}function xD(b){_b("create_campaign",b),H1("create_campaign",b);let w=F(b,"prompt")!==void 0,$=b.html!==void 0,W=b.blocks!==void 0,Q=b.templateId!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(w&&($||W||Q))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!w&&F(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function uD(b){_b("create_template",b),H1("create_template",b);let w=F(b,"prompt")!==void 0,$=[w,b.html!==void 0,b.blocks!==void 0].filter(Boolean).length;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_template`.");if($!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!w&&F(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function yD(b){if(F(b,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(b.targetLists!==void 0&&!y(b.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(b.sendTimeOptimization!==void 0){if(typeof b.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(b.spreadOverHours!==void 0){if(typeof b.spreadOverHours!=="number"||!Number.isInteger(b.spreadOverHours)||b.spreadOverHours<1||b.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(b.recurringInterval!==void 0&&b.recurringInterval!=="weekly"&&b.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function g$(b,w,$){let W=new Set(["companyId","landingPageId","name","slug","content"]),Q=Object.keys(w).filter((G)=>!W.has(G));if(Q.length>0)throw Error(`\`${b}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${Q.length===1?"":"s"}: ${Q.map((G)=>`\`${G}\``).join(", ")}.`);if($.requireUpdate&&w.name===void 0&&w.slug===void 0&&w.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${b}\`.`);return{...w.name!==void 0&&{name:w.name},...w.slug!==void 0&&{slug:w.slug},...w.content!==void 0&&{content:w.content}}}function hD(b){let w=new Set(["companyId","domain","verify"]),$=Object.keys(b).filter((W)=>!w.has(W));if($.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${$.length===1?"":"s"}: ${$.map((W)=>`\`${W}\``).join(", ")}.`);if(b.domain===void 0&&b.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...b.domain!==void 0&&{domain:b.domain},...typeof b.verify==="boolean"&&{verify:b.verify}}}function fD(b){_b("create_transactional_email",b);let w=F(b,"prompt")!==void 0,$=b.html!==void 0,W=b.blocks!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(w&&($||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!w&&!$&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!w&&F(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var Y0={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},PW={senderProfileId:{type:"string",description:"Sender profile for this step's From identity. Mutually exclusive with fromEmail."},fromEmail:{type:"string",description:"From address for this step. Its domain must be configured and verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this step. Alone it only changes the visible name; with fromEmail it also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this step's Reply-To. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Reply-To address for this step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."}},m$={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:{...Y0,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:W1,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:G1,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:Q1,name:{type:"string",description:"Email template name for email steps."},senderProfileId:{type:"string",description:"Sender profile for this email step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"From address for this email step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this email step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this email step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},replyTo:{type:"string",description:"Reply-To address for this email step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},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 cD(b){if(!b||typeof b!=="object")return null;let w=b;if(w.success!==!1)return null;if(typeof w.error==="string")return Error(w.error);if(w.error&&typeof w.error==="object"&&typeof w.error.message==="string")return Error(w.error.message);if(typeof w.message==="string")return Error(w.message);return Error("The tool returned an unsuccessful response.")}function MW(b){return b.trim().toLowerCase().replace(/\s+/g,"-")}function dP(b){let w=new URLSearchParams;if(typeof b.query==="string"&&b.query.trim()!=="")w.set("query",b.query.trim());if(Array.isArray(b.tags)&&b.tags.length>0)w.set("tags",b.tags.filter(($)=>typeof $==="string"&&$.trim()!=="").join(","));if(typeof b.list==="string"&&b.list.trim()!=="")w.set("list",b.list.trim());if(typeof b.listId==="string"&&b.listId.trim()!=="")w.set("listId",b.listId.trim());if(typeof b.listName==="string"&&b.listName.trim()!=="")w.set("listName",b.listName.trim());if(typeof b.segmentId==="string"&&b.segmentId.trim()!=="")w.set("segmentId",b.segmentId);if(typeof b.status==="string"&&b.status.trim()!=="")w.set("status",b.status.trim());return w.set("page",String(b.page)),w.set("limit",String(b.pageSize)),w}async function mD(b,w){let $=typeof b.limit==="number"&&Number.isFinite(b.limit)?Math.max(1,Math.trunc(b.limit)):void 0,W=Math.min(100,Math.max(1,$??100)),Q=[],G=1,X=0,Y=0,H=0;while(!0){let D=dP({query:b.query,tags:b.tags,list:b.list,listId:b.listId,listName:b.listName,segmentId:b.segmentId,status:b.status,page:G,pageSize:W}),z=await A("GET",`/api/v1/subscribers?${D.toString()}`,void 0,w);X=z.pagination?.total??z.subscribers.length,Y=z.pagination?.totalPages??1,H+=1,Q.push(...z.subscribers??[]);let O=$!==void 0&&Q.length>=$,q=z.pagination?G>=z.pagination.totalPages:(z.subscribers??[]).length<W;if(O||q)break;G+=1}let J=$!==void 0?Q.slice(0,$):Q;return{success:!0,subscribers:J,pagination:{page:1,limit:W,total:X,totalPages:Y,fetchedPages:H},returned:J.length,truncated:$!==void 0&&X>0&&J.length<X}}function tP(b){let w=typeof b.email==="string"&&b.email.trim()!==""?b.email.trim():void 0,$=typeof b.externalId==="string"&&b.externalId.trim()!==""?b.externalId.trim():void 0;return{...w?{email:w}:{},...$?{externalId:$}:{}}}function Aw(b,w){let $=tP(w);if(!$.email&&!$.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${b}\`.`);return $}function n$(b,w){let $=new URLSearchParams;if(w?.includeMachineEngagement)$.set("includeMachineEngagement","true");let W=$.toString(),Q=W?`?${W}`:"";if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}${Q}`;return $.set("externalId",String(b.externalId)),`/api/v1/subscribers/external?${$.toString()}`}function ZW(b){if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}/notes`;let w=new URLSearchParams;return w.set("externalId",String(b.externalId)),`/api/v1/subscribers/external/notes?${w.toString()}`}async function H0(b,w,$){return A("GET",n$(b,$),void 0,w)}function Vb(b,w,$,W){let Q=F(w,$);if(Q===void 0)return;if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${b}\`.`);return Q}function J0(b,w,$,W){let Q=j(b,w,$);if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${b}\`.`);return Q}function zw(b,w,$,W,Q){let G=w[$];if(G===void 0)return;if(typeof G!=="number"||!Number.isInteger(G)||G<W||G>Q)throw Error(`\`${$}\` must be an integer between ${W} and ${Q} when calling \`${b}\`.`);return G}function rP(b,w){let $=[],W=Vb(b,w,"eventType",v$);if(W)$.push(W);if(w.eventTypes!==void 0){if(!Array.isArray(w.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${b}\`.`);w.eventTypes.forEach((Q,G)=>{if(typeof Q!=="string")throw Error(`\`eventTypes\` item ${G+1} must be a string when calling \`${b}\`.`);let X=Q.trim();if(!v$.includes(X))throw Error(`\`eventTypes\` item ${G+1} must be one of ${v$.join(", ")} when calling \`${b}\`.`);$.push(X)})}return[...new Set($)]}function IW(b,w){let $=new URLSearchParams,W=rP(b,w);if(W.length>0)$.set("eventTypes",W.join(","));let Q=Vb(b,w,"period",["1h","24h","7d","30d","90d"]);if(Q)$.set("period",Q);let G=F(w,"start");if(G)$.set("start",G);let X=F(w,"end");if(X)$.set("end",X);let Y=zw(b,w,"page",1,1e6);if(Y!==void 0)$.set("page",String(Y));let H=zw(b,w,"limit",1,500);if(H!==void 0)$.set("limit",String(H));if(w.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");return $}function jW(b,w){if(w.events===void 0)return;if(!Array.isArray(w.events))throw Error(`\`events\` must be an array when calling \`${b}\`.`);let $=w.events.map((W,Q)=>{if(typeof W!=="string"||!Y1.includes(W))throw Error(`\`events\` item ${Q+1} must be one of ${Y1.join(", ")} when calling \`${b}\`.`);return W});if($.length===0)throw Error(`\`events\` must include at least one event type when calling \`${b}\`.`);return $}function VW(b,w){if(!Array.isArray(w.emails))throw Error(`\`emails\` must be an array when calling \`${b}\`.`);let $=[];if(w.emails.forEach((W,Q)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${Q+1} must be a string when calling \`${b}\`.`);let G=W.trim();if(G.length>0)$.push(G)}),$.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${b}\`.`);if($.length>DW)throw Error(`\`emails\` must include no more than ${DW} email addresses when calling \`${b}\`. Split larger batches into multiple calls.`);return $}function gD(b,w,$,W){let Q=w[$];if(Q===void 0)return;if(!Array.isArray(Q))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`);let G=[];if(Q.forEach((X,Y)=>{if(typeof X!=="string")throw Error(`\`${$}\` item ${Y+1} must be a string when calling \`${b}\`.`);let H=X.trim();if(H.length>0)G.push(H)}),G.length===0)throw Error(`\`${$}\` must include at least one ${W} when calling \`${b}\`.`);return G}function nD(b){let $=gD("enroll_subscribers_in_sequence",b,"emails","email address"),W=gD("enroll_subscribers_in_sequence",b,"subscriberIds","subscriber ID"),Q=($?.length??0)+(W?.length??0);if(Q===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(Q>zW)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${zW} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let G=F(b,"targetNodeId");return{...$!==void 0&&{emails:$},...W!==void 0&&{subscriberIds:W},...G!==void 0&&{targetNodeId:G}}}import{readFileSync as eP,statSync as sP}from"node:fs";import{basename as aP}from"node:path";var bM={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 wM(b){let w=b.split(".").pop()?.toLowerCase()??"";return bM[w]??null}var $M=104857600;async function lD(b,w){if(!z0())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 $=wM(b);if(!$)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=sP(b).size;if(W>$M)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let Q=eP(b),G=await A("POST","/api/v1/products/delivery/upload-url",{filename:aP(b),contentType:$,fileSizeBytes:W},w),X=await fetch(G.uploadUrl,{method:"PUT",headers:{"Content-Type":$},body:Q});if(!X.ok)throw Error(`File upload failed (${X.status})`);return{url:G.publicUrl,fileName:G.fileName,fileSizeBytes:W,mimeType:$}}async function l$(b){let w=F(b,"companyId");if(w)return w;let $=qw();if($)return $;try{return(await A("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function iD(b,w){let $=await l$(w);if(!$)throw Error(`A company is required when calling \`${b}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return $}function J1(b,w){if(!y(b)||!w)return b;return{...b,url:w}}function pD(b,w){if(!y(b))return b;return{...b,...w.campaign!==void 0&&{url:w.campaign},...w.campaignPreview!==void 0&&{previewUrl:w.campaignPreview}}}function D0(b,w,$){if(!Array.isArray(b)||!w)return b;return b.map((W)=>{if(!y(W))return W;let Q=F(W,"id");if(!Q)return W;let G=Hw({companyId:w,...$==="campaign"&&{campaignId:Q},...$==="landingPage"&&{landingPageId:Q},...$==="sequence"&&{sequenceId:Q},...$==="template"&&{emailId:Q},...$==="transactional"&&{transactionalId:Q}});if($==="campaign")return pD(W,G.urls);let X=$==="sequence"?G.urls.sequence:$==="landingPage"?G.urls.landingPage:$==="template"?G.urls.email:G.urls.transactionalEmail;return J1(W,X)})}function WM(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(!y(w))return w;let $=F(w,"id");if(!$)return w;let W=Hw({companyId:$});return{...w,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var NW=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","update_sequence_node","update_sequence_nodes","edit_sequence_graph","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","set_template_localization","sync_template_localizations","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function oD(b,w,$){if(!y($)||!NW.has(b))return $;let W=y($.company)?$.company:void 0,G=F($,"selectedCompanyId")??F($,"currentCompanyId")??F($,"companyId")??(W?F(W,"id"):void 0)??(W?F(W,"companyId"):void 0)??await l$(w);if(!G)return $;let X=y($.campaign)?$.campaign:void 0,Y=y($.sequence)?$.sequence:void 0,H=y($.landingPage)?$.landingPage:void 0,J=y($.template)?$.template:void 0,D=y($.transactional)&&!Array.isArray($.transactional)?$.transactional:void 0,z={companyId:G,campaignId:F(w,"campaignId")??F($,"campaignId")??(X?F(X,"id"):void 0),landingPageId:F(w,"landingPageId")??F($,"landingPageId")??(H?F(H,"id"):void 0),sequenceId:F(w,"sequenceId")??F($,"sequenceId")??(Y?F(Y,"id"):void 0),emailId:F($,"templateId")??(J?F(J,"id"):void 0)??(D?F(D,"emailId"):void 0)??F(w,"templateId"),transactionalId:F(w,"transactionalId")??(D?F(D,"id"):void 0)??F(w,"idOrSlug"),emailSendId:F(w,"emailSendId")??F($,"emailSendId")??(y($.emailSend)?F($.emailSend,"id"):void 0),status:F(w,"status")},O=Hw(z),q=W?Hw({companyId:G}):void 0;return{...$,...Array.isArray($.companies)&&{companies:WM($.companies)},...Array.isArray($.campaigns)&&{campaigns:D0($.campaigns,G,"campaign")},...Array.isArray($.landingPages)&&{landingPages:D0($.landingPages,G,"landingPage")},...Array.isArray($.sequences)&&{sequences:D0($.sequences,G,"sequence")},...Array.isArray($.templates)&&{templates:D0($.templates,G,"template")},...Array.isArray($.transactional)&&{transactional:D0($.transactional,G,"transactional")},...W&&q!==void 0&&{company:{...W,url:q.urls.dashboard,settingsUrl:q.urls.settings}},...X&&O.urls.campaign!==void 0&&{campaign:pD(X,O.urls)},...Y&&O.urls.sequence!==void 0&&{sequence:J1(Y,O.urls.sequence)},...H&&O.urls.landingPage!==void 0&&{landingPage:J1(H,O.urls.landingPage)},...J&&O.urls.email!==void 0&&{template:J1(J,O.urls.email)},...D&&O.urls.transactionalEmail!==void 0&&{transactional:J1(D,O.urls.transactionalEmail)},...y($.emailSend)&&O.urls.emailSend!==void 0&&{emailSend:J1($.emailSend,O.urls.emailSend)},appUrls:O.urls}}import{readFileSync as QM,statSync as GM}from"node:fs";import{basename as XM,extname as tD}from"node:path";var TW=5242880,YM=Math.ceil(TW/3)*4,HM=Math.ceil(YM*1.05)+256,rD={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},JM=new Set(Object.values(rD));function EW(b){return b?.split(";")[0]?.trim().toLowerCase()||void 0}function DM(b){return rD[tD(b).toLowerCase()]}function zM(b){let w=tD(b);return(w?b.slice(0,-w.length):b).replace(/[-_]+/g," ").trim()||"Image"}function AM(b){if(b.length>HM)throw Error("Image assets must be 5MB or smaller.")}function OM(b){let w=0,$=0;for(let Q=0;Q<b.length;Q+=1){let G=b.charCodeAt(Q);if(G===9||G===10||G===11||G===12||G===13||G===32)continue;w+=1,$=G===61?$+1:0}if(Math.floor(w*3/4)-Math.min($,2)>TW)throw Error("Image assets must be 5MB or smaller.")}function qM(b){AM(b);let w=b.trim(),$=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(w),W=$?.[2]??w;OM(W);let Q=W.replace(/\s+/g,"");if(Q.length===0||Q.length%4===1||!/^[A-Za-z0-9+/]*={0,2}$/.test(Q))throw Error("`imageBase64` must contain valid base64 image bytes.");return{bytes:Buffer.from(Q,"base64"),...$?.[1]?{dataUrlContentType:EW($[1])}:{}}}function dD(b){if(b<=0)throw Error("The image file is empty.");if(b>TW)throw Error("Image assets must be 5MB or smaller.")}function LM(b){let w=DM(b.filename)??EW(b.explicitContentType)??EW(b.dataUrlContentType);if(!w||!JM.has(w))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return w}function UM(b){let w,$,W;if(b.filePath!==void 0){if(!z0())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. For a remote MCP connection, pass `imageBase64` and `filename` instead.");let G=GM(b.filePath).size;dD(G),w=QM(b.filePath),$=b.filename??XM(b.filePath)}else{if(!b.imageBase64)throw Error("Provide either `filePath` or `imageBase64` when uploading an image asset.");if(!b.filename)throw Error("`filename` is required with `imageBase64` when uploading an image asset.");let G=qM(b.imageBase64);w=G.bytes,W=G.dataUrlContentType,$=b.filename,dD(w.byteLength)}let Q=LM({filename:$,explicitContentType:b.contentType,dataUrlContentType:W});return{bytes:w,filename:$,contentType:Q,altText:b.altText??zM($)}}async function eD(b){let w=UM(b),$=w.bytes.byteLength,W=await A("POST","/api/v1/media/upload-url",{filename:w.filename,contentType:w.contentType,fileSizeBytes:$},b.companyId);return await lW(W.uploadUrl,w.bytes,w.contentType,b.companyId),(await A("POST","/api/v1/media/complete-upload",{key:W.key,filename:W.fileName,contentType:w.contentType,fileSizeBytes:$,...b.sourceWidth!==void 0&&{width:b.sourceWidth},...b.sourceHeight!==void 0&&{height:b.sourceHeight},altText:w.altText},b.companyId)).asset}var BM={type:"boolean",description:"Whether the Sequenzy operation succeeded."},FM={type:"string",description:"Human-readable status, confirmation, or next-step message."},KM={type:"string",description:"Additional context about the result."};function t(b){return{type:"object",description:b,additionalProperties:!0}}function PM(b){return{type:"array",description:b,items:t("One item in the returned collection.")}}function T(b){return{type:"string",description:b}}function Kb(b){return{type:"number",description:b}}function eb(b){return{type:"boolean",description:b}}function P(b){return t(`The ${b} record returned by Sequenzy.`)}function i(b){return PM(`List of ${b} records returned by Sequenzy.`)}var MM={appUrls:t("Dashboard URLs for relevant Sequenzy resources."),url:T("Primary dashboard URL for this result."),settingsUrl:T("Company settings URL when available.")},ZM={success:BM,message:FM,note:KM,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:t("One returned item.")},value:t("Fallback object wrapper used only when a tool returns a non-object value.")},IM={get_account:{account:P("account"),companies:i("company"),apiKeyPermissions:t("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:T("Company ID selected by the authenticated API key, when available."),selectedCompanyId:T("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:T("Selected company ID."),companyName:T("Selected company name.")},get_app_urls:{dashboard:T("Company dashboard URL."),settings:T("Company settings URL."),campaign:T("Campaign editor URL."),landingPage:T("Landing page editor URL."),sequence:T("Sequence editor URL."),email:T("Email editor URL."),transactionalEmail:T("Transactional email URL."),emailSend:T("Sent email detail URL."),domain:T("Sending domain settings URL."),urls:t("All generated URLs keyed by resource type.")},create_company:{company:P("company"),autoSelected:eb("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:P("company")},get_company:{company:P("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:t("One sync rule.")},isDefault:eb("Whether the company still uses the platform default rules.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:t("One sync rule.")},isDefault:eb("Whether the company now uses the platform default rules.")},get_shopify_automation_settings:{browseAbandonment:t("Effective browse-abandonment settings (defaults applied)."),priceDrop:t("Effective price-drop settings (defaults applied)."),shopDomain:T("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:t("Effective browse-abandonment settings after the update."),priceDrop:t("Effective price-drop settings after the update."),shopDomain:T("Connected Shopify store domain.")},create_api_key:{apiKey:t("Created API key metadata: the newly created secret in `key`, plus `scopes` listing the assigned permission scopes (null when the key has full access)."),key:T("Newly created API key if the API response uses the short key field.")},list_websites:{websites:i("sender website")},add_website:{website:P("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},add_sending_domain:{website:P("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},check_website:{website:P("sender website"),ready:eb("Whether the sender website is ready."),status:T("Current processing or verification status.")},verify_sending_domain:{website:P("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:eb("Whether the sending domain passed the fresh verification check."),message:T("Verification result summary.")},get_integration_guide:{guide:P("integration guide"),code:T("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:t("One setup step.")}},add_subscriber:{subscriber:P("subscriber")},update_subscriber:{subscriber:P("subscriber")},remove_subscriber:{subscriber:P("subscriber"),hardDeleted:eb("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:P("subscriber")},list_subscriber_notes:{notes:i("subscriber note")},add_subscriber_note:{note:P("subscriber note")},delete_subscriber_note:{id:T("Deleted subscriber note ID."),deleted:eb("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:i("subscriber"),pagination:t("Pagination metadata."),returned:Kb("Number of subscribers returned."),truncated:eb("Whether the result was truncated by the requested limit.")},list_products:{products:i("product")},upsert_products:{products:i("product"),created:Kb("Number of products created."),updated:Kb("Number of products updated.")},delete_product:{productId:T("Deleted product ID.")},attach_product_file:{product:P("product"),delivery:P("digital delivery file")},remove_product_file:{product:P("product")},upload_image_asset:{asset:P("hosted image asset"),imageBlock:t("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:P("product sync job"),jobId:T("Queued product sync job ID.")},list_tags:{tags:i("tag")},create_tag:{tag:P("tag")},update_tag:{tag:P("tag")},delete_tag:{tagId:T("Deleted tag ID.")},list_lists:{lists:i("list")},create_list:{list:P("list")},update_list:{list:P("list")},delete_list:{listId:T("Deleted list ID.")},add_subscribers_to_list:{list:P("list"),added:Kb("Number of subscribers added to the list."),skipped:Kb("Number of subscribers skipped.")},remove_subscribers_from_list:{list:P("list"),removed:Kb("Number of subscribers removed from the list."),skipped:Kb("Number of subscribers skipped.")},list_segments:{segments:i("segment")},create_segment:{segment:P("segment")},update_segment:{segment:P("segment")},delete_segment:{segmentId:T("Deleted segment ID.")},get_segment_count:{count:Kb("Number of subscribers matching the segment."),segmentId:T("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:i("audience sync")},list_ad_accounts:{adAccounts:i("ad account")},create_audience_sync:{audienceSync:P("audience sync")},update_audience_sync:{audienceSync:P("audience sync")},delete_audience_sync:{audienceSyncId:T("Deleted audience sync ID.")},sync_audience_now:{audienceSync:P("audience sync"),job:P("audience sync job"),jobId:T("Queued audience sync job ID.")},list_templates:{templates:i("email template")},get_template:{template:P("email template")},create_template:{template:P("email template")},update_template:{template:P("email template")},set_template_localization:{templateId:T("Localized template ID."),localization:P("template localization")},sync_template_localizations:{templateId:T("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:T("One queued locale code.")},queuedVariantCount:Kb("Number of localized variants queued for translation.")},delete_template:{templateId:T("Deleted template ID.")},list_ab_tests:{abTests:i("A/B test")},get_ab_test:{abTest:P("A/B test")},get_ab_test_stats:{abTest:P("A/B test"),stats:P("A/B test statistics")},restart_ab_test:{abTest:P("A/B test")},update_ab_test_variant:{abTest:P("A/B test"),variant:P("A/B test variant")},create_ab_test:{abTest:P("A/B test")},add_ab_test_variant:{abTest:P("A/B test"),variant:P("A/B test variant")},delete_ab_test_variant:{abTest:P("A/B test"),variantId:T("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:T("Deleted A/B test ID.")},list_campaigns:{campaigns:i("campaign")},get_campaign:{campaign:P("campaign")},get_email_send:{emailSend:P("email send")},create_campaign:{campaign:P("campaign")},update_campaign:{campaign:P("campaign")},schedule_campaign:{campaign:P("campaign"),scheduledAt:T("Scheduled send timestamp.")},send_test_email:{emailSend:P("test email send"),recipient:T("Test email recipient.")},send_test_sms:{smsSendId:T("Created test SMS send ID."),toPhone:T("Normalized E.164 destination phone.")},cancel_campaign:{campaign:P("campaign")},pause_campaign:{campaign:P("campaign")},resume_campaign:{campaign:P("campaign")},delete_campaign:{campaignId:T("Deleted campaign ID.")},duplicate_campaign:{campaign:P("duplicated campaign")},resend_campaign_to_non_openers:{campaign:P("non-opener resend draft campaign"),estimatedNonOpenerCount:Kb("Estimated number of subscribers who haven't opened the original campaign.")},list_landing_pages:{landingPages:i("landing page")},get_landing_page:{landingPage:P("landing page")},create_landing_page:{landingPage:P("landing page")},update_landing_page:{landingPage:P("landing page")},delete_landing_page:{landingPageId:T("Deleted landing page ID.")},publish_landing_page:{landingPage:P("landing page")},unpublish_landing_page:{landingPage:P("landing page")},connect_landing_page_domain:{landingPage:P("landing page"),domain:T("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:P("landing page"),domain:T("Landing page domain.")},list_sequences:{sequences:i("sequence")},get_sequence:{sequence:P("sequence")},create_sequence:{sequence:P("sequence"),eventTrackingCode:T("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:t("Custom-event endpoint, payload contract, example payload, documentation URL, and get_integration_guide arguments."),requiredEvents:{type:"array",description:"Event names the application or an integration must send.",items:T("One required event name.")}},update_sequence:{sequence:P("sequence")},update_sequence_node:{sequence:P("sequence")},update_sequence_nodes:{sequence:P("sequence")},edit_sequence_graph:{sequence:P("sequence")},insert_sequence_step:{sequence:P("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for the inserted step, including any delay node.",items:T("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:T("Inserted email template ID.")},insertedEmailCount:Kb("Number of email steps inserted.")},enable_sequence:{sequence:P("sequence")},disable_sequence:{sequence:P("sequence")},pause_sequence_enrollments:{sequenceId:T("Sequence ID."),enrollmentPaused:eb("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:T("Sequence ID."),enrollmentPaused:eb("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:P("sequence"),enrollments:i("sequence enrollment"),enrolled:Kb("Number of subscribers enrolled."),skipped:Kb("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:P("sequence"),cancelled:Kb("Number of enrollments cancelled."),skipped:Kb("Number of enrollments skipped.")},delete_sequence:{sequenceId:T("Deleted sequence ID.")},list_transactional_emails:{transactional:i("transactional email")},get_transactional_email:{transactional:P("transactional email")},create_transactional_email:{transactional:P("transactional email")},update_transactional_email:{transactional:P("transactional email")},send_email:{emailSend:P("transactional email send"),transactional:P("transactional email")},get_stats:{stats:P("account or company statistics")},get_campaign_stats:{campaign:P("campaign"),stats:P("campaign statistics"),clickedLinks:{type:"array",description:"Per-link click breakdown, most clicked first (top 20). Each entry has url, clicks, and percentage (that link's share of every recorded link click). Present only when the campaign has tracked link clicks.",items:t("One clicked link with url/clicks/share.")},polls:{type:"array",description:`Poll and NPS summaries. Each subscriber counts once per campaign poll block using their latest answer to that block; NPS entries include score, average, and promoter/passive/detractor counts. To list the exact historical respondents behind a count, use the summary blockId and the get_campaign_stats campaignId with create_segment. ${_w} A summary's attributeKey identifies the subscriber attribute that stores their current/latest response and may be overwritten by a later poll that reuses the key.`,items:t("One poll or NPS results summary.")}},get_sequence_stats:{sequence:P("sequence"),stats:P("sequence statistics")},list_campaign_events:{events:i("campaign email event"),pagination:t("Pagination metadata.")},list_sequence_events:{events:i("sequence email event"),pagination:t("Pagination metadata.")},get_subscriber_activity:{activity:i("subscriber activity event"),subscribers:i("subscriber"),pagination:t("Pagination metadata.")},list_team_members:{members:i("team member"),invitations:i("team invitation")},invite_team_member:{invitation:P("team invitation")},cancel_team_invitation:{invitationId:T("Cancelled invitation ID.")},list_conversations:{conversations:i("inbox conversation"),pagination:t("Pagination metadata.")},get_conversation:{conversation:P("inbox conversation"),messages:i("conversation message")},reply_to_conversation:{conversation:P("inbox conversation"),message:P("conversation message")},update_conversation_status:{conversation:P("inbox conversation")},mark_conversation_read:{conversation:P("inbox conversation")},list_webhooks:{webhooks:i("outbound webhook")},create_webhook:{webhook:P("outbound webhook")},update_webhook:{webhook:P("outbound webhook")},delete_webhook:{webhookId:T("Deleted outbound webhook ID.")},test_webhook:{webhook:P("outbound webhook"),delivery:P("test webhook delivery")},list_webhook_deliveries:{deliveries:i("webhook delivery")},replay_webhook_delivery:{delivery:P("webhook delivery"),job:P("webhook replay job")},generate_email:{email:P("generated email"),html:T("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:t("One generated email block.")},subject:T("Generated subject line."),previewText:T("Generated inbox preview text.")},generate_sequence:{sequence:P("generated sequence"),steps:i("generated sequence step")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:T("One generated subject line.")},variants:i("generated subject line variant")},generate_sms:{prompt:T("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:t("One generated SMS message.")}},get_sms_settings:{sms:t("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{}};function jM(b){let w=IM[b];if(w===void 0)throw Error(`MCP tool "${b}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${b}\` MCP tool.`,properties:{...ZM,...w,...NW.has(b)?MM:{}},additionalProperties:!0}}function sD(b){return{...b,outputSchema:jM(b.name)}}function aD(b){if(y(b))return b;if(Array.isArray(b))return{items:b};return{value:b}}var bz=[{name:"list_ab_tests",description:"List A/B tests and their variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Optional sequence ID to filter automation A/B tests."}}}},{name:"get_ab_test",description:"Get A/B test details, variants, and per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"}},required:["abTestId"]}},{name:"get_ab_test_stats",description:"Get A/B test aggregate stats and per-variant stats. Supports period or custom start/end ranges.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},period:{type:"string",description:"Optional period: 1h, 24h, 7d, 30d, or 90d."},start:{type:"string",description:"Custom range start as ISO 8601. Requires end."},end:{type:"string",description:"Custom range end as ISO 8601. Requires start."},includeMachineEngagement:lb},required:["abTestId"]}},{name:"restart_ab_test",description:"Run another sequence A/B test after a winner is selected. By default the winner becomes the new control; pass sourceVariantId to use another variant as the control email.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to restart"},sourceVariantId:{type:"string",description:"Optional variant ID to use as the new control email. Defaults to the selected winner."},testType:{type:"string",description:"Optional test type: subject or content."},winnerThreshold:{type:"number",description:"Optional number of subscribers before selecting a winner. Must be from 10 to 1000."},variantCount:{type:"number",description:"Optional total variants including the control. Must be from 2 to 4."}},required:["abTestId"],additionalProperties:!1}},{name:"update_ab_test_variant",description:"Update a draft A/B test variant. Provide at least one of subject, previewText, html, or blocks. Use either html or blocks, not both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID"},subject:{type:"string",description:"Variant subject line"},previewText:{type:"string",description:"Variant preview text. Pass an empty string to clear it."},html:{type:"string",description:"Replacement HTML body. Mutually exclusive with blocks."},blocks:{type:"array",description:`${Dw} Mutually exclusive with html.`,items:{type:"object"}}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"create_ab_test",description:"Create a campaign A/B test. Control variant A is created automatically from the campaign's current email; optionally provide extra variants. The campaign must be in draft or rejected status, and each campaign can only have one A/B test.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Draft campaign ID to create the A/B test for."},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Percentage of the audience used for the test phase, from 5 to 50. Defaults to 20."},testDurationMinutes:{type:"number",description:"Test phase duration in minutes before the winner is selected, from 15 to 1440. Defaults to 240."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Defaults to open_rate."},variants:{type:"array",description:"Optional extra variants to create in addition to control variant A.",items:{type:"object",properties:{subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:Dw,items:{type:"object"}}},required:["subject"]}}},required:["campaignId"]}},{name:"add_ab_test_variant",description:"Add a variant to a draft campaign A/B test. Variants cannot be added after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:Dw,items:{type:"object"}}},required:["abTestId","subject"]}},{name:"delete_ab_test_variant",description:"Permanently delete a variant from a draft campaign A/B test. This cannot be undone. Variant A is the control and cannot be deleted, and the test must keep at least the minimum number of variants. Variants cannot be removed after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID to delete."}},required:["abTestId","variantId"]}},{name:"delete_ab_test",description:"Permanently delete a campaign A/B test and all of its variants. This cannot be undone. Running tests (testing or winner_selected) cannot be deleted, and the linked campaign must be in draft or rejected status.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to delete."}},required:["abTestId"]}}];var wz=[{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
|
|