@sequenzy/mcp 0.0.49 → 0.0.51
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 +8 -3
- package/dist/server.js +8 -3
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/server.js
CHANGED
|
@@ -25,7 +25,7 @@ var T5=Object.create;var{getPrototypeOf:S5,defineProperty:L6,getOwnPropertyNames
|
|
|
25
25
|
newResult[${T}] = ${x}.value;
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
-
`)}L.write("payload.value = newResult;"),L.write("return payload;");let S=L.compile();return(E,x)=>S(D,E,x)},z,J=L1,$=!m4.jitless,A=$&&V6.value,U=Y.catchall,K;Q._zod.parse=(D,L)=>{K??(K=W.value);let q=D.value;if(!J(q))return D.issues.push({expected:"object",code:"invalid_type",input:q,inst:Q}),D;if($&&A&&L?.async===!1&&L.jitless!==!0){if(!z)z=G(Y.shape);if(D=z(D,L),!U)return D;return k8([],q,D,L,K,Q)}return X(D,L)}});function oX(Q,Y,X,W){for(let z of Q)if(z.issues.length===0)return Y.value=z.value,Y;let G=Q.filter((z)=>!Q1(z));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map((z)=>z.issues.map((J)=>T0(J,W,w0())))}),Y}var C6=F("$ZodUnion",(Q,Y)=>{i.init(Q,Y),m(Q._zod,"optin",()=>Y.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),m(Q._zod,"optout",()=>Y.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),m(Q._zod,"values",()=>{if(Y.options.every((G)=>G._zod.values))return new Set(Y.options.flatMap((G)=>Array.from(G._zod.values)));return}),m(Q._zod,"pattern",()=>{if(Y.options.every((G)=>G._zod.pattern)){let G=Y.options.map((z)=>z._zod.pattern);return new RegExp(`^(${G.map((z)=>d1(z.source)).join("|")})$`)}return});let X=Y.options.length===1,W=Y.options[0]._zod.run;Q._zod.parse=(G,z)=>{if(X)return W(G,z);let J=!1,$=[];for(let H of Y.options){let A=H._zod.run({value:G.value,issues:[]},z);if(A instanceof Promise)$.push(A),J=!0;else{if(A.issues.length===0)return A;$.push(A)}}if(!J)return oX($,G,Q,z);return Promise.all($).then((H)=>{return oX(H,G,Q,z)})}}),_8=F("$ZodDiscriminatedUnion",(Q,Y)=>{C6.init(Q,Y);let X=Q._zod.parse;m(Q._zod,"propValues",()=>{let G={};for(let z of Y.options){let J=z._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(z)}"`);for(let[$,H]of Object.entries(J)){if(!G[$])G[$]=new Set;for(let A of H)G[$].add(A)}}return G});let W=j1(()=>{let G=Y.options,z=new Map;for(let J of G){let $=J._zod.propValues?.[Y.discriminator];if(!$||$.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(J)}"`);for(let H of $){if(z.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);z.set(H,J)}}return z});Q._zod.parse=(G,z)=>{let J=G.value;if(!L1(J))return G.issues.push({code:"invalid_type",expected:"object",input:J,inst:Q}),G;let $=W.value.get(J?.[Y.discriminator]);if($)return $._zod.run(G,z);if(Y.unionFallback)return X(G,z);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,input:J,path:[Y.discriminator],inst:Q}),G}}),g8=F("$ZodIntersection",(Q,Y)=>{i.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value,z=Y.left._zod.run({value:G,issues:[]},W),J=Y.right._zod.run({value:G,issues:[]},W);if(z instanceof Promise||J instanceof Promise)return Promise.all([z,J]).then(([H,A])=>{return tX(X,H,A)});return tX(X,z,J)}});function S6(Q,Y){if(Q===Y)return{valid:!0,data:Q};if(Q instanceof Date&&Y instanceof Date&&+Q===+Y)return{valid:!0,data:Q};if(e0(Q)&&e0(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter((z)=>X.indexOf(z)!==-1),G={...Q,...Y};for(let z of W){let J=S6(Q[z],Y[z]);if(!J.valid)return{valid:!1,mergeErrorPath:[z,...J.mergeErrorPath]};G[z]=J.data}return{valid:!0,data:G}}if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let W=0;W<Q.length;W++){let G=Q[W],z=Y[W],J=S6(G,z);if(!J.valid)return{valid:!1,mergeErrorPath:[W,...J.mergeErrorPath]};X.push(J.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function tX(Q,Y,X){if(Y.issues.length)Q.issues.push(...Y.issues);if(X.issues.length)Q.issues.push(...X.issues);if(Q1(Q))return Q;let W=S6(Y.value,X.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return Q.value=W.data,Q}var y8=F("$ZodRecord",(Q,Y)=>{i.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!e0(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let z=[];if(Y.keyType._zod.values){let J=Y.keyType._zod.values;X.value={};for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let A=Y.valueType._zod.run({value:G[H],issues:[]},W);if(A instanceof Promise)z.push(A.then((U)=>{if(U.issues.length)X.issues.push(...c0(H,U.issues));X.value[H]=U.value}));else{if(A.issues.length)X.issues.push(...c0(H,A.issues));X.value[H]=A.value}}let $;for(let H in G)if(!J.has(H))$=$??[],$.push(H);if($&&$.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:$})}else{X.value={};for(let J of Reflect.ownKeys(G)){if(J==="__proto__")continue;let $=Y.keyType._zod.run({value:J,issues:[]},W);if($ instanceof Promise)throw Error("Async schemas not supported in object keys currently");if($.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:$.issues.map((A)=>T0(A,W,w0())),input:J,path:[J],inst:Q}),X.value[$.value]=$.value;continue}let H=Y.valueType._zod.run({value:G[J],issues:[]},W);if(H instanceof Promise)z.push(H.then((A)=>{if(A.issues.length)X.issues.push(...c0(J,A.issues));X.value[$.value]=A.value}));else{if(H.issues.length)X.issues.push(...c0(J,H.issues));X.value[$.value]=H.value}}}if(z.length)return Promise.all(z).then(()=>X);return X}});var u8=F("$ZodEnum",(Q,Y)=>{i.init(Q,Y);let X=O6(Y.entries),W=new Set(X);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${X.filter((G)=>N6.has(typeof G)).map((G)=>typeof G==="string"?m0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,z)=>{let J=G.value;if(W.has(J))return G;return G.issues.push({code:"invalid_value",values:X,input:J,inst:Q}),G}}),h8=F("$ZodLiteral",(Q,Y)=>{if(i.init(Q,Y),Y.values.length===0)throw Error("Cannot create literal schema with no valid values");Q._zod.values=new Set(Y.values),Q._zod.pattern=new RegExp(`^(${Y.values.map((X)=>typeof X==="string"?m0(X):X?m0(X.toString()):String(X)).join("|")})$`),Q._zod.parse=(X,W)=>{let G=X.value;if(Q._zod.values.has(G))return X;return X.issues.push({code:"invalid_value",values:Y.values,input:G,inst:Q}),X}});var f8=F("$ZodTransform",(Q,Y)=>{i.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new i1(Q.constructor.name);let G=Y.transform(X.value,X);if(W.async)return(G instanceof Promise?G:Promise.resolve(G)).then((J)=>{return X.value=J,X});if(G instanceof Promise)throw new l0;return X.value=G,X}});function aX(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var l8=F("$ZodOptional",(Q,Y)=>{i.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",m(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),m(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${d1(X.source)})?$`):void 0}),Q._zod.parse=(X,W)=>{if(Y.innerType._zod.optin==="optional"){let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>aX(z,X.value));return aX(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),m8=F("$ZodNullable",(Q,Y)=>{i.init(Q,Y),m(Q._zod,"optin",()=>Y.innerType._zod.optin),m(Q._zod,"optout",()=>Y.innerType._zod.optout),m(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${d1(X.source)}|null)$`):void 0}),m(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,null]):void 0}),Q._zod.parse=(X,W)=>{if(X.value===null)return X;return Y.innerType._zod.run(X,W)}}),c8=F("$ZodDefault",(Q,Y)=>{i.init(Q,Y),Q._zod.optin="optional",m(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)return X.value=Y.defaultValue,X;let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>sX(z,Y));return sX(G,Y)}});function sX(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var p8=F("$ZodPrefault",(Q,Y)=>{i.init(Q,Y),Q._zod.optin="optional",m(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)X.value=Y.defaultValue;return Y.innerType._zod.run(X,W)}}),i8=F("$ZodNonOptional",(Q,Y)=>{i.init(Q,Y),m(Q._zod,"values",()=>{let X=Y.innerType._zod.values;return X?new Set([...X].filter((W)=>W!==void 0)):void 0}),Q._zod.parse=(X,W)=>{let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>eX(z,Q));return eX(G,Q)}});function eX(Q,Y){if(!Q.issues.length&&Q.value===void 0)Q.issues.push({code:"invalid_type",expected:"nonoptional",input:Q.value,inst:Y});return Q}var r8=F("$ZodCatch",(Q,Y)=>{i.init(Q,Y),m(Q._zod,"optin",()=>Y.innerType._zod.optin),m(Q._zod,"optout",()=>Y.innerType._zod.optout),m(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>{if(X.value=z.value,z.issues.length)X.value=Y.catchValue({...X,error:{issues:z.issues.map((J)=>T0(J,W,w0()))},input:X.value}),X.issues=[];return X});if(X.value=G.value,G.issues.length)X.value=Y.catchValue({...X,error:{issues:G.issues.map((z)=>T0(z,W,w0()))},input:X.value}),X.issues=[];return X}});var n8=F("$ZodPipe",(Q,Y)=>{i.init(Q,Y),m(Q._zod,"values",()=>Y.in._zod.values),m(Q._zod,"optin",()=>Y.in._zod.optin),m(Q._zod,"optout",()=>Y.out._zod.optout),m(Q._zod,"propValues",()=>Y.in._zod.propValues),Q._zod.parse=(X,W)=>{if(W.direction==="backward"){let z=Y.out._zod.run(X,W);if(z instanceof Promise)return z.then((J)=>s4(J,Y.in,W));return s4(z,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>s4(z,Y.out,W));return s4(G,Y.out,W)}});function s4(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var d8=F("$ZodReadonly",(Q,Y)=>{i.init(Q,Y),m(Q._zod,"propValues",()=>Y.innerType._zod.propValues),m(Q._zod,"values",()=>Y.innerType._zod.values),m(Q._zod,"optin",()=>Y.innerType._zod.optin),m(Q._zod,"optout",()=>Y.innerType._zod.optout),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(Q8);return Q8(G)}});function Q8(Q){return Q.value=Object.freeze(Q.value),Q}var o8=F("$ZodCustom",(Q,Y)=>{W0.init(Q,Y),i.init(Q,Y),Q._zod.parse=(X,W)=>{return X},Q._zod.check=(X)=>{let W=X.value,G=Y.fn(W);if(G instanceof Promise)return G.then((z)=>Y8(z,X,W,Q));Y8(G,X,W,Q);return}});function Y8(Q,Y,X,W){if(!Q){let G={code:"custom",input:X,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)G.params=W._zod.def.params;Y.issues.push(I1(G))}}var ZH=(Q)=>{let Y=typeof Q;switch(Y){case"number":return Number.isNaN(Q)?"NaN":"number";case"object":{if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Object.getPrototypeOf(Q)!==Object.prototype&&Q.constructor)return Q.constructor.name}}return Y},wH=()=>{let Q={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function Y(W){return Q[W]??null}let X={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${ZH(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${r4(W.values[0])}`;return`Invalid option: expected one of ${c4(W.values,"|")}`;case"too_big":{let G=W.inclusive?"<=":"<",z=Y(W.origin);if(z)return`Too big: expected ${W.origin??"value"} to have ${G}${W.maximum.toString()} ${z.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${G}${W.maximum.toString()}`}case"too_small":{let G=W.inclusive?">=":">",z=Y(W.origin);if(z)return`Too small: expected ${W.origin} to have ${G}${W.minimum.toString()} ${z.unit}`;return`Too small: expected ${W.origin} to be ${G}${W.minimum.toString()}`}case"invalid_format":{let G=W;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${X[G.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${c4(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 v6(){return{localeError:wH()}}var KV=Symbol("ZodOutput"),DV=Symbol("ZodInput");class t8{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Q,...Y){let X=Y[0];if(this._map.set(Q,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.id,Q)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Q){let Y=this._map.get(Q);if(Y&&typeof Y==="object"&&"id"in Y)this._idmap.delete(Y.id);return this._map.delete(Q),this}get(Q){let Y=Q._zod.parent;if(Y){let X={...this.get(Y)??{}};delete X.id;let W={...X,...this._map.get(Q)};return Object.keys(W).length?W:void 0}return this._map.get(Q)}has(Q){return this._map.has(Q)}}function bH(){return new t8}var Q4=bH();function a8(Q,Y){return new Q({type:"string",...I(Y)})}function s8(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...I(Y)})}function k6(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...I(Y)})}function e8(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...I(Y)})}function QW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(Y)})}function YW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(Y)})}function XW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(Y)})}function WW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...I(Y)})}function GW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...I(Y)})}function zW(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(Y)})}function JW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...I(Y)})}function $W(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(Y)})}function HW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...I(Y)})}function AW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...I(Y)})}function UW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(Y)})}function KW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(Y)})}function DW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(Y)})}function BW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(Y)})}function LW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(Y)})}function FW(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...I(Y)})}function qW(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...I(Y)})}function OW(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...I(Y)})}function MW(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...I(Y)})}function VW(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(Y)})}function NW(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...I(Y)})}function ZW(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...I(Y)})}function wW(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...I(Y)})}function bW(Q,Y){return new Q({type:"number",checks:[],...I(Y)})}function PW(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...I(Y)})}function jW(Q,Y){return new Q({type:"boolean",...I(Y)})}function IW(Q,Y){return new Q({type:"null",...I(Y)})}function EW(Q){return new Q({type:"unknown"})}function TW(Q,Y){return new Q({type:"never",...I(Y)})}function YQ(Q,Y){return new I6({check:"less_than",...I(Y),value:Q,inclusive:!1})}function Y4(Q,Y){return new I6({check:"less_than",...I(Y),value:Q,inclusive:!0})}function XQ(Q,Y){return new E6({check:"greater_than",...I(Y),value:Q,inclusive:!1})}function X4(Q,Y){return new E6({check:"greater_than",...I(Y),value:Q,inclusive:!0})}function WQ(Q,Y){return new xX({check:"multiple_of",...I(Y),value:Q})}function GQ(Q,Y){return new gX({check:"max_length",...I(Y),maximum:Q})}function E1(Q,Y){return new yX({check:"min_length",...I(Y),minimum:Q})}function zQ(Q,Y){return new uX({check:"length_equals",...I(Y),length:Q})}function x6(Q,Y){return new hX({check:"string_format",format:"regex",...I(Y),pattern:Q})}function _6(Q){return new fX({check:"string_format",format:"lowercase",...I(Q)})}function g6(Q){return new lX({check:"string_format",format:"uppercase",...I(Q)})}function y6(Q,Y){return new mX({check:"string_format",format:"includes",...I(Y),includes:Q})}function u6(Q,Y){return new cX({check:"string_format",format:"starts_with",...I(Y),prefix:Q})}function h6(Q,Y){return new pX({check:"string_format",format:"ends_with",...I(Y),suffix:Q})}function F1(Q){return new iX({check:"overwrite",tx:Q})}function f6(Q){return F1((Y)=>Y.normalize(Q))}function l6(){return F1((Q)=>Q.trim())}function m6(){return F1((Q)=>Q.toLowerCase())}function c6(){return F1((Q)=>Q.toUpperCase())}function SW(Q,Y,X){return new Q({type:"array",element:Y,...I(X)})}function RW(Q,Y,X){let W=I(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function CW(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...I(X)})}function vW(Q){let Y=PH((X)=>{return X.addIssue=(W)=>{if(typeof W==="string")X.issues.push(I1(W,X.value,Y._zod.def));else{let G=W;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=X.value),G.inst??(G.inst=Y),G.continue??(G.continue=!Y._zod.def.abort),X.issues.push(I1(G))}},Q(X.value,X)});return Y}function PH(Q,Y){let X=new W0({check:"custom",...I(Y)});return X._zod.check=Q,X}function T1(Q){return!!Q._zod}function Y1(Q,Y){if(T1(Q))return a1(Q,Y);return Q.safeParse(Y)}function JQ(Q){if(!Q)return;let Y;if(T1(Q))Y=Q._zod?.def?.shape;else Y=Q.shape;if(!Y)return;if(typeof Y==="function")try{return Y()}catch{return}return Y}function kW(Q){if(T1(Q)){let z=Q._zod?.def;if(z){if(z.value!==void 0)return z.value;if(Array.isArray(z.values)&&z.values.length>0)return z.values[0]}}let X=Q._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let W=Q.value;if(W!==void 0)return W;return}var G4={};_9(G4,{time:()=>r6,duration:()=>n6,datetime:()=>p6,date:()=>i6,ZodISOTime:()=>gW,ZodISODuration:()=>yW,ZodISODateTime:()=>xW,ZodISODate:()=>_W});var xW=F("ZodISODateTime",(Q,Y)=>{B8.init(Q,Y),d.init(Q,Y)});function p6(Q){return VW(xW,Q)}var _W=F("ZodISODate",(Q,Y)=>{L8.init(Q,Y),d.init(Q,Y)});function i6(Q){return NW(_W,Q)}var gW=F("ZodISOTime",(Q,Y)=>{F8.init(Q,Y),d.init(Q,Y)});function r6(Q){return ZW(gW,Q)}var yW=F("ZodISODuration",(Q,Y)=>{q8.init(Q,Y),d.init(Q,Y)});function n6(Q){return wW(yW,Q)}var uW=(Q,Y)=>{n4.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>o9(Q,X)},flatten:{value:(X)=>d9(Q,X)},addIssue:{value:(X)=>{Q.issues.push(X),Q.message=JSON.stringify(Q.issues,P1,2)}},addIssues:{value:(X)=>{Q.issues.push(...X),Q.message=JSON.stringify(Q.issues,P1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},aV=F("ZodError",uW),N0=F("ZodError",uW,{Parent:Error});var hW=d4(N0),fW=o4(N0),lW=t1(N0),mW=s1(N0),cW=t9(N0),pW=a9(N0),iW=s9(N0),rW=e9(N0),nW=QX(N0),dW=YX(N0),oW=XX(N0),tW=WX(N0);var s=F("ZodType",(Q,Y)=>{return i.init(Q,Y),Q.def=Y,Q.type=Y.type,Object.defineProperty(Q,"_def",{value:Y}),Q.check=(...X)=>{return Q.clone(h.mergeDefs(Y,{checks:[...Y.checks??[],...X.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},Q.clone=(X,W)=>E0(Q,X,W),Q.brand=()=>Q,Q.register=(X,W)=>{return X.add(Q,W),Q},Q.parse=(X,W)=>hW(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>lW(Q,X,W),Q.parseAsync=async(X,W)=>fW(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>mW(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>cW(Q,X,W),Q.decode=(X,W)=>pW(Q,X,W),Q.encodeAsync=async(X,W)=>iW(Q,X,W),Q.decodeAsync=async(X,W)=>rW(Q,X,W),Q.safeEncode=(X,W)=>nW(Q,X,W),Q.safeDecode=(X,W)=>dW(Q,X,W),Q.safeEncodeAsync=async(X,W)=>oW(Q,X,W),Q.safeDecodeAsync=async(X,W)=>tW(Q,X,W),Q.refine=(X,W)=>Q.check(NA(X,W)),Q.superRefine=(X)=>Q.check(ZA(X)),Q.overwrite=(X)=>Q.check(F1(X)),Q.optional=()=>a(Q),Q.nullable=()=>eW(Q),Q.nullish=()=>a(eW(Q)),Q.nonoptional=(X)=>LA(Q,X),Q.array=()=>_(Q),Q.or=(X)=>p([Q,X]),Q.and=(X)=>HQ(Q,X),Q.transform=(X)=>o6(Q,GG(X)),Q.default=(X)=>KA(Q,X),Q.prefault=(X)=>BA(Q,X),Q.catch=(X)=>qA(Q,X),Q.pipe=(X)=>o6(Q,X),Q.readonly=()=>VA(Q),Q.describe=(X)=>{let W=Q.clone();return Q4.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return Q4.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return Q4.get(Q);let W=Q.clone();return Q4.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),QG=F("_ZodString",(Q,Y)=>{QQ.init(Q,Y),s.init(Q,Y);let X=Q._zod.bag;Q.format=X.format??null,Q.minLength=X.minimum??null,Q.maxLength=X.maximum??null,Q.regex=(...W)=>Q.check(x6(...W)),Q.includes=(...W)=>Q.check(y6(...W)),Q.startsWith=(...W)=>Q.check(u6(...W)),Q.endsWith=(...W)=>Q.check(h6(...W)),Q.min=(...W)=>Q.check(E1(...W)),Q.max=(...W)=>Q.check(GQ(...W)),Q.length=(...W)=>Q.check(zQ(...W)),Q.nonempty=(...W)=>Q.check(E1(1,...W)),Q.lowercase=(W)=>Q.check(_6(W)),Q.uppercase=(W)=>Q.check(g6(W)),Q.trim=()=>Q.check(l6()),Q.normalize=(...W)=>Q.check(f6(...W)),Q.toLowerCase=()=>Q.check(m6()),Q.toUpperCase=()=>Q.check(c6())}),kH=F("ZodString",(Q,Y)=>{QQ.init(Q,Y),QG.init(Q,Y),Q.email=(X)=>Q.check(s8(xH,X)),Q.url=(X)=>Q.check(WW(_H,X)),Q.jwt=(X)=>Q.check(MW(tH,X)),Q.emoji=(X)=>Q.check(GW(gH,X)),Q.guid=(X)=>Q.check(k6(aW,X)),Q.uuid=(X)=>Q.check(e8($Q,X)),Q.uuidv4=(X)=>Q.check(QW($Q,X)),Q.uuidv6=(X)=>Q.check(YW($Q,X)),Q.uuidv7=(X)=>Q.check(XW($Q,X)),Q.nanoid=(X)=>Q.check(zW(yH,X)),Q.guid=(X)=>Q.check(k6(aW,X)),Q.cuid=(X)=>Q.check(JW(uH,X)),Q.cuid2=(X)=>Q.check($W(hH,X)),Q.ulid=(X)=>Q.check(HW(fH,X)),Q.base64=(X)=>Q.check(FW(nH,X)),Q.base64url=(X)=>Q.check(qW(dH,X)),Q.xid=(X)=>Q.check(AW(lH,X)),Q.ksuid=(X)=>Q.check(UW(mH,X)),Q.ipv4=(X)=>Q.check(KW(cH,X)),Q.ipv6=(X)=>Q.check(DW(pH,X)),Q.cidrv4=(X)=>Q.check(BW(iH,X)),Q.cidrv6=(X)=>Q.check(LW(rH,X)),Q.e164=(X)=>Q.check(OW(oH,X)),Q.datetime=(X)=>Q.check(p6(X)),Q.date=(X)=>Q.check(i6(X)),Q.time=(X)=>Q.check(r6(X)),Q.duration=(X)=>Q.check(n6(X))});function B(Q){return a8(kH,Q)}var d=F("ZodStringFormat",(Q,Y)=>{r.init(Q,Y),QG.init(Q,Y)}),xH=F("ZodEmail",(Q,Y)=>{G8.init(Q,Y),d.init(Q,Y)});var aW=F("ZodGUID",(Q,Y)=>{X8.init(Q,Y),d.init(Q,Y)});var $Q=F("ZodUUID",(Q,Y)=>{W8.init(Q,Y),d.init(Q,Y)});var _H=F("ZodURL",(Q,Y)=>{z8.init(Q,Y),d.init(Q,Y)});var gH=F("ZodEmoji",(Q,Y)=>{J8.init(Q,Y),d.init(Q,Y)});var yH=F("ZodNanoID",(Q,Y)=>{$8.init(Q,Y),d.init(Q,Y)});var uH=F("ZodCUID",(Q,Y)=>{H8.init(Q,Y),d.init(Q,Y)});var hH=F("ZodCUID2",(Q,Y)=>{A8.init(Q,Y),d.init(Q,Y)});var fH=F("ZodULID",(Q,Y)=>{U8.init(Q,Y),d.init(Q,Y)});var lH=F("ZodXID",(Q,Y)=>{K8.init(Q,Y),d.init(Q,Y)});var mH=F("ZodKSUID",(Q,Y)=>{D8.init(Q,Y),d.init(Q,Y)});var cH=F("ZodIPv4",(Q,Y)=>{O8.init(Q,Y),d.init(Q,Y)});var pH=F("ZodIPv6",(Q,Y)=>{M8.init(Q,Y),d.init(Q,Y)});var iH=F("ZodCIDRv4",(Q,Y)=>{V8.init(Q,Y),d.init(Q,Y)});var rH=F("ZodCIDRv6",(Q,Y)=>{N8.init(Q,Y),d.init(Q,Y)});var nH=F("ZodBase64",(Q,Y)=>{w8.init(Q,Y),d.init(Q,Y)});var dH=F("ZodBase64URL",(Q,Y)=>{b8.init(Q,Y),d.init(Q,Y)});var oH=F("ZodE164",(Q,Y)=>{P8.init(Q,Y),d.init(Q,Y)});var tH=F("ZodJWT",(Q,Y)=>{j8.init(Q,Y),d.init(Q,Y)});var YG=F("ZodNumber",(Q,Y)=>{R6.init(Q,Y),s.init(Q,Y),Q.gt=(W,G)=>Q.check(XQ(W,G)),Q.gte=(W,G)=>Q.check(X4(W,G)),Q.min=(W,G)=>Q.check(X4(W,G)),Q.lt=(W,G)=>Q.check(YQ(W,G)),Q.lte=(W,G)=>Q.check(Y4(W,G)),Q.max=(W,G)=>Q.check(Y4(W,G)),Q.int=(W)=>Q.check(sW(W)),Q.safe=(W)=>Q.check(sW(W)),Q.positive=(W)=>Q.check(XQ(0,W)),Q.nonnegative=(W)=>Q.check(X4(0,W)),Q.negative=(W)=>Q.check(YQ(0,W)),Q.nonpositive=(W)=>Q.check(Y4(0,W)),Q.multipleOf=(W,G)=>Q.check(WQ(W,G)),Q.step=(W,G)=>Q.check(WQ(W,G)),Q.finite=()=>Q;let X=Q._zod.bag;Q.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Q.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Q.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Q.isFinite=!0,Q.format=X.format??null});function l(Q){return bW(YG,Q)}var aH=F("ZodNumberFormat",(Q,Y)=>{I8.init(Q,Y),YG.init(Q,Y)});function sW(Q){return PW(aH,Q)}var sH=F("ZodBoolean",(Q,Y)=>{E8.init(Q,Y),s.init(Q,Y)});function X0(Q){return jW(sH,Q)}var eH=F("ZodNull",(Q,Y)=>{T8.init(Q,Y),s.init(Q,Y)});function t6(Q){return IW(eH,Q)}var QA=F("ZodUnknown",(Q,Y)=>{S8.init(Q,Y),s.init(Q,Y)});function o(){return EW(QA)}var YA=F("ZodNever",(Q,Y)=>{R8.init(Q,Y),s.init(Q,Y)});function XA(Q){return TW(YA,Q)}var WA=F("ZodArray",(Q,Y)=>{C8.init(Q,Y),s.init(Q,Y),Q.element=Y.element,Q.min=(X,W)=>Q.check(E1(X,W)),Q.nonempty=(X)=>Q.check(E1(1,X)),Q.max=(X,W)=>Q.check(GQ(X,W)),Q.length=(X,W)=>Q.check(zQ(X,W)),Q.unwrap=()=>Q.element});function _(Q,Y){return SW(WA,Q,Y)}var XG=F("ZodObject",(Q,Y)=>{x8.init(Q,Y),s.init(Q,Y),h.defineLazy(Q,"shape",()=>{return Y.shape}),Q.keyof=()=>L0(Object.keys(Q._zod.def.shape)),Q.catchall=(X)=>Q.clone({...Q._zod.def,catchall:X}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:o()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:o()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:XA()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(X)=>{return h.extend(Q,X)},Q.safeExtend=(X)=>{return h.safeExtend(Q,X)},Q.merge=(X)=>h.merge(Q,X),Q.pick=(X)=>h.pick(Q,X),Q.omit=(X)=>h.omit(Q,X),Q.partial=(...X)=>h.partial(zG,Q,X[0]),Q.required=(...X)=>h.required(JG,Q,X[0])});function w(Q,Y){let X={type:"object",shape:Q??{},...h.normalizeParams(Y)};return new XG(X)}function U0(Q,Y){return new XG({type:"object",shape:Q,catchall:o(),...h.normalizeParams(Y)})}var WG=F("ZodUnion",(Q,Y)=>{C6.init(Q,Y),s.init(Q,Y),Q.options=Y.options});function p(Q,Y){return new WG({type:"union",options:Q,...h.normalizeParams(Y)})}var GA=F("ZodDiscriminatedUnion",(Q,Y)=>{WG.init(Q,Y),_8.init(Q,Y)});function a6(Q,Y,X){return new GA({type:"union",options:Y,discriminator:Q,...h.normalizeParams(X)})}var zA=F("ZodIntersection",(Q,Y)=>{g8.init(Q,Y),s.init(Q,Y)});function HQ(Q,Y){return new zA({type:"intersection",left:Q,right:Y})}var JA=F("ZodRecord",(Q,Y)=>{y8.init(Q,Y),s.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function t(Q,Y,X){return new JA({type:"record",keyType:Q,valueType:Y,...h.normalizeParams(X)})}var d6=F("ZodEnum",(Q,Y)=>{u8.init(Q,Y),s.init(Q,Y),Q.enum=Y.entries,Q.options=Object.values(Y.entries);let X=new Set(Object.keys(Y.entries));Q.extract=(W,G)=>{let z={};for(let J of W)if(X.has(J))z[J]=Y.entries[J];else throw Error(`Key ${J} not found in enum`);return new d6({...Y,checks:[],...h.normalizeParams(G),entries:z})},Q.exclude=(W,G)=>{let z={...Y.entries};for(let J of W)if(X.has(J))delete z[J];else throw Error(`Key ${J} not found in enum`);return new d6({...Y,checks:[],...h.normalizeParams(G),entries:z})}});function L0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new d6({type:"enum",entries:X,...h.normalizeParams(Y)})}var $A=F("ZodLiteral",(Q,Y)=>{h8.init(Q,Y),s.init(Q,Y),Q.values=new Set(Y.values),Object.defineProperty(Q,"value",{get(){if(Y.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return Y.values[0]}})});function b(Q,Y){return new $A({type:"literal",values:Array.isArray(Q)?Q:[Q],...h.normalizeParams(Y)})}var HA=F("ZodTransform",(Q,Y)=>{f8.init(Q,Y),s.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new i1(Q.constructor.name);X.addIssue=(z)=>{if(typeof z==="string")X.issues.push(h.issue(z,X.value,Y));else{let J=z;if(J.fatal)J.continue=!1;J.code??(J.code="custom"),J.input??(J.input=X.value),J.inst??(J.inst=Q),X.issues.push(h.issue(J))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then((z)=>{return X.value=z,X});return X.value=G,X}});function GG(Q){return new HA({type:"transform",transform:Q})}var zG=F("ZodOptional",(Q,Y)=>{l8.init(Q,Y),s.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function a(Q){return new zG({type:"optional",innerType:Q})}var AA=F("ZodNullable",(Q,Y)=>{m8.init(Q,Y),s.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function eW(Q){return new AA({type:"nullable",innerType:Q})}var UA=F("ZodDefault",(Q,Y)=>{c8.init(Q,Y),s.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function KA(Q,Y){return new UA({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():h.shallowClone(Y)}})}var DA=F("ZodPrefault",(Q,Y)=>{p8.init(Q,Y),s.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function BA(Q,Y){return new DA({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():h.shallowClone(Y)}})}var JG=F("ZodNonOptional",(Q,Y)=>{i8.init(Q,Y),s.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function LA(Q,Y){return new JG({type:"nonoptional",innerType:Q,...h.normalizeParams(Y)})}var FA=F("ZodCatch",(Q,Y)=>{r8.init(Q,Y),s.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function qA(Q,Y){return new FA({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var OA=F("ZodPipe",(Q,Y)=>{n8.init(Q,Y),s.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function o6(Q,Y){return new OA({type:"pipe",in:Q,out:Y})}var MA=F("ZodReadonly",(Q,Y)=>{d8.init(Q,Y),s.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function VA(Q){return new MA({type:"readonly",innerType:Q})}var $G=F("ZodCustom",(Q,Y)=>{o8.init(Q,Y),s.init(Q,Y)});function HG(Q,Y){return RW($G,Q??(()=>!0),Y)}function NA(Q,Y={}){return CW($G,Q,Y)}function ZA(Q){return vW(Q)}function s6(Q,Y){return o6(GG(Q),Y)}w0(v6());var e6="2025-11-25";var AG=[e6,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],X1="io.modelcontextprotocol/related-task",UQ="2.0",G0=HG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),UG=p([B(),l().int()]),KG=B(),rN=U0({ttl:p([l(),t6()]).optional(),pollInterval:l().optional()}),wA=w({ttl:l().optional()}),bA=w({taskId:B()}),QY=U0({progressToken:UG.optional(),[X1]:bA.optional()}),Z0=w({_meta:QY.optional()}),z4=Z0.extend({task:wA.optional()}),DG=(Q)=>z4.safeParse(Q).success,z0=w({method:B(),params:Z0.loose().optional()}),b0=w({_meta:QY.optional()}),P0=w({method:B(),params:b0.loose().optional()}),J0=U0({_meta:QY.optional()}),KQ=p([B(),l().int()]),BG=w({jsonrpc:b(UQ),id:KQ,...z0.shape}).strict(),YY=(Q)=>BG.safeParse(Q).success,LG=w({jsonrpc:b(UQ),...P0.shape}).strict(),FG=(Q)=>LG.safeParse(Q).success,XY=w({jsonrpc:b(UQ),id:KQ,result:J0}).strict(),J4=(Q)=>XY.safeParse(Q).success;var g;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(g||(g={}));var WY=w({jsonrpc:b(UQ),id:KQ.optional(),error:w({code:l().int(),message:B(),data:o().optional()})}).strict();var qG=(Q)=>WY.safeParse(Q).success;var nN=p([BG,LG,XY,WY]),dN=p([XY,WY]),DQ=J0.strict(),PA=b0.extend({requestId:KQ.optional(),reason:B().optional()}),BQ=P0.extend({method:b("notifications/cancelled"),params:PA}),jA=w({src:B(),mimeType:B().optional(),sizes:_(B()).optional(),theme:L0(["light","dark"]).optional()}),$4=w({icons:_(jA).optional()}),S1=w({name:B(),title:B().optional()}),OG=S1.extend({...S1.shape,...$4.shape,version:B(),websiteUrl:B().optional(),description:B().optional()}),IA=HQ(w({applyDefaults:X0().optional()}),t(B(),o())),EA=s6((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},HQ(w({form:IA.optional(),url:G0.optional()}),t(B(),o()).optional())),TA=U0({list:G0.optional(),cancel:G0.optional(),requests:U0({sampling:U0({createMessage:G0.optional()}).optional(),elicitation:U0({create:G0.optional()}).optional()}).optional()}),SA=U0({list:G0.optional(),cancel:G0.optional(),requests:U0({tools:U0({call:G0.optional()}).optional()}).optional()}),RA=w({experimental:t(B(),G0).optional(),sampling:w({context:G0.optional(),tools:G0.optional()}).optional(),elicitation:EA.optional(),roots:w({listChanged:X0().optional()}).optional(),tasks:TA.optional()}),CA=Z0.extend({protocolVersion:B(),capabilities:RA,clientInfo:OG}),GY=z0.extend({method:b("initialize"),params:CA});var vA=w({experimental:t(B(),G0).optional(),logging:G0.optional(),completions:G0.optional(),prompts:w({listChanged:X0().optional()}).optional(),resources:w({subscribe:X0().optional(),listChanged:X0().optional()}).optional(),tools:w({listChanged:X0().optional()}).optional(),tasks:SA.optional()}),kA=J0.extend({protocolVersion:B(),capabilities:vA,serverInfo:OG,instructions:B().optional()}),zY=P0.extend({method:b("notifications/initialized"),params:b0.optional()});var LQ=z0.extend({method:b("ping"),params:Z0.optional()}),xA=w({progress:l(),total:a(l()),message:a(B())}),_A=w({...b0.shape,...xA.shape,progressToken:UG}),FQ=P0.extend({method:b("notifications/progress"),params:_A}),gA=Z0.extend({cursor:KG.optional()}),H4=z0.extend({params:gA.optional()}),A4=J0.extend({nextCursor:KG.optional()}),yA=L0(["working","input_required","completed","failed","cancelled"]),U4=w({taskId:B(),status:yA,ttl:p([l(),t6()]),createdAt:B(),lastUpdatedAt:B(),pollInterval:a(l()),statusMessage:a(B())}),R1=J0.extend({task:U4}),uA=b0.merge(U4),K4=P0.extend({method:b("notifications/tasks/status"),params:uA}),qQ=z0.extend({method:b("tasks/get"),params:Z0.extend({taskId:B()})}),OQ=J0.merge(U4),MQ=z0.extend({method:b("tasks/result"),params:Z0.extend({taskId:B()})}),oN=J0.loose(),VQ=H4.extend({method:b("tasks/list")}),NQ=A4.extend({tasks:_(U4)}),ZQ=z0.extend({method:b("tasks/cancel"),params:Z0.extend({taskId:B()})}),MG=J0.merge(U4),VG=w({uri:B(),mimeType:a(B()),_meta:t(B(),o()).optional()}),NG=VG.extend({text:B()}),JY=B().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),ZG=VG.extend({blob:JY}),D4=L0(["user","assistant"]),C1=w({audience:_(D4).optional(),priority:l().min(0).max(1).optional(),lastModified:G4.datetime({offset:!0}).optional()}),wG=w({...S1.shape,...$4.shape,uri:B(),description:a(B()),mimeType:a(B()),annotations:C1.optional(),_meta:a(U0({}))}),hA=w({...S1.shape,...$4.shape,uriTemplate:B(),description:a(B()),mimeType:a(B()),annotations:C1.optional(),_meta:a(U0({}))}),$Y=H4.extend({method:b("resources/list")}),fA=A4.extend({resources:_(wG)}),lA=H4.extend({method:b("resources/templates/list")}),mA=A4.extend({resourceTemplates:_(hA)}),HY=Z0.extend({uri:B()}),cA=HY,AY=z0.extend({method:b("resources/read"),params:cA}),pA=J0.extend({contents:_(p([NG,ZG]))}),iA=P0.extend({method:b("notifications/resources/list_changed"),params:b0.optional()}),rA=HY,nA=z0.extend({method:b("resources/subscribe"),params:rA}),dA=HY,oA=z0.extend({method:b("resources/unsubscribe"),params:dA}),tA=b0.extend({uri:B()}),aA=P0.extend({method:b("notifications/resources/updated"),params:tA}),sA=w({name:B(),description:a(B()),required:a(X0())}),eA=w({...S1.shape,...$4.shape,description:a(B()),arguments:a(_(sA)),_meta:a(U0({}))}),QU=H4.extend({method:b("prompts/list")}),YU=A4.extend({prompts:_(eA)}),XU=Z0.extend({name:B(),arguments:t(B(),B()).optional()}),WU=z0.extend({method:b("prompts/get"),params:XU}),UY=w({type:b("text"),text:B(),annotations:C1.optional(),_meta:t(B(),o()).optional()}),KY=w({type:b("image"),data:JY,mimeType:B(),annotations:C1.optional(),_meta:t(B(),o()).optional()}),DY=w({type:b("audio"),data:JY,mimeType:B(),annotations:C1.optional(),_meta:t(B(),o()).optional()}),GU=w({type:b("tool_use"),name:B(),id:B(),input:t(B(),o()),_meta:t(B(),o()).optional()}),zU=w({type:b("resource"),resource:p([NG,ZG]),annotations:C1.optional(),_meta:t(B(),o()).optional()}),JU=wG.extend({type:b("resource_link")}),BY=p([UY,KY,DY,JU,zU]),$U=w({role:D4,content:BY}),HU=J0.extend({description:B().optional(),messages:_($U)}),AU=P0.extend({method:b("notifications/prompts/list_changed"),params:b0.optional()}),UU=w({title:B().optional(),readOnlyHint:X0().optional(),destructiveHint:X0().optional(),idempotentHint:X0().optional(),openWorldHint:X0().optional()}),KU=w({taskSupport:L0(["required","optional","forbidden"]).optional()}),bG=w({...S1.shape,...$4.shape,description:B().optional(),inputSchema:w({type:b("object"),properties:t(B(),G0).optional(),required:_(B()).optional()}).catchall(o()),outputSchema:w({type:b("object"),properties:t(B(),G0).optional(),required:_(B()).optional()}).catchall(o()).optional(),annotations:UU.optional(),execution:KU.optional(),_meta:t(B(),o()).optional()}),LY=H4.extend({method:b("tools/list")}),DU=A4.extend({tools:_(bG)}),wQ=J0.extend({content:_(BY).default([]),structuredContent:t(B(),o()).optional(),isError:X0().optional()}),tN=wQ.or(J0.extend({toolResult:o()})),BU=z4.extend({name:B(),arguments:t(B(),o()).optional()}),B4=z0.extend({method:b("tools/call"),params:BU}),LU=P0.extend({method:b("notifications/tools/list_changed"),params:b0.optional()}),aN=w({autoRefresh:X0().default(!0),debounceMs:l().int().nonnegative().default(300)}),L4=L0(["debug","info","notice","warning","error","critical","alert","emergency"]),FU=Z0.extend({level:L4}),FY=z0.extend({method:b("logging/setLevel"),params:FU}),qU=b0.extend({level:L4,logger:B().optional(),data:o()}),OU=P0.extend({method:b("notifications/message"),params:qU}),MU=w({name:B().optional()}),VU=w({hints:_(MU).optional(),costPriority:l().min(0).max(1).optional(),speedPriority:l().min(0).max(1).optional(),intelligencePriority:l().min(0).max(1).optional()}),NU=w({mode:L0(["auto","required","none"]).optional()}),ZU=w({type:b("tool_result"),toolUseId:B().describe("The unique identifier for the corresponding tool call."),content:_(BY).default([]),structuredContent:w({}).loose().optional(),isError:X0().optional(),_meta:t(B(),o()).optional()}),wU=a6("type",[UY,KY,DY]),AQ=a6("type",[UY,KY,DY,GU,ZU]),bU=w({role:D4,content:p([AQ,_(AQ)]),_meta:t(B(),o()).optional()}),PU=z4.extend({messages:_(bU),modelPreferences:VU.optional(),systemPrompt:B().optional(),includeContext:L0(["none","thisServer","allServers"]).optional(),temperature:l().optional(),maxTokens:l().int(),stopSequences:_(B()).optional(),metadata:G0.optional(),tools:_(bG).optional(),toolChoice:NU.optional()}),jU=z0.extend({method:b("sampling/createMessage"),params:PU}),qY=J0.extend({model:B(),stopReason:a(L0(["endTurn","stopSequence","maxTokens"]).or(B())),role:D4,content:wU}),OY=J0.extend({model:B(),stopReason:a(L0(["endTurn","stopSequence","maxTokens","toolUse"]).or(B())),role:D4,content:p([AQ,_(AQ)])}),IU=w({type:b("boolean"),title:B().optional(),description:B().optional(),default:X0().optional()}),EU=w({type:b("string"),title:B().optional(),description:B().optional(),minLength:l().optional(),maxLength:l().optional(),format:L0(["email","uri","date","date-time"]).optional(),default:B().optional()}),TU=w({type:L0(["number","integer"]),title:B().optional(),description:B().optional(),minimum:l().optional(),maximum:l().optional(),default:l().optional()}),SU=w({type:b("string"),title:B().optional(),description:B().optional(),enum:_(B()),default:B().optional()}),RU=w({type:b("string"),title:B().optional(),description:B().optional(),oneOf:_(w({const:B(),title:B()})),default:B().optional()}),CU=w({type:b("string"),title:B().optional(),description:B().optional(),enum:_(B()),enumNames:_(B()).optional(),default:B().optional()}),vU=p([SU,RU]),kU=w({type:b("array"),title:B().optional(),description:B().optional(),minItems:l().optional(),maxItems:l().optional(),items:w({type:b("string"),enum:_(B())}),default:_(B()).optional()}),xU=w({type:b("array"),title:B().optional(),description:B().optional(),minItems:l().optional(),maxItems:l().optional(),items:w({anyOf:_(w({const:B(),title:B()}))}),default:_(B()).optional()}),_U=p([kU,xU]),gU=p([CU,vU,_U]),yU=p([gU,IU,EU,TU]),uU=z4.extend({mode:b("form").optional(),message:B(),requestedSchema:w({type:b("object"),properties:t(B(),yU),required:_(B()).optional()})}),hU=z4.extend({mode:b("url"),message:B(),elicitationId:B(),url:B().url()}),fU=p([uU,hU]),lU=z0.extend({method:b("elicitation/create"),params:fU}),mU=b0.extend({elicitationId:B()}),cU=P0.extend({method:b("notifications/elicitation/complete"),params:mU}),bQ=J0.extend({action:L0(["accept","decline","cancel"]),content:s6((Q)=>Q===null?void 0:Q,t(B(),p([B(),l(),X0(),_(B())])).optional())}),pU=w({type:b("ref/resource"),uri:B()});var iU=w({type:b("ref/prompt"),name:B()}),rU=Z0.extend({ref:p([iU,pU]),argument:w({name:B(),value:B()}),context:w({arguments:t(B(),B()).optional()}).optional()}),nU=z0.extend({method:b("completion/complete"),params:rU});var dU=J0.extend({completion:U0({values:_(B()).max(100),total:a(l().int()),hasMore:a(X0())})}),oU=w({uri:B().startsWith("file://"),name:B().optional(),_meta:t(B(),o()).optional()}),tU=z0.extend({method:b("roots/list"),params:Z0.optional()}),MY=J0.extend({roots:_(oU)}),aU=P0.extend({method:b("notifications/roots/list_changed"),params:b0.optional()}),sN=p([LQ,GY,nU,FY,WU,QU,$Y,lA,AY,nA,oA,B4,LY,qQ,MQ,VQ,ZQ]),eN=p([BQ,FQ,zY,aU,K4]),QZ=p([DQ,qY,OY,bQ,MY,OQ,NQ,R1]),YZ=p([LQ,jU,lU,tU,qQ,MQ,VQ,ZQ]),XZ=p([BQ,FQ,OU,aA,iA,LU,AU,K4,cU]),WZ=p([DQ,kA,dU,HU,YU,fA,mA,pA,wQ,DU,OQ,NQ,R1]);class v extends Error{constructor(Q,Y,X){super(`MCP error ${Q}: ${Y}`);this.code=Q,this.data=X,this.name="McpError"}static fromError(Q,Y,X){if(Q===g.UrlElicitationRequired&&X){let W=X;if(W.elicitations)return new PG(W.elicitations,Y)}return new v(Q,Y,X)}}class PG extends v{constructor(Q,Y=`URL elicitation${Q.length>1?"s":""} required`){super(g.UrlElicitationRequired,Y,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function W1(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var sU=Symbol("Let zodToJsonSchema decide on which parser to use");var gZ=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function VY(Q){let X=JQ(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=kW(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function NY(Q,Y){let X=Y1(Q,Y);if(!X.success)throw X.error;return X.data}var G3=60000;class ZY{constructor(Q){if(this._options=Q,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(BQ,(Y)=>{this._oncancel(Y)}),this.setNotificationHandler(FQ,(Y)=>{this._onprogress(Y)}),this.setRequestHandler(LQ,(Y)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(qQ,async(Y,X)=>{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new v(g.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(MQ,async(Y,X)=>{let W=async()=>{let G=Y.params.taskId;if(this._taskMessageQueue){let J;while(J=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(J.type==="response"||J.type==="error"){let $=J.message,H=$.id,A=this._requestResolvers.get(H);if(A)if(this._requestResolvers.delete(H),J.type==="response")A($);else{let U=$,K=new v(U.error.code,U.error.message,U.error.data);A(K)}else{let U=J.type==="response"?"Response":"Error";this._onerror(Error(`${U} handler missing for request ${H}`))}continue}await this._transport?.send(J.message,{relatedRequestId:X.requestId})}}let z=await this._taskStore.getTask(G,X.sessionId);if(!z)throw new v(g.InvalidParams,`Task not found: ${G}`);if(!W1(z.status))return await this._waitForTaskUpdate(G,X.signal),await W();if(W1(z.status)){let J=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...J,_meta:{...J._meta,[X1]:{taskId:G}}}}return await W()};return await W()}),this.setRequestHandler(VQ,async(Y,X)=>{try{let{tasks:W,nextCursor:G}=await this._taskStore.listTasks(Y.params?.cursor,X.sessionId);return{tasks:W,nextCursor:G,_meta:{}}}catch(W){throw new v(g.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(ZQ,async(Y,X)=>{try{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new v(g.InvalidParams,`Task not found: ${Y.params.taskId}`);if(W1(W.status))throw new v(g.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(Y.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Y.params.taskId);let G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new v(g.InvalidParams,`Task not found after cancellation: ${Y.params.taskId}`);return{_meta:{},...G}}catch(W){if(W instanceof v)throw W;throw new v(g.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,Y,X,W,G=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,Y),startTime:Date.now(),timeout:Y,maxTotalTimeout:X,resetTimeoutOnProgress:G,onTimeout:W})}_resetTimeout(Q){let Y=this._timeoutInfo.get(Q);if(!Y)return!1;let X=Date.now()-Y.startTime;if(Y.maxTotalTimeout&&X>=Y.maxTotalTimeout)throw this._timeoutInfo.delete(Q),v.fromError(g.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Y.maxTotalTimeout,totalElapsed:X});return clearTimeout(Y.timeoutId),Y.timeoutId=setTimeout(Y.onTimeout,Y.timeout),!0}_cleanupTimeout(Q){let Y=this._timeoutInfo.get(Q);if(Y)clearTimeout(Y.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let Y=this.transport?.onclose;this._transport.onclose=()=>{Y?.(),this._onclose()};let X=this.transport?.onerror;this._transport.onerror=(G)=>{X?.(G),this._onerror(G)};let W=this._transport?.onmessage;this._transport.onmessage=(G,z)=>{if(W?.(G,z),J4(G)||qG(G))this._onresponse(G);else if(YY(G))this._onrequest(G,z);else if(FG(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let Y=v.fromError(g.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of Q.values())X(Y)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let Y=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(Y===void 0)return;Promise.resolve().then(()=>Y(Q)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(Q,Y){let X=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,G=Q.params?._meta?.[X1]?.taskId;if(X===void 0){let A={jsonrpc:"2.0",id:Q.id,error:{code:g.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId).catch((U)=>this._onerror(Error(`Failed to enqueue error response: ${U}`)));else W?.send(A).catch((U)=>this._onerror(Error(`Failed to send an error response: ${U}`)));return}let z=new AbortController;this._requestHandlerAbortControllers.set(Q.id,z);let J=DG(Q.params)?Q.params.task:void 0,$=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:z.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(A)=>{let U={relatedRequestId:Q.id};if(G)U.relatedTask={taskId:G};await this.notification(A,U)},sendRequest:async(A,U,K)=>{let D={...K,relatedRequestId:Q.id};if(G&&!D.relatedTask)D.relatedTask={taskId:G};let L=D.relatedTask?.taskId??G;if(L&&$)await $.updateTaskStatus(L,"input_required");return await this.request(A,U,D)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:$,taskRequestedTtl:J?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(J)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(A)=>{if(z.signal.aborted)return;let U={result:A,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:U,timestamp:Date.now()},W?.sessionId);else await W?.send(U)},async(A)=>{if(z.signal.aborted)return;let U={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(A.code)?A.code:g.InternalError,message:A.message??"Internal error",...A.data!==void 0&&{data:A.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId);else await W?.send(U)}).catch((A)=>this._onerror(Error(`Failed to send response: ${A}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:Y,...X}=Q.params,W=Number(Y),G=this._progressHandlers.get(W);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let z=this._responseHandlers.get(W),J=this._timeoutInfo.get(W);if(J&&z&&J.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch($){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),z($);return}G(X)}_onresponse(Q){let Y=Number(Q.id),X=this._requestResolvers.get(Y);if(X){if(this._requestResolvers.delete(Y),J4(Q))X(Q);else{let z=new v(Q.error.code,Q.error.message,Q.error.data);X(z)}return}let W=this._responseHandlers.get(Y);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(Y),this._cleanupTimeout(Y);let G=!1;if(J4(Q)&&Q.result&&typeof Q.result==="object"){let z=Q.result;if(z.task&&typeof z.task==="object"){let J=z.task;if(typeof J.taskId==="string")G=!0,this._taskProgressTokens.set(J.taskId,Y)}}if(!G)this._progressHandlers.delete(Y);if(J4(Q))W(Q);else{let z=v.fromError(Q.error.code,Q.error.message,Q.error.data);W(z)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,Y,X){let{task:W}=X??{};if(!W){try{yield{type:"result",result:await this.request(Q,Y,X)}}catch(z){yield{type:"error",error:z instanceof v?z:new v(g.InternalError,String(z))}}return}let G;try{let z=await this.request(Q,R1,X);if(z.task)G=z.task.taskId,yield{type:"taskCreated",task:z.task};else throw new v(g.InternalError,"Task creation did not return a task");while(!0){let J=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:J},W1(J.status)){if(J.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(J.status==="failed")yield{type:"error",error:new v(g.InternalError,`Task ${G} failed`)};else if(J.status==="cancelled")yield{type:"error",error:new v(g.InternalError,`Task ${G} was cancelled`)};return}if(J.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let $=J.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,$)),X?.signal?.throwIfAborted()}}catch(z){yield{type:"error",error:z instanceof v?z:new v(g.InternalError,String(z))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:z,task:J,relatedTask:$}=X??{};return new Promise((H,A)=>{let U=(M)=>{A(M)};if(!this._transport){U(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),J)this.assertTaskCapability(Q.method)}catch(M){U(M);return}X?.signal?.throwIfAborted();let K=this._requestMessageId++,D={...Q,jsonrpc:"2.0",id:K};if(X?.onprogress)this._progressHandlers.set(K,X.onprogress),D.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:K}};if(J)D.params={...D.params,task:J};if($)D.params={...D.params,_meta:{...D.params?._meta||{},[X1]:$}};let L=(M)=>{this._responseHandlers.delete(K),this._progressHandlers.delete(K),this._cleanupTimeout(K),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:K,reason:String(M)}},{relatedRequestId:W,resumptionToken:G,onresumptiontoken:z}).catch((E)=>this._onerror(Error(`Failed to send cancellation: ${E}`)));let S=M instanceof v?M:new v(g.RequestTimeout,String(M));A(S)};this._responseHandlers.set(K,(M)=>{if(X?.signal?.aborted)return;if(M instanceof Error)return A(M);try{let S=Y1(Y,M.result);if(!S.success)A(S.error);else H(S.data)}catch(S){A(S)}}),X?.signal?.addEventListener("abort",()=>{L(X?.signal?.reason)});let q=X?.timeout??G3,O=()=>L(v.fromError(g.RequestTimeout,"Request timed out",{timeout:q}));this._setupTimeout(K,q,X?.maxTotalTimeout,O,X?.resetTimeoutOnProgress??!1);let V=$?.taskId;if(V){let M=(S)=>{let E=this._responseHandlers.get(K);if(E)E(S);else this._onerror(Error(`Response handler missing for side-channeled request ${K}`))};this._requestResolvers.set(K,M),this._enqueueTaskMessage(V,{type:"request",message:D,timestamp:Date.now()}).catch((S)=>{this._cleanupTimeout(K),A(S)})}else this._transport.send(D,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:z}).catch((M)=>{this._cleanupTimeout(K),A(M)})})}async getTask(Q,Y){return this.request({method:"tasks/get",params:Q},OQ,Y)}async getTaskResult(Q,Y,X){return this.request({method:"tasks/result",params:Q},Y,X)}async listTasks(Q,Y){return this.request({method:"tasks/list",params:Q},NQ,Y)}async cancelTask(Q,Y){return this.request({method:"tasks/cancel",params:Q},MG,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let J={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[X1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:J,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!Y?.relatedRequestId&&!Y?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let J={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[X1]:Y.relatedTask}}};this._transport?.send(J,Y).catch(($)=>this._onerror($))});return}let z={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)z={...z,params:{...z.params,_meta:{...z.params?._meta||{},[X1]:Y.relatedTask}}};await this._transport.send(z,Y)}setRequestHandler(Q,Y){let X=VY(Q);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(W,G)=>{let z=NY(Q,W);return Promise.resolve(Y(z,G))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,Y){let X=VY(Q);this._notificationHandlers.set(X,(W)=>{let G=NY(Q,W);return Promise.resolve(Y(G))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let Y=this._taskProgressTokens.get(Q);if(Y!==void 0)this._progressHandlers.delete(Y),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,Y,X){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,Y,X,W)}async _clearTaskQueue(Q,Y){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll(Q,Y);for(let W of X)if(W.type==="request"&&YY(W.message)){let G=W.message.id,z=this._requestResolvers.get(G);if(z)z(new v(g.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,Y){let X=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)X=W.pollInterval}catch{}return new Promise((W,G)=>{if(Y.aborted){G(new v(g.InvalidRequest,"Request cancelled"));return}let z=setTimeout(W,X);Y.addEventListener("abort",()=>{clearTimeout(z),G(new v(g.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,Y){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await X.createTask(W,Q.id,{method:Q.method,params:Q.params},Y)},getTask:async(W)=>{let G=await X.getTask(W,Y);if(!G)throw new v(g.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(W,G,z)=>{await X.storeTaskResult(W,G,z,Y);let J=await X.getTask(W,Y);if(J){let $=K4.parse({method:"notifications/tasks/status",params:J});if(await this.notification($),W1(J.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,z)=>{let J=await X.getTask(W,Y);if(!J)throw new v(g.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(W1(J.status))throw new v(g.InvalidParams,`Cannot update task "${W}" from terminal status "${J.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,z,Y);let $=await X.getTask(W,Y);if($){let H=K4.parse({method:"notifications/tasks/status",params:$});if(await this.notification(H),W1($.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function jG(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function IG(Q,Y){let X={...Q};for(let W in Y){let G=W,z=Y[G];if(z===void 0)continue;let J=X[G];if(jG(J)&&jG(z))X[G]={...J,...z};else X[G]=z}return X}var W5=x9(F9(),1),G5=x9(X5(),1);function BM(){let Q=new W5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return G5.default(Q),Q}class j9{constructor(Q){this._ajv=Q??BM()}getValidator(Q){let Y="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(X)=>{if(Y(X))return{valid:!0,data:X,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(Y.errors)}}}}class I9{constructor(Q){this._server=Q}requestStream(Q,Y,X){return this._server.requestStream(Q,Y,X)}async getTask(Q,Y){return this._server.getTask({taskId:Q},Y)}async getTaskResult(Q,Y,X){return this._server.getTaskResult({taskId:Q},Y,X)}async listTasks(Q,Y){return this._server.listTasks(Q?{cursor:Q}:void 0,Y)}async cancelTask(Q,Y){return this._server.cancelTask({taskId:Q},Y)}}function z5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"tools/call":if(!Q.tools?.call)throw Error(`${X} does not support task creation for tools/call (required for ${Y})`);break;default:break}}function J5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${X} does not support task creation for sampling/createMessage (required for ${Y})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${X} does not support task creation for elicitation/create (required for ${Y})`);break;default:break}}class E9 extends ZY{constructor(Q,Y){super(Y);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(L4.options.map((X,W)=>[X,W])),this.isMessageIgnored=(X,W)=>{let G=this._loggingLevels.get(W);return G?this.LOG_LEVEL_SEVERITY.get(X)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=Y?.capabilities??{},this._instructions=Y?.instructions,this._jsonSchemaValidator=Y?.jsonSchemaValidator??new j9,this.setRequestHandler(GY,(X)=>this._oninitialize(X)),this.setNotificationHandler(zY,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(FY,async(X,W)=>{let G=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:z}=X.params,J=L4.safeParse(z);if(J.success)this._loggingLevels.set(G,J.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new I9(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=IG(this._capabilities,Q)}setRequestHandler(Q,Y){let W=JQ(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let G;if(T1(W)){let J=W;G=J._zod?.def?.value??J.value}else{let J=W;G=J._def?.value??J.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let J=async($,H)=>{let A=Y1(B4,$);if(!A.success){let L=A.error instanceof Error?A.error.message:String(A.error);throw new v(g.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:U}=A.data,K=await Promise.resolve(Y($,H));if(U.task){let L=Y1(R1,K);if(!L.success){let q=L.error instanceof Error?L.error.message:String(L.error);throw new v(g.InvalidParams,`Invalid task creation result: ${q}`)}return L.data}let D=Y1(wQ,K);if(!D.success){let L=D.error instanceof Error?D.error.message:String(D.error);throw new v(g.InvalidParams,`Invalid tools/call result: ${L}`)}return D.data};return super.setRequestHandler(Q,J)}return super.setRequestHandler(Q,Y)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){J5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;z5(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let Y=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:AG.includes(Y)?Y:e6,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"},DQ)}async createMessage(Q,Y){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let X=Q.messages[Q.messages.length-1],W=Array.isArray(X.content)?X.content:[X.content],G=W.some((H)=>H.type==="tool_result"),z=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,J=z?Array.isArray(z.content)?z.content:[z.content]:[],$=J.some((H)=>H.type==="tool_use");if(G){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!$)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if($){let H=new Set(J.filter((U)=>U.type==="tool_use").map((U)=>U.id)),A=new Set(W.filter((U)=>U.type==="tool_result").map((U)=>U.toolUseId));if(H.size!==A.size||![...H].every((U)=>A.has(U)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},OY,Y);return this.request({method:"sampling/createMessage",params:Q},qY,Y)}async elicitInput(Q,Y){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},bQ,Y)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},G=await this.request({method:"elicitation/create",params:W},bQ,Y);if(G.action==="accept"&&G.content&&W.requestedSchema)try{let J=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!J.valid)throw new v(g.InvalidParams,`Elicitation response content does not match requested schema: ${J.errorMessage}`)}catch(z){if(z instanceof v)throw z;throw new v(g.InternalError,`Error validating elicitation response: ${z instanceof Error?z.message:String(z)}`)}return G}}}createElicitationCompletionNotifier(Q,Y){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},Y)}async listRoots(Q,Y){return this.request({method:"roots/list",params:Q},MY,Y)}async sendLoggingMessage(Q,Y){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,Y))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var $5={name:"@sequenzy/mcp",version:"0.0.49",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^5.8.0"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var T9=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],H5={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}",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 FM(Q){let X=(Q??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return X.length>0?X:"https://sequenzy.com"}function h0(Q){let Y=Q?.trim();return Y?Y:void 0}function t0(Q){return encodeURIComponent(Q)}function Q0(Q,Y){return`${Q}${Y}`}function Y0(Q,Y=""){return`/dashboard/company/${t0(Q)}${Y}`}function A5(Q,Y,X){return Q0(Q,`${Y0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function qM(Q,Y){let X=T9.map((W)=>[W,Y?A5(Q,Y,W):""]);return Object.fromEntries(X)}function K1(Q={},Y){let X=FM(Y),W=h0(Q.companyId),G={},z=qM(X,W);if(!W)return{appUrl:X,routeTemplates:H5,settingsTabValues:T9,urls:G,settingsUrls:z};G.dashboard=Q0(X,Y0(W)),G.campaigns=Q0(X,Y0(W,"/campaign")),G.sequences=Q0(X,Y0(W,"/sequences")),G.settings=Q0(X,Y0(W,"/settings")),G.emails=Q0(X,Y0(W,"/emails")),G.subscribers=Q0(X,Y0(W,"/subscribers")),G.sentEmails=Q0(X,Y0(W,"/sent-emails")),G.segments=Q0(X,Y0(W,"/segments")),G.metrics=Q0(X,Y0(W,"/metrics")),G.transactional=Q0(X,Y0(W,"/transactional"));let J=h0(Q.campaignId);if(J)G.campaign=Q0(X,Y0(W,`/campaign/${t0(J)}`)),G.campaignPreview=`${G.campaign}?step=review`;let $=h0(Q.sequenceId);if($)G.sequence=Q0(X,Y0(W,`/sequences/${t0($)}`));let H=h0(Q.emailId)??h0(Q.templateId);if(H)G.email=Q0(X,Y0(W,`/emails/${t0(H)}`)),G.template=G.email;let A=h0(Q.transactionalId);if(A)G.transactionalEmail=Q0(X,Y0(W,`/transactional/${t0(A)}`));let U=h0(Q.emailSendId);if(U)G.emailSend=Q0(X,Y0(W,`/sent-emails/${t0(U)}`));let K=h0(Q.domainId);if(K)G.domain=Q0(X,Y0(W,`/settings/domain/${t0(K)}`)),G.domainVerify=`${G.domain}/verify`;let D=h0(Q.status);if(D)G.campaignList=Q0(X,Y0(W,`/campaign/list/${t0(D)}`)),G.sequenceList=Q0(X,Y0(W,`/sequences/list/${t0(D)}`));let L=h0(Q.settingsTab);if(L)G.settingsTab=A5(X,W,L);return{appUrl:X,routeTemplates:H5,settingsTabValues:T9,urls:G,settingsUrls:z}}var U5=[{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 K5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await N("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await N("GET","/api/v1/account"),W=B1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await N("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await N("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await N("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await N("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await N("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await N("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await N("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await N("GET","/api/v1/tags");break;case"sequenzy://health":Y=await N("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=K1();break;default:throw Error(`Unknown resource: ${Q}`)}return{contents:[{uri:Q,mimeType:"application/json",text:JSON.stringify(Y,null,2)}]}}catch(Y){return{contents:[{uri:Q,mimeType:"text/plain",text:b1(Y)}]}}}var h4="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`. Use this for editor-compatible content, including conditional and repeat blocks. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.",H6="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`.",O5="Sequenzy email blocks. Provide blocks or html for email steps. 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.",D5=500,R9={status:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"]},OM=Object.entries(R9).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),MM={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","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct"],description:"Filter field. Use `event` for custom subscriber events, `segment` for saved segment membership, and `stripeProduct`/`stripeCurrentProduct`/`stripeTrialProduct` for Stripe product-based segments. Engagement fields (`emailSent`, `emailDelivered`, `emailOpened`, `emailClicked`, `emailBounced`, `emailComplained`) accept a time range as the value or a specific campaign via `campaign:<campaign_id>`."},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${OM}.`},value:{type:"string",description:"Filter value. For custom attribute empty checks, use `attributeName:` such as `last_logged_in:`. Event examples: `saas.purchase:30d`, `saas.purchase:all`, or `saas.purchase:5:30d` for thresholds. Segment values are segment IDs. Stripe product examples: `prod_123` for bought/didn't buy/current/trialing, `prod_123:3` for payment thresholds, `prod_123:is_canceled` for products set to cancel, `prod_123:cancels_at:2026-05-26`, `prod_123:end_at:2026-05-26`, or `prod_123:start_at:7 days ago` for product-scoped dates. Engagement examples: `7d`, `30d`, `90d`, `180d`, `all` for rolling time windows, or `campaign:<campaign_id>` to scope to a specific sent campaign (use `list_campaigns` to find IDs)."}},required:["field","operator","value"],additionalProperties:!1},VM={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 M5(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(typeof Y!=="object"||Y===null)return Y;let X=Y;if(typeof X.id==="string"&&X.id.trim()!=="")return X;return{...X,id:crypto.randomUUID()}})}function V5(Q){if(typeof Q!=="object"||Q===null)return Q;let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=M5([Y]);return Array.isArray(X)?X[0]:Y}if(Y.kind!=="group")return Q;return{...Y,id:typeof Y.id==="string"&&Y.id.trim()!==""?Y.id:crypto.randomUUID(),children:Array.isArray(Y.children)?Y.children.map(V5):[]}}function NM(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function ZM(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function B5(Q){if(Q==="all")return!0;let Y=Q.match(/^(\d+)d$/);if(!Y?.[1])return!1;let X=Number.parseInt(Y[1],10);return Number.isInteger(X)&&X>0}function wM(Q,Y){let X=Y.split(":");if(Q==="at_least"||Q==="less_than_count"){if(X.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let z=X.slice(0,-2).join(":").trim(),J=X.at(-2),$=X.at(-1),H=J===void 0?Number.NaN:Number.parseInt(J,10);return z&&Number.isInteger(H)&&H>0&&$!==void 0&&B5($)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(X.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=X.slice(0,-1).join(":").trim(),G=X.at(-1);return W&&G!==void 0&&B5(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function bM(Q){let Y=Q.indexOf(":");if(Y===-1)return{productId:Q,subfilter:null,rawValue:null};let X=Q.substring(0,Y),W=Q.substring(Y+1),G=W.indexOf(":");if(G===-1)return{productId:X,subfilter:W,rawValue:null};return{productId:X,subfilter:W.substring(0,G),rawValue:W.substring(G+1)}}function PM(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function jM(Q){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(Q)}function IM(Q,Y){if(Y==="cancels_at"||Y==="cancel_at"||Y==="cancellation_at")return!0;if(Q==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(Y);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(Y)}function EM(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function TM(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let $=X.indexOf(":");if($===-1)return null;let H=X.substring(0,$).trim(),A=Number.parseInt(X.substring($+1).trim(),10);return H&&Number.isInteger(A)&&A>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(Q!=="stripeCurrentProduct"&&Q!=="stripeTrialProduct")return null;let{productId:W,subfilter:G,rawValue:z}=bM(X);if(!W.trim())return"Stripe product filters must include a product ID.";if(!G)return Y==="is"||Y==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let J=PM(G);if(jM(J))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!IM(Q,J))return`Unsupported Stripe product subfilter "${G}".`;if(!EM(Y))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return z?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}function N5(Q){if(typeof Q!=="object"||Q===null)return"Segment filters must be objects.";let Y=Q,X=Y.field,W=Y.operator,G=Y.value;if(typeof X!=="string"||!(X in R9))return`Unsupported segment filter field "${String(X)}".`;if(typeof W!=="string")return`Segment filter "${X}" must include an operator.`;let z=R9[X];if(!z.includes(W))return`Operator "${W}" is not supported for ${X} filters. Use one of: ${z.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${X}" must include a value.`;if(X==="attribute"&&typeof G==="string"){if(!NM(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!ZM(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let J=wM(W,G);if(J)return J}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let J=TM(X,W,G);if(J)return J}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map(($)=>$.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function Z5(Q){if(typeof Q!=="object"||Q===null)return[];let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=N5(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap(Z5);return[]}function w1(Q,Y,X){if(Y.html!==void 0&&Y.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`, not both.`);if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error(`\`blocks\` must be an array when calling \`${Q}\`.`);if(X?.requireContent&&Y.html===void 0&&Y.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`.`)}function U6(Q,Y){if(Y.labels===void 0)return;if(!Array.isArray(Y.labels))throw Error(`\`labels\` must be an array when calling \`${Q}\`.`);if(Y.labels.some((X)=>typeof X!=="string"||X.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${Q}\`.`)}function SM(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!Y&&!X)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=Y?Q.filters.flatMap((G)=>{let z=N5(G);return z?[z]:[]}):Z5(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function RM(Q){if(Q.clearEnrollmentFieldPath===!0&&Q.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");let Y={...Q};if(delete Y.clearEnrollmentFieldPath,Q.clearEnrollmentFieldPath===!0)Y.enrollmentFieldPath=null;return Y}function CM(Q){let Y=j(Q,"subscriberId"),X=Q.fieldValues,W=X===void 0?void 0:Array.isArray(X)?X:void 0;if(X!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let G=W?.map(($)=>typeof $==="string"?$.trim():"").filter(($)=>$.length>0)??[];if(W?.some(($)=>typeof $!=="string")||W!==void 0&&G.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(Y!==void 0===G.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let z=j(Q,"fieldPath"),J=j(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...z!==void 0&&{fieldPath:z},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...J!==void 0&&{reason:J}}}function vM(Q){w1("create_campaign",Q),U6("create_campaign",Q);let Y=j(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0,G=Q.templateId!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(Y&&(X||W||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!Y&&j(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function kM(Q){if(j(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!B0(Q.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(Q.sendTimeOptimization!==void 0){if(typeof Q.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(Q.spreadOverHours!==void 0){if(typeof Q.spreadOverHours!=="number"||!Number.isInteger(Q.spreadOverHours)||Q.spreadOverHours<1||Q.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}}function xM(Q){w1("create_transactional_email",Q);let Y=j(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(Y&&(X||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!Y&&!X&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!Y&&j(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var L5={type:"object",description:"A step to create inside a branch path. Use type:'delay' for a standalone delay, type:'email' for an email, or type:'create_discount' for a discount action.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","webhook"],description:"Branch path step type. Omit for email steps; use delay for standalone waits."},nodeType:{type:"string",enum:["logic_delay","action_email","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","action_webhook"],description:"Advanced branch path node type. Prefer type unless creating a non-email action."},config:{type:"object",description:"Config for advanced nodeType steps such as tag/list/webhook/wait-for-event actions.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:O5,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps."},delay:{type:"object",description:"Delay before this step, or the delay duration when type is delay.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}}},delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"]},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 _M(Q){if(!Q||typeof Q!=="object")return null;let Y=Q;if(Y.success!==!1)return null;if(typeof Y.error==="string")return Error(Y.error);if(Y.error&&typeof Y.error==="object"&&typeof Y.error.message==="string")return Error(Y.error.message);if(typeof Y.message==="string")return Error(Y.message);return Error("The tool returned an unsuccessful response.")}function B0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function F5(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function gM(Q){let Y=new URLSearchParams;if(typeof Q.query==="string"&&Q.query.trim()!=="")Y.set("query",Q.query.trim());if(Array.isArray(Q.tags)&&Q.tags.length>0)Y.set("tags",Q.tags.filter((X)=>typeof X==="string"&&X.trim()!=="").join(","));if(typeof Q.list==="string"&&Q.list.trim()!=="")Y.set("list",Q.list.trim());if(typeof Q.listId==="string"&&Q.listId.trim()!=="")Y.set("listId",Q.listId.trim());if(typeof Q.listName==="string"&&Q.listName.trim()!=="")Y.set("listName",Q.listName.trim());if(typeof Q.segmentId==="string"&&Q.segmentId.trim()!=="")Y.set("segmentId",Q.segmentId);if(typeof Q.status==="string"&&Q.status.trim()!=="")Y.set("status",Q.status.trim());return Y.set("page",String(Q.page)),Y.set("limit",String(Q.pageSize)),Y}async function yM(Q,Y){let X=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,W=Math.min(100,Math.max(1,X??100)),G=[],z=1,J=0,$=0,H=0;while(!0){let U=gM({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:z,pageSize:W}),K=await N("GET",`/api/v1/subscribers?${U.toString()}`,void 0,Y);J=K.pagination?.total??K.subscribers.length,$=K.pagination?.totalPages??1,H+=1,G.push(...K.subscribers??[]);let D=X!==void 0&&G.length>=X,L=K.pagination?z>=K.pagination.totalPages:(K.subscribers??[]).length<W;if(D||L)break;z+=1}let A=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:A,pagination:{page:1,limit:W,total:J,totalPages:$,fetchedPages:H},returned:A.length,truncated:X!==void 0&&J>0&&A.length<J}}function uM(Q){let Y=typeof Q.email==="string"&&Q.email.trim()!==""?Q.email.trim():void 0,X=typeof Q.externalId==="string"&&Q.externalId.trim()!==""?Q.externalId.trim():void 0;return{...Y?{email:Y}:{},...X?{externalId:X}:{}}}function f4(Q,Y){let X=uM(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function C9(Q){if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}`;return`/api/v1/subscribers/external?externalId=${encodeURIComponent(String(Q.externalId))}`}async function S9(Q,Y){return N("GET",C9(Q),void 0,Y)}function j(Q,Y){let X=Q[Y];if(typeof X!=="string")return;let W=X.trim();return W.length>0?W:void 0}function hM(Q,Y,X){let W=j(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function q5(Q,Y,X,W){let G=j(Y,X);if(G===void 0)return;if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function fM(Q,Y){if(!Array.isArray(Y.emails))throw Error(`\`emails\` must be an array when calling \`${Q}\`.`);let X=[];if(Y.emails.forEach((W,G)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${Q}\`.`);let z=W.trim();if(z.length>0)X.push(z)}),X.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${Q}\`.`);if(X.length>D5)throw Error(`\`emails\` must include no more than ${D5} email addresses when calling \`${Q}\`. Split larger batches into multiple calls.`);return X}async function w5(Q){let Y=j(Q,"companyId");if(Y)return Y;let X=B1();if(X)return X;try{return(await N("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}function l4(Q,Y){if(!B0(Q)||!Y)return Q;return{...Q,url:Y}}function b5(Q,Y){if(!B0(Q))return Q;return{...Q,...Y.campaign!==void 0&&{url:Y.campaign},...Y.campaignPreview!==void 0&&{previewUrl:Y.campaignPreview}}}function A6(Q,Y,X){if(!Array.isArray(Q)||!Y)return Q;return Q.map((W)=>{if(!B0(W))return W;let G=j(W,"id");if(!G)return W;let z=K1({companyId:Y,...X==="campaign"&&{campaignId:G},...X==="sequence"&&{sequenceId:G},...X==="template"&&{emailId:G},...X==="transactional"&&{transactionalId:G}});if(X==="campaign")return b5(W,z.urls);let J=X==="sequence"?z.urls.sequence:X==="template"?z.urls.email:z.urls.transactionalEmail;return l4(W,J)})}function lM(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!B0(Y))return Y;let X=j(Y,"id");if(!X)return Y;let W=K1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var mM=new Set(["get_account","select_company","create_company","get_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","list_sequences","get_sequence","create_sequence","update_sequence","enable_sequence","disable_sequence","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function cM(Q,Y,X){if(!B0(X)||!mM.has(Q))return X;let W=B0(X.company)?X.company:void 0,z=j(X,"selectedCompanyId")??j(X,"currentCompanyId")??j(X,"companyId")??(W?j(W,"id"):void 0)??(W?j(W,"companyId"):void 0)??await w5(Y);if(!z)return X;let J=B0(X.campaign)?X.campaign:void 0,$=B0(X.sequence)?X.sequence:void 0,H=B0(X.template)?X.template:void 0,A=B0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,U={companyId:z,campaignId:j(Y,"campaignId")??j(X,"campaignId")??(J?j(J,"id"):void 0),sequenceId:j(Y,"sequenceId")??j(X,"sequenceId")??($?j($,"id"):void 0),emailId:j(X,"templateId")??(H?j(H,"id"):void 0)??(A?j(A,"emailId"):void 0)??j(Y,"templateId"),transactionalId:j(Y,"transactionalId")??(A?j(A,"id"):void 0)??j(Y,"idOrSlug"),emailSendId:j(Y,"emailSendId")??j(X,"emailSendId")??(B0(X.emailSend)?j(X.emailSend,"id"):void 0),status:j(Y,"status")},K=K1(U),D=W?K1({companyId:z}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:lM(X.companies)},...Array.isArray(X.campaigns)&&{campaigns:A6(X.campaigns,z,"campaign")},...Array.isArray(X.sequences)&&{sequences:A6(X.sequences,z,"sequence")},...Array.isArray(X.templates)&&{templates:A6(X.templates,z,"template")},...Array.isArray(X.transactional)&&{transactional:A6(X.transactional,z,"transactional")},...W&&D!==void 0&&{company:{...W,url:D.urls.dashboard,settingsUrl:D.urls.settings}},...J&&K.urls.campaign!==void 0&&{campaign:b5(J,K.urls)},...$&&K.urls.sequence!==void 0&&{sequence:l4($,K.urls.sequence)},...H&&K.urls.email!==void 0&&{template:l4(H,K.urls.email)},...A&&K.urls.transactionalEmail!==void 0&&{transactional:l4(A,K.urls.transactionalEmail)},...B0(X.emailSend)&&K.urls.emailSend!==void 0&&{emailSend:l4(X.emailSend,K.urls.emailSend)},appUrls:K.urls}}var P5=[{name:"get_account",description:`Get current account information including available companies. IMPORTANT: If you have access to multiple companies, you MUST either:
|
|
28
|
+
`)}L.write("payload.value = newResult;"),L.write("return payload;");let S=L.compile();return(E,x)=>S(D,E,x)},z,J=L1,$=!m4.jitless,A=$&&V6.value,U=Y.catchall,K;Q._zod.parse=(D,L)=>{K??(K=W.value);let q=D.value;if(!J(q))return D.issues.push({expected:"object",code:"invalid_type",input:q,inst:Q}),D;if($&&A&&L?.async===!1&&L.jitless!==!0){if(!z)z=G(Y.shape);if(D=z(D,L),!U)return D;return k8([],q,D,L,K,Q)}return X(D,L)}});function oX(Q,Y,X,W){for(let z of Q)if(z.issues.length===0)return Y.value=z.value,Y;let G=Q.filter((z)=>!Q1(z));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map((z)=>z.issues.map((J)=>T0(J,W,w0())))}),Y}var C6=F("$ZodUnion",(Q,Y)=>{i.init(Q,Y),m(Q._zod,"optin",()=>Y.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),m(Q._zod,"optout",()=>Y.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),m(Q._zod,"values",()=>{if(Y.options.every((G)=>G._zod.values))return new Set(Y.options.flatMap((G)=>Array.from(G._zod.values)));return}),m(Q._zod,"pattern",()=>{if(Y.options.every((G)=>G._zod.pattern)){let G=Y.options.map((z)=>z._zod.pattern);return new RegExp(`^(${G.map((z)=>d1(z.source)).join("|")})$`)}return});let X=Y.options.length===1,W=Y.options[0]._zod.run;Q._zod.parse=(G,z)=>{if(X)return W(G,z);let J=!1,$=[];for(let H of Y.options){let A=H._zod.run({value:G.value,issues:[]},z);if(A instanceof Promise)$.push(A),J=!0;else{if(A.issues.length===0)return A;$.push(A)}}if(!J)return oX($,G,Q,z);return Promise.all($).then((H)=>{return oX(H,G,Q,z)})}}),_8=F("$ZodDiscriminatedUnion",(Q,Y)=>{C6.init(Q,Y);let X=Q._zod.parse;m(Q._zod,"propValues",()=>{let G={};for(let z of Y.options){let J=z._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(z)}"`);for(let[$,H]of Object.entries(J)){if(!G[$])G[$]=new Set;for(let A of H)G[$].add(A)}}return G});let W=j1(()=>{let G=Y.options,z=new Map;for(let J of G){let $=J._zod.propValues?.[Y.discriminator];if(!$||$.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(J)}"`);for(let H of $){if(z.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);z.set(H,J)}}return z});Q._zod.parse=(G,z)=>{let J=G.value;if(!L1(J))return G.issues.push({code:"invalid_type",expected:"object",input:J,inst:Q}),G;let $=W.value.get(J?.[Y.discriminator]);if($)return $._zod.run(G,z);if(Y.unionFallback)return X(G,z);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,input:J,path:[Y.discriminator],inst:Q}),G}}),g8=F("$ZodIntersection",(Q,Y)=>{i.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value,z=Y.left._zod.run({value:G,issues:[]},W),J=Y.right._zod.run({value:G,issues:[]},W);if(z instanceof Promise||J instanceof Promise)return Promise.all([z,J]).then(([H,A])=>{return tX(X,H,A)});return tX(X,z,J)}});function S6(Q,Y){if(Q===Y)return{valid:!0,data:Q};if(Q instanceof Date&&Y instanceof Date&&+Q===+Y)return{valid:!0,data:Q};if(e0(Q)&&e0(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter((z)=>X.indexOf(z)!==-1),G={...Q,...Y};for(let z of W){let J=S6(Q[z],Y[z]);if(!J.valid)return{valid:!1,mergeErrorPath:[z,...J.mergeErrorPath]};G[z]=J.data}return{valid:!0,data:G}}if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let W=0;W<Q.length;W++){let G=Q[W],z=Y[W],J=S6(G,z);if(!J.valid)return{valid:!1,mergeErrorPath:[W,...J.mergeErrorPath]};X.push(J.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function tX(Q,Y,X){if(Y.issues.length)Q.issues.push(...Y.issues);if(X.issues.length)Q.issues.push(...X.issues);if(Q1(Q))return Q;let W=S6(Y.value,X.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return Q.value=W.data,Q}var y8=F("$ZodRecord",(Q,Y)=>{i.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!e0(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let z=[];if(Y.keyType._zod.values){let J=Y.keyType._zod.values;X.value={};for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let A=Y.valueType._zod.run({value:G[H],issues:[]},W);if(A instanceof Promise)z.push(A.then((U)=>{if(U.issues.length)X.issues.push(...c0(H,U.issues));X.value[H]=U.value}));else{if(A.issues.length)X.issues.push(...c0(H,A.issues));X.value[H]=A.value}}let $;for(let H in G)if(!J.has(H))$=$??[],$.push(H);if($&&$.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:$})}else{X.value={};for(let J of Reflect.ownKeys(G)){if(J==="__proto__")continue;let $=Y.keyType._zod.run({value:J,issues:[]},W);if($ instanceof Promise)throw Error("Async schemas not supported in object keys currently");if($.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:$.issues.map((A)=>T0(A,W,w0())),input:J,path:[J],inst:Q}),X.value[$.value]=$.value;continue}let H=Y.valueType._zod.run({value:G[J],issues:[]},W);if(H instanceof Promise)z.push(H.then((A)=>{if(A.issues.length)X.issues.push(...c0(J,A.issues));X.value[$.value]=A.value}));else{if(H.issues.length)X.issues.push(...c0(J,H.issues));X.value[$.value]=H.value}}}if(z.length)return Promise.all(z).then(()=>X);return X}});var u8=F("$ZodEnum",(Q,Y)=>{i.init(Q,Y);let X=O6(Y.entries),W=new Set(X);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${X.filter((G)=>N6.has(typeof G)).map((G)=>typeof G==="string"?m0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,z)=>{let J=G.value;if(W.has(J))return G;return G.issues.push({code:"invalid_value",values:X,input:J,inst:Q}),G}}),h8=F("$ZodLiteral",(Q,Y)=>{if(i.init(Q,Y),Y.values.length===0)throw Error("Cannot create literal schema with no valid values");Q._zod.values=new Set(Y.values),Q._zod.pattern=new RegExp(`^(${Y.values.map((X)=>typeof X==="string"?m0(X):X?m0(X.toString()):String(X)).join("|")})$`),Q._zod.parse=(X,W)=>{let G=X.value;if(Q._zod.values.has(G))return X;return X.issues.push({code:"invalid_value",values:Y.values,input:G,inst:Q}),X}});var f8=F("$ZodTransform",(Q,Y)=>{i.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new i1(Q.constructor.name);let G=Y.transform(X.value,X);if(W.async)return(G instanceof Promise?G:Promise.resolve(G)).then((J)=>{return X.value=J,X});if(G instanceof Promise)throw new l0;return X.value=G,X}});function aX(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var l8=F("$ZodOptional",(Q,Y)=>{i.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",m(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),m(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${d1(X.source)})?$`):void 0}),Q._zod.parse=(X,W)=>{if(Y.innerType._zod.optin==="optional"){let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>aX(z,X.value));return aX(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),m8=F("$ZodNullable",(Q,Y)=>{i.init(Q,Y),m(Q._zod,"optin",()=>Y.innerType._zod.optin),m(Q._zod,"optout",()=>Y.innerType._zod.optout),m(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${d1(X.source)}|null)$`):void 0}),m(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,null]):void 0}),Q._zod.parse=(X,W)=>{if(X.value===null)return X;return Y.innerType._zod.run(X,W)}}),c8=F("$ZodDefault",(Q,Y)=>{i.init(Q,Y),Q._zod.optin="optional",m(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)return X.value=Y.defaultValue,X;let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>sX(z,Y));return sX(G,Y)}});function sX(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var p8=F("$ZodPrefault",(Q,Y)=>{i.init(Q,Y),Q._zod.optin="optional",m(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)X.value=Y.defaultValue;return Y.innerType._zod.run(X,W)}}),i8=F("$ZodNonOptional",(Q,Y)=>{i.init(Q,Y),m(Q._zod,"values",()=>{let X=Y.innerType._zod.values;return X?new Set([...X].filter((W)=>W!==void 0)):void 0}),Q._zod.parse=(X,W)=>{let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>eX(z,Q));return eX(G,Q)}});function eX(Q,Y){if(!Q.issues.length&&Q.value===void 0)Q.issues.push({code:"invalid_type",expected:"nonoptional",input:Q.value,inst:Y});return Q}var r8=F("$ZodCatch",(Q,Y)=>{i.init(Q,Y),m(Q._zod,"optin",()=>Y.innerType._zod.optin),m(Q._zod,"optout",()=>Y.innerType._zod.optout),m(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>{if(X.value=z.value,z.issues.length)X.value=Y.catchValue({...X,error:{issues:z.issues.map((J)=>T0(J,W,w0()))},input:X.value}),X.issues=[];return X});if(X.value=G.value,G.issues.length)X.value=Y.catchValue({...X,error:{issues:G.issues.map((z)=>T0(z,W,w0()))},input:X.value}),X.issues=[];return X}});var n8=F("$ZodPipe",(Q,Y)=>{i.init(Q,Y),m(Q._zod,"values",()=>Y.in._zod.values),m(Q._zod,"optin",()=>Y.in._zod.optin),m(Q._zod,"optout",()=>Y.out._zod.optout),m(Q._zod,"propValues",()=>Y.in._zod.propValues),Q._zod.parse=(X,W)=>{if(W.direction==="backward"){let z=Y.out._zod.run(X,W);if(z instanceof Promise)return z.then((J)=>s4(J,Y.in,W));return s4(z,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>s4(z,Y.out,W));return s4(G,Y.out,W)}});function s4(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var d8=F("$ZodReadonly",(Q,Y)=>{i.init(Q,Y),m(Q._zod,"propValues",()=>Y.innerType._zod.propValues),m(Q._zod,"values",()=>Y.innerType._zod.values),m(Q._zod,"optin",()=>Y.innerType._zod.optin),m(Q._zod,"optout",()=>Y.innerType._zod.optout),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(Q8);return Q8(G)}});function Q8(Q){return Q.value=Object.freeze(Q.value),Q}var o8=F("$ZodCustom",(Q,Y)=>{W0.init(Q,Y),i.init(Q,Y),Q._zod.parse=(X,W)=>{return X},Q._zod.check=(X)=>{let W=X.value,G=Y.fn(W);if(G instanceof Promise)return G.then((z)=>Y8(z,X,W,Q));Y8(G,X,W,Q);return}});function Y8(Q,Y,X,W){if(!Q){let G={code:"custom",input:X,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)G.params=W._zod.def.params;Y.issues.push(I1(G))}}var ZH=(Q)=>{let Y=typeof Q;switch(Y){case"number":return Number.isNaN(Q)?"NaN":"number";case"object":{if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Object.getPrototypeOf(Q)!==Object.prototype&&Q.constructor)return Q.constructor.name}}return Y},wH=()=>{let Q={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function Y(W){return Q[W]??null}let X={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${ZH(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${r4(W.values[0])}`;return`Invalid option: expected one of ${c4(W.values,"|")}`;case"too_big":{let G=W.inclusive?"<=":"<",z=Y(W.origin);if(z)return`Too big: expected ${W.origin??"value"} to have ${G}${W.maximum.toString()} ${z.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${G}${W.maximum.toString()}`}case"too_small":{let G=W.inclusive?">=":">",z=Y(W.origin);if(z)return`Too small: expected ${W.origin} to have ${G}${W.minimum.toString()} ${z.unit}`;return`Too small: expected ${W.origin} to be ${G}${W.minimum.toString()}`}case"invalid_format":{let G=W;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${X[G.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${c4(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 v6(){return{localeError:wH()}}var KV=Symbol("ZodOutput"),DV=Symbol("ZodInput");class t8{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Q,...Y){let X=Y[0];if(this._map.set(Q,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.id,Q)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Q){let Y=this._map.get(Q);if(Y&&typeof Y==="object"&&"id"in Y)this._idmap.delete(Y.id);return this._map.delete(Q),this}get(Q){let Y=Q._zod.parent;if(Y){let X={...this.get(Y)??{}};delete X.id;let W={...X,...this._map.get(Q)};return Object.keys(W).length?W:void 0}return this._map.get(Q)}has(Q){return this._map.has(Q)}}function bH(){return new t8}var Q4=bH();function a8(Q,Y){return new Q({type:"string",...I(Y)})}function s8(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...I(Y)})}function k6(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...I(Y)})}function e8(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...I(Y)})}function QW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(Y)})}function YW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(Y)})}function XW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(Y)})}function WW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...I(Y)})}function GW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...I(Y)})}function zW(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(Y)})}function JW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...I(Y)})}function $W(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(Y)})}function HW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...I(Y)})}function AW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...I(Y)})}function UW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(Y)})}function KW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(Y)})}function DW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(Y)})}function BW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(Y)})}function LW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(Y)})}function FW(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...I(Y)})}function qW(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...I(Y)})}function OW(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...I(Y)})}function MW(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...I(Y)})}function VW(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(Y)})}function NW(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...I(Y)})}function ZW(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...I(Y)})}function wW(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...I(Y)})}function bW(Q,Y){return new Q({type:"number",checks:[],...I(Y)})}function PW(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...I(Y)})}function jW(Q,Y){return new Q({type:"boolean",...I(Y)})}function IW(Q,Y){return new Q({type:"null",...I(Y)})}function EW(Q){return new Q({type:"unknown"})}function TW(Q,Y){return new Q({type:"never",...I(Y)})}function YQ(Q,Y){return new I6({check:"less_than",...I(Y),value:Q,inclusive:!1})}function Y4(Q,Y){return new I6({check:"less_than",...I(Y),value:Q,inclusive:!0})}function XQ(Q,Y){return new E6({check:"greater_than",...I(Y),value:Q,inclusive:!1})}function X4(Q,Y){return new E6({check:"greater_than",...I(Y),value:Q,inclusive:!0})}function WQ(Q,Y){return new xX({check:"multiple_of",...I(Y),value:Q})}function GQ(Q,Y){return new gX({check:"max_length",...I(Y),maximum:Q})}function E1(Q,Y){return new yX({check:"min_length",...I(Y),minimum:Q})}function zQ(Q,Y){return new uX({check:"length_equals",...I(Y),length:Q})}function x6(Q,Y){return new hX({check:"string_format",format:"regex",...I(Y),pattern:Q})}function _6(Q){return new fX({check:"string_format",format:"lowercase",...I(Q)})}function g6(Q){return new lX({check:"string_format",format:"uppercase",...I(Q)})}function y6(Q,Y){return new mX({check:"string_format",format:"includes",...I(Y),includes:Q})}function u6(Q,Y){return new cX({check:"string_format",format:"starts_with",...I(Y),prefix:Q})}function h6(Q,Y){return new pX({check:"string_format",format:"ends_with",...I(Y),suffix:Q})}function F1(Q){return new iX({check:"overwrite",tx:Q})}function f6(Q){return F1((Y)=>Y.normalize(Q))}function l6(){return F1((Q)=>Q.trim())}function m6(){return F1((Q)=>Q.toLowerCase())}function c6(){return F1((Q)=>Q.toUpperCase())}function SW(Q,Y,X){return new Q({type:"array",element:Y,...I(X)})}function RW(Q,Y,X){let W=I(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function CW(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...I(X)})}function vW(Q){let Y=PH((X)=>{return X.addIssue=(W)=>{if(typeof W==="string")X.issues.push(I1(W,X.value,Y._zod.def));else{let G=W;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=X.value),G.inst??(G.inst=Y),G.continue??(G.continue=!Y._zod.def.abort),X.issues.push(I1(G))}},Q(X.value,X)});return Y}function PH(Q,Y){let X=new W0({check:"custom",...I(Y)});return X._zod.check=Q,X}function T1(Q){return!!Q._zod}function Y1(Q,Y){if(T1(Q))return a1(Q,Y);return Q.safeParse(Y)}function JQ(Q){if(!Q)return;let Y;if(T1(Q))Y=Q._zod?.def?.shape;else Y=Q.shape;if(!Y)return;if(typeof Y==="function")try{return Y()}catch{return}return Y}function kW(Q){if(T1(Q)){let z=Q._zod?.def;if(z){if(z.value!==void 0)return z.value;if(Array.isArray(z.values)&&z.values.length>0)return z.values[0]}}let X=Q._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let W=Q.value;if(W!==void 0)return W;return}var G4={};_9(G4,{time:()=>r6,duration:()=>n6,datetime:()=>p6,date:()=>i6,ZodISOTime:()=>gW,ZodISODuration:()=>yW,ZodISODateTime:()=>xW,ZodISODate:()=>_W});var xW=F("ZodISODateTime",(Q,Y)=>{B8.init(Q,Y),d.init(Q,Y)});function p6(Q){return VW(xW,Q)}var _W=F("ZodISODate",(Q,Y)=>{L8.init(Q,Y),d.init(Q,Y)});function i6(Q){return NW(_W,Q)}var gW=F("ZodISOTime",(Q,Y)=>{F8.init(Q,Y),d.init(Q,Y)});function r6(Q){return ZW(gW,Q)}var yW=F("ZodISODuration",(Q,Y)=>{q8.init(Q,Y),d.init(Q,Y)});function n6(Q){return wW(yW,Q)}var uW=(Q,Y)=>{n4.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>o9(Q,X)},flatten:{value:(X)=>d9(Q,X)},addIssue:{value:(X)=>{Q.issues.push(X),Q.message=JSON.stringify(Q.issues,P1,2)}},addIssues:{value:(X)=>{Q.issues.push(...X),Q.message=JSON.stringify(Q.issues,P1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},aV=F("ZodError",uW),N0=F("ZodError",uW,{Parent:Error});var hW=d4(N0),fW=o4(N0),lW=t1(N0),mW=s1(N0),cW=t9(N0),pW=a9(N0),iW=s9(N0),rW=e9(N0),nW=QX(N0),dW=YX(N0),oW=XX(N0),tW=WX(N0);var s=F("ZodType",(Q,Y)=>{return i.init(Q,Y),Q.def=Y,Q.type=Y.type,Object.defineProperty(Q,"_def",{value:Y}),Q.check=(...X)=>{return Q.clone(h.mergeDefs(Y,{checks:[...Y.checks??[],...X.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},Q.clone=(X,W)=>E0(Q,X,W),Q.brand=()=>Q,Q.register=(X,W)=>{return X.add(Q,W),Q},Q.parse=(X,W)=>hW(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>lW(Q,X,W),Q.parseAsync=async(X,W)=>fW(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>mW(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>cW(Q,X,W),Q.decode=(X,W)=>pW(Q,X,W),Q.encodeAsync=async(X,W)=>iW(Q,X,W),Q.decodeAsync=async(X,W)=>rW(Q,X,W),Q.safeEncode=(X,W)=>nW(Q,X,W),Q.safeDecode=(X,W)=>dW(Q,X,W),Q.safeEncodeAsync=async(X,W)=>oW(Q,X,W),Q.safeDecodeAsync=async(X,W)=>tW(Q,X,W),Q.refine=(X,W)=>Q.check(NA(X,W)),Q.superRefine=(X)=>Q.check(ZA(X)),Q.overwrite=(X)=>Q.check(F1(X)),Q.optional=()=>a(Q),Q.nullable=()=>eW(Q),Q.nullish=()=>a(eW(Q)),Q.nonoptional=(X)=>LA(Q,X),Q.array=()=>_(Q),Q.or=(X)=>p([Q,X]),Q.and=(X)=>HQ(Q,X),Q.transform=(X)=>o6(Q,GG(X)),Q.default=(X)=>KA(Q,X),Q.prefault=(X)=>BA(Q,X),Q.catch=(X)=>qA(Q,X),Q.pipe=(X)=>o6(Q,X),Q.readonly=()=>VA(Q),Q.describe=(X)=>{let W=Q.clone();return Q4.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return Q4.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return Q4.get(Q);let W=Q.clone();return Q4.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),QG=F("_ZodString",(Q,Y)=>{QQ.init(Q,Y),s.init(Q,Y);let X=Q._zod.bag;Q.format=X.format??null,Q.minLength=X.minimum??null,Q.maxLength=X.maximum??null,Q.regex=(...W)=>Q.check(x6(...W)),Q.includes=(...W)=>Q.check(y6(...W)),Q.startsWith=(...W)=>Q.check(u6(...W)),Q.endsWith=(...W)=>Q.check(h6(...W)),Q.min=(...W)=>Q.check(E1(...W)),Q.max=(...W)=>Q.check(GQ(...W)),Q.length=(...W)=>Q.check(zQ(...W)),Q.nonempty=(...W)=>Q.check(E1(1,...W)),Q.lowercase=(W)=>Q.check(_6(W)),Q.uppercase=(W)=>Q.check(g6(W)),Q.trim=()=>Q.check(l6()),Q.normalize=(...W)=>Q.check(f6(...W)),Q.toLowerCase=()=>Q.check(m6()),Q.toUpperCase=()=>Q.check(c6())}),kH=F("ZodString",(Q,Y)=>{QQ.init(Q,Y),QG.init(Q,Y),Q.email=(X)=>Q.check(s8(xH,X)),Q.url=(X)=>Q.check(WW(_H,X)),Q.jwt=(X)=>Q.check(MW(tH,X)),Q.emoji=(X)=>Q.check(GW(gH,X)),Q.guid=(X)=>Q.check(k6(aW,X)),Q.uuid=(X)=>Q.check(e8($Q,X)),Q.uuidv4=(X)=>Q.check(QW($Q,X)),Q.uuidv6=(X)=>Q.check(YW($Q,X)),Q.uuidv7=(X)=>Q.check(XW($Q,X)),Q.nanoid=(X)=>Q.check(zW(yH,X)),Q.guid=(X)=>Q.check(k6(aW,X)),Q.cuid=(X)=>Q.check(JW(uH,X)),Q.cuid2=(X)=>Q.check($W(hH,X)),Q.ulid=(X)=>Q.check(HW(fH,X)),Q.base64=(X)=>Q.check(FW(nH,X)),Q.base64url=(X)=>Q.check(qW(dH,X)),Q.xid=(X)=>Q.check(AW(lH,X)),Q.ksuid=(X)=>Q.check(UW(mH,X)),Q.ipv4=(X)=>Q.check(KW(cH,X)),Q.ipv6=(X)=>Q.check(DW(pH,X)),Q.cidrv4=(X)=>Q.check(BW(iH,X)),Q.cidrv6=(X)=>Q.check(LW(rH,X)),Q.e164=(X)=>Q.check(OW(oH,X)),Q.datetime=(X)=>Q.check(p6(X)),Q.date=(X)=>Q.check(i6(X)),Q.time=(X)=>Q.check(r6(X)),Q.duration=(X)=>Q.check(n6(X))});function B(Q){return a8(kH,Q)}var d=F("ZodStringFormat",(Q,Y)=>{r.init(Q,Y),QG.init(Q,Y)}),xH=F("ZodEmail",(Q,Y)=>{G8.init(Q,Y),d.init(Q,Y)});var aW=F("ZodGUID",(Q,Y)=>{X8.init(Q,Y),d.init(Q,Y)});var $Q=F("ZodUUID",(Q,Y)=>{W8.init(Q,Y),d.init(Q,Y)});var _H=F("ZodURL",(Q,Y)=>{z8.init(Q,Y),d.init(Q,Y)});var gH=F("ZodEmoji",(Q,Y)=>{J8.init(Q,Y),d.init(Q,Y)});var yH=F("ZodNanoID",(Q,Y)=>{$8.init(Q,Y),d.init(Q,Y)});var uH=F("ZodCUID",(Q,Y)=>{H8.init(Q,Y),d.init(Q,Y)});var hH=F("ZodCUID2",(Q,Y)=>{A8.init(Q,Y),d.init(Q,Y)});var fH=F("ZodULID",(Q,Y)=>{U8.init(Q,Y),d.init(Q,Y)});var lH=F("ZodXID",(Q,Y)=>{K8.init(Q,Y),d.init(Q,Y)});var mH=F("ZodKSUID",(Q,Y)=>{D8.init(Q,Y),d.init(Q,Y)});var cH=F("ZodIPv4",(Q,Y)=>{O8.init(Q,Y),d.init(Q,Y)});var pH=F("ZodIPv6",(Q,Y)=>{M8.init(Q,Y),d.init(Q,Y)});var iH=F("ZodCIDRv4",(Q,Y)=>{V8.init(Q,Y),d.init(Q,Y)});var rH=F("ZodCIDRv6",(Q,Y)=>{N8.init(Q,Y),d.init(Q,Y)});var nH=F("ZodBase64",(Q,Y)=>{w8.init(Q,Y),d.init(Q,Y)});var dH=F("ZodBase64URL",(Q,Y)=>{b8.init(Q,Y),d.init(Q,Y)});var oH=F("ZodE164",(Q,Y)=>{P8.init(Q,Y),d.init(Q,Y)});var tH=F("ZodJWT",(Q,Y)=>{j8.init(Q,Y),d.init(Q,Y)});var YG=F("ZodNumber",(Q,Y)=>{R6.init(Q,Y),s.init(Q,Y),Q.gt=(W,G)=>Q.check(XQ(W,G)),Q.gte=(W,G)=>Q.check(X4(W,G)),Q.min=(W,G)=>Q.check(X4(W,G)),Q.lt=(W,G)=>Q.check(YQ(W,G)),Q.lte=(W,G)=>Q.check(Y4(W,G)),Q.max=(W,G)=>Q.check(Y4(W,G)),Q.int=(W)=>Q.check(sW(W)),Q.safe=(W)=>Q.check(sW(W)),Q.positive=(W)=>Q.check(XQ(0,W)),Q.nonnegative=(W)=>Q.check(X4(0,W)),Q.negative=(W)=>Q.check(YQ(0,W)),Q.nonpositive=(W)=>Q.check(Y4(0,W)),Q.multipleOf=(W,G)=>Q.check(WQ(W,G)),Q.step=(W,G)=>Q.check(WQ(W,G)),Q.finite=()=>Q;let X=Q._zod.bag;Q.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Q.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Q.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Q.isFinite=!0,Q.format=X.format??null});function l(Q){return bW(YG,Q)}var aH=F("ZodNumberFormat",(Q,Y)=>{I8.init(Q,Y),YG.init(Q,Y)});function sW(Q){return PW(aH,Q)}var sH=F("ZodBoolean",(Q,Y)=>{E8.init(Q,Y),s.init(Q,Y)});function X0(Q){return jW(sH,Q)}var eH=F("ZodNull",(Q,Y)=>{T8.init(Q,Y),s.init(Q,Y)});function t6(Q){return IW(eH,Q)}var QA=F("ZodUnknown",(Q,Y)=>{S8.init(Q,Y),s.init(Q,Y)});function o(){return EW(QA)}var YA=F("ZodNever",(Q,Y)=>{R8.init(Q,Y),s.init(Q,Y)});function XA(Q){return TW(YA,Q)}var WA=F("ZodArray",(Q,Y)=>{C8.init(Q,Y),s.init(Q,Y),Q.element=Y.element,Q.min=(X,W)=>Q.check(E1(X,W)),Q.nonempty=(X)=>Q.check(E1(1,X)),Q.max=(X,W)=>Q.check(GQ(X,W)),Q.length=(X,W)=>Q.check(zQ(X,W)),Q.unwrap=()=>Q.element});function _(Q,Y){return SW(WA,Q,Y)}var XG=F("ZodObject",(Q,Y)=>{x8.init(Q,Y),s.init(Q,Y),h.defineLazy(Q,"shape",()=>{return Y.shape}),Q.keyof=()=>L0(Object.keys(Q._zod.def.shape)),Q.catchall=(X)=>Q.clone({...Q._zod.def,catchall:X}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:o()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:o()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:XA()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(X)=>{return h.extend(Q,X)},Q.safeExtend=(X)=>{return h.safeExtend(Q,X)},Q.merge=(X)=>h.merge(Q,X),Q.pick=(X)=>h.pick(Q,X),Q.omit=(X)=>h.omit(Q,X),Q.partial=(...X)=>h.partial(zG,Q,X[0]),Q.required=(...X)=>h.required(JG,Q,X[0])});function w(Q,Y){let X={type:"object",shape:Q??{},...h.normalizeParams(Y)};return new XG(X)}function U0(Q,Y){return new XG({type:"object",shape:Q,catchall:o(),...h.normalizeParams(Y)})}var WG=F("ZodUnion",(Q,Y)=>{C6.init(Q,Y),s.init(Q,Y),Q.options=Y.options});function p(Q,Y){return new WG({type:"union",options:Q,...h.normalizeParams(Y)})}var GA=F("ZodDiscriminatedUnion",(Q,Y)=>{WG.init(Q,Y),_8.init(Q,Y)});function a6(Q,Y,X){return new GA({type:"union",options:Y,discriminator:Q,...h.normalizeParams(X)})}var zA=F("ZodIntersection",(Q,Y)=>{g8.init(Q,Y),s.init(Q,Y)});function HQ(Q,Y){return new zA({type:"intersection",left:Q,right:Y})}var JA=F("ZodRecord",(Q,Y)=>{y8.init(Q,Y),s.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function t(Q,Y,X){return new JA({type:"record",keyType:Q,valueType:Y,...h.normalizeParams(X)})}var d6=F("ZodEnum",(Q,Y)=>{u8.init(Q,Y),s.init(Q,Y),Q.enum=Y.entries,Q.options=Object.values(Y.entries);let X=new Set(Object.keys(Y.entries));Q.extract=(W,G)=>{let z={};for(let J of W)if(X.has(J))z[J]=Y.entries[J];else throw Error(`Key ${J} not found in enum`);return new d6({...Y,checks:[],...h.normalizeParams(G),entries:z})},Q.exclude=(W,G)=>{let z={...Y.entries};for(let J of W)if(X.has(J))delete z[J];else throw Error(`Key ${J} not found in enum`);return new d6({...Y,checks:[],...h.normalizeParams(G),entries:z})}});function L0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new d6({type:"enum",entries:X,...h.normalizeParams(Y)})}var $A=F("ZodLiteral",(Q,Y)=>{h8.init(Q,Y),s.init(Q,Y),Q.values=new Set(Y.values),Object.defineProperty(Q,"value",{get(){if(Y.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return Y.values[0]}})});function b(Q,Y){return new $A({type:"literal",values:Array.isArray(Q)?Q:[Q],...h.normalizeParams(Y)})}var HA=F("ZodTransform",(Q,Y)=>{f8.init(Q,Y),s.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new i1(Q.constructor.name);X.addIssue=(z)=>{if(typeof z==="string")X.issues.push(h.issue(z,X.value,Y));else{let J=z;if(J.fatal)J.continue=!1;J.code??(J.code="custom"),J.input??(J.input=X.value),J.inst??(J.inst=Q),X.issues.push(h.issue(J))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then((z)=>{return X.value=z,X});return X.value=G,X}});function GG(Q){return new HA({type:"transform",transform:Q})}var zG=F("ZodOptional",(Q,Y)=>{l8.init(Q,Y),s.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function a(Q){return new zG({type:"optional",innerType:Q})}var AA=F("ZodNullable",(Q,Y)=>{m8.init(Q,Y),s.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function eW(Q){return new AA({type:"nullable",innerType:Q})}var UA=F("ZodDefault",(Q,Y)=>{c8.init(Q,Y),s.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function KA(Q,Y){return new UA({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():h.shallowClone(Y)}})}var DA=F("ZodPrefault",(Q,Y)=>{p8.init(Q,Y),s.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function BA(Q,Y){return new DA({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():h.shallowClone(Y)}})}var JG=F("ZodNonOptional",(Q,Y)=>{i8.init(Q,Y),s.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function LA(Q,Y){return new JG({type:"nonoptional",innerType:Q,...h.normalizeParams(Y)})}var FA=F("ZodCatch",(Q,Y)=>{r8.init(Q,Y),s.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function qA(Q,Y){return new FA({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var OA=F("ZodPipe",(Q,Y)=>{n8.init(Q,Y),s.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function o6(Q,Y){return new OA({type:"pipe",in:Q,out:Y})}var MA=F("ZodReadonly",(Q,Y)=>{d8.init(Q,Y),s.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function VA(Q){return new MA({type:"readonly",innerType:Q})}var $G=F("ZodCustom",(Q,Y)=>{o8.init(Q,Y),s.init(Q,Y)});function HG(Q,Y){return RW($G,Q??(()=>!0),Y)}function NA(Q,Y={}){return CW($G,Q,Y)}function ZA(Q){return vW(Q)}function s6(Q,Y){return o6(GG(Q),Y)}w0(v6());var e6="2025-11-25";var AG=[e6,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],X1="io.modelcontextprotocol/related-task",UQ="2.0",G0=HG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),UG=p([B(),l().int()]),KG=B(),rN=U0({ttl:p([l(),t6()]).optional(),pollInterval:l().optional()}),wA=w({ttl:l().optional()}),bA=w({taskId:B()}),QY=U0({progressToken:UG.optional(),[X1]:bA.optional()}),Z0=w({_meta:QY.optional()}),z4=Z0.extend({task:wA.optional()}),DG=(Q)=>z4.safeParse(Q).success,z0=w({method:B(),params:Z0.loose().optional()}),b0=w({_meta:QY.optional()}),P0=w({method:B(),params:b0.loose().optional()}),J0=U0({_meta:QY.optional()}),KQ=p([B(),l().int()]),BG=w({jsonrpc:b(UQ),id:KQ,...z0.shape}).strict(),YY=(Q)=>BG.safeParse(Q).success,LG=w({jsonrpc:b(UQ),...P0.shape}).strict(),FG=(Q)=>LG.safeParse(Q).success,XY=w({jsonrpc:b(UQ),id:KQ,result:J0}).strict(),J4=(Q)=>XY.safeParse(Q).success;var g;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(g||(g={}));var WY=w({jsonrpc:b(UQ),id:KQ.optional(),error:w({code:l().int(),message:B(),data:o().optional()})}).strict();var qG=(Q)=>WY.safeParse(Q).success;var nN=p([BG,LG,XY,WY]),dN=p([XY,WY]),DQ=J0.strict(),PA=b0.extend({requestId:KQ.optional(),reason:B().optional()}),BQ=P0.extend({method:b("notifications/cancelled"),params:PA}),jA=w({src:B(),mimeType:B().optional(),sizes:_(B()).optional(),theme:L0(["light","dark"]).optional()}),$4=w({icons:_(jA).optional()}),S1=w({name:B(),title:B().optional()}),OG=S1.extend({...S1.shape,...$4.shape,version:B(),websiteUrl:B().optional(),description:B().optional()}),IA=HQ(w({applyDefaults:X0().optional()}),t(B(),o())),EA=s6((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},HQ(w({form:IA.optional(),url:G0.optional()}),t(B(),o()).optional())),TA=U0({list:G0.optional(),cancel:G0.optional(),requests:U0({sampling:U0({createMessage:G0.optional()}).optional(),elicitation:U0({create:G0.optional()}).optional()}).optional()}),SA=U0({list:G0.optional(),cancel:G0.optional(),requests:U0({tools:U0({call:G0.optional()}).optional()}).optional()}),RA=w({experimental:t(B(),G0).optional(),sampling:w({context:G0.optional(),tools:G0.optional()}).optional(),elicitation:EA.optional(),roots:w({listChanged:X0().optional()}).optional(),tasks:TA.optional()}),CA=Z0.extend({protocolVersion:B(),capabilities:RA,clientInfo:OG}),GY=z0.extend({method:b("initialize"),params:CA});var vA=w({experimental:t(B(),G0).optional(),logging:G0.optional(),completions:G0.optional(),prompts:w({listChanged:X0().optional()}).optional(),resources:w({subscribe:X0().optional(),listChanged:X0().optional()}).optional(),tools:w({listChanged:X0().optional()}).optional(),tasks:SA.optional()}),kA=J0.extend({protocolVersion:B(),capabilities:vA,serverInfo:OG,instructions:B().optional()}),zY=P0.extend({method:b("notifications/initialized"),params:b0.optional()});var LQ=z0.extend({method:b("ping"),params:Z0.optional()}),xA=w({progress:l(),total:a(l()),message:a(B())}),_A=w({...b0.shape,...xA.shape,progressToken:UG}),FQ=P0.extend({method:b("notifications/progress"),params:_A}),gA=Z0.extend({cursor:KG.optional()}),H4=z0.extend({params:gA.optional()}),A4=J0.extend({nextCursor:KG.optional()}),yA=L0(["working","input_required","completed","failed","cancelled"]),U4=w({taskId:B(),status:yA,ttl:p([l(),t6()]),createdAt:B(),lastUpdatedAt:B(),pollInterval:a(l()),statusMessage:a(B())}),R1=J0.extend({task:U4}),uA=b0.merge(U4),K4=P0.extend({method:b("notifications/tasks/status"),params:uA}),qQ=z0.extend({method:b("tasks/get"),params:Z0.extend({taskId:B()})}),OQ=J0.merge(U4),MQ=z0.extend({method:b("tasks/result"),params:Z0.extend({taskId:B()})}),oN=J0.loose(),VQ=H4.extend({method:b("tasks/list")}),NQ=A4.extend({tasks:_(U4)}),ZQ=z0.extend({method:b("tasks/cancel"),params:Z0.extend({taskId:B()})}),MG=J0.merge(U4),VG=w({uri:B(),mimeType:a(B()),_meta:t(B(),o()).optional()}),NG=VG.extend({text:B()}),JY=B().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),ZG=VG.extend({blob:JY}),D4=L0(["user","assistant"]),C1=w({audience:_(D4).optional(),priority:l().min(0).max(1).optional(),lastModified:G4.datetime({offset:!0}).optional()}),wG=w({...S1.shape,...$4.shape,uri:B(),description:a(B()),mimeType:a(B()),annotations:C1.optional(),_meta:a(U0({}))}),hA=w({...S1.shape,...$4.shape,uriTemplate:B(),description:a(B()),mimeType:a(B()),annotations:C1.optional(),_meta:a(U0({}))}),$Y=H4.extend({method:b("resources/list")}),fA=A4.extend({resources:_(wG)}),lA=H4.extend({method:b("resources/templates/list")}),mA=A4.extend({resourceTemplates:_(hA)}),HY=Z0.extend({uri:B()}),cA=HY,AY=z0.extend({method:b("resources/read"),params:cA}),pA=J0.extend({contents:_(p([NG,ZG]))}),iA=P0.extend({method:b("notifications/resources/list_changed"),params:b0.optional()}),rA=HY,nA=z0.extend({method:b("resources/subscribe"),params:rA}),dA=HY,oA=z0.extend({method:b("resources/unsubscribe"),params:dA}),tA=b0.extend({uri:B()}),aA=P0.extend({method:b("notifications/resources/updated"),params:tA}),sA=w({name:B(),description:a(B()),required:a(X0())}),eA=w({...S1.shape,...$4.shape,description:a(B()),arguments:a(_(sA)),_meta:a(U0({}))}),QU=H4.extend({method:b("prompts/list")}),YU=A4.extend({prompts:_(eA)}),XU=Z0.extend({name:B(),arguments:t(B(),B()).optional()}),WU=z0.extend({method:b("prompts/get"),params:XU}),UY=w({type:b("text"),text:B(),annotations:C1.optional(),_meta:t(B(),o()).optional()}),KY=w({type:b("image"),data:JY,mimeType:B(),annotations:C1.optional(),_meta:t(B(),o()).optional()}),DY=w({type:b("audio"),data:JY,mimeType:B(),annotations:C1.optional(),_meta:t(B(),o()).optional()}),GU=w({type:b("tool_use"),name:B(),id:B(),input:t(B(),o()),_meta:t(B(),o()).optional()}),zU=w({type:b("resource"),resource:p([NG,ZG]),annotations:C1.optional(),_meta:t(B(),o()).optional()}),JU=wG.extend({type:b("resource_link")}),BY=p([UY,KY,DY,JU,zU]),$U=w({role:D4,content:BY}),HU=J0.extend({description:B().optional(),messages:_($U)}),AU=P0.extend({method:b("notifications/prompts/list_changed"),params:b0.optional()}),UU=w({title:B().optional(),readOnlyHint:X0().optional(),destructiveHint:X0().optional(),idempotentHint:X0().optional(),openWorldHint:X0().optional()}),KU=w({taskSupport:L0(["required","optional","forbidden"]).optional()}),bG=w({...S1.shape,...$4.shape,description:B().optional(),inputSchema:w({type:b("object"),properties:t(B(),G0).optional(),required:_(B()).optional()}).catchall(o()),outputSchema:w({type:b("object"),properties:t(B(),G0).optional(),required:_(B()).optional()}).catchall(o()).optional(),annotations:UU.optional(),execution:KU.optional(),_meta:t(B(),o()).optional()}),LY=H4.extend({method:b("tools/list")}),DU=A4.extend({tools:_(bG)}),wQ=J0.extend({content:_(BY).default([]),structuredContent:t(B(),o()).optional(),isError:X0().optional()}),tN=wQ.or(J0.extend({toolResult:o()})),BU=z4.extend({name:B(),arguments:t(B(),o()).optional()}),B4=z0.extend({method:b("tools/call"),params:BU}),LU=P0.extend({method:b("notifications/tools/list_changed"),params:b0.optional()}),aN=w({autoRefresh:X0().default(!0),debounceMs:l().int().nonnegative().default(300)}),L4=L0(["debug","info","notice","warning","error","critical","alert","emergency"]),FU=Z0.extend({level:L4}),FY=z0.extend({method:b("logging/setLevel"),params:FU}),qU=b0.extend({level:L4,logger:B().optional(),data:o()}),OU=P0.extend({method:b("notifications/message"),params:qU}),MU=w({name:B().optional()}),VU=w({hints:_(MU).optional(),costPriority:l().min(0).max(1).optional(),speedPriority:l().min(0).max(1).optional(),intelligencePriority:l().min(0).max(1).optional()}),NU=w({mode:L0(["auto","required","none"]).optional()}),ZU=w({type:b("tool_result"),toolUseId:B().describe("The unique identifier for the corresponding tool call."),content:_(BY).default([]),structuredContent:w({}).loose().optional(),isError:X0().optional(),_meta:t(B(),o()).optional()}),wU=a6("type",[UY,KY,DY]),AQ=a6("type",[UY,KY,DY,GU,ZU]),bU=w({role:D4,content:p([AQ,_(AQ)]),_meta:t(B(),o()).optional()}),PU=z4.extend({messages:_(bU),modelPreferences:VU.optional(),systemPrompt:B().optional(),includeContext:L0(["none","thisServer","allServers"]).optional(),temperature:l().optional(),maxTokens:l().int(),stopSequences:_(B()).optional(),metadata:G0.optional(),tools:_(bG).optional(),toolChoice:NU.optional()}),jU=z0.extend({method:b("sampling/createMessage"),params:PU}),qY=J0.extend({model:B(),stopReason:a(L0(["endTurn","stopSequence","maxTokens"]).or(B())),role:D4,content:wU}),OY=J0.extend({model:B(),stopReason:a(L0(["endTurn","stopSequence","maxTokens","toolUse"]).or(B())),role:D4,content:p([AQ,_(AQ)])}),IU=w({type:b("boolean"),title:B().optional(),description:B().optional(),default:X0().optional()}),EU=w({type:b("string"),title:B().optional(),description:B().optional(),minLength:l().optional(),maxLength:l().optional(),format:L0(["email","uri","date","date-time"]).optional(),default:B().optional()}),TU=w({type:L0(["number","integer"]),title:B().optional(),description:B().optional(),minimum:l().optional(),maximum:l().optional(),default:l().optional()}),SU=w({type:b("string"),title:B().optional(),description:B().optional(),enum:_(B()),default:B().optional()}),RU=w({type:b("string"),title:B().optional(),description:B().optional(),oneOf:_(w({const:B(),title:B()})),default:B().optional()}),CU=w({type:b("string"),title:B().optional(),description:B().optional(),enum:_(B()),enumNames:_(B()).optional(),default:B().optional()}),vU=p([SU,RU]),kU=w({type:b("array"),title:B().optional(),description:B().optional(),minItems:l().optional(),maxItems:l().optional(),items:w({type:b("string"),enum:_(B())}),default:_(B()).optional()}),xU=w({type:b("array"),title:B().optional(),description:B().optional(),minItems:l().optional(),maxItems:l().optional(),items:w({anyOf:_(w({const:B(),title:B()}))}),default:_(B()).optional()}),_U=p([kU,xU]),gU=p([CU,vU,_U]),yU=p([gU,IU,EU,TU]),uU=z4.extend({mode:b("form").optional(),message:B(),requestedSchema:w({type:b("object"),properties:t(B(),yU),required:_(B()).optional()})}),hU=z4.extend({mode:b("url"),message:B(),elicitationId:B(),url:B().url()}),fU=p([uU,hU]),lU=z0.extend({method:b("elicitation/create"),params:fU}),mU=b0.extend({elicitationId:B()}),cU=P0.extend({method:b("notifications/elicitation/complete"),params:mU}),bQ=J0.extend({action:L0(["accept","decline","cancel"]),content:s6((Q)=>Q===null?void 0:Q,t(B(),p([B(),l(),X0(),_(B())])).optional())}),pU=w({type:b("ref/resource"),uri:B()});var iU=w({type:b("ref/prompt"),name:B()}),rU=Z0.extend({ref:p([iU,pU]),argument:w({name:B(),value:B()}),context:w({arguments:t(B(),B()).optional()}).optional()}),nU=z0.extend({method:b("completion/complete"),params:rU});var dU=J0.extend({completion:U0({values:_(B()).max(100),total:a(l().int()),hasMore:a(X0())})}),oU=w({uri:B().startsWith("file://"),name:B().optional(),_meta:t(B(),o()).optional()}),tU=z0.extend({method:b("roots/list"),params:Z0.optional()}),MY=J0.extend({roots:_(oU)}),aU=P0.extend({method:b("notifications/roots/list_changed"),params:b0.optional()}),sN=p([LQ,GY,nU,FY,WU,QU,$Y,lA,AY,nA,oA,B4,LY,qQ,MQ,VQ,ZQ]),eN=p([BQ,FQ,zY,aU,K4]),QZ=p([DQ,qY,OY,bQ,MY,OQ,NQ,R1]),YZ=p([LQ,jU,lU,tU,qQ,MQ,VQ,ZQ]),XZ=p([BQ,FQ,OU,aA,iA,LU,AU,K4,cU]),WZ=p([DQ,kA,dU,HU,YU,fA,mA,pA,wQ,DU,OQ,NQ,R1]);class v extends Error{constructor(Q,Y,X){super(`MCP error ${Q}: ${Y}`);this.code=Q,this.data=X,this.name="McpError"}static fromError(Q,Y,X){if(Q===g.UrlElicitationRequired&&X){let W=X;if(W.elicitations)return new PG(W.elicitations,Y)}return new v(Q,Y,X)}}class PG extends v{constructor(Q,Y=`URL elicitation${Q.length>1?"s":""} required`){super(g.UrlElicitationRequired,Y,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function W1(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var sU=Symbol("Let zodToJsonSchema decide on which parser to use");var gZ=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function VY(Q){let X=JQ(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=kW(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function NY(Q,Y){let X=Y1(Q,Y);if(!X.success)throw X.error;return X.data}var G3=60000;class ZY{constructor(Q){if(this._options=Q,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(BQ,(Y)=>{this._oncancel(Y)}),this.setNotificationHandler(FQ,(Y)=>{this._onprogress(Y)}),this.setRequestHandler(LQ,(Y)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(qQ,async(Y,X)=>{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new v(g.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(MQ,async(Y,X)=>{let W=async()=>{let G=Y.params.taskId;if(this._taskMessageQueue){let J;while(J=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(J.type==="response"||J.type==="error"){let $=J.message,H=$.id,A=this._requestResolvers.get(H);if(A)if(this._requestResolvers.delete(H),J.type==="response")A($);else{let U=$,K=new v(U.error.code,U.error.message,U.error.data);A(K)}else{let U=J.type==="response"?"Response":"Error";this._onerror(Error(`${U} handler missing for request ${H}`))}continue}await this._transport?.send(J.message,{relatedRequestId:X.requestId})}}let z=await this._taskStore.getTask(G,X.sessionId);if(!z)throw new v(g.InvalidParams,`Task not found: ${G}`);if(!W1(z.status))return await this._waitForTaskUpdate(G,X.signal),await W();if(W1(z.status)){let J=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...J,_meta:{...J._meta,[X1]:{taskId:G}}}}return await W()};return await W()}),this.setRequestHandler(VQ,async(Y,X)=>{try{let{tasks:W,nextCursor:G}=await this._taskStore.listTasks(Y.params?.cursor,X.sessionId);return{tasks:W,nextCursor:G,_meta:{}}}catch(W){throw new v(g.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(ZQ,async(Y,X)=>{try{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new v(g.InvalidParams,`Task not found: ${Y.params.taskId}`);if(W1(W.status))throw new v(g.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(Y.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Y.params.taskId);let G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new v(g.InvalidParams,`Task not found after cancellation: ${Y.params.taskId}`);return{_meta:{},...G}}catch(W){if(W instanceof v)throw W;throw new v(g.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,Y,X,W,G=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,Y),startTime:Date.now(),timeout:Y,maxTotalTimeout:X,resetTimeoutOnProgress:G,onTimeout:W})}_resetTimeout(Q){let Y=this._timeoutInfo.get(Q);if(!Y)return!1;let X=Date.now()-Y.startTime;if(Y.maxTotalTimeout&&X>=Y.maxTotalTimeout)throw this._timeoutInfo.delete(Q),v.fromError(g.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Y.maxTotalTimeout,totalElapsed:X});return clearTimeout(Y.timeoutId),Y.timeoutId=setTimeout(Y.onTimeout,Y.timeout),!0}_cleanupTimeout(Q){let Y=this._timeoutInfo.get(Q);if(Y)clearTimeout(Y.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let Y=this.transport?.onclose;this._transport.onclose=()=>{Y?.(),this._onclose()};let X=this.transport?.onerror;this._transport.onerror=(G)=>{X?.(G),this._onerror(G)};let W=this._transport?.onmessage;this._transport.onmessage=(G,z)=>{if(W?.(G,z),J4(G)||qG(G))this._onresponse(G);else if(YY(G))this._onrequest(G,z);else if(FG(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let Y=v.fromError(g.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of Q.values())X(Y)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let Y=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(Y===void 0)return;Promise.resolve().then(()=>Y(Q)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(Q,Y){let X=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,G=Q.params?._meta?.[X1]?.taskId;if(X===void 0){let A={jsonrpc:"2.0",id:Q.id,error:{code:g.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId).catch((U)=>this._onerror(Error(`Failed to enqueue error response: ${U}`)));else W?.send(A).catch((U)=>this._onerror(Error(`Failed to send an error response: ${U}`)));return}let z=new AbortController;this._requestHandlerAbortControllers.set(Q.id,z);let J=DG(Q.params)?Q.params.task:void 0,$=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:z.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(A)=>{let U={relatedRequestId:Q.id};if(G)U.relatedTask={taskId:G};await this.notification(A,U)},sendRequest:async(A,U,K)=>{let D={...K,relatedRequestId:Q.id};if(G&&!D.relatedTask)D.relatedTask={taskId:G};let L=D.relatedTask?.taskId??G;if(L&&$)await $.updateTaskStatus(L,"input_required");return await this.request(A,U,D)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:$,taskRequestedTtl:J?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(J)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(A)=>{if(z.signal.aborted)return;let U={result:A,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:U,timestamp:Date.now()},W?.sessionId);else await W?.send(U)},async(A)=>{if(z.signal.aborted)return;let U={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(A.code)?A.code:g.InternalError,message:A.message??"Internal error",...A.data!==void 0&&{data:A.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId);else await W?.send(U)}).catch((A)=>this._onerror(Error(`Failed to send response: ${A}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:Y,...X}=Q.params,W=Number(Y),G=this._progressHandlers.get(W);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let z=this._responseHandlers.get(W),J=this._timeoutInfo.get(W);if(J&&z&&J.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch($){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),z($);return}G(X)}_onresponse(Q){let Y=Number(Q.id),X=this._requestResolvers.get(Y);if(X){if(this._requestResolvers.delete(Y),J4(Q))X(Q);else{let z=new v(Q.error.code,Q.error.message,Q.error.data);X(z)}return}let W=this._responseHandlers.get(Y);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(Y),this._cleanupTimeout(Y);let G=!1;if(J4(Q)&&Q.result&&typeof Q.result==="object"){let z=Q.result;if(z.task&&typeof z.task==="object"){let J=z.task;if(typeof J.taskId==="string")G=!0,this._taskProgressTokens.set(J.taskId,Y)}}if(!G)this._progressHandlers.delete(Y);if(J4(Q))W(Q);else{let z=v.fromError(Q.error.code,Q.error.message,Q.error.data);W(z)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,Y,X){let{task:W}=X??{};if(!W){try{yield{type:"result",result:await this.request(Q,Y,X)}}catch(z){yield{type:"error",error:z instanceof v?z:new v(g.InternalError,String(z))}}return}let G;try{let z=await this.request(Q,R1,X);if(z.task)G=z.task.taskId,yield{type:"taskCreated",task:z.task};else throw new v(g.InternalError,"Task creation did not return a task");while(!0){let J=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:J},W1(J.status)){if(J.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(J.status==="failed")yield{type:"error",error:new v(g.InternalError,`Task ${G} failed`)};else if(J.status==="cancelled")yield{type:"error",error:new v(g.InternalError,`Task ${G} was cancelled`)};return}if(J.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let $=J.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,$)),X?.signal?.throwIfAborted()}}catch(z){yield{type:"error",error:z instanceof v?z:new v(g.InternalError,String(z))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:z,task:J,relatedTask:$}=X??{};return new Promise((H,A)=>{let U=(M)=>{A(M)};if(!this._transport){U(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),J)this.assertTaskCapability(Q.method)}catch(M){U(M);return}X?.signal?.throwIfAborted();let K=this._requestMessageId++,D={...Q,jsonrpc:"2.0",id:K};if(X?.onprogress)this._progressHandlers.set(K,X.onprogress),D.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:K}};if(J)D.params={...D.params,task:J};if($)D.params={...D.params,_meta:{...D.params?._meta||{},[X1]:$}};let L=(M)=>{this._responseHandlers.delete(K),this._progressHandlers.delete(K),this._cleanupTimeout(K),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:K,reason:String(M)}},{relatedRequestId:W,resumptionToken:G,onresumptiontoken:z}).catch((E)=>this._onerror(Error(`Failed to send cancellation: ${E}`)));let S=M instanceof v?M:new v(g.RequestTimeout,String(M));A(S)};this._responseHandlers.set(K,(M)=>{if(X?.signal?.aborted)return;if(M instanceof Error)return A(M);try{let S=Y1(Y,M.result);if(!S.success)A(S.error);else H(S.data)}catch(S){A(S)}}),X?.signal?.addEventListener("abort",()=>{L(X?.signal?.reason)});let q=X?.timeout??G3,O=()=>L(v.fromError(g.RequestTimeout,"Request timed out",{timeout:q}));this._setupTimeout(K,q,X?.maxTotalTimeout,O,X?.resetTimeoutOnProgress??!1);let V=$?.taskId;if(V){let M=(S)=>{let E=this._responseHandlers.get(K);if(E)E(S);else this._onerror(Error(`Response handler missing for side-channeled request ${K}`))};this._requestResolvers.set(K,M),this._enqueueTaskMessage(V,{type:"request",message:D,timestamp:Date.now()}).catch((S)=>{this._cleanupTimeout(K),A(S)})}else this._transport.send(D,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:z}).catch((M)=>{this._cleanupTimeout(K),A(M)})})}async getTask(Q,Y){return this.request({method:"tasks/get",params:Q},OQ,Y)}async getTaskResult(Q,Y,X){return this.request({method:"tasks/result",params:Q},Y,X)}async listTasks(Q,Y){return this.request({method:"tasks/list",params:Q},NQ,Y)}async cancelTask(Q,Y){return this.request({method:"tasks/cancel",params:Q},MG,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let J={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[X1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:J,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!Y?.relatedRequestId&&!Y?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let J={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[X1]:Y.relatedTask}}};this._transport?.send(J,Y).catch(($)=>this._onerror($))});return}let z={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)z={...z,params:{...z.params,_meta:{...z.params?._meta||{},[X1]:Y.relatedTask}}};await this._transport.send(z,Y)}setRequestHandler(Q,Y){let X=VY(Q);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(W,G)=>{let z=NY(Q,W);return Promise.resolve(Y(z,G))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,Y){let X=VY(Q);this._notificationHandlers.set(X,(W)=>{let G=NY(Q,W);return Promise.resolve(Y(G))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let Y=this._taskProgressTokens.get(Q);if(Y!==void 0)this._progressHandlers.delete(Y),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,Y,X){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,Y,X,W)}async _clearTaskQueue(Q,Y){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll(Q,Y);for(let W of X)if(W.type==="request"&&YY(W.message)){let G=W.message.id,z=this._requestResolvers.get(G);if(z)z(new v(g.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,Y){let X=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)X=W.pollInterval}catch{}return new Promise((W,G)=>{if(Y.aborted){G(new v(g.InvalidRequest,"Request cancelled"));return}let z=setTimeout(W,X);Y.addEventListener("abort",()=>{clearTimeout(z),G(new v(g.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,Y){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await X.createTask(W,Q.id,{method:Q.method,params:Q.params},Y)},getTask:async(W)=>{let G=await X.getTask(W,Y);if(!G)throw new v(g.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(W,G,z)=>{await X.storeTaskResult(W,G,z,Y);let J=await X.getTask(W,Y);if(J){let $=K4.parse({method:"notifications/tasks/status",params:J});if(await this.notification($),W1(J.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,z)=>{let J=await X.getTask(W,Y);if(!J)throw new v(g.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(W1(J.status))throw new v(g.InvalidParams,`Cannot update task "${W}" from terminal status "${J.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,z,Y);let $=await X.getTask(W,Y);if($){let H=K4.parse({method:"notifications/tasks/status",params:$});if(await this.notification(H),W1($.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function jG(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function IG(Q,Y){let X={...Q};for(let W in Y){let G=W,z=Y[G];if(z===void 0)continue;let J=X[G];if(jG(J)&&jG(z))X[G]={...J,...z};else X[G]=z}return X}var W5=x9(F9(),1),G5=x9(X5(),1);function BM(){let Q=new W5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return G5.default(Q),Q}class j9{constructor(Q){this._ajv=Q??BM()}getValidator(Q){let Y="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(X)=>{if(Y(X))return{valid:!0,data:X,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(Y.errors)}}}}class I9{constructor(Q){this._server=Q}requestStream(Q,Y,X){return this._server.requestStream(Q,Y,X)}async getTask(Q,Y){return this._server.getTask({taskId:Q},Y)}async getTaskResult(Q,Y,X){return this._server.getTaskResult({taskId:Q},Y,X)}async listTasks(Q,Y){return this._server.listTasks(Q?{cursor:Q}:void 0,Y)}async cancelTask(Q,Y){return this._server.cancelTask({taskId:Q},Y)}}function z5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"tools/call":if(!Q.tools?.call)throw Error(`${X} does not support task creation for tools/call (required for ${Y})`);break;default:break}}function J5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${X} does not support task creation for sampling/createMessage (required for ${Y})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${X} does not support task creation for elicitation/create (required for ${Y})`);break;default:break}}class E9 extends ZY{constructor(Q,Y){super(Y);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(L4.options.map((X,W)=>[X,W])),this.isMessageIgnored=(X,W)=>{let G=this._loggingLevels.get(W);return G?this.LOG_LEVEL_SEVERITY.get(X)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=Y?.capabilities??{},this._instructions=Y?.instructions,this._jsonSchemaValidator=Y?.jsonSchemaValidator??new j9,this.setRequestHandler(GY,(X)=>this._oninitialize(X)),this.setNotificationHandler(zY,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(FY,async(X,W)=>{let G=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:z}=X.params,J=L4.safeParse(z);if(J.success)this._loggingLevels.set(G,J.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new I9(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=IG(this._capabilities,Q)}setRequestHandler(Q,Y){let W=JQ(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let G;if(T1(W)){let J=W;G=J._zod?.def?.value??J.value}else{let J=W;G=J._def?.value??J.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let J=async($,H)=>{let A=Y1(B4,$);if(!A.success){let L=A.error instanceof Error?A.error.message:String(A.error);throw new v(g.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:U}=A.data,K=await Promise.resolve(Y($,H));if(U.task){let L=Y1(R1,K);if(!L.success){let q=L.error instanceof Error?L.error.message:String(L.error);throw new v(g.InvalidParams,`Invalid task creation result: ${q}`)}return L.data}let D=Y1(wQ,K);if(!D.success){let L=D.error instanceof Error?D.error.message:String(D.error);throw new v(g.InvalidParams,`Invalid tools/call result: ${L}`)}return D.data};return super.setRequestHandler(Q,J)}return super.setRequestHandler(Q,Y)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){J5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;z5(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let Y=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:AG.includes(Y)?Y:e6,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"},DQ)}async createMessage(Q,Y){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let X=Q.messages[Q.messages.length-1],W=Array.isArray(X.content)?X.content:[X.content],G=W.some((H)=>H.type==="tool_result"),z=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,J=z?Array.isArray(z.content)?z.content:[z.content]:[],$=J.some((H)=>H.type==="tool_use");if(G){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!$)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if($){let H=new Set(J.filter((U)=>U.type==="tool_use").map((U)=>U.id)),A=new Set(W.filter((U)=>U.type==="tool_result").map((U)=>U.toolUseId));if(H.size!==A.size||![...H].every((U)=>A.has(U)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},OY,Y);return this.request({method:"sampling/createMessage",params:Q},qY,Y)}async elicitInput(Q,Y){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},bQ,Y)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},G=await this.request({method:"elicitation/create",params:W},bQ,Y);if(G.action==="accept"&&G.content&&W.requestedSchema)try{let J=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!J.valid)throw new v(g.InvalidParams,`Elicitation response content does not match requested schema: ${J.errorMessage}`)}catch(z){if(z instanceof v)throw z;throw new v(g.InternalError,`Error validating elicitation response: ${z instanceof Error?z.message:String(z)}`)}return G}}}createElicitationCompletionNotifier(Q,Y){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},Y)}async listRoots(Q,Y){return this.request({method:"roots/list",params:Q},MY,Y)}async sendLoggingMessage(Q,Y){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,Y))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var $5={name:"@sequenzy/mcp",version:"0.0.51",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^5.8.0"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var T9=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],H5={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}",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 FM(Q){let X=(Q??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return X.length>0?X:"https://sequenzy.com"}function h0(Q){let Y=Q?.trim();return Y?Y:void 0}function t0(Q){return encodeURIComponent(Q)}function Q0(Q,Y){return`${Q}${Y}`}function Y0(Q,Y=""){return`/dashboard/company/${t0(Q)}${Y}`}function A5(Q,Y,X){return Q0(Q,`${Y0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function qM(Q,Y){let X=T9.map((W)=>[W,Y?A5(Q,Y,W):""]);return Object.fromEntries(X)}function K1(Q={},Y){let X=FM(Y),W=h0(Q.companyId),G={},z=qM(X,W);if(!W)return{appUrl:X,routeTemplates:H5,settingsTabValues:T9,urls:G,settingsUrls:z};G.dashboard=Q0(X,Y0(W)),G.campaigns=Q0(X,Y0(W,"/campaign")),G.sequences=Q0(X,Y0(W,"/sequences")),G.settings=Q0(X,Y0(W,"/settings")),G.emails=Q0(X,Y0(W,"/emails")),G.subscribers=Q0(X,Y0(W,"/subscribers")),G.sentEmails=Q0(X,Y0(W,"/sent-emails")),G.segments=Q0(X,Y0(W,"/segments")),G.metrics=Q0(X,Y0(W,"/metrics")),G.transactional=Q0(X,Y0(W,"/transactional"));let J=h0(Q.campaignId);if(J)G.campaign=Q0(X,Y0(W,`/campaign/${t0(J)}`)),G.campaignPreview=`${G.campaign}?step=review`;let $=h0(Q.sequenceId);if($)G.sequence=Q0(X,Y0(W,`/sequences/${t0($)}`));let H=h0(Q.emailId)??h0(Q.templateId);if(H)G.email=Q0(X,Y0(W,`/emails/${t0(H)}`)),G.template=G.email;let A=h0(Q.transactionalId);if(A)G.transactionalEmail=Q0(X,Y0(W,`/transactional/${t0(A)}`));let U=h0(Q.emailSendId);if(U)G.emailSend=Q0(X,Y0(W,`/sent-emails/${t0(U)}`));let K=h0(Q.domainId);if(K)G.domain=Q0(X,Y0(W,`/settings/domain/${t0(K)}`)),G.domainVerify=`${G.domain}/verify`;let D=h0(Q.status);if(D)G.campaignList=Q0(X,Y0(W,`/campaign/list/${t0(D)}`)),G.sequenceList=Q0(X,Y0(W,`/sequences/list/${t0(D)}`));let L=h0(Q.settingsTab);if(L)G.settingsTab=A5(X,W,L);return{appUrl:X,routeTemplates:H5,settingsTabValues:T9,urls:G,settingsUrls:z}}var U5=[{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 K5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await N("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await N("GET","/api/v1/account"),W=B1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await N("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await N("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await N("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await N("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await N("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await N("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await N("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await N("GET","/api/v1/tags");break;case"sequenzy://health":Y=await N("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=K1();break;default:throw Error(`Unknown resource: ${Q}`)}return{contents:[{uri:Q,mimeType:"application/json",text:JSON.stringify(Y,null,2)}]}}catch(Y){return{contents:[{uri:Q,mimeType:"text/plain",text:b1(Y)}]}}}var h4="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`. Use this for editor-compatible content, including conditional and repeat blocks. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.",H6="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`.",O5="Sequenzy email blocks. Provide blocks or html for email steps. 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.",D5=500,R9={status:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"]},OM=Object.entries(R9).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),MM={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","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct"],description:"Filter field. Use `event` for custom subscriber events, `segment` for saved segment membership, and `stripeProduct`/`stripeCurrentProduct`/`stripeTrialProduct` for Stripe product-based segments. Engagement fields (`emailSent`, `emailDelivered`, `emailOpened`, `emailClicked`, `emailBounced`, `emailComplained`) accept a time range as the value or a specific campaign via `campaign:<campaign_id>`."},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${OM}.`},value:{type:"string",description:"Filter value. For custom attribute empty checks, use `attributeName:` such as `last_logged_in:`. Event examples: `saas.purchase:30d`, `saas.purchase:all`, or `saas.purchase:5:30d` for thresholds. Segment values are segment IDs. Stripe product examples: `prod_123` for bought/didn't buy/current/trialing, `prod_123:3` for payment thresholds, `prod_123:is_canceled` for products set to cancel, `prod_123:cancels_at:2026-05-26`, `prod_123:end_at:2026-05-26`, or `prod_123:start_at:7 days ago` for product-scoped dates. Engagement examples: `7d`, `30d`, `90d`, `180d`, `all` for rolling time windows, or `campaign:<campaign_id>` to scope to a specific sent campaign (use `list_campaigns` to find IDs)."}},required:["field","operator","value"],additionalProperties:!1},VM={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 M5(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(typeof Y!=="object"||Y===null)return Y;let X=Y;if(typeof X.id==="string"&&X.id.trim()!=="")return X;return{...X,id:crypto.randomUUID()}})}function V5(Q){if(typeof Q!=="object"||Q===null)return Q;let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=M5([Y]);return Array.isArray(X)?X[0]:Y}if(Y.kind!=="group")return Q;return{...Y,id:typeof Y.id==="string"&&Y.id.trim()!==""?Y.id:crypto.randomUUID(),children:Array.isArray(Y.children)?Y.children.map(V5):[]}}function NM(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function ZM(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function B5(Q){if(Q==="all")return!0;let Y=Q.match(/^(\d+)d$/);if(!Y?.[1])return!1;let X=Number.parseInt(Y[1],10);return Number.isInteger(X)&&X>0}function wM(Q,Y){let X=Y.split(":");if(Q==="at_least"||Q==="less_than_count"){if(X.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let z=X.slice(0,-2).join(":").trim(),J=X.at(-2),$=X.at(-1),H=J===void 0?Number.NaN:Number.parseInt(J,10);return z&&Number.isInteger(H)&&H>0&&$!==void 0&&B5($)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(X.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=X.slice(0,-1).join(":").trim(),G=X.at(-1);return W&&G!==void 0&&B5(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function bM(Q){let Y=Q.indexOf(":");if(Y===-1)return{productId:Q,subfilter:null,rawValue:null};let X=Q.substring(0,Y),W=Q.substring(Y+1),G=W.indexOf(":");if(G===-1)return{productId:X,subfilter:W,rawValue:null};return{productId:X,subfilter:W.substring(0,G),rawValue:W.substring(G+1)}}function PM(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function jM(Q){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(Q)}function IM(Q,Y){if(Y==="cancels_at"||Y==="cancel_at"||Y==="cancellation_at")return!0;if(Q==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(Y);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(Y)}function EM(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function TM(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let $=X.indexOf(":");if($===-1)return null;let H=X.substring(0,$).trim(),A=Number.parseInt(X.substring($+1).trim(),10);return H&&Number.isInteger(A)&&A>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(Q!=="stripeCurrentProduct"&&Q!=="stripeTrialProduct")return null;let{productId:W,subfilter:G,rawValue:z}=bM(X);if(!W.trim())return"Stripe product filters must include a product ID.";if(!G)return Y==="is"||Y==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let J=PM(G);if(jM(J))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!IM(Q,J))return`Unsupported Stripe product subfilter "${G}".`;if(!EM(Y))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return z?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}function N5(Q){if(typeof Q!=="object"||Q===null)return"Segment filters must be objects.";let Y=Q,X=Y.field,W=Y.operator,G=Y.value;if(typeof X!=="string"||!(X in R9))return`Unsupported segment filter field "${String(X)}".`;if(typeof W!=="string")return`Segment filter "${X}" must include an operator.`;let z=R9[X];if(!z.includes(W))return`Operator "${W}" is not supported for ${X} filters. Use one of: ${z.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${X}" must include a value.`;if(X==="attribute"&&typeof G==="string"){if(!NM(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!ZM(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let J=wM(W,G);if(J)return J}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let J=TM(X,W,G);if(J)return J}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map(($)=>$.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function Z5(Q){if(typeof Q!=="object"||Q===null)return[];let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=N5(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap(Z5);return[]}function w1(Q,Y,X){if(Y.html!==void 0&&Y.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`, not both.`);if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error(`\`blocks\` must be an array when calling \`${Q}\`.`);if(X?.requireContent&&Y.html===void 0&&Y.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`.`)}function U6(Q,Y){if(Y.labels===void 0)return;if(!Array.isArray(Y.labels))throw Error(`\`labels\` must be an array when calling \`${Q}\`.`);if(Y.labels.some((X)=>typeof X!=="string"||X.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${Q}\`.`)}function SM(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!Y&&!X)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=Y?Q.filters.flatMap((G)=>{let z=N5(G);return z?[z]:[]}):Z5(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function RM(Q){if(Q.clearEnrollmentFieldPath===!0&&Q.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");let Y={...Q};if(delete Y.clearEnrollmentFieldPath,Q.clearEnrollmentFieldPath===!0)Y.enrollmentFieldPath=null;return Y}function CM(Q){let Y=j(Q,"subscriberId"),X=Q.fieldValues,W=X===void 0?void 0:Array.isArray(X)?X:void 0;if(X!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let G=W?.map(($)=>typeof $==="string"?$.trim():"").filter(($)=>$.length>0)??[];if(W?.some(($)=>typeof $!=="string")||W!==void 0&&G.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(Y!==void 0===G.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let z=j(Q,"fieldPath"),J=j(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...z!==void 0&&{fieldPath:z},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...J!==void 0&&{reason:J}}}function vM(Q){w1("create_campaign",Q),U6("create_campaign",Q);let Y=j(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0,G=Q.templateId!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(Y&&(X||W||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!Y&&j(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function kM(Q){if(j(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!B0(Q.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(Q.sendTimeOptimization!==void 0){if(typeof Q.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(Q.spreadOverHours!==void 0){if(typeof Q.spreadOverHours!=="number"||!Number.isInteger(Q.spreadOverHours)||Q.spreadOverHours<1||Q.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}}function xM(Q){w1("create_transactional_email",Q);let Y=j(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(Y&&(X||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!Y&&!X&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!Y&&j(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var L5={type:"object",description:"A step to create inside a branch path. Use type:'delay' for a standalone delay, type:'email' for an email, or type:'create_discount' for a discount action.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","webhook"],description:"Branch path step type. Omit for email steps; use delay for standalone waits."},nodeType:{type:"string",enum:["logic_delay","action_email","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","action_webhook"],description:"Advanced branch path node type. Prefer type unless creating a non-email action."},config:{type:"object",description:"Config for advanced nodeType steps such as tag/list/webhook/wait-for-event actions.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:O5,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps."},delay:{type:"object",description:"Delay before this step, or the delay duration when type is delay.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}}},delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"]},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 _M(Q){if(!Q||typeof Q!=="object")return null;let Y=Q;if(Y.success!==!1)return null;if(typeof Y.error==="string")return Error(Y.error);if(Y.error&&typeof Y.error==="object"&&typeof Y.error.message==="string")return Error(Y.error.message);if(typeof Y.message==="string")return Error(Y.message);return Error("The tool returned an unsuccessful response.")}function B0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function F5(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function gM(Q){let Y=new URLSearchParams;if(typeof Q.query==="string"&&Q.query.trim()!=="")Y.set("query",Q.query.trim());if(Array.isArray(Q.tags)&&Q.tags.length>0)Y.set("tags",Q.tags.filter((X)=>typeof X==="string"&&X.trim()!=="").join(","));if(typeof Q.list==="string"&&Q.list.trim()!=="")Y.set("list",Q.list.trim());if(typeof Q.listId==="string"&&Q.listId.trim()!=="")Y.set("listId",Q.listId.trim());if(typeof Q.listName==="string"&&Q.listName.trim()!=="")Y.set("listName",Q.listName.trim());if(typeof Q.segmentId==="string"&&Q.segmentId.trim()!=="")Y.set("segmentId",Q.segmentId);if(typeof Q.status==="string"&&Q.status.trim()!=="")Y.set("status",Q.status.trim());return Y.set("page",String(Q.page)),Y.set("limit",String(Q.pageSize)),Y}async function yM(Q,Y){let X=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,W=Math.min(100,Math.max(1,X??100)),G=[],z=1,J=0,$=0,H=0;while(!0){let U=gM({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:z,pageSize:W}),K=await N("GET",`/api/v1/subscribers?${U.toString()}`,void 0,Y);J=K.pagination?.total??K.subscribers.length,$=K.pagination?.totalPages??1,H+=1,G.push(...K.subscribers??[]);let D=X!==void 0&&G.length>=X,L=K.pagination?z>=K.pagination.totalPages:(K.subscribers??[]).length<W;if(D||L)break;z+=1}let A=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:A,pagination:{page:1,limit:W,total:J,totalPages:$,fetchedPages:H},returned:A.length,truncated:X!==void 0&&J>0&&A.length<J}}function uM(Q){let Y=typeof Q.email==="string"&&Q.email.trim()!==""?Q.email.trim():void 0,X=typeof Q.externalId==="string"&&Q.externalId.trim()!==""?Q.externalId.trim():void 0;return{...Y?{email:Y}:{},...X?{externalId:X}:{}}}function f4(Q,Y){let X=uM(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function C9(Q){if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}`;return`/api/v1/subscribers/external?externalId=${encodeURIComponent(String(Q.externalId))}`}async function S9(Q,Y){return N("GET",C9(Q),void 0,Y)}function j(Q,Y){let X=Q[Y];if(typeof X!=="string")return;let W=X.trim();return W.length>0?W:void 0}function hM(Q,Y,X){let W=j(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function q5(Q,Y,X,W){let G=j(Y,X);if(G===void 0)return;if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function fM(Q,Y){if(!Array.isArray(Y.emails))throw Error(`\`emails\` must be an array when calling \`${Q}\`.`);let X=[];if(Y.emails.forEach((W,G)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${Q}\`.`);let z=W.trim();if(z.length>0)X.push(z)}),X.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${Q}\`.`);if(X.length>D5)throw Error(`\`emails\` must include no more than ${D5} email addresses when calling \`${Q}\`. Split larger batches into multiple calls.`);return X}async function w5(Q){let Y=j(Q,"companyId");if(Y)return Y;let X=B1();if(X)return X;try{return(await N("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}function l4(Q,Y){if(!B0(Q)||!Y)return Q;return{...Q,url:Y}}function b5(Q,Y){if(!B0(Q))return Q;return{...Q,...Y.campaign!==void 0&&{url:Y.campaign},...Y.campaignPreview!==void 0&&{previewUrl:Y.campaignPreview}}}function A6(Q,Y,X){if(!Array.isArray(Q)||!Y)return Q;return Q.map((W)=>{if(!B0(W))return W;let G=j(W,"id");if(!G)return W;let z=K1({companyId:Y,...X==="campaign"&&{campaignId:G},...X==="sequence"&&{sequenceId:G},...X==="template"&&{emailId:G},...X==="transactional"&&{transactionalId:G}});if(X==="campaign")return b5(W,z.urls);let J=X==="sequence"?z.urls.sequence:X==="template"?z.urls.email:z.urls.transactionalEmail;return l4(W,J)})}function lM(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!B0(Y))return Y;let X=j(Y,"id");if(!X)return Y;let W=K1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var mM=new Set(["get_account","select_company","create_company","get_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","list_sequences","get_sequence","create_sequence","update_sequence","enable_sequence","disable_sequence","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function cM(Q,Y,X){if(!B0(X)||!mM.has(Q))return X;let W=B0(X.company)?X.company:void 0,z=j(X,"selectedCompanyId")??j(X,"currentCompanyId")??j(X,"companyId")??(W?j(W,"id"):void 0)??(W?j(W,"companyId"):void 0)??await w5(Y);if(!z)return X;let J=B0(X.campaign)?X.campaign:void 0,$=B0(X.sequence)?X.sequence:void 0,H=B0(X.template)?X.template:void 0,A=B0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,U={companyId:z,campaignId:j(Y,"campaignId")??j(X,"campaignId")??(J?j(J,"id"):void 0),sequenceId:j(Y,"sequenceId")??j(X,"sequenceId")??($?j($,"id"):void 0),emailId:j(X,"templateId")??(H?j(H,"id"):void 0)??(A?j(A,"emailId"):void 0)??j(Y,"templateId"),transactionalId:j(Y,"transactionalId")??(A?j(A,"id"):void 0)??j(Y,"idOrSlug"),emailSendId:j(Y,"emailSendId")??j(X,"emailSendId")??(B0(X.emailSend)?j(X.emailSend,"id"):void 0),status:j(Y,"status")},K=K1(U),D=W?K1({companyId:z}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:lM(X.companies)},...Array.isArray(X.campaigns)&&{campaigns:A6(X.campaigns,z,"campaign")},...Array.isArray(X.sequences)&&{sequences:A6(X.sequences,z,"sequence")},...Array.isArray(X.templates)&&{templates:A6(X.templates,z,"template")},...Array.isArray(X.transactional)&&{transactional:A6(X.transactional,z,"transactional")},...W&&D!==void 0&&{company:{...W,url:D.urls.dashboard,settingsUrl:D.urls.settings}},...J&&K.urls.campaign!==void 0&&{campaign:b5(J,K.urls)},...$&&K.urls.sequence!==void 0&&{sequence:l4($,K.urls.sequence)},...H&&K.urls.email!==void 0&&{template:l4(H,K.urls.email)},...A&&K.urls.transactionalEmail!==void 0&&{transactional:l4(A,K.urls.transactionalEmail)},...B0(X.emailSend)&&K.urls.emailSend!==void 0&&{emailSend:l4(X.emailSend,K.urls.emailSend)},appUrls:K.urls}}var P5=[{name:"get_account",description:`Get current account information including available companies. IMPORTANT: If you have access to multiple companies, you MUST either:
|
|
29
29
|
1. Call select_company first to choose which company to work with, OR
|
|
30
30
|
2. Pass companyId explicitly in each tool call
|
|
31
31
|
|
|
@@ -35,14 +35,19 @@ CRITICAL - FOR SAAS/SUBSCRIPTION APPS:
|
|
|
35
35
|
If the app uses Stripe, Polar, Paddle, Dodo, or Creem - tell the user to connect it in Sequenzy dashboard (Settings → Integrations).
|
|
36
36
|
The native integration automatically handles all payment events and customer tags - no code needed!
|
|
37
37
|
|
|
38
|
+
CRITICAL - FOR E-COMMERCE STORES:
|
|
39
|
+
If the store runs on Shopify or WooCommerce - tell the user to connect the native integration in the dashboard instead (it syncs products, orders, and customers automatically).
|
|
40
|
+
For any other e-commerce stack (custom checkouts, CheckoutChamp, Sticky.io, headless storefronts), use the 'ecommerce' use case to integrate via the Commerce API.
|
|
41
|
+
|
|
38
42
|
Only provide manual event tracking code if the user explicitly asks for it.
|
|
39
43
|
|
|
40
44
|
Use cases:
|
|
41
45
|
- 'transactional': Sending one-off emails (welcome, password reset, receipts)
|
|
42
46
|
- 'subscribe_form': Adding subscribers from signup forms
|
|
43
47
|
- 'event_tracking': Tracking CUSTOM events only (not payment events - those come from the integration)
|
|
48
|
+
- 'ecommerce': Connecting a custom e-commerce platform via the Commerce API (sync products, push orders/checkouts, power abandoned cart + back-in-stock automations)
|
|
44
49
|
|
|
45
|
-
Before implementing, use create_api_key to generate an API key and save it to .env as SEQUENZY_API_KEY.`,inputSchema:{type:"object",properties:{framework:{type:"string",description:"Framework/language (nextjs, express, python, etc.)"},use_case:{type:"string",description:"Use case: 'transactional' (sending emails), 'subscribe_form' (adding subscribers), 'event_tracking' (tracking CUSTOM events only - payment events should come from Stripe/Polar/etc integration)"}}}},{name:"add_subscriber",description:"Add a new subscriber to your list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to add subscriber to. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},attributes:{type:"object",description:"Custom attributes (name, plan, etc.)"},tags:{type:"array",items:{type:"string"},description:"Tags to apply to the subscriber"},listIds:{type:"array",items:{type:"string"},description:"List IDs to add subscriber to"},status:{type:"string",description:"Initial subscriber status: active, unsubscribed, or bounced. Defaults to active."},optInMode:{type:"string",description:"Consent mode: confirmed creates active immediately when consent is verified, double_opt_in sends a confirmation email before activation, and default obeys company double opt-in settings."}},required:[]}},{name:"update_subscriber",description:"Update an existing subscriber's attributes or tags",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},attributes:{type:"object",description:"Attributes to update"},addTags:{type:"array",items:{type:"string"},description:"Tags to add"},removeTags:{type:"array",items:{type:"string"},description:"Tags to remove"}},required:[]}},{name:"remove_subscriber",description:"Unsubscribe or delete a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},hardDelete:{type:"boolean",description:"If true, permanently deletes. If false, just unsubscribes."}},required:[]}},{name:"get_subscriber",description:"Get the full subscriber profile, including tags, list memberships, sequence enrollments, email stats, and recent activity",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."}},required:[]}},{name:"search_subscribers",description:"Search subscribers by free-text query, tags, list, or segment. If you omit limit, the tool fetches all pages and returns every match.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},query:{type:"string",description:"Search query (email or name)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"},list:{type:"string",description:"Filter by subscriber list ID or exact list name. Prefer listId when known."},listId:{type:"string",description:"Filter by subscriber list ID."},listName:{type:"string",description:"Filter by exact subscriber list name when the list ID is not known."},segmentId:{type:"string",description:"Filter by segment ID"},status:{type:"string",description:"Filter by subscriber status: active, unsubscribed, or bounced."},limit:{type:"number",description:"Maximum results to return. If omitted, the tool returns all matches across pages."}}}},{name:"list_tags",description:"List all tags in the account",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list tags for. If not provided, uses the currently selected company."}}}},{name:"list_lists",description:"List all subscriber lists",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list lists for. If not provided, uses the currently selected company."}}}},{name:"create_list",description:"Create a new subscriber list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the list in. If not provided, uses the currently selected company."},name:{type:"string",description:"List name"},description:{type:"string",description:"List description"}},required:["name"]}},{name:"add_subscribers_to_list",description:"Bulk add existing or new subscribers to a subscriber list from an email array. Existing subscribers are added to the list without requiring a per-subscriber update call.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to add subscribers to."},emails:{type:"array",items:{type:"string"},description:"Email addresses to add to the list. Maximum 500 per call."},duplicateStrategy:{type:"string",description:"Duplicate strategy for existing subscribers: skip, merge, or overwrite. Defaults to skip."},enrollInSequences:{type:"boolean",description:"Whether newly created subscribers should enroll in matching sequences. Defaults to false."},optInMode:{type:"string",description:"Consent mode for newly created subscribers: default, confirmed, or double_opt_in. Defaults to default."}},required:["listId","emails"]}},{name:"list_segments",description:"List all segments",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list segments for. If not provided, uses the currently selected company."}}}},{name:"create_segment",description:'Create a new segment from explicit filter rules. Use `filters` plus `filterJoinOperator` for flat legacy rules, or `root` for nested AND/OR groups such as `{ "kind": "group", "joinOperator": "and", "children": [{ "kind": "filter", "field": "attribute", "operator": "gte", "value": "mrr:50" }, { "kind": "group", "joinOperator": "or", "children": [{ "kind": "filter", "field": "tag", "operator": "contains", "value": "vip" }, { "kind": "filter", "field": "event", "operator": "is_not", "value": "saas.purchase:30d" }] }] }`. Supports `event` and `segment` fields, Stripe product purchase/current/trial/date filters, and campaign-specific engagement filters.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the segment in. If not provided, uses the currently selected company."},name:{type:"string",description:"Segment name"},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:MM,minItems:1,description:'Array of segment filters. Example custom attribute empty check: [{"id":"filter-1","field":"attribute","operator":"is_empty","value":"last_logged_in:"}]. Example Stripe purchase filter: [{"id":"filter-1","field":"stripeProduct","operator":"is","value":"prod_123"}]. Example threshold filter: [{"id":"filter-1","field":"stripeProduct","operator":"at_least","value":"prod_123:3"}]. Example trial cancellation filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:is_canceled"}]. Example trial end filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:end_at:2026-05-26"}]. Example campaign-specific engagement combo: [{"id":"filter-1","field":"emailBounced","operator":"is","value":"campaign:cmp_abc"},{"id":"filter-2","field":"emailBounced","operator":"is_not","value":"campaign:cmp_xyz"}]. Combine them with `filterJoinOperator: "or"` to match any filter.'},root:{...VM,description:"Nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["name"]}},{name:"get_segment_count",description:"Get the number of subscribers in a segment",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID"}},required:["segmentId"]}},{name:"list_templates",description:"List all email templates, including per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_template",description:"Get a template's details, content, and all localized variants with sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"create_template",description:"Create a new email template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line"},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:h4,items:{type:"object"}},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name","subject"]}},{name:"update_template",description:"Update an existing template. At least one of `name`, `subject`, `html`, `blocks`, or `labels` is required, and only those update fields are accepted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line"},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:h4,items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"delete_template",description:"Delete a template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{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."}},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:`${H6} Mutually exclusive with html.`,items:{type:"object"}}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"list_campaigns",description:"List all campaigns",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list campaigns for. If not provided, uses the currently selected company."},status:{type:"string",description:"Filter by status (draft, scheduled, sent)"},label:{type:"string",description:"Optional label name filter. Only campaigns assigned this label are returned."}}}},{name:"get_campaign",description:"Get campaign details and stats",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_email_send",description:"Get a sent email by emailSendId, including the stored HTML body when available and the ClickHouse event timeline. If the short-lived email send row has been cleaned up, returns the retained ClickHouse events and a sparse summary.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailSendId:{type:"string",description:"Email send ID to inspect."}},required:["emailSendId"]}},{name:"create_campaign",description:"Create a new campaign (as draft)",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:h4,items:{type:"object"}},prompt:{type:"string",description:"Generate campaign blocks from a prompt. Mutually exclusive with `html`, `blocks`, and `templateId`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},templateId:{type:"string",description:"Use a template instead of html"},segmentId:{type:"string",description:"Target segment ID"},campaignData:{type:"object",description:"Optional campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Optional computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_campaign",description:"Update a draft campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line"},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested. Send an empty string to clear it."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:h4,items:{type:"object"}},replyTo:{type:"string",description:"Set reply-to using an existing reply profile email address for this company."},replyProfileId:{type:"string",description:"Set reply-to using a reply profile ID for this company."},campaignData:{type:"object",description:"Set campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Set computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["campaignId"],additionalProperties:!1}},{name:"schedule_campaign",description:"Schedule a draft or already scheduled campaign. Returns dashboard edit and preview URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},scheduledAt:{type:"string",description:"Future ISO 8601 timestamp for the send, for example 2026-06-01T14:00:00Z."},targetLists:{type:"object",description:"Optional campaign targeting object. Omit to use saved targeting or all active subscribers. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, or {type:'filtered', filters:[...], filterJoinOperator:'and'}.",additionalProperties:!0},sendTimeOptimization:{type:"boolean",description:"Whether to use send-time optimization."},spreadOverHours:{type:"number",description:"Spread delivery over an integer number of hours from 1 to 72. When set, spread delivery takes precedence over send-time optimization."}},required:["campaignId","scheduledAt"],additionalProperties:!1}},{name:"send_test_email",description:"Send a test email to a single address",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"list_sequences",description:"List all email sequences (automations)",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list sequences for. If not provided, uses the currently selected company."}}}},{name:"get_sequence",description:"Get sequence details plus editable step content. The response includes sequence.emails with each step's nodeId, linked emailId, subject, previewText, and blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"],additionalProperties:!1}},{name:"create_sequence",description:`Create a new email sequence. Provide either a goal for AI generation or explicit steps. Explicit steps can include email content and create_discount actions; emails after a discount action can use merge tags such as {{discount.code}} and {{discount.percentOff}}. For AI-generated sequences, the tool polls until emails are generated (typically 30-60 seconds).
|
|
50
|
+
Before implementing, use create_api_key to generate an API key and save it to .env as SEQUENZY_API_KEY.`,inputSchema:{type:"object",properties:{framework:{type:"string",description:"Framework/language (nextjs, express, python, etc.)"},use_case:{type:"string",description:"Use case: 'transactional' (sending emails), 'subscribe_form' (adding subscribers), 'event_tracking' (tracking CUSTOM events only - payment events should come from Stripe/Polar/etc integration), 'ecommerce' (connecting a custom e-commerce platform via the Commerce API)"}}}},{name:"add_subscriber",description:"Add a new subscriber to your list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to add subscriber to. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},attributes:{type:"object",description:"Custom attributes (name, plan, etc.)"},tags:{type:"array",items:{type:"string"},description:"Tags to apply to the subscriber"},listIds:{type:"array",items:{type:"string"},description:"List IDs to add subscriber to"},status:{type:"string",description:"Initial subscriber status: active, unsubscribed, or bounced. Defaults to active."},optInMode:{type:"string",description:"Consent mode: confirmed creates active immediately when consent is verified, double_opt_in sends a confirmation email before activation, and default obeys company double opt-in settings."}},required:[]}},{name:"update_subscriber",description:"Update an existing subscriber's attributes or tags",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},attributes:{type:"object",description:"Attributes to update"},addTags:{type:"array",items:{type:"string"},description:"Tags to add"},removeTags:{type:"array",items:{type:"string"},description:"Tags to remove"}},required:[]}},{name:"remove_subscriber",description:"Unsubscribe or delete a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},hardDelete:{type:"boolean",description:"If true, permanently deletes. If false, just unsubscribes."}},required:[]}},{name:"get_subscriber",description:"Get the full subscriber profile, including tags, list memberships, sequence enrollments, email stats, and recent activity",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."}},required:[]}},{name:"search_subscribers",description:"Search subscribers by free-text query, tags, list, or segment. If you omit limit, the tool fetches all pages and returns every match.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},query:{type:"string",description:"Search query (email or name)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"},list:{type:"string",description:"Filter by subscriber list ID or exact list name. Prefer listId when known."},listId:{type:"string",description:"Filter by subscriber list ID."},listName:{type:"string",description:"Filter by exact subscriber list name when the list ID is not known."},segmentId:{type:"string",description:"Filter by segment ID"},status:{type:"string",description:"Filter by subscriber status: active, unsubscribed, or bounced."},limit:{type:"number",description:"Maximum results to return. If omitted, the tool returns all matches across pages."}}}},{name:"list_tags",description:"List all tags in the account",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list tags for. If not provided, uses the currently selected company."}}}},{name:"list_lists",description:"List all subscriber lists",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list lists for. If not provided, uses the currently selected company."}}}},{name:"create_list",description:"Create a new subscriber list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the list in. If not provided, uses the currently selected company."},name:{type:"string",description:"List name"},description:{type:"string",description:"List description"}},required:["name"]}},{name:"add_subscribers_to_list",description:"Bulk add existing or new subscribers to a subscriber list from an email array. Existing subscribers are added to the list without requiring a per-subscriber update call.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to add subscribers to."},emails:{type:"array",items:{type:"string"},description:"Email addresses to add to the list. Maximum 500 per call."},duplicateStrategy:{type:"string",description:"Duplicate strategy for existing subscribers: skip, merge, or overwrite. Defaults to skip."},enrollInSequences:{type:"boolean",description:"Whether newly created subscribers should enroll in matching sequences. Defaults to false."},optInMode:{type:"string",description:"Consent mode for newly created subscribers: default, confirmed, or double_opt_in. Defaults to default."}},required:["listId","emails"]}},{name:"list_segments",description:"List all segments",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list segments for. If not provided, uses the currently selected company."}}}},{name:"create_segment",description:'Create a new segment from explicit filter rules. Use `filters` plus `filterJoinOperator` for flat legacy rules, or `root` for nested AND/OR groups such as `{ "kind": "group", "joinOperator": "and", "children": [{ "kind": "filter", "field": "attribute", "operator": "gte", "value": "mrr:50" }, { "kind": "group", "joinOperator": "or", "children": [{ "kind": "filter", "field": "tag", "operator": "contains", "value": "vip" }, { "kind": "filter", "field": "event", "operator": "is_not", "value": "saas.purchase:30d" }] }] }`. Supports `event` and `segment` fields, Stripe product purchase/current/trial/date filters, and campaign-specific engagement filters.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the segment in. If not provided, uses the currently selected company."},name:{type:"string",description:"Segment name"},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:MM,minItems:1,description:'Array of segment filters. Example custom attribute empty check: [{"id":"filter-1","field":"attribute","operator":"is_empty","value":"last_logged_in:"}]. Example Stripe purchase filter: [{"id":"filter-1","field":"stripeProduct","operator":"is","value":"prod_123"}]. Example threshold filter: [{"id":"filter-1","field":"stripeProduct","operator":"at_least","value":"prod_123:3"}]. Example trial cancellation filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:is_canceled"}]. Example trial end filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:end_at:2026-05-26"}]. Example campaign-specific engagement combo: [{"id":"filter-1","field":"emailBounced","operator":"is","value":"campaign:cmp_abc"},{"id":"filter-2","field":"emailBounced","operator":"is_not","value":"campaign:cmp_xyz"}]. Combine them with `filterJoinOperator: "or"` to match any filter.'},root:{...VM,description:"Nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["name"]}},{name:"get_segment_count",description:"Get the number of subscribers in a segment",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID"}},required:["segmentId"]}},{name:"list_templates",description:"List all email templates, including per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_template",description:"Get a template's details, content, and all localized variants with sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"create_template",description:"Create a new email template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line"},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:h4,items:{type:"object"}},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name","subject"]}},{name:"update_template",description:"Update an existing template. At least one of `name`, `subject`, `html`, `blocks`, or `labels` is required, and only those update fields are accepted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line"},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:h4,items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"delete_template",description:"Delete a template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{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."}},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:`${H6} Mutually exclusive with html.`,items:{type:"object"}}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"list_campaigns",description:"List all campaigns",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list campaigns for. If not provided, uses the currently selected company."},status:{type:"string",description:"Filter by status (draft, scheduled, sent)"},label:{type:"string",description:"Optional label name filter. Only campaigns assigned this label are returned."}}}},{name:"get_campaign",description:"Get campaign details and stats",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_email_send",description:"Get a sent email by emailSendId, including the stored HTML body when available and the ClickHouse event timeline. If the short-lived email send row has been cleaned up, returns the retained ClickHouse events and a sparse summary.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailSendId:{type:"string",description:"Email send ID to inspect."}},required:["emailSendId"]}},{name:"create_campaign",description:"Create a new campaign (as draft)",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:h4,items:{type:"object"}},prompt:{type:"string",description:"Generate campaign blocks from a prompt. Mutually exclusive with `html`, `blocks`, and `templateId`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},templateId:{type:"string",description:"Use a template instead of html"},segmentId:{type:"string",description:"Target segment ID"},campaignData:{type:"object",description:"Optional campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Optional computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_campaign",description:"Update a draft campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line"},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested. Send an empty string to clear it."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:h4,items:{type:"object"}},replyTo:{type:"string",description:"Set reply-to using an existing reply profile email address for this company."},replyProfileId:{type:"string",description:"Set reply-to using a reply profile ID for this company."},campaignData:{type:"object",description:"Set campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Set computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["campaignId"],additionalProperties:!1}},{name:"schedule_campaign",description:"Schedule a draft or already scheduled campaign. Returns dashboard edit and preview URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},scheduledAt:{type:"string",description:"Future ISO 8601 timestamp for the send, for example 2026-06-01T14:00:00Z."},targetLists:{type:"object",description:"Optional campaign targeting object. Omit to use saved targeting or all active subscribers. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, or {type:'filtered', filters:[...], filterJoinOperator:'and'}.",additionalProperties:!0},sendTimeOptimization:{type:"boolean",description:"Whether to use send-time optimization."},spreadOverHours:{type:"number",description:"Spread delivery over an integer number of hours from 1 to 72. When set, spread delivery takes precedence over send-time optimization."}},required:["campaignId","scheduledAt"],additionalProperties:!1}},{name:"send_test_email",description:"Send a test email to a single address",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"list_sequences",description:"List all email sequences (automations)",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list sequences for. If not provided, uses the currently selected company."}}}},{name:"get_sequence",description:"Get sequence details plus editable step content. The response includes sequence.emails with each step's nodeId, linked emailId, subject, previewText, and blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"],additionalProperties:!1}},{name:"create_sequence",description:`Create a new email sequence. Provide either a goal for AI generation or explicit steps. Explicit steps can include email content and create_discount actions; emails after a discount action can use merge tags such as {{discount.code}} and {{discount.percentOff}}. For AI-generated sequences, the tool polls until emails are generated (typically 30-60 seconds).
|
|
46
51
|
|
|
47
52
|
IMPORTANT GUIDELINES:
|
|
48
53
|
|
|
@@ -171,4 +176,4 @@ BUILT-IN EVENTS (auto-fired by payment integrations):
|
|
|
171
176
|
|
|
172
177
|
OTHER BUILT-IN EVENTS:
|
|
173
178
|
- email.opened, email.clicked, email.replied, email.bounced, email.unsubscribed
|
|
174
|
-
- contact.subscribed, contact.unsubscribed`,inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inactivity","frequency"],description:"Trigger type: 'contact_added' (when added to a list), 'tag_added' (when tag is applied), 'segment_entered' (when a contact newly enters a saved segment), 'event_received' (when custom event fires), 'inactivity' (when subscriber hasn't performed an event for X days), 'frequency' (when subscriber performs event X times in Y days)"},listId:{type:"string",description:"List ID to trigger on (for contact_added trigger). If not provided, triggers on any list."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger)"},segmentId:{type:"string",description:"Segment ID to trigger on (required for segment_entered trigger). Use list_segments first to choose a saved segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inactivity, and frequency triggers)"},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value."},enrollmentFieldPath:{type:"string",description:"Dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},stopCondition:{type:"object",description:"Optional explicit auto-stop condition. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'does_not_have_tag', value: 'trial' } when a tag is removed, { type: 'removed_from_list', value: 'list_123' } when they leave a list, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","event_received"],description:"Stop condition type."},value:{type:["string","null"],description:"Tag name, list ID, or event name for the stop condition. Use null or omit for type 'none'."}},required:["type"]},steps:{type:"array",description:"Explicit sequence steps. Omit type for email steps, or use type: 'create_discount' for a Stripe discount action. Later email steps can reference the most recent discount with {{discount.code}}, {{discount.percentOff}}, {{discount.amountOff}}, and {{discount.expiresAt}}.",items:{type:"object",properties:{type:{type:"string",enum:["email","create_discount","discount"],description:"Step type. Omit or use 'email' for email content. Use 'create_discount' to generate a discount code before later emails."},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:O5,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Will be converted to Sequenzy blocks."},delay:{type:"object",description:"Delay before this step.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}}},name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Prefer this nested shape for new integrations; legacy top-level discount fields are still accepted.",properties:{label:{type:"string",description:"Builder label for the discount step."},provider:{type:"string",enum:["stripe"],description:"Discount provider. Currently only 'stripe'."},discountType:{type:"string",enum:["percent","amount"],description:"Discount type."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Stripe coupon duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Stripe product IDs, such as prod_abc123, when appliesToAllPlans is false.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated promotion codes."},maxRedemptions:{type:"number",description:"Maximum promotion code redemptions. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Stripe-only. Restrict each generated promotion code to the matched subscriber's Stripe customer."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."},name:{type:"string",description:"Optional provider coupon name."}}},label:{type:"string",description:"Legacy top-level discount label. Prefer discount.label."},provider:{type:"string",enum:["stripe"],description:"Legacy top-level discount provider. Prefer discount.provider."},discountType:{type:"string",enum:["percent","amount"],description:"Legacy top-level discount type. Prefer discount.discountType."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Stripe coupon duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Stripe product IDs, such as prod_abc123, when appliesToAllPlans is false.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated promotion codes."},maxRedemptions:{type:"number",description:"Maximum promotion code redemptions. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Legacy top-level Stripe-only flag. Prefer discount.lockToSubscriber."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."}}}}},required:["name","trigger"]}},{name:"update_sequence",description:"Update an existing sequence. To target a specific step, use the emailId or nodeId returned in get_sequence.sequence.emails. You can also update enrollmentMode and enrollmentFieldPath for event-triggered matching-field enrollment. When inserting an if/else branch, include steps for every branch arm and elseSteps so the branch is usable immediately. Branch conditions support tags, lists, saved segments, custom events, clicked links, and subscriber field comparisons.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},name:{type:"string",description:"Sequence name"},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Updated sequence re-entry mode. 'matching_field' is only valid for event-based sequence triggers."},enrollmentFieldPath:{type:"string",description:"Dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Omit to leave unchanged. Use clearEnrollmentFieldPath to clear it."},clearEnrollmentFieldPath:{type:"boolean",description:"Set true to clear enrollmentFieldPath without sending a nullable schema value."},stopCondition:{type:"object",description:"Update the sequence auto-stop condition. Example: { type: 'has_tag', value: 'customer' } ends the sequence when the subscriber has that tag. Use { type: 'removed_from_list', value: 'list_123' } to stop when they leave a list, or { type: 'none', value: null } to clear it.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","event_received"]},value:{type:["string","null"],description:"Tag name, list ID, or event name for the stop condition."}},required:["type"]},branch:{type:"object",description:"Insert an if/else branch into an existing sequence. The branch is inserted after afterNodeId and creates an if path plus an else fallback path. Use get_sequence first to choose afterNodeId. Each branch condition should include steps, and elseSteps is required unless allowEmptyPaths is true. Conditions support tags, lists, saved segments, events, clicked links, and field comparisons. Use activityScope for event_received and link_clicked checks.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert the branch after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails."},label:{type:"string",description:"Optional branch node label."},branches:{type:"array",description:"Conditional branches evaluated in order. An else fallback is created automatically.",items:{type:"object",properties:{id:{type:"string",description:"Optional stable branch ID. Defaults to branch-0, branch-1, etc."},label:{type:"string",description:"Display label, e.g. 'If has customer tag'."},conditionType:{type:"string",enum:["has_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than"],description:"Condition type for this branch."},tagName:{type:"string",description:"Tag name for has_tag conditions. This can be used instead of tagId."},tagId:{type:"string",description:"Tag ID or tag name for has_tag conditions."},listId:{type:"string",description:"List ID for in_list conditions."},segmentId:{type:"string",description:"Segment ID for in_segment conditions."},segmentName:{type:"string",description:"Optional display name for in_segment conditions."},eventName:{type:"string",description:"Event name for event_received conditions, such as project.invite.accepted."},linkUrl:{type:"string",description:"Optional URL substring for link_clicked conditions. Omit to match any clicked link."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"Scope for event_received and link_clicked conditions. Omit to check ever."},fieldName:{type:"string",description:"Subscriber attribute name for field conditions."},fieldValue:{type:"string",description:"Comparison value for field conditions."},steps:{type:"array",description:"Steps to create inside this branch path. Required by default so the branch is not an empty placeholder.",items:L5}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:L5},allowEmptyPaths:{type:"boolean",description:"Set true only when intentionally creating empty UI placeholders. Normal API/MCP use should omit this and provide branch steps plus elseSteps."}},required:["afterNodeId","branches"]},emails:{type:"array",description:"Updated sequence emails. If you omit emailId/nodeId, items are matched by existing step order.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Will be converted to Sequenzy blocks."},htmlContent:{type:"string",description:"Alias for html. Use this when updating HTML content for a step."},blocks:{type:"array",description:H6,items:{type:"object"}}}}},steps:{type:"array",description:"Alias for emails. Supports the same fields and matching rules.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Will be converted to Sequenzy blocks."},htmlContent:{type:"string",description:"Alias for html. Use this when updating HTML content for a step."},blocks:{type:"array",description:H6,items:{type:"object"}}}}}},required:["sequenceId"]}},{name:"enable_sequence",description:"Enable/activate a sequence. IMPORTANT: Only call this when the user EXPLICITLY asks to enable or activate a sequence. Never enable sequences automatically after creation - the user must review the content first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"disable_sequence",description:"Disable/pause a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"cancel_sequence_enrollments",description:"Cancel active/waiting enrollments in one sequence. Provide sequenceId and exactly one target: subscriberId for one subscriber, or fieldValues to match stored entry event properties. For fieldValues, fieldPath is optional when the sequence has enrollmentFieldPath configured; otherwise provide a dot path such as order.id.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be cancelled."},subscriberId:{type:"string",description:"Subscriber ID to cancel in this sequence. Provide subscriberId or fieldValues, not both."},fieldPath:{type:"string",description:"Dot-path inside the token's stored entry event properties, such as order.id or event.id. Optional when the sequence has enrollmentFieldPath configured."},fieldValues:{type:"array",items:{type:"string"},description:"Entry field values to match. Cancels all active/waiting enrollments in the sequence whose entry field value is in this list. Provide fieldValues or subscriberId, not both."},dryRun:{type:"boolean",description:"When true, returns matching enrollments without cancelling them. Field-value cancellation defaults to dryRun on the API unless explicitly false."},reason:{type:"string",description:"Optional cancellation reason stored on matched enrollment tokens."}},required:["sequenceId"],additionalProperties:!1}},{name:"delete_sequence",description:"Delete a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"list_transactional_emails",description:"List transactional email templates, including their API slugs and linked email IDs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_transactional_email",description:"Get a transactional email by ID or slug, including subject, preview text, blocks, variables, and linked dashboard URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"]}},{name:"create_transactional_email",description:"Create a saved transactional email template with an API slug. Provide `prompt` to generate the email with AI, or provide either `html` or Sequenzy `blocks` for the email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Transactional email name."},slug:{type:"string",description:"Optional API slug used when sending by slug, for example `password-reset`. If omitted, Sequenzy generates one from the name."},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:`${h4} Mutually exclusive with \`html\`.`,items:{type:"object"}},prompt:{type:"string",description:"Generate transactional email blocks from a prompt. Mutually exclusive with `html` and `blocks`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},enabled:{type:"boolean",description:"Whether this transactional email can be sent immediately. Defaults to true."}},required:["name"],additionalProperties:!1}},{name:"update_transactional_email",description:"Update a transactional email by ID or slug. At least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` is required. Use `html` or `blocks` to replace the linked email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."},name:{type:"string",description:"Transactional email name."},enabled:{type:"boolean",description:"Whether this transactional email can be sent."},subject:{type:"string",description:"Email subject line."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:`${H6} Mutually exclusive with \`html\`.`,items:{type:"object"}}},required:["idOrSlug"],additionalProperties:!1}},{name:"send_email",description:"Send a transactional email to a single recipient",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject (required if not using templateId)"},html:{type:"string",description:"Email HTML content (required if not using templateId)"},templateId:{type:"string",description:"Template ID to use (alternative to html)"},variables:{type:"object",description:"Variables for template personalization. Nested objects and arrays are supported for repeat blocks, for example { items: [...] }."},subscriberExternalId:{type:"string",description:"Customer-owned subscriber ID for attaching analytics/localization on single-recipient sends."}},required:["to"]}},{name:"get_stats",description:"Get overview statistics for a time period",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},period:{type:"string",description:"Time period: 7d, 30d, or 90d (default: 7d)"}}}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_sequence_stats",description:"Get statistics for a sequence, including per-step failed subscribers and failure reasons",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"get_subscriber_activity",description:"Get recent activity, email stats, and current sequence enrollments for a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."}},required:[]}},{name:"generate_email",description:"Generate email blocks from a prompt",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the email to generate"},style:{type:"string",description:"Style: minimal, branded, promotional"},tone:{type:"string",description:"Tone: professional, casual, friendly"}},required:["prompt"]}},{name:"generate_sequence",description:"[DEPRECATED - Use create_sequence instead] Generate a multi-email sequence from a goal. Note: create_sequence now handles AI generation automatically.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},goal:{type:"string",description:"Goal of the sequence (e.g., 'onboard new SaaS trial users')"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days (default: 14)"}},required:["goal"]}},{name:"generate_subject_lines",description:"Generate A/B test subject line variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},topic:{type:"string",description:"Topic or context for the subject lines"},count:{type:"number",description:"Number of variants to generate (default: 5)"}},required:["topic"]}}];async function j5(Q,Y){try{let X;switch(Q){case"get_account":{let G=await N("GET","/api/v1/account"),z=B1();X={...G,selectedCompanyId:z??G.currentCompanyId};break}case"select_company":{let G=Y.companyId,z=await N("GET","/api/v1/account"),J=z.companies?.find(($)=>$.id===G);if(!J)throw Error(`Company not found. Available companies: ${z.companies?.map(($)=>`${$.name} (${$.id})`).join(", ")??"none"}`);F6(G),X={success:!0,message:`Switched to company: ${J.name}`,companyId:J.id,companyName:J.name};break}case"get_app_urls":{let G=await w5(Y);X={...K1({companyId:G,campaignId:j(Y,"campaignId"),sequenceId:j(Y,"sequenceId"),emailId:j(Y,"emailId")??j(Y,"templateId"),transactionalId:j(Y,"transactionalId"),emailSendId:j(Y,"emailSendId"),domainId:j(Y,"domainId"),status:j(Y,"status"),settingsTab:j(Y,"settingsTab")}),...G===void 0&&{note:"No company ID is selected. Call get_account, select_company, or pass companyId to get concrete dashboard URLs."}};break}case"create_company":{let G=await N("POST","/api/v1/companies",{name:Y.name,domain:Y.domain});if(!G.success)throw Error("Failed to create company");let z=G.company.id,J=6,$=0,H=G.company.status;while(H==="processing"&&$<J){await new Promise((K)=>setTimeout(K,20000)),$++;let U=await N("GET",`/api/v1/companies/${z}`);if(U.success)H=U.company.status}F6(z);let A=await N("GET",`/api/v1/companies/${z}`);X={success:!0,company:A.company,message:H==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${A.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let G=Y.companyId;X=await N("GET",`/api/v1/companies/${G}`);break}case"create_api_key":{let G=Y.companyId;X=await N("POST","/api/v1/api-keys",{name:Y.name},G);break}case"list_websites":{let G=Y.companyId;X=await N("GET","/api/v1/websites",void 0,G);break}case"add_website":{let G=Y.companyId;X=await N("POST","/api/v1/websites",{domain:Y.domain},G);break}case"check_website":{let G=Y.companyId;X=await N("GET",`/api/v1/websites/${Y.domain}`,void 0,G);break}case"get_integration_guide":X=await N("POST","/api/v1/integration-guide",Y);break;case"add_subscriber":{let G=Y.companyId,z=f4("add_subscriber",Y);X=await N("POST","/api/v1/subscribers",{...z,customAttributes:Y.attributes,tags:Y.tags,lists:Y.listIds,...Y.status!==void 0&&{status:Y.status},...Y.optInMode!==void 0&&{optInMode:Y.optInMode}},G);break}case"update_subscriber":{let G=Y.companyId,z=f4("update_subscriber",Y),J=await S9(z,G),$=Array.isArray(J.subscriber.tags)?J.subscriber.tags.filter((D)=>typeof D==="string"):[],H=Array.isArray(Y.addTags)?Y.addTags.filter((D)=>typeof D==="string"&&D.trim()!=="").map(F5):[],A=new Set(Array.isArray(Y.removeTags)?Y.removeTags.filter((D)=>typeof D==="string"&&D.trim()!=="").map(F5):[]),U=$.filter((D)=>!A.has(D));for(let D of H)if(!U.includes(D))U.push(D);let K={};if(z.email&&z.externalId)K.externalId=z.externalId;if(B0(Y.attributes))K.customAttributes={...B0(J.subscriber.customAttributes)?J.subscriber.customAttributes:{},...Y.attributes};if(Y.addTags||Y.removeTags)K.tags=U;X=await N("PATCH",C9(z),K,G);break}case"remove_subscriber":{let G=Y.companyId,z=f4("remove_subscriber",Y),J=C9(z);if(Y.hardDelete===!0)X=await N("DELETE",J,void 0,G);else X=await N("PATCH",J,{status:"unsubscribed"},G);break}case"get_subscriber":{let G=Y.companyId,z=f4("get_subscriber",Y);X=await S9(z,G);break}case"search_subscribers":{let G=Y.companyId;X=await yM(Y,G);break}case"list_tags":{let G=Y.companyId;X=await N("GET","/api/v1/tags",void 0,G);break}case"list_lists":{let G=Y.companyId;X=await N("GET","/api/v1/lists",void 0,G);break}case"create_list":{let G=Y.companyId;X=await N("POST","/api/v1/lists",Y,G);break}case"add_subscribers_to_list":{let G=Y.companyId,z=hM("add_subscribers_to_list",Y,"listId"),J=fM("add_subscribers_to_list",Y),$=q5("add_subscribers_to_list",Y,"duplicateStrategy",["skip","merge","overwrite"])??"skip",H=q5("add_subscribers_to_list",Y,"optInMode",["default","confirmed","double_opt_in"])??"default";X=await N("POST",`/api/v1/lists/${encodeURIComponent(z)}/subscribers`,{emails:J,duplicateStrategy:$,enrollInSequences:Y.enrollInSequences===!0,optInMode:H},G);break}case"list_segments":{let G=Y.companyId;X=await N("GET","/api/v1/segments",void 0,G);break}case"create_segment":{SM(Y);let G=Y.companyId;X=await N("POST","/api/v1/segments",{...Y,...Y.filters!==void 0?{filters:M5(Y.filters)}:{},...Y.root!==void 0?{root:V5(Y.root)}:{}},G);break}case"get_segment_count":{let G=Y.companyId;X=await N("GET",`/api/v1/segments/${Y.segmentId}/count`,void 0,G);break}case"list_templates":{let G=Y.companyId,z=new URLSearchParams,J=j(Y,"label");if(J)z.set("label",J);X=await N("GET",`/api/v1/templates${z.size>0?`?${z}`:""}`,void 0,G);break}case"get_template":{let G=Y.companyId;X=await N("GET",`/api/v1/templates/${Y.templateId}`,void 0,G);break}case"create_template":{let G=Y.companyId;w1("create_template",Y,{requireContent:!0}),U6("create_template",Y),X=await N("POST","/api/v1/templates",Y,G);break}case"update_template":{let G=Y.companyId,z=new Set(["companyId","templateId","name","subject","html","blocks","labels"]),J=Object.keys(Y).filter(($)=>!z.has($));if(J.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${J.length===1?"":"s"}: ${J.map(($)=>`\`${$}\``).join(", ")}.`);if(w1("update_template",Y),U6("update_template",Y),Y.name===void 0&&Y.subject===void 0&&Y.html===void 0&&Y.blocks===void 0&&Y.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `html`, `blocks`, or `labels` when calling `update_template`.");X=await N("PUT",`/api/v1/templates/${Y.templateId}`,Y,G);break}case"delete_template":{let G=Y.companyId;X=await N("DELETE",`/api/v1/templates/${Y.templateId}`,void 0,G);break}case"list_ab_tests":{let G=Y.companyId,z=new URLSearchParams,J=j(Y,"sequenceId");if(J)z.set("sequenceId",J);X=await N("GET",`/api/v1/ab-tests${z.size>0?`?${z}`:""}`,void 0,G);break}case"get_ab_test":{let G=Y.companyId;X=await N("GET",`/api/v1/ab-tests/${Y.abTestId}`,void 0,G);break}case"get_ab_test_stats":{let G=Y.companyId,z=new URLSearchParams,J=j(Y,"period"),$=j(Y,"start"),H=j(Y,"end");if(J)z.set("period",J);if($)z.set("start",$);if(H)z.set("end",H);X=await N("GET",`/api/v1/ab-tests/${Y.abTestId}/stats${z.size>0?`?${z}`:""}`,void 0,G);break}case"restart_ab_test":{let G=Y.companyId,z=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),J=Object.keys(Y).filter((U)=>!z.has(U));if(J.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${J.length===1?"":"s"}: ${J.map((U)=>`\`${U}\``).join(", ")}.`);let $=j(Y,"testType");if($!==void 0&&$!=="subject"&&$!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let H=Y.winnerThreshold===void 0?void 0:Number(Y.winnerThreshold);if(H!==void 0&&(!Number.isInteger(H)||H<10||H>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let A=Y.variantCount===void 0?void 0:Number(Y.variantCount);if(A!==void 0&&(!Number.isInteger(A)||A<2||A>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");X=await N("POST",`/api/v1/ab-tests/${Y.abTestId}/restart`,{sourceVariantId:j(Y,"sourceVariantId"),testType:$,winnerThreshold:H,variantCount:A},G);break}case"update_ab_test_variant":{let G=Y.companyId,z=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks"]),J=Object.keys(Y).filter(($)=>!z.has($));if(J.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${J.length===1?"":"s"}: ${J.map(($)=>`\`${$}\``).join(", ")}.`);if(w1("update_ab_test_variant",Y),Y.subject===void 0&&Y.previewText===void 0&&Y.html===void 0&&Y.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");X=await N("PATCH",`/api/v1/ab-tests/${Y.abTestId}/variants/${Y.variantId}`,Y,G);break}case"list_campaigns":{let G=Y.companyId,z=new URLSearchParams;if(Y.status)z.set("status",String(Y.status));let J=j(Y,"label");if(J)z.set("label",J);X=await N("GET",`/api/v1/campaigns?${z}`,void 0,G);break}case"get_campaign":{let G=Y.companyId;X=await N("GET",`/api/v1/campaigns/${Y.campaignId}`,void 0,G);break}case"get_email_send":{let G=Y.companyId;X=await N("GET",`/api/v1/email-sends/${encodeURIComponent(String(Y.emailSendId))}`,void 0,G);break}case"create_campaign":{let G=Y.companyId;vM(Y);let z=j(Y,"prompt");if(z!==void 0){let J=await N("POST","/api/v1/generate/email",{prompt:z,...Y.style!==void 0&&{style:Y.style},...Y.tone!==void 0&&{tone:Y.tone}},G),$=j(Y,"subject")??(typeof J.subject==="string"&&J.subject.trim()!==""?J.subject.trim():void 0);if(!$)throw Error("`create_campaign` prompt generation did not return a subject. Provide `subject` explicitly.");let H=Array.isArray(J.blocks)&&J.blocks.length>0?J.blocks:void 0,A=typeof J.html==="string"&&J.html.trim()!==""?J.html:void 0;if(H===void 0&&A===void 0)throw Error("`create_campaign` prompt generation did not return email blocks. Try again or provide `html` or `blocks` explicitly.");X=await N("POST","/api/v1/campaigns",{name:Y.name,subject:$,...H!==void 0?{blocks:H}:{html:A},...Y.segmentId!==void 0&&{segmentId:Y.segmentId},...Y.trackingCode!==void 0&&{trackingCode:Y.trackingCode},...Y.campaignData!==void 0&&{campaignData:Y.campaignData},...Y.computedLists!==void 0&&{computedLists:Y.computedLists},...Y.labels!==void 0&&{labels:Y.labels}},G);break}X=await N("POST","/api/v1/campaigns",Y,G);break}case"update_campaign":{let G=Y.companyId,z=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","replyTo","replyProfileId","campaignData","computedLists","labels"]),J=Object.keys(Y).filter(($)=>!z.has($));if(J.length>0)throw Error(`\`update_campaign\` accepts only \`name\`, \`subject\`, \`trackingCode\`, \`html\`, \`blocks\`, \`replyTo\`, \`replyProfileId\`, \`campaignData\`, \`computedLists\`, and \`labels\` update fields. Unsupported field${J.length===1?"":"s"}: ${J.map(($)=>`\`${$}\``).join(", ")}.`);if(w1("update_campaign",Y),U6("update_campaign",Y),Y.replyTo!==void 0&&Y.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_campaign`, not both.");if(Y.name===void 0&&Y.subject===void 0&&Y.trackingCode===void 0&&Y.html===void 0&&Y.blocks===void 0&&Y.replyTo===void 0&&Y.replyProfileId===void 0&&Y.campaignData===void 0&&Y.computedLists===void 0&&Y.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `trackingCode`, `html`, `blocks`, `replyTo`, `replyProfileId`, `campaignData`, `computedLists`, or `labels` when calling `update_campaign`.");X=await N("PUT",`/api/v1/campaigns/${Y.campaignId}`,Y,G);break}case"schedule_campaign":{let G=Y.companyId,z=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours"]),J=Object.keys(Y).filter(($)=>!z.has($));if(J.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, and \`spreadOverHours\`. Unsupported field${J.length===1?"":"s"}: ${J.map(($)=>`\`${$}\``).join(", ")}.`);kM(Y),X=await N("POST",`/api/v1/campaigns/${Y.campaignId}/schedule`,{scheduledAt:Y.scheduledAt,...Y.targetLists!==void 0&&{targetLists:Y.targetLists},...Y.sendTimeOptimization!==void 0&&{sendTimeOptimization:Y.sendTimeOptimization},...Y.spreadOverHours!==void 0&&{spreadOverHours:Y.spreadOverHours}},G);break}case"send_test_email":{let G=Y.companyId;X=await N("POST",`/api/v1/campaigns/${Y.campaignId}/test`,{to:Y.to},G);break}case"list_sequences":{let G=Y.companyId;X=await N("GET","/api/v1/sequences",void 0,G);break}case"get_sequence":{let G=Y.companyId;X=await N("GET",`/api/v1/sequences/${Y.sequenceId}`,void 0,G);break}case"create_sequence":{let G=Y.companyId,z=Array.isArray(Y.steps)&&Y.steps.length>0,J=await N("POST","/api/v1/sequences",Y,G);if(!J.success){X=J;break}let $=J.sequence.id;if(z){let D=await N("GET",`/api/v1/sequences/${$}`,void 0,G);if(D.success)X={success:!0,sequence:D.sequence,message:`Sequence "${D.sequence.name}" created with explicit steps. Review it before enabling.`};else X=D;break}let H=6,A=0,U="pending";while(U!=="complete"&&A<H){await new Promise((L)=>setTimeout(L,20000)),A++;let D=await N("GET",`/api/v1/sequences/${$}`,void 0,G);if(D.success)U=D.sequence.enrichmentStatus}let K=await N("GET",`/api/v1/sequences/${$}`,void 0,G);if(K.success)X={success:!0,sequence:K.sequence,message:K.sequence.enrichmentStatus==="complete"?`Sequence "${K.sequence.name}" created with ${K.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.`:`Sequence "${K.sequence.name}" created. Email enrichment is still in progress (${K.sequence.enrichedCount}/${K.sequence.emailCount} emails generated). You can check status with get_sequence.`};else X=K;break}case"update_sequence":{let G=Y.companyId,z=RM(Y);X=await N("PUT",`/api/v1/sequences/${Y.sequenceId}`,z,G);break}case"enable_sequence":{let G=Y.companyId;X=await N("POST",`/api/v1/sequences/${Y.sequenceId}/enable`,void 0,G);break}case"disable_sequence":{let G=Y.companyId;X=await N("POST",`/api/v1/sequences/${Y.sequenceId}/disable`,void 0,G);break}case"cancel_sequence_enrollments":{let G=Y.companyId,z=CM(Y);X=await N("POST",`/api/v1/sequences/${Y.sequenceId}/enrollments/cancel`,z,G);break}case"delete_sequence":{let G=Y.companyId;X=await N("DELETE",`/api/v1/sequences/${Y.sequenceId}`,void 0,G);break}case"list_transactional_emails":{let G=Y.companyId;X=await N("GET","/api/v1/transactional",void 0,G);break}case"get_transactional_email":{let G=Y.companyId;X=await N("GET",`/api/v1/transactional/${Y.idOrSlug}`,void 0,G);break}case"create_transactional_email":{let G=Y.companyId,z=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),J=Object.keys(Y).filter((A)=>!z.has(A));if(J.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${J.length===1?"":"s"}: ${J.map((A)=>`\`${A}\``).join(", ")}.`);xM(Y);let $=j(Y,"prompt");if($!==void 0){let A={companyId:G??B1()??"",name:typeof Y.name==="string"&&Y.name.trim()!==""?Y.name.trim():"",slug:typeof Y.slug==="string"&&Y.slug.trim()!==""?Y.slug.trim():"",promptLength:$.length,style:typeof Y.style==="string"?Y.style:"",tone:typeof Y.tone==="string"?Y.tone:""};try{console.error("[mcp:create_transactional_email] generating from prompt",A);let U=await N("POST","/api/v1/generate/email",{prompt:$,...Y.style!==void 0&&{style:Y.style},...Y.tone!==void 0&&{tone:Y.tone}},G);console.error("[mcp:create_transactional_email] prompt generation complete",{...A,subject:U.subject??"",previewTextLength:typeof U.previewText==="string"?U.previewText.length:0,blockCount:Array.isArray(U.blocks)?U.blocks.length:0,htmlLength:typeof U.html==="string"?U.html.length:0});let K=j(Y,"subject")??(typeof U.subject==="string"&&U.subject.trim()!==""?U.subject.trim():void 0);if(!K)throw Error("`create_transactional_email` prompt generation did not return a subject. Provide `subject` explicitly.");let D=Array.isArray(U.blocks)&&U.blocks.length>0?U.blocks:void 0,L=typeof U.html==="string"&&U.html.trim()!==""?U.html:void 0,q=j(Y,"previewText")??(typeof U.previewText==="string"?U.previewText.trim():void 0);if(D===void 0&&L===void 0)throw Error("`create_transactional_email` prompt generation did not return email blocks. Try again or provide `html` or `blocks` explicitly.");console.error("[mcp:create_transactional_email] creating generated transactional",{...A,subject:K,contentSource:D!==void 0?"blocks":"html",blockCount:D?.length??0,htmlLength:L?.length??0}),X=await N("POST","/api/v1/transactional",{name:Y.name,...Y.slug!==void 0&&{slug:Y.slug},subject:K,...q!==void 0&&{previewText:q},...D!==void 0?{blocks:D}:{html:L},...Y.enabled!==void 0&&{enabled:Y.enabled}},G),console.error("[mcp:create_transactional_email] generated transactional created",A)}catch(U){throw console.error("[mcp:create_transactional_email] prompt-based create failed",{...A,error:U instanceof Error?U.message:String(U)}),U}break}let H=Object.fromEntries(Object.entries(Y).filter(([A])=>A!=="companyId"));X=await N("POST","/api/v1/transactional",H,G);break}case"update_transactional_email":{let G=Y.companyId,z=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),J=Object.keys(Y).filter((H)=>!z.has(H));if(J.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${J.length===1?"":"s"}: ${J.map((H)=>`\`${H}\``).join(", ")}.`);if(w1("update_transactional_email",Y),Y.name===void 0&&Y.enabled===void 0&&Y.subject===void 0&&Y.previewText===void 0&&Y.html===void 0&&Y.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let $=Object.fromEntries(Object.entries(Y).filter(([H])=>H!=="companyId"&&H!=="idOrSlug"));X=await N("PATCH",`/api/v1/transactional/${Y.idOrSlug}`,$,G);break}case"send_email":{let G=Y.companyId;X=await N("POST","/api/v1/transactional/send",Y,G);break}case"get_stats":{let G=Y.companyId,z=Y.period??"7d";X=await N("GET",`/api/v1/metrics?period=${z}`,void 0,G);break}case"get_campaign_stats":{let G=Y.companyId;X=await N("GET",`/api/v1/metrics/campaigns/${Y.campaignId}`,void 0,G);break}case"get_sequence_stats":{let G=Y.companyId;X=await N("GET",`/api/v1/metrics/sequences/${Y.sequenceId}`,void 0,G);break}case"get_subscriber_activity":{let G=Y.companyId,z=f4("get_subscriber_activity",Y),J=await S9(z,G);X={success:J.success,email:J.subscriber.email,emailStats:J.subscriber.emailStats??null,activity:J.subscriber.activity??[],sequenceEnrollments:J.subscriber.sequenceEnrollments??[]};break}case"generate_email":{let G=Y.companyId;X=await N("POST","/api/v1/generate/email",Y,G);break}case"generate_sequence":{let G=Y.companyId;X=await N("POST","/api/v1/generate/sequence",Y,G);break}case"generate_subject_lines":{let G=Y.companyId;X=await N("POST","/api/v1/generate/subjects",Y,G);break}default:throw Error(`Unknown tool: ${Q}`)}let W=_M(X);if(W)throw W;return X=await cM(Q,Y,X),{content:[{type:"text",text:JSON.stringify(X,null,2)}]}}catch(X){return{isError:!0,content:[{type:"text",text:b1(X)}]}}}async function I5(Q,Y,X){let W=Y.getRequestContext?.(Q)??{};try{return await y9(W,X)}finally{await Y.onRequestContextUpdated?.(W,Q)}}function nI(Q={}){let Y=new E9({name:"sequenzy",version:$5.version},{capabilities:{tools:{},resources:{}}});return Y.setRequestHandler(LY,async()=>{return{tools:P5}}),Y.setRequestHandler(B4,async(X,W)=>{let{name:G,arguments:z}=X.params;return I5(W,Q,()=>j5(G,z??{}))}),Y.setRequestHandler($Y,async()=>{return{resources:U5}}),Y.setRequestHandler(AY,async(X,W)=>{let{uri:G}=X.params;return I5(W,Q,()=>K5(G))}),Y}export{nI as createSequenzyMcpServer};
|
|
179
|
+
- contact.subscribed, contact.unsubscribed`,inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inactivity","frequency"],description:"Trigger type: 'contact_added' (when added to a list), 'tag_added' (when tag is applied), 'segment_entered' (when a contact newly enters a saved segment), 'event_received' (when custom event fires), 'inactivity' (when subscriber hasn't performed an event for X days), 'frequency' (when subscriber performs event X times in Y days)"},listId:{type:"string",description:"List ID to trigger on (for contact_added trigger). If not provided, triggers on any list."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger)"},segmentId:{type:"string",description:"Segment ID to trigger on (required for segment_entered trigger). Use list_segments first to choose a saved segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inactivity, and frequency triggers)"},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"When to start counting inactivity for subscribers who never had the event. Defaults to sequence_created_at."},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value."},enrollmentFieldPath:{type:"string",description:"Dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},stopCondition:{type:"object",description:"Optional explicit auto-stop condition. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'does_not_have_tag', value: 'trial' } when a tag is removed, { type: 'removed_from_list', value: 'list_123' } when they leave a list, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","event_received"],description:"Stop condition type."},value:{type:["string","null"],description:"Tag name, list ID, or event name for the stop condition. Use null or omit for type 'none'."}},required:["type"]},steps:{type:"array",description:"Explicit sequence steps. Omit type for email steps, or use type: 'create_discount' for a Stripe discount action. Later email steps can reference the most recent discount with {{discount.code}}, {{discount.percentOff}}, {{discount.amountOff}}, and {{discount.expiresAt}}.",items:{type:"object",properties:{type:{type:"string",enum:["email","create_discount","discount"],description:"Step type. Omit or use 'email' for email content. Use 'create_discount' to generate a discount code before later emails."},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:O5,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Will be converted to Sequenzy blocks."},delay:{type:"object",description:"Delay before this step.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}}},name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Prefer this nested shape for new integrations; legacy top-level discount fields are still accepted.",properties:{label:{type:"string",description:"Builder label for the discount step."},provider:{type:"string",enum:["stripe"],description:"Discount provider. Currently only 'stripe'."},discountType:{type:"string",enum:["percent","amount"],description:"Discount type."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Stripe coupon duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Stripe product IDs, such as prod_abc123, when appliesToAllPlans is false.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated promotion codes."},maxRedemptions:{type:"number",description:"Maximum promotion code redemptions. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Stripe-only. Restrict each generated promotion code to the matched subscriber's Stripe customer."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."},name:{type:"string",description:"Optional provider coupon name."}}},label:{type:"string",description:"Legacy top-level discount label. Prefer discount.label."},provider:{type:"string",enum:["stripe"],description:"Legacy top-level discount provider. Prefer discount.provider."},discountType:{type:"string",enum:["percent","amount"],description:"Legacy top-level discount type. Prefer discount.discountType."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Stripe coupon duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Stripe product IDs, such as prod_abc123, when appliesToAllPlans is false.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated promotion codes."},maxRedemptions:{type:"number",description:"Maximum promotion code redemptions. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Legacy top-level Stripe-only flag. Prefer discount.lockToSubscriber."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."}}}}},required:["name","trigger"]}},{name:"update_sequence",description:"Update an existing sequence. To target a specific step, use the emailId or nodeId returned in get_sequence.sequence.emails. You can also update enrollmentMode and enrollmentFieldPath for event-triggered matching-field enrollment. When inserting an if/else branch, include steps for every branch arm and elseSteps so the branch is usable immediately. Branch conditions support tags, lists, saved segments, custom events, clicked links, and subscriber field comparisons.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},name:{type:"string",description:"Sequence name"},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Updated sequence re-entry mode. 'matching_field' is only valid for event-based sequence triggers."},enrollmentFieldPath:{type:"string",description:"Dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Omit to leave unchanged. Use clearEnrollmentFieldPath to clear it."},clearEnrollmentFieldPath:{type:"boolean",description:"Set true to clear enrollmentFieldPath without sending a nullable schema value."},stopCondition:{type:"object",description:"Update the sequence auto-stop condition. Example: { type: 'has_tag', value: 'customer' } ends the sequence when the subscriber has that tag. Use { type: 'removed_from_list', value: 'list_123' } to stop when they leave a list, or { type: 'none', value: null } to clear it.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","event_received"]},value:{type:["string","null"],description:"Tag name, list ID, or event name for the stop condition."}},required:["type"]},branch:{type:"object",description:"Insert an if/else branch into an existing sequence. The branch is inserted after afterNodeId and creates an if path plus an else fallback path. Use get_sequence first to choose afterNodeId. Each branch condition should include steps, and elseSteps is required unless allowEmptyPaths is true. Conditions support tags, lists, saved segments, events, clicked links, and field comparisons. Use activityScope for event_received and link_clicked checks.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert the branch after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails."},label:{type:"string",description:"Optional branch node label."},branches:{type:"array",description:"Conditional branches evaluated in order. An else fallback is created automatically.",items:{type:"object",properties:{id:{type:"string",description:"Optional stable branch ID. Defaults to branch-0, branch-1, etc."},label:{type:"string",description:"Display label, e.g. 'If has customer tag'."},conditionType:{type:"string",enum:["has_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than"],description:"Condition type for this branch."},tagName:{type:"string",description:"Tag name for has_tag conditions. This can be used instead of tagId."},tagId:{type:"string",description:"Tag ID or tag name for has_tag conditions."},listId:{type:"string",description:"List ID for in_list conditions."},segmentId:{type:"string",description:"Segment ID for in_segment conditions."},segmentName:{type:"string",description:"Optional display name for in_segment conditions."},eventName:{type:"string",description:"Event name for event_received conditions, such as project.invite.accepted."},linkUrl:{type:"string",description:"Optional URL substring for link_clicked conditions. Omit to match any clicked link."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"Scope for event_received and link_clicked conditions. Omit to check ever."},fieldName:{type:"string",description:"Subscriber attribute name for field conditions."},fieldValue:{type:"string",description:"Comparison value for field conditions."},steps:{type:"array",description:"Steps to create inside this branch path. Required by default so the branch is not an empty placeholder.",items:L5}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:L5},allowEmptyPaths:{type:"boolean",description:"Set true only when intentionally creating empty UI placeholders. Normal API/MCP use should omit this and provide branch steps plus elseSteps."}},required:["afterNodeId","branches"]},emails:{type:"array",description:"Updated sequence emails. If you omit emailId/nodeId, items are matched by existing step order.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Will be converted to Sequenzy blocks."},htmlContent:{type:"string",description:"Alias for html. Use this when updating HTML content for a step."},blocks:{type:"array",description:H6,items:{type:"object"}}}}},steps:{type:"array",description:"Alias for emails. Supports the same fields and matching rules.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Will be converted to Sequenzy blocks."},htmlContent:{type:"string",description:"Alias for html. Use this when updating HTML content for a step."},blocks:{type:"array",description:H6,items:{type:"object"}}}}}},required:["sequenceId"]}},{name:"enable_sequence",description:"Enable/activate a sequence. IMPORTANT: Only call this when the user EXPLICITLY asks to enable or activate a sequence. Never enable sequences automatically after creation - the user must review the content first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"disable_sequence",description:"Disable/pause a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"cancel_sequence_enrollments",description:"Cancel active/waiting enrollments in one sequence. Provide sequenceId and exactly one target: subscriberId for one subscriber, or fieldValues to match stored entry event properties. For fieldValues, fieldPath is optional when the sequence has enrollmentFieldPath configured; otherwise provide a dot path such as order.id.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be cancelled."},subscriberId:{type:"string",description:"Subscriber ID to cancel in this sequence. Provide subscriberId or fieldValues, not both."},fieldPath:{type:"string",description:"Dot-path inside the token's stored entry event properties, such as order.id or event.id. Optional when the sequence has enrollmentFieldPath configured."},fieldValues:{type:"array",items:{type:"string"},description:"Entry field values to match. Cancels all active/waiting enrollments in the sequence whose entry field value is in this list. Provide fieldValues or subscriberId, not both."},dryRun:{type:"boolean",description:"When true, returns matching enrollments without cancelling them. Field-value cancellation defaults to dryRun on the API unless explicitly false."},reason:{type:"string",description:"Optional cancellation reason stored on matched enrollment tokens."}},required:["sequenceId"],additionalProperties:!1}},{name:"delete_sequence",description:"Delete a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"list_transactional_emails",description:"List transactional email templates, including their API slugs and linked email IDs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_transactional_email",description:"Get a transactional email by ID or slug, including subject, preview text, blocks, variables, and linked dashboard URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"]}},{name:"create_transactional_email",description:"Create a saved transactional email template with an API slug. Provide `prompt` to generate the email with AI, or provide either `html` or Sequenzy `blocks` for the email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Transactional email name."},slug:{type:"string",description:"Optional API slug used when sending by slug, for example `password-reset`. If omitted, Sequenzy generates one from the name."},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:`${h4} Mutually exclusive with \`html\`.`,items:{type:"object"}},prompt:{type:"string",description:"Generate transactional email blocks from a prompt. Mutually exclusive with `html` and `blocks`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},enabled:{type:"boolean",description:"Whether this transactional email can be sent immediately. Defaults to true."}},required:["name"],additionalProperties:!1}},{name:"update_transactional_email",description:"Update a transactional email by ID or slug. At least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` is required. Use `html` or `blocks` to replace the linked email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."},name:{type:"string",description:"Transactional email name."},enabled:{type:"boolean",description:"Whether this transactional email can be sent."},subject:{type:"string",description:"Email subject line."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:`${H6} Mutually exclusive with \`html\`.`,items:{type:"object"}}},required:["idOrSlug"],additionalProperties:!1}},{name:"send_email",description:"Send a transactional email to a single recipient",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject (required if not using templateId)"},html:{type:"string",description:"Email HTML content (required if not using templateId)"},templateId:{type:"string",description:"Template ID to use (alternative to html)"},variables:{type:"object",description:"Variables for template personalization. Nested objects and arrays are supported for repeat blocks, for example { items: [...] }."},subscriberExternalId:{type:"string",description:"Customer-owned subscriber ID for attaching analytics/localization on single-recipient sends."}},required:["to"]}},{name:"get_stats",description:"Get overview statistics for a time period",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},period:{type:"string",description:"Time period: 7d, 30d, or 90d (default: 7d)"}}}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_sequence_stats",description:"Get statistics for a sequence, including per-step failed subscribers and failure reasons",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"get_subscriber_activity",description:"Get recent activity, email stats, and current sequence enrollments for a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."}},required:[]}},{name:"generate_email",description:"Generate email blocks from a prompt",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the email to generate"},style:{type:"string",description:"Style: minimal, branded, promotional"},tone:{type:"string",description:"Tone: professional, casual, friendly"}},required:["prompt"]}},{name:"generate_sequence",description:"[DEPRECATED - Use create_sequence instead] Generate a multi-email sequence from a goal. Note: create_sequence now handles AI generation automatically.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},goal:{type:"string",description:"Goal of the sequence (e.g., 'onboard new SaaS trial users')"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days (default: 14)"}},required:["goal"]}},{name:"generate_subject_lines",description:"Generate A/B test subject line variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},topic:{type:"string",description:"Topic or context for the subject lines"},count:{type:"number",description:"Number of variants to generate (default: 5)"}},required:["topic"]}}];async function j5(Q,Y){try{let X;switch(Q){case"get_account":{let G=await N("GET","/api/v1/account"),z=B1();X={...G,selectedCompanyId:z??G.currentCompanyId};break}case"select_company":{let G=Y.companyId,z=await N("GET","/api/v1/account"),J=z.companies?.find(($)=>$.id===G);if(!J)throw Error(`Company not found. Available companies: ${z.companies?.map(($)=>`${$.name} (${$.id})`).join(", ")??"none"}`);F6(G),X={success:!0,message:`Switched to company: ${J.name}`,companyId:J.id,companyName:J.name};break}case"get_app_urls":{let G=await w5(Y);X={...K1({companyId:G,campaignId:j(Y,"campaignId"),sequenceId:j(Y,"sequenceId"),emailId:j(Y,"emailId")??j(Y,"templateId"),transactionalId:j(Y,"transactionalId"),emailSendId:j(Y,"emailSendId"),domainId:j(Y,"domainId"),status:j(Y,"status"),settingsTab:j(Y,"settingsTab")}),...G===void 0&&{note:"No company ID is selected. Call get_account, select_company, or pass companyId to get concrete dashboard URLs."}};break}case"create_company":{let G=await N("POST","/api/v1/companies",{name:Y.name,domain:Y.domain});if(!G.success)throw Error("Failed to create company");let z=G.company.id,J=6,$=0,H=G.company.status;while(H==="processing"&&$<J){await new Promise((K)=>setTimeout(K,20000)),$++;let U=await N("GET",`/api/v1/companies/${z}`);if(U.success)H=U.company.status}F6(z);let A=await N("GET",`/api/v1/companies/${z}`);X={success:!0,company:A.company,message:H==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${A.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let G=Y.companyId;X=await N("GET",`/api/v1/companies/${G}`);break}case"create_api_key":{let G=Y.companyId;X=await N("POST","/api/v1/api-keys",{name:Y.name},G);break}case"list_websites":{let G=Y.companyId;X=await N("GET","/api/v1/websites",void 0,G);break}case"add_website":{let G=Y.companyId;X=await N("POST","/api/v1/websites",{domain:Y.domain},G);break}case"check_website":{let G=Y.companyId;X=await N("GET",`/api/v1/websites/${Y.domain}`,void 0,G);break}case"get_integration_guide":X=await N("POST","/api/v1/integration-guide",Y);break;case"add_subscriber":{let G=Y.companyId,z=f4("add_subscriber",Y);X=await N("POST","/api/v1/subscribers",{...z,customAttributes:Y.attributes,tags:Y.tags,lists:Y.listIds,...Y.status!==void 0&&{status:Y.status},...Y.optInMode!==void 0&&{optInMode:Y.optInMode}},G);break}case"update_subscriber":{let G=Y.companyId,z=f4("update_subscriber",Y),J=await S9(z,G),$=Array.isArray(J.subscriber.tags)?J.subscriber.tags.filter((D)=>typeof D==="string"):[],H=Array.isArray(Y.addTags)?Y.addTags.filter((D)=>typeof D==="string"&&D.trim()!=="").map(F5):[],A=new Set(Array.isArray(Y.removeTags)?Y.removeTags.filter((D)=>typeof D==="string"&&D.trim()!=="").map(F5):[]),U=$.filter((D)=>!A.has(D));for(let D of H)if(!U.includes(D))U.push(D);let K={};if(z.email&&z.externalId)K.externalId=z.externalId;if(B0(Y.attributes))K.customAttributes={...B0(J.subscriber.customAttributes)?J.subscriber.customAttributes:{},...Y.attributes};if(Y.addTags||Y.removeTags)K.tags=U;X=await N("PATCH",C9(z),K,G);break}case"remove_subscriber":{let G=Y.companyId,z=f4("remove_subscriber",Y),J=C9(z);if(Y.hardDelete===!0)X=await N("DELETE",J,void 0,G);else X=await N("PATCH",J,{status:"unsubscribed"},G);break}case"get_subscriber":{let G=Y.companyId,z=f4("get_subscriber",Y);X=await S9(z,G);break}case"search_subscribers":{let G=Y.companyId;X=await yM(Y,G);break}case"list_tags":{let G=Y.companyId;X=await N("GET","/api/v1/tags",void 0,G);break}case"list_lists":{let G=Y.companyId;X=await N("GET","/api/v1/lists",void 0,G);break}case"create_list":{let G=Y.companyId;X=await N("POST","/api/v1/lists",Y,G);break}case"add_subscribers_to_list":{let G=Y.companyId,z=hM("add_subscribers_to_list",Y,"listId"),J=fM("add_subscribers_to_list",Y),$=q5("add_subscribers_to_list",Y,"duplicateStrategy",["skip","merge","overwrite"])??"skip",H=q5("add_subscribers_to_list",Y,"optInMode",["default","confirmed","double_opt_in"])??"default";X=await N("POST",`/api/v1/lists/${encodeURIComponent(z)}/subscribers`,{emails:J,duplicateStrategy:$,enrollInSequences:Y.enrollInSequences===!0,optInMode:H},G);break}case"list_segments":{let G=Y.companyId;X=await N("GET","/api/v1/segments",void 0,G);break}case"create_segment":{SM(Y);let G=Y.companyId;X=await N("POST","/api/v1/segments",{...Y,...Y.filters!==void 0?{filters:M5(Y.filters)}:{},...Y.root!==void 0?{root:V5(Y.root)}:{}},G);break}case"get_segment_count":{let G=Y.companyId;X=await N("GET",`/api/v1/segments/${Y.segmentId}/count`,void 0,G);break}case"list_templates":{let G=Y.companyId,z=new URLSearchParams,J=j(Y,"label");if(J)z.set("label",J);X=await N("GET",`/api/v1/templates${z.size>0?`?${z}`:""}`,void 0,G);break}case"get_template":{let G=Y.companyId;X=await N("GET",`/api/v1/templates/${Y.templateId}`,void 0,G);break}case"create_template":{let G=Y.companyId;w1("create_template",Y,{requireContent:!0}),U6("create_template",Y),X=await N("POST","/api/v1/templates",Y,G);break}case"update_template":{let G=Y.companyId,z=new Set(["companyId","templateId","name","subject","html","blocks","labels"]),J=Object.keys(Y).filter(($)=>!z.has($));if(J.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${J.length===1?"":"s"}: ${J.map(($)=>`\`${$}\``).join(", ")}.`);if(w1("update_template",Y),U6("update_template",Y),Y.name===void 0&&Y.subject===void 0&&Y.html===void 0&&Y.blocks===void 0&&Y.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `html`, `blocks`, or `labels` when calling `update_template`.");X=await N("PUT",`/api/v1/templates/${Y.templateId}`,Y,G);break}case"delete_template":{let G=Y.companyId;X=await N("DELETE",`/api/v1/templates/${Y.templateId}`,void 0,G);break}case"list_ab_tests":{let G=Y.companyId,z=new URLSearchParams,J=j(Y,"sequenceId");if(J)z.set("sequenceId",J);X=await N("GET",`/api/v1/ab-tests${z.size>0?`?${z}`:""}`,void 0,G);break}case"get_ab_test":{let G=Y.companyId;X=await N("GET",`/api/v1/ab-tests/${Y.abTestId}`,void 0,G);break}case"get_ab_test_stats":{let G=Y.companyId,z=new URLSearchParams,J=j(Y,"period"),$=j(Y,"start"),H=j(Y,"end");if(J)z.set("period",J);if($)z.set("start",$);if(H)z.set("end",H);X=await N("GET",`/api/v1/ab-tests/${Y.abTestId}/stats${z.size>0?`?${z}`:""}`,void 0,G);break}case"restart_ab_test":{let G=Y.companyId,z=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),J=Object.keys(Y).filter((U)=>!z.has(U));if(J.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${J.length===1?"":"s"}: ${J.map((U)=>`\`${U}\``).join(", ")}.`);let $=j(Y,"testType");if($!==void 0&&$!=="subject"&&$!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let H=Y.winnerThreshold===void 0?void 0:Number(Y.winnerThreshold);if(H!==void 0&&(!Number.isInteger(H)||H<10||H>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let A=Y.variantCount===void 0?void 0:Number(Y.variantCount);if(A!==void 0&&(!Number.isInteger(A)||A<2||A>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");X=await N("POST",`/api/v1/ab-tests/${Y.abTestId}/restart`,{sourceVariantId:j(Y,"sourceVariantId"),testType:$,winnerThreshold:H,variantCount:A},G);break}case"update_ab_test_variant":{let G=Y.companyId,z=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks"]),J=Object.keys(Y).filter(($)=>!z.has($));if(J.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${J.length===1?"":"s"}: ${J.map(($)=>`\`${$}\``).join(", ")}.`);if(w1("update_ab_test_variant",Y),Y.subject===void 0&&Y.previewText===void 0&&Y.html===void 0&&Y.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");X=await N("PATCH",`/api/v1/ab-tests/${Y.abTestId}/variants/${Y.variantId}`,Y,G);break}case"list_campaigns":{let G=Y.companyId,z=new URLSearchParams;if(Y.status)z.set("status",String(Y.status));let J=j(Y,"label");if(J)z.set("label",J);X=await N("GET",`/api/v1/campaigns?${z}`,void 0,G);break}case"get_campaign":{let G=Y.companyId;X=await N("GET",`/api/v1/campaigns/${Y.campaignId}`,void 0,G);break}case"get_email_send":{let G=Y.companyId;X=await N("GET",`/api/v1/email-sends/${encodeURIComponent(String(Y.emailSendId))}`,void 0,G);break}case"create_campaign":{let G=Y.companyId;vM(Y);let z=j(Y,"prompt");if(z!==void 0){let J=await N("POST","/api/v1/generate/email",{prompt:z,...Y.style!==void 0&&{style:Y.style},...Y.tone!==void 0&&{tone:Y.tone}},G),$=j(Y,"subject")??(typeof J.subject==="string"&&J.subject.trim()!==""?J.subject.trim():void 0);if(!$)throw Error("`create_campaign` prompt generation did not return a subject. Provide `subject` explicitly.");let H=Array.isArray(J.blocks)&&J.blocks.length>0?J.blocks:void 0,A=typeof J.html==="string"&&J.html.trim()!==""?J.html:void 0;if(H===void 0&&A===void 0)throw Error("`create_campaign` prompt generation did not return email blocks. Try again or provide `html` or `blocks` explicitly.");X=await N("POST","/api/v1/campaigns",{name:Y.name,subject:$,...H!==void 0?{blocks:H}:{html:A},...Y.segmentId!==void 0&&{segmentId:Y.segmentId},...Y.trackingCode!==void 0&&{trackingCode:Y.trackingCode},...Y.campaignData!==void 0&&{campaignData:Y.campaignData},...Y.computedLists!==void 0&&{computedLists:Y.computedLists},...Y.labels!==void 0&&{labels:Y.labels}},G);break}X=await N("POST","/api/v1/campaigns",Y,G);break}case"update_campaign":{let G=Y.companyId,z=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","replyTo","replyProfileId","campaignData","computedLists","labels"]),J=Object.keys(Y).filter(($)=>!z.has($));if(J.length>0)throw Error(`\`update_campaign\` accepts only \`name\`, \`subject\`, \`trackingCode\`, \`html\`, \`blocks\`, \`replyTo\`, \`replyProfileId\`, \`campaignData\`, \`computedLists\`, and \`labels\` update fields. Unsupported field${J.length===1?"":"s"}: ${J.map(($)=>`\`${$}\``).join(", ")}.`);if(w1("update_campaign",Y),U6("update_campaign",Y),Y.replyTo!==void 0&&Y.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_campaign`, not both.");if(Y.name===void 0&&Y.subject===void 0&&Y.trackingCode===void 0&&Y.html===void 0&&Y.blocks===void 0&&Y.replyTo===void 0&&Y.replyProfileId===void 0&&Y.campaignData===void 0&&Y.computedLists===void 0&&Y.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `trackingCode`, `html`, `blocks`, `replyTo`, `replyProfileId`, `campaignData`, `computedLists`, or `labels` when calling `update_campaign`.");X=await N("PUT",`/api/v1/campaigns/${Y.campaignId}`,Y,G);break}case"schedule_campaign":{let G=Y.companyId,z=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours"]),J=Object.keys(Y).filter(($)=>!z.has($));if(J.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, and \`spreadOverHours\`. Unsupported field${J.length===1?"":"s"}: ${J.map(($)=>`\`${$}\``).join(", ")}.`);kM(Y),X=await N("POST",`/api/v1/campaigns/${Y.campaignId}/schedule`,{scheduledAt:Y.scheduledAt,...Y.targetLists!==void 0&&{targetLists:Y.targetLists},...Y.sendTimeOptimization!==void 0&&{sendTimeOptimization:Y.sendTimeOptimization},...Y.spreadOverHours!==void 0&&{spreadOverHours:Y.spreadOverHours}},G);break}case"send_test_email":{let G=Y.companyId;X=await N("POST",`/api/v1/campaigns/${Y.campaignId}/test`,{to:Y.to},G);break}case"list_sequences":{let G=Y.companyId;X=await N("GET","/api/v1/sequences",void 0,G);break}case"get_sequence":{let G=Y.companyId;X=await N("GET",`/api/v1/sequences/${Y.sequenceId}`,void 0,G);break}case"create_sequence":{let G=Y.companyId,z=Array.isArray(Y.steps)&&Y.steps.length>0,J=await N("POST","/api/v1/sequences",Y,G);if(!J.success){X=J;break}let $=J.sequence.id;if(z){let D=await N("GET",`/api/v1/sequences/${$}`,void 0,G);if(D.success)X={success:!0,sequence:D.sequence,message:`Sequence "${D.sequence.name}" created with explicit steps. Review it before enabling.`};else X=D;break}let H=6,A=0,U="pending";while(U!=="complete"&&A<H){await new Promise((L)=>setTimeout(L,20000)),A++;let D=await N("GET",`/api/v1/sequences/${$}`,void 0,G);if(D.success)U=D.sequence.enrichmentStatus}let K=await N("GET",`/api/v1/sequences/${$}`,void 0,G);if(K.success)X={success:!0,sequence:K.sequence,message:K.sequence.enrichmentStatus==="complete"?`Sequence "${K.sequence.name}" created with ${K.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.`:`Sequence "${K.sequence.name}" created. Email enrichment is still in progress (${K.sequence.enrichedCount}/${K.sequence.emailCount} emails generated). You can check status with get_sequence.`};else X=K;break}case"update_sequence":{let G=Y.companyId,z=RM(Y);X=await N("PUT",`/api/v1/sequences/${Y.sequenceId}`,z,G);break}case"enable_sequence":{let G=Y.companyId;X=await N("POST",`/api/v1/sequences/${Y.sequenceId}/enable`,void 0,G);break}case"disable_sequence":{let G=Y.companyId;X=await N("POST",`/api/v1/sequences/${Y.sequenceId}/disable`,void 0,G);break}case"cancel_sequence_enrollments":{let G=Y.companyId,z=CM(Y);X=await N("POST",`/api/v1/sequences/${Y.sequenceId}/enrollments/cancel`,z,G);break}case"delete_sequence":{let G=Y.companyId;X=await N("DELETE",`/api/v1/sequences/${Y.sequenceId}`,void 0,G);break}case"list_transactional_emails":{let G=Y.companyId;X=await N("GET","/api/v1/transactional",void 0,G);break}case"get_transactional_email":{let G=Y.companyId;X=await N("GET",`/api/v1/transactional/${Y.idOrSlug}`,void 0,G);break}case"create_transactional_email":{let G=Y.companyId,z=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),J=Object.keys(Y).filter((A)=>!z.has(A));if(J.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${J.length===1?"":"s"}: ${J.map((A)=>`\`${A}\``).join(", ")}.`);xM(Y);let $=j(Y,"prompt");if($!==void 0){let A={companyId:G??B1()??"",name:typeof Y.name==="string"&&Y.name.trim()!==""?Y.name.trim():"",slug:typeof Y.slug==="string"&&Y.slug.trim()!==""?Y.slug.trim():"",promptLength:$.length,style:typeof Y.style==="string"?Y.style:"",tone:typeof Y.tone==="string"?Y.tone:""};try{console.error("[mcp:create_transactional_email] generating from prompt",A);let U=await N("POST","/api/v1/generate/email",{prompt:$,...Y.style!==void 0&&{style:Y.style},...Y.tone!==void 0&&{tone:Y.tone}},G);console.error("[mcp:create_transactional_email] prompt generation complete",{...A,subject:U.subject??"",previewTextLength:typeof U.previewText==="string"?U.previewText.length:0,blockCount:Array.isArray(U.blocks)?U.blocks.length:0,htmlLength:typeof U.html==="string"?U.html.length:0});let K=j(Y,"subject")??(typeof U.subject==="string"&&U.subject.trim()!==""?U.subject.trim():void 0);if(!K)throw Error("`create_transactional_email` prompt generation did not return a subject. Provide `subject` explicitly.");let D=Array.isArray(U.blocks)&&U.blocks.length>0?U.blocks:void 0,L=typeof U.html==="string"&&U.html.trim()!==""?U.html:void 0,q=j(Y,"previewText")??(typeof U.previewText==="string"?U.previewText.trim():void 0);if(D===void 0&&L===void 0)throw Error("`create_transactional_email` prompt generation did not return email blocks. Try again or provide `html` or `blocks` explicitly.");console.error("[mcp:create_transactional_email] creating generated transactional",{...A,subject:K,contentSource:D!==void 0?"blocks":"html",blockCount:D?.length??0,htmlLength:L?.length??0}),X=await N("POST","/api/v1/transactional",{name:Y.name,...Y.slug!==void 0&&{slug:Y.slug},subject:K,...q!==void 0&&{previewText:q},...D!==void 0?{blocks:D}:{html:L},...Y.enabled!==void 0&&{enabled:Y.enabled}},G),console.error("[mcp:create_transactional_email] generated transactional created",A)}catch(U){throw console.error("[mcp:create_transactional_email] prompt-based create failed",{...A,error:U instanceof Error?U.message:String(U)}),U}break}let H=Object.fromEntries(Object.entries(Y).filter(([A])=>A!=="companyId"));X=await N("POST","/api/v1/transactional",H,G);break}case"update_transactional_email":{let G=Y.companyId,z=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),J=Object.keys(Y).filter((H)=>!z.has(H));if(J.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${J.length===1?"":"s"}: ${J.map((H)=>`\`${H}\``).join(", ")}.`);if(w1("update_transactional_email",Y),Y.name===void 0&&Y.enabled===void 0&&Y.subject===void 0&&Y.previewText===void 0&&Y.html===void 0&&Y.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let $=Object.fromEntries(Object.entries(Y).filter(([H])=>H!=="companyId"&&H!=="idOrSlug"));X=await N("PATCH",`/api/v1/transactional/${Y.idOrSlug}`,$,G);break}case"send_email":{let G=Y.companyId;X=await N("POST","/api/v1/transactional/send",Y,G);break}case"get_stats":{let G=Y.companyId,z=Y.period??"7d";X=await N("GET",`/api/v1/metrics?period=${z}`,void 0,G);break}case"get_campaign_stats":{let G=Y.companyId;X=await N("GET",`/api/v1/metrics/campaigns/${Y.campaignId}`,void 0,G);break}case"get_sequence_stats":{let G=Y.companyId;X=await N("GET",`/api/v1/metrics/sequences/${Y.sequenceId}`,void 0,G);break}case"get_subscriber_activity":{let G=Y.companyId,z=f4("get_subscriber_activity",Y),J=await S9(z,G);X={success:J.success,email:J.subscriber.email,emailStats:J.subscriber.emailStats??null,activity:J.subscriber.activity??[],sequenceEnrollments:J.subscriber.sequenceEnrollments??[]};break}case"generate_email":{let G=Y.companyId;X=await N("POST","/api/v1/generate/email",Y,G);break}case"generate_sequence":{let G=Y.companyId;X=await N("POST","/api/v1/generate/sequence",Y,G);break}case"generate_subject_lines":{let G=Y.companyId;X=await N("POST","/api/v1/generate/subjects",Y,G);break}default:throw Error(`Unknown tool: ${Q}`)}let W=_M(X);if(W)throw W;return X=await cM(Q,Y,X),{content:[{type:"text",text:JSON.stringify(X,null,2)}]}}catch(X){return{isError:!0,content:[{type:"text",text:b1(X)}]}}}async function I5(Q,Y,X){let W=Y.getRequestContext?.(Q)??{};try{return await y9(W,X)}finally{await Y.onRequestContextUpdated?.(W,Q)}}function nI(Q={}){let Y=new E9({name:"sequenzy",version:$5.version},{capabilities:{tools:{},resources:{}}});return Y.setRequestHandler(LY,async()=>{return{tools:P5}}),Y.setRequestHandler(B4,async(X,W)=>{let{name:G,arguments:z}=X.params;return I5(W,Q,()=>j5(G,z??{}))}),Y.setRequestHandler($Y,async()=>{return{resources:U5}}),Y.setRequestHandler(AY,async(X,W)=>{let{uri:G}=X.params;return I5(W,Q,()=>K5(G))}),Y}export{nI as createSequenzyMcpServer};
|