@sequenzy/mcp 0.0.63 → 0.0.65
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 +3 -3
- package/dist/server.js +3 -3
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/server.js
CHANGED
|
@@ -25,7 +25,7 @@ var a5=Object.create;var{getPrototypeOf:s5,defineProperty:IQ,getOwnPropertyNames
|
|
|
25
25
|
newResult[${S}] = ${y}.value;
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
-
`)}D.write("payload.value = newResult;"),D.write("return payload;");let R=D.compile();return(T,y)=>R(K,T,y)},$,z=Z1,J=!s6.jitless,U=J&&CQ.value,A=Y.catchall,B;Q._zod.parse=(K,D)=>{B??(B=W.value);let O=K.value;if(!z(O))return K.issues.push({expected:"object",code:"invalid_type",input:O,inst:Q}),K;if(J&&U&&D?.async===!1&&D.jitless!==!0){if(!$)$=G(Y.shape);if(K=$(K,D),!A)return K;return e8([],O,K,D,B,Q)}return X(K,D)}});function q8(Q,Y,X,W){for(let $ of Q)if($.issues.length===0)return Y.value=$.value,Y;let G=Q.filter(($)=>!J1($));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map(($)=>$.issues.map((z)=>v0(z,W,I0())))}),Y}var cQ=F("$ZodUnion",(Q,Y)=>{o.init(Q,Y),i(Q._zod,"optin",()=>Y.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),i(Q._zod,"optout",()=>Y.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),i(Q._zod,"values",()=>{if(Y.options.every((G)=>G._zod.values))return new Set(Y.options.flatMap((G)=>Array.from(G._zod.values)));return}),i(Q._zod,"pattern",()=>{if(Y.options.every((G)=>G._zod.pattern)){let G=Y.options.map(($)=>$._zod.pattern);return new RegExp(`^(${G.map(($)=>W6($.source)).join("|")})$`)}return});let X=Y.options.length===1,W=Y.options[0]._zod.run;Q._zod.parse=(G,$)=>{if(X)return W(G,$);let z=!1,J=[];for(let H of Y.options){let U=H._zod.run({value:G.value,issues:[]},$);if(U instanceof Promise)J.push(U),z=!0;else{if(U.issues.length===0)return U;J.push(U)}}if(!z)return q8(J,G,Q,$);return Promise.all(J).then((H)=>{return q8(H,G,Q,$)})}}),YW=F("$ZodDiscriminatedUnion",(Q,Y)=>{cQ.init(Q,Y);let X=Q._zod.parse;i(Q._zod,"propValues",()=>{let G={};for(let $ of Y.options){let z=$._zod.propValues;if(!z||Object.keys(z).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf($)}"`);for(let[J,H]of Object.entries(z)){if(!G[J])G[J]=new Set;for(let U of H)G[J].add(U)}}return G});let W=k1(()=>{let G=Y.options,$=new Map;for(let z of G){let J=z._zod.propValues?.[Y.discriminator];if(!J||J.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(z)}"`);for(let H of J){if($.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);$.set(H,z)}}return $});Q._zod.parse=(G,$)=>{let z=G.value;if(!Z1(z))return G.issues.push({code:"invalid_type",expected:"object",input:z,inst:Q}),G;let J=W.value.get(z?.[Y.discriminator]);if(J)return J._zod.run(G,$);if(Y.unionFallback)return X(G,$);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,input:z,path:[Y.discriminator],inst:Q}),G}}),XW=F("$ZodIntersection",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value,$=Y.left._zod.run({value:G,issues:[]},W),z=Y.right._zod.run({value:G,issues:[]},W);if($ instanceof Promise||z instanceof Promise)return Promise.all([$,z]).then(([H,U])=>{return F8(X,H,U)});return F8(X,$,z)}});function lQ(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(z1(Q)&&z1(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter(($)=>X.indexOf($)!==-1),G={...Q,...Y};for(let $ of W){let z=lQ(Q[$],Y[$]);if(!z.valid)return{valid:!1,mergeErrorPath:[$,...z.mergeErrorPath]};G[$]=z.data}return{valid:!0,data:G}}if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let W=0;W<Q.length;W++){let G=Q[W],$=Y[W],z=lQ(G,$);if(!z.valid)return{valid:!1,mergeErrorPath:[W,...z.mergeErrorPath]};X.push(z.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function F8(Q,Y,X){if(Y.issues.length)Q.issues.push(...Y.issues);if(X.issues.length)Q.issues.push(...X.issues);if(J1(Q))return Q;let W=lQ(Y.value,X.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return Q.value=W.data,Q}var WW=F("$ZodRecord",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!z1(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let $=[];if(Y.keyType._zod.values){let z=Y.keyType._zod.values;X.value={};for(let H of z)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let U=Y.valueType._zod.run({value:G[H],issues:[]},W);if(U instanceof Promise)$.push(U.then((A)=>{if(A.issues.length)X.issues.push(...t0(H,A.issues));X.value[H]=A.value}));else{if(U.issues.length)X.issues.push(...t0(H,U.issues));X.value[H]=U.value}}let J;for(let H in G)if(!z.has(H))J=J??[],J.push(H);if(J&&J.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:J})}else{X.value={};for(let z of Reflect.ownKeys(G)){if(z==="__proto__")continue;let J=Y.keyType._zod.run({value:z,issues:[]},W);if(J instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(J.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:J.issues.map((U)=>v0(U,W,I0())),input:z,path:[z],inst:Q}),X.value[J.value]=J.value;continue}let H=Y.valueType._zod.run({value:G[z],issues:[]},W);if(H instanceof Promise)$.push(H.then((U)=>{if(U.issues.length)X.issues.push(...t0(z,U.issues));X.value[J.value]=U.value}));else{if(H.issues.length)X.issues.push(...t0(z,H.issues));X.value[J.value]=H.value}}}if($.length)return Promise.all($).then(()=>X);return X}});var GW=F("$ZodEnum",(Q,Y)=>{o.init(Q,Y);let X=SQ(Y.entries),W=new Set(X);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${X.filter((G)=>kQ.has(typeof G)).map((G)=>typeof G==="string"?o0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,$)=>{let z=G.value;if(W.has(z))return G;return G.issues.push({code:"invalid_value",values:X,input:z,inst:Q}),G}}),$W=F("$ZodLiteral",(Q,Y)=>{if(o.init(Q,Y),Y.values.length===0)throw Error("Cannot create literal schema with no valid values");Q._zod.values=new Set(Y.values),Q._zod.pattern=new RegExp(`^(${Y.values.map((X)=>typeof X==="string"?o0(X):X?o0(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 zW=F("$ZodTransform",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new Q6(Q.constructor.name);let G=Y.transform(X.value,X);if(W.async)return(G instanceof Promise?G:Promise.resolve(G)).then((z)=>{return X.value=z,X});if(G instanceof Promise)throw new d0;return X.value=G,X}});function O8(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var JW=F("$ZodOptional",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",i(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),i(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${W6(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(($)=>O8($,X.value));return O8(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),HW=F("$ZodNullable",(Q,Y)=>{o.init(Q,Y),i(Q._zod,"optin",()=>Y.innerType._zod.optin),i(Q._zod,"optout",()=>Y.innerType._zod.optout),i(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${W6(X.source)}|null)$`):void 0}),i(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)}}),UW=F("$ZodDefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",i(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(($)=>M8($,Y));return M8(G,Y)}});function M8(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var AW=F("$ZodPrefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",i(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)}}),BW=F("$ZodNonOptional",(Q,Y)=>{o.init(Q,Y),i(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(($)=>V8($,Q));return V8(G,Q)}});function V8(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 KW=F("$ZodCatch",(Q,Y)=>{o.init(Q,Y),i(Q._zod,"optin",()=>Y.innerType._zod.optin),i(Q._zod,"optout",()=>Y.innerType._zod.optout),i(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>{if(X.value=$.value,$.issues.length)X.value=Y.catchValue({...X,error:{issues:$.issues.map((z)=>v0(z,W,I0()))},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(($)=>v0($,W,I0()))},input:X.value}),X.issues=[];return X}});var DW=F("$ZodPipe",(Q,Y)=>{o.init(Q,Y),i(Q._zod,"values",()=>Y.in._zod.values),i(Q._zod,"optin",()=>Y.in._zod.optin),i(Q._zod,"optout",()=>Y.out._zod.optout),i(Q._zod,"propValues",()=>Y.in._zod.propValues),Q._zod.parse=(X,W)=>{if(W.direction==="backward"){let $=Y.out._zod.run(X,W);if($ instanceof Promise)return $.then((z)=>H4(z,Y.in,W));return H4($,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>H4($,Y.out,W));return H4(G,Y.out,W)}});function H4(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var LW=F("$ZodReadonly",(Q,Y)=>{o.init(Q,Y),i(Q._zod,"propValues",()=>Y.innerType._zod.propValues),i(Q._zod,"values",()=>Y.innerType._zod.values),i(Q._zod,"optin",()=>Y.innerType._zod.optin),i(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(N8);return N8(G)}});function N8(Q){return Q.value=Object.freeze(Q.value),Q}var qW=F("$ZodCustom",(Q,Y)=>{H0.init(Q,Y),o.init(Q,Y),Q._zod.parse=(X,W)=>{return X},Q._zod.check=(X)=>{let W=X.value,G=Y.fn(W);if(G instanceof Promise)return G.then(($)=>Z8($,X,W,Q));Z8(G,X,W,Q);return}});function Z8(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(v1(G))}}var pH=(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},iH=()=>{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 ${pH(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${X4(W.values[0])}`;return`Invalid option: expected one of ${e6(W.values,"|")}`;case"too_big":{let G=W.inclusive?"<=":"<",$=Y(W.origin);if($)return`Too big: expected ${W.origin??"value"} to have ${G}${W.maximum.toString()} ${$.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${G}${W.maximum.toString()}`}case"too_small":{let G=W.inclusive?">=":">",$=Y(W.origin);if($)return`Too small: expected ${W.origin} to have ${G}${W.minimum.toString()} ${$.unit}`;return`Too small: expected ${W.origin} to be ${G}${W.minimum.toString()}`}case"invalid_format":{let G=W;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${X[G.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${e6(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 pQ(){return{localeError:iH()}}var zN=Symbol("ZodOutput"),JN=Symbol("ZodInput");class FW{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 nH(){return new FW}var U6=nH();function OW(Q,Y){return new Q({type:"string",...E(Y)})}function MW(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...E(Y)})}function iQ(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...E(Y)})}function VW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...E(Y)})}function NW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...E(Y)})}function ZW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...E(Y)})}function wW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...E(Y)})}function jW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...E(Y)})}function PW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...E(Y)})}function bW(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...E(Y)})}function IW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...E(Y)})}function EW(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...E(Y)})}function TW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...E(Y)})}function SW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...E(Y)})}function RW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...E(Y)})}function CW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...E(Y)})}function kW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...E(Y)})}function vW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...E(Y)})}function xW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...E(Y)})}function _W(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...E(Y)})}function gW(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...E(Y)})}function yW(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...E(Y)})}function uW(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...E(Y)})}function hW(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...E(Y)})}function fW(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...E(Y)})}function lW(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...E(Y)})}function mW(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...E(Y)})}function cW(Q,Y){return new Q({type:"number",checks:[],...E(Y)})}function pW(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...E(Y)})}function iW(Q,Y){return new Q({type:"boolean",...E(Y)})}function nW(Q,Y){return new Q({type:"null",...E(Y)})}function rW(Q){return new Q({type:"unknown"})}function dW(Q,Y){return new Q({type:"never",...E(Y)})}function B4(Q,Y){return new uQ({check:"less_than",...E(Y),value:Q,inclusive:!1})}function A6(Q,Y){return new uQ({check:"less_than",...E(Y),value:Q,inclusive:!0})}function K4(Q,Y){return new hQ({check:"greater_than",...E(Y),value:Q,inclusive:!1})}function B6(Q,Y){return new hQ({check:"greater_than",...E(Y),value:Q,inclusive:!0})}function D4(Q,Y){return new Q8({check:"multiple_of",...E(Y),value:Q})}function L4(Q,Y){return new X8({check:"max_length",...E(Y),maximum:Q})}function x1(Q,Y){return new W8({check:"min_length",...E(Y),minimum:Q})}function q4(Q,Y){return new G8({check:"length_equals",...E(Y),length:Q})}function nQ(Q,Y){return new $8({check:"string_format",format:"regex",...E(Y),pattern:Q})}function rQ(Q){return new z8({check:"string_format",format:"lowercase",...E(Q)})}function dQ(Q){return new J8({check:"string_format",format:"uppercase",...E(Q)})}function oQ(Q,Y){return new H8({check:"string_format",format:"includes",...E(Y),includes:Q})}function tQ(Q,Y){return new U8({check:"string_format",format:"starts_with",...E(Y),prefix:Q})}function aQ(Q,Y){return new A8({check:"string_format",format:"ends_with",...E(Y),suffix:Q})}function w1(Q){return new B8({check:"overwrite",tx:Q})}function sQ(Q){return w1((Y)=>Y.normalize(Q))}function eQ(){return w1((Q)=>Q.trim())}function Q9(){return w1((Q)=>Q.toLowerCase())}function Y9(){return w1((Q)=>Q.toUpperCase())}function oW(Q,Y,X){return new Q({type:"array",element:Y,...E(X)})}function tW(Q,Y,X){let W=E(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function aW(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...E(X)})}function sW(Q){let Y=rH((X)=>{return X.addIssue=(W)=>{if(typeof W==="string")X.issues.push(v1(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(v1(G))}},Q(X.value,X)});return Y}function rH(Q,Y){let X=new H0({check:"custom",...E(Y)});return X._zod.check=Q,X}function _1(Q){return!!Q._zod}function H1(Q,Y){if(_1(Q))return z6(Q,Y);return Q.safeParse(Y)}function F4(Q){if(!Q)return;let Y;if(_1(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 eW(Q){if(_1(Q)){let $=Q._zod?.def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}}let X=Q._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let W=Q.value;if(W!==void 0)return W;return}var D6={};eY(D6,{time:()=>G9,duration:()=>$9,datetime:()=>X9,date:()=>W9,ZodISOTime:()=>XG,ZodISODuration:()=>WG,ZodISODateTime:()=>QG,ZodISODate:()=>YG});var QG=F("ZodISODateTime",(Q,Y)=>{v8.init(Q,Y),s.init(Q,Y)});function X9(Q){return hW(QG,Q)}var YG=F("ZodISODate",(Q,Y)=>{x8.init(Q,Y),s.init(Q,Y)});function W9(Q){return fW(YG,Q)}var XG=F("ZodISOTime",(Q,Y)=>{_8.init(Q,Y),s.init(Q,Y)});function G9(Q){return lW(XG,Q)}var WG=F("ZodISODuration",(Q,Y)=>{g8.init(Q,Y),s.init(Q,Y)});function $9(Q){return mW(WG,Q)}var GG=(Q,Y)=>{W4.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>qX(Q,X)},flatten:{value:(X)=>LX(Q,X)},addIssue:{value:(X)=>{Q.issues.push(X),Q.message=JSON.stringify(Q.issues,C1,2)}},addIssues:{value:(X)=>{Q.issues.push(...X),Q.message=JSON.stringify(Q.issues,C1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},nN=F("ZodError",GG),P0=F("ZodError",GG,{Parent:Error});var $G=G4(P0),zG=$4(P0),JG=$6(P0),HG=J6(P0),UG=FX(P0),AG=OX(P0),BG=MX(P0),KG=VX(P0),DG=NX(P0),LG=ZX(P0),qG=wX(P0),FG=jX(P0);var X0=F("ZodType",(Q,Y)=>{return o.init(Q,Y),Q.def=Y,Q.type=Y.type,Object.defineProperty(Q,"_def",{value:Y}),Q.check=(...X)=>{return Q.clone(m.mergeDefs(Y,{checks:[...Y.checks??[],...X.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},Q.clone=(X,W)=>k0(Q,X,W),Q.brand=()=>Q,Q.register=(X,W)=>{return X.add(Q,W),Q},Q.parse=(X,W)=>$G(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>JG(Q,X,W),Q.parseAsync=async(X,W)=>zG(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>HG(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>UG(Q,X,W),Q.decode=(X,W)=>AG(Q,X,W),Q.encodeAsync=async(X,W)=>BG(Q,X,W),Q.decodeAsync=async(X,W)=>KG(Q,X,W),Q.safeEncode=(X,W)=>DG(Q,X,W),Q.safeDecode=(X,W)=>LG(Q,X,W),Q.safeEncodeAsync=async(X,W)=>qG(Q,X,W),Q.safeDecodeAsync=async(X,W)=>FG(Q,X,W),Q.refine=(X,W)=>Q.check(c3(X,W)),Q.superRefine=(X)=>Q.check(p3(X)),Q.overwrite=(X)=>Q.check(w1(X)),Q.optional=()=>Y0(Q),Q.nullable=()=>VG(Q),Q.nullish=()=>Y0(VG(Q)),Q.nonoptional=(X)=>y3(Q,X),Q.array=()=>u(Q),Q.or=(X)=>d([Q,X]),Q.and=(X)=>M4(Q,X),Q.transform=(X)=>J9(Q,PG(X)),Q.default=(X)=>x3(Q,X),Q.prefault=(X)=>g3(Q,X),Q.catch=(X)=>h3(Q,X),Q.pipe=(X)=>J9(Q,X),Q.readonly=()=>m3(Q),Q.describe=(X)=>{let W=Q.clone();return U6.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return U6.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return U6.get(Q);let W=Q.clone();return U6.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),NG=F("_ZodString",(Q,Y)=>{A4.init(Q,Y),X0.init(Q,Y);let X=Q._zod.bag;Q.format=X.format??null,Q.minLength=X.minimum??null,Q.maxLength=X.maximum??null,Q.regex=(...W)=>Q.check(nQ(...W)),Q.includes=(...W)=>Q.check(oQ(...W)),Q.startsWith=(...W)=>Q.check(tQ(...W)),Q.endsWith=(...W)=>Q.check(aQ(...W)),Q.min=(...W)=>Q.check(x1(...W)),Q.max=(...W)=>Q.check(L4(...W)),Q.length=(...W)=>Q.check(q4(...W)),Q.nonempty=(...W)=>Q.check(x1(1,...W)),Q.lowercase=(W)=>Q.check(rQ(W)),Q.uppercase=(W)=>Q.check(dQ(W)),Q.trim=()=>Q.check(eQ()),Q.normalize=(...W)=>Q.check(sQ(...W)),Q.toLowerCase=()=>Q.check(Q9()),Q.toUpperCase=()=>Q.check(Y9())}),X3=F("ZodString",(Q,Y)=>{A4.init(Q,Y),NG.init(Q,Y),Q.email=(X)=>Q.check(MW(W3,X)),Q.url=(X)=>Q.check(jW(G3,X)),Q.jwt=(X)=>Q.check(uW(V3,X)),Q.emoji=(X)=>Q.check(PW($3,X)),Q.guid=(X)=>Q.check(iQ(OG,X)),Q.uuid=(X)=>Q.check(VW(O4,X)),Q.uuidv4=(X)=>Q.check(NW(O4,X)),Q.uuidv6=(X)=>Q.check(ZW(O4,X)),Q.uuidv7=(X)=>Q.check(wW(O4,X)),Q.nanoid=(X)=>Q.check(bW(z3,X)),Q.guid=(X)=>Q.check(iQ(OG,X)),Q.cuid=(X)=>Q.check(IW(J3,X)),Q.cuid2=(X)=>Q.check(EW(H3,X)),Q.ulid=(X)=>Q.check(TW(U3,X)),Q.base64=(X)=>Q.check(_W(F3,X)),Q.base64url=(X)=>Q.check(gW(O3,X)),Q.xid=(X)=>Q.check(SW(A3,X)),Q.ksuid=(X)=>Q.check(RW(B3,X)),Q.ipv4=(X)=>Q.check(CW(K3,X)),Q.ipv6=(X)=>Q.check(kW(D3,X)),Q.cidrv4=(X)=>Q.check(vW(L3,X)),Q.cidrv6=(X)=>Q.check(xW(q3,X)),Q.e164=(X)=>Q.check(yW(M3,X)),Q.datetime=(X)=>Q.check(X9(X)),Q.date=(X)=>Q.check(W9(X)),Q.time=(X)=>Q.check(G9(X)),Q.duration=(X)=>Q.check($9(X))});function q(Q){return OW(X3,Q)}var s=F("ZodStringFormat",(Q,Y)=>{t.init(Q,Y),NG.init(Q,Y)}),W3=F("ZodEmail",(Q,Y)=>{P8.init(Q,Y),s.init(Q,Y)});var OG=F("ZodGUID",(Q,Y)=>{w8.init(Q,Y),s.init(Q,Y)});var O4=F("ZodUUID",(Q,Y)=>{j8.init(Q,Y),s.init(Q,Y)});var G3=F("ZodURL",(Q,Y)=>{b8.init(Q,Y),s.init(Q,Y)});var $3=F("ZodEmoji",(Q,Y)=>{I8.init(Q,Y),s.init(Q,Y)});var z3=F("ZodNanoID",(Q,Y)=>{E8.init(Q,Y),s.init(Q,Y)});var J3=F("ZodCUID",(Q,Y)=>{T8.init(Q,Y),s.init(Q,Y)});var H3=F("ZodCUID2",(Q,Y)=>{S8.init(Q,Y),s.init(Q,Y)});var U3=F("ZodULID",(Q,Y)=>{R8.init(Q,Y),s.init(Q,Y)});var A3=F("ZodXID",(Q,Y)=>{C8.init(Q,Y),s.init(Q,Y)});var B3=F("ZodKSUID",(Q,Y)=>{k8.init(Q,Y),s.init(Q,Y)});var K3=F("ZodIPv4",(Q,Y)=>{y8.init(Q,Y),s.init(Q,Y)});var D3=F("ZodIPv6",(Q,Y)=>{u8.init(Q,Y),s.init(Q,Y)});var L3=F("ZodCIDRv4",(Q,Y)=>{h8.init(Q,Y),s.init(Q,Y)});var q3=F("ZodCIDRv6",(Q,Y)=>{f8.init(Q,Y),s.init(Q,Y)});var F3=F("ZodBase64",(Q,Y)=>{m8.init(Q,Y),s.init(Q,Y)});var O3=F("ZodBase64URL",(Q,Y)=>{c8.init(Q,Y),s.init(Q,Y)});var M3=F("ZodE164",(Q,Y)=>{p8.init(Q,Y),s.init(Q,Y)});var V3=F("ZodJWT",(Q,Y)=>{i8.init(Q,Y),s.init(Q,Y)});var ZG=F("ZodNumber",(Q,Y)=>{mQ.init(Q,Y),X0.init(Q,Y),Q.gt=(W,G)=>Q.check(K4(W,G)),Q.gte=(W,G)=>Q.check(B6(W,G)),Q.min=(W,G)=>Q.check(B6(W,G)),Q.lt=(W,G)=>Q.check(B4(W,G)),Q.lte=(W,G)=>Q.check(A6(W,G)),Q.max=(W,G)=>Q.check(A6(W,G)),Q.int=(W)=>Q.check(MG(W)),Q.safe=(W)=>Q.check(MG(W)),Q.positive=(W)=>Q.check(K4(0,W)),Q.nonnegative=(W)=>Q.check(B6(0,W)),Q.negative=(W)=>Q.check(B4(0,W)),Q.nonpositive=(W)=>Q.check(A6(0,W)),Q.multipleOf=(W,G)=>Q.check(D4(W,G)),Q.step=(W,G)=>Q.check(D4(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 p(Q){return cW(ZG,Q)}var N3=F("ZodNumberFormat",(Q,Y)=>{n8.init(Q,Y),ZG.init(Q,Y)});function MG(Q){return pW(N3,Q)}var Z3=F("ZodBoolean",(Q,Y)=>{r8.init(Q,Y),X0.init(Q,Y)});function z0(Q){return iW(Z3,Q)}var w3=F("ZodNull",(Q,Y)=>{d8.init(Q,Y),X0.init(Q,Y)});function H9(Q){return nW(w3,Q)}var j3=F("ZodUnknown",(Q,Y)=>{o8.init(Q,Y),X0.init(Q,Y)});function e(){return rW(j3)}var P3=F("ZodNever",(Q,Y)=>{t8.init(Q,Y),X0.init(Q,Y)});function b3(Q){return dW(P3,Q)}var I3=F("ZodArray",(Q,Y)=>{a8.init(Q,Y),X0.init(Q,Y),Q.element=Y.element,Q.min=(X,W)=>Q.check(x1(X,W)),Q.nonempty=(X)=>Q.check(x1(1,X)),Q.max=(X,W)=>Q.check(L4(X,W)),Q.length=(X,W)=>Q.check(q4(X,W)),Q.unwrap=()=>Q.element});function u(Q,Y){return oW(I3,Q,Y)}var wG=F("ZodObject",(Q,Y)=>{QW.init(Q,Y),X0.init(Q,Y),m.defineLazy(Q,"shape",()=>{return Y.shape}),Q.keyof=()=>M0(Object.keys(Q._zod.def.shape)),Q.catchall=(X)=>Q.clone({...Q._zod.def,catchall:X}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:b3()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(X)=>{return m.extend(Q,X)},Q.safeExtend=(X)=>{return m.safeExtend(Q,X)},Q.merge=(X)=>m.merge(Q,X),Q.pick=(X)=>m.pick(Q,X),Q.omit=(X)=>m.omit(Q,X),Q.partial=(...X)=>m.partial(bG,Q,X[0]),Q.required=(...X)=>m.required(IG,Q,X[0])});function P(Q,Y){let X={type:"object",shape:Q??{},...m.normalizeParams(Y)};return new wG(X)}function q0(Q,Y){return new wG({type:"object",shape:Q,catchall:e(),...m.normalizeParams(Y)})}var jG=F("ZodUnion",(Q,Y)=>{cQ.init(Q,Y),X0.init(Q,Y),Q.options=Y.options});function d(Q,Y){return new jG({type:"union",options:Q,...m.normalizeParams(Y)})}var E3=F("ZodDiscriminatedUnion",(Q,Y)=>{jG.init(Q,Y),YW.init(Q,Y)});function U9(Q,Y,X){return new E3({type:"union",options:Y,discriminator:Q,...m.normalizeParams(X)})}var T3=F("ZodIntersection",(Q,Y)=>{XW.init(Q,Y),X0.init(Q,Y)});function M4(Q,Y){return new T3({type:"intersection",left:Q,right:Y})}var S3=F("ZodRecord",(Q,Y)=>{WW.init(Q,Y),X0.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function Q0(Q,Y,X){return new S3({type:"record",keyType:Q,valueType:Y,...m.normalizeParams(X)})}var z9=F("ZodEnum",(Q,Y)=>{GW.init(Q,Y),X0.init(Q,Y),Q.enum=Y.entries,Q.options=Object.values(Y.entries);let X=new Set(Object.keys(Y.entries));Q.extract=(W,G)=>{let $={};for(let z of W)if(X.has(z))$[z]=Y.entries[z];else throw Error(`Key ${z} not found in enum`);return new z9({...Y,checks:[],...m.normalizeParams(G),entries:$})},Q.exclude=(W,G)=>{let $={...Y.entries};for(let z of W)if(X.has(z))delete $[z];else throw Error(`Key ${z} not found in enum`);return new z9({...Y,checks:[],...m.normalizeParams(G),entries:$})}});function M0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new z9({type:"enum",entries:X,...m.normalizeParams(Y)})}var R3=F("ZodLiteral",(Q,Y)=>{$W.init(Q,Y),X0.init(Q,Y),Q.values=new Set(Y.values),Object.defineProperty(Q,"value",{get(){if(Y.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return Y.values[0]}})});function b(Q,Y){return new R3({type:"literal",values:Array.isArray(Q)?Q:[Q],...m.normalizeParams(Y)})}var C3=F("ZodTransform",(Q,Y)=>{zW.init(Q,Y),X0.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new Q6(Q.constructor.name);X.addIssue=($)=>{if(typeof $==="string")X.issues.push(m.issue($,X.value,Y));else{let z=$;if(z.fatal)z.continue=!1;z.code??(z.code="custom"),z.input??(z.input=X.value),z.inst??(z.inst=Q),X.issues.push(m.issue(z))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then(($)=>{return X.value=$,X});return X.value=G,X}});function PG(Q){return new C3({type:"transform",transform:Q})}var bG=F("ZodOptional",(Q,Y)=>{JW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function Y0(Q){return new bG({type:"optional",innerType:Q})}var k3=F("ZodNullable",(Q,Y)=>{HW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function VG(Q){return new k3({type:"nullable",innerType:Q})}var v3=F("ZodDefault",(Q,Y)=>{UW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function x3(Q,Y){return new v3({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var _3=F("ZodPrefault",(Q,Y)=>{AW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function g3(Q,Y){return new _3({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var IG=F("ZodNonOptional",(Q,Y)=>{BW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function y3(Q,Y){return new IG({type:"nonoptional",innerType:Q,...m.normalizeParams(Y)})}var u3=F("ZodCatch",(Q,Y)=>{KW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function h3(Q,Y){return new u3({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var f3=F("ZodPipe",(Q,Y)=>{DW.init(Q,Y),X0.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function J9(Q,Y){return new f3({type:"pipe",in:Q,out:Y})}var l3=F("ZodReadonly",(Q,Y)=>{LW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function m3(Q){return new l3({type:"readonly",innerType:Q})}var EG=F("ZodCustom",(Q,Y)=>{qW.init(Q,Y),X0.init(Q,Y)});function TG(Q,Y){return tW(EG,Q??(()=>!0),Y)}function c3(Q,Y={}){return aW(EG,Q,Y)}function p3(Q){return sW(Q)}function A9(Q,Y){return J9(PG(Q),Y)}I0(pQ());var B9="2025-11-25";var SG=[B9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],U1="io.modelcontextprotocol/related-task",N4="2.0",U0=TG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),RG=d([q(),p().int()]),CG=q(),lZ=q0({ttl:d([p(),H9()]).optional(),pollInterval:p().optional()}),i3=P({ttl:p().optional()}),n3=P({taskId:q()}),K9=q0({progressToken:RG.optional(),[U1]:n3.optional()}),b0=P({_meta:K9.optional()}),L6=b0.extend({task:i3.optional()}),kG=(Q)=>L6.safeParse(Q).success,A0=P({method:q(),params:b0.loose().optional()}),E0=P({_meta:K9.optional()}),T0=P({method:q(),params:E0.loose().optional()}),B0=q0({_meta:K9.optional()}),Z4=d([q(),p().int()]),vG=P({jsonrpc:b(N4),id:Z4,...A0.shape}).strict(),D9=(Q)=>vG.safeParse(Q).success,xG=P({jsonrpc:b(N4),...T0.shape}).strict(),_G=(Q)=>xG.safeParse(Q).success,L9=P({jsonrpc:b(N4),id:Z4,result:B0}).strict(),q6=(Q)=>L9.safeParse(Q).success;var h;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(h||(h={}));var q9=P({jsonrpc:b(N4),id:Z4.optional(),error:P({code:p().int(),message:q(),data:e().optional()})}).strict();var gG=(Q)=>q9.safeParse(Q).success;var mZ=d([vG,xG,L9,q9]),cZ=d([L9,q9]),w4=B0.strict(),r3=E0.extend({requestId:Z4.optional(),reason:q().optional()}),j4=T0.extend({method:b("notifications/cancelled"),params:r3}),d3=P({src:q(),mimeType:q().optional(),sizes:u(q()).optional(),theme:M0(["light","dark"]).optional()}),F6=P({icons:u(d3).optional()}),g1=P({name:q(),title:q().optional()}),yG=g1.extend({...g1.shape,...F6.shape,version:q(),websiteUrl:q().optional(),description:q().optional()}),o3=M4(P({applyDefaults:z0().optional()}),Q0(q(),e())),t3=A9((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},M4(P({form:o3.optional(),url:U0.optional()}),Q0(q(),e()).optional())),a3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({sampling:q0({createMessage:U0.optional()}).optional(),elicitation:q0({create:U0.optional()}).optional()}).optional()}),s3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({tools:q0({call:U0.optional()}).optional()}).optional()}),e3=P({experimental:Q0(q(),U0).optional(),sampling:P({context:U0.optional(),tools:U0.optional()}).optional(),elicitation:t3.optional(),roots:P({listChanged:z0().optional()}).optional(),tasks:a3.optional()}),QU=b0.extend({protocolVersion:q(),capabilities:e3,clientInfo:yG}),F9=A0.extend({method:b("initialize"),params:QU});var YU=P({experimental:Q0(q(),U0).optional(),logging:U0.optional(),completions:U0.optional(),prompts:P({listChanged:z0().optional()}).optional(),resources:P({subscribe:z0().optional(),listChanged:z0().optional()}).optional(),tools:P({listChanged:z0().optional()}).optional(),tasks:s3.optional()}),XU=B0.extend({protocolVersion:q(),capabilities:YU,serverInfo:yG,instructions:q().optional()}),O9=T0.extend({method:b("notifications/initialized"),params:E0.optional()});var P4=A0.extend({method:b("ping"),params:b0.optional()}),WU=P({progress:p(),total:Y0(p()),message:Y0(q())}),GU=P({...E0.shape,...WU.shape,progressToken:RG}),b4=T0.extend({method:b("notifications/progress"),params:GU}),$U=b0.extend({cursor:CG.optional()}),O6=A0.extend({params:$U.optional()}),M6=B0.extend({nextCursor:CG.optional()}),zU=M0(["working","input_required","completed","failed","cancelled"]),V6=P({taskId:q(),status:zU,ttl:d([p(),H9()]),createdAt:q(),lastUpdatedAt:q(),pollInterval:Y0(p()),statusMessage:Y0(q())}),y1=B0.extend({task:V6}),JU=E0.merge(V6),N6=T0.extend({method:b("notifications/tasks/status"),params:JU}),I4=A0.extend({method:b("tasks/get"),params:b0.extend({taskId:q()})}),E4=B0.merge(V6),T4=A0.extend({method:b("tasks/result"),params:b0.extend({taskId:q()})}),pZ=B0.loose(),S4=O6.extend({method:b("tasks/list")}),R4=M6.extend({tasks:u(V6)}),C4=A0.extend({method:b("tasks/cancel"),params:b0.extend({taskId:q()})}),uG=B0.merge(V6),hG=P({uri:q(),mimeType:Y0(q()),_meta:Q0(q(),e()).optional()}),fG=hG.extend({text:q()}),M9=q().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),lG=hG.extend({blob:M9}),Z6=M0(["user","assistant"]),u1=P({audience:u(Z6).optional(),priority:p().min(0).max(1).optional(),lastModified:D6.datetime({offset:!0}).optional()}),mG=P({...g1.shape,...F6.shape,uri:q(),description:Y0(q()),mimeType:Y0(q()),annotations:u1.optional(),_meta:Y0(q0({}))}),HU=P({...g1.shape,...F6.shape,uriTemplate:q(),description:Y0(q()),mimeType:Y0(q()),annotations:u1.optional(),_meta:Y0(q0({}))}),V9=O6.extend({method:b("resources/list")}),UU=M6.extend({resources:u(mG)}),AU=O6.extend({method:b("resources/templates/list")}),BU=M6.extend({resourceTemplates:u(HU)}),N9=b0.extend({uri:q()}),KU=N9,Z9=A0.extend({method:b("resources/read"),params:KU}),DU=B0.extend({contents:u(d([fG,lG]))}),LU=T0.extend({method:b("notifications/resources/list_changed"),params:E0.optional()}),qU=N9,FU=A0.extend({method:b("resources/subscribe"),params:qU}),OU=N9,MU=A0.extend({method:b("resources/unsubscribe"),params:OU}),VU=E0.extend({uri:q()}),NU=T0.extend({method:b("notifications/resources/updated"),params:VU}),ZU=P({name:q(),description:Y0(q()),required:Y0(z0())}),wU=P({...g1.shape,...F6.shape,description:Y0(q()),arguments:Y0(u(ZU)),_meta:Y0(q0({}))}),jU=O6.extend({method:b("prompts/list")}),PU=M6.extend({prompts:u(wU)}),bU=b0.extend({name:q(),arguments:Q0(q(),q()).optional()}),IU=A0.extend({method:b("prompts/get"),params:bU}),w9=P({type:b("text"),text:q(),annotations:u1.optional(),_meta:Q0(q(),e()).optional()}),j9=P({type:b("image"),data:M9,mimeType:q(),annotations:u1.optional(),_meta:Q0(q(),e()).optional()}),P9=P({type:b("audio"),data:M9,mimeType:q(),annotations:u1.optional(),_meta:Q0(q(),e()).optional()}),EU=P({type:b("tool_use"),name:q(),id:q(),input:Q0(q(),e()),_meta:Q0(q(),e()).optional()}),TU=P({type:b("resource"),resource:d([fG,lG]),annotations:u1.optional(),_meta:Q0(q(),e()).optional()}),SU=mG.extend({type:b("resource_link")}),b9=d([w9,j9,P9,SU,TU]),RU=P({role:Z6,content:b9}),CU=B0.extend({description:q().optional(),messages:u(RU)}),kU=T0.extend({method:b("notifications/prompts/list_changed"),params:E0.optional()}),vU=P({title:q().optional(),readOnlyHint:z0().optional(),destructiveHint:z0().optional(),idempotentHint:z0().optional(),openWorldHint:z0().optional()}),xU=P({taskSupport:M0(["required","optional","forbidden"]).optional()}),cG=P({...g1.shape,...F6.shape,description:q().optional(),inputSchema:P({type:b("object"),properties:Q0(q(),U0).optional(),required:u(q()).optional()}).catchall(e()),outputSchema:P({type:b("object"),properties:Q0(q(),U0).optional(),required:u(q()).optional()}).catchall(e()).optional(),annotations:vU.optional(),execution:xU.optional(),_meta:Q0(q(),e()).optional()}),I9=O6.extend({method:b("tools/list")}),_U=M6.extend({tools:u(cG)}),k4=B0.extend({content:u(b9).default([]),structuredContent:Q0(q(),e()).optional(),isError:z0().optional()}),iZ=k4.or(B0.extend({toolResult:e()})),gU=L6.extend({name:q(),arguments:Q0(q(),e()).optional()}),w6=A0.extend({method:b("tools/call"),params:gU}),yU=T0.extend({method:b("notifications/tools/list_changed"),params:E0.optional()}),nZ=P({autoRefresh:z0().default(!0),debounceMs:p().int().nonnegative().default(300)}),j6=M0(["debug","info","notice","warning","error","critical","alert","emergency"]),uU=b0.extend({level:j6}),E9=A0.extend({method:b("logging/setLevel"),params:uU}),hU=E0.extend({level:j6,logger:q().optional(),data:e()}),fU=T0.extend({method:b("notifications/message"),params:hU}),lU=P({name:q().optional()}),mU=P({hints:u(lU).optional(),costPriority:p().min(0).max(1).optional(),speedPriority:p().min(0).max(1).optional(),intelligencePriority:p().min(0).max(1).optional()}),cU=P({mode:M0(["auto","required","none"]).optional()}),pU=P({type:b("tool_result"),toolUseId:q().describe("The unique identifier for the corresponding tool call."),content:u(b9).default([]),structuredContent:P({}).loose().optional(),isError:z0().optional(),_meta:Q0(q(),e()).optional()}),iU=U9("type",[w9,j9,P9]),V4=U9("type",[w9,j9,P9,EU,pU]),nU=P({role:Z6,content:d([V4,u(V4)]),_meta:Q0(q(),e()).optional()}),rU=L6.extend({messages:u(nU),modelPreferences:mU.optional(),systemPrompt:q().optional(),includeContext:M0(["none","thisServer","allServers"]).optional(),temperature:p().optional(),maxTokens:p().int(),stopSequences:u(q()).optional(),metadata:U0.optional(),tools:u(cG).optional(),toolChoice:cU.optional()}),dU=A0.extend({method:b("sampling/createMessage"),params:rU}),T9=B0.extend({model:q(),stopReason:Y0(M0(["endTurn","stopSequence","maxTokens"]).or(q())),role:Z6,content:iU}),S9=B0.extend({model:q(),stopReason:Y0(M0(["endTurn","stopSequence","maxTokens","toolUse"]).or(q())),role:Z6,content:d([V4,u(V4)])}),oU=P({type:b("boolean"),title:q().optional(),description:q().optional(),default:z0().optional()}),tU=P({type:b("string"),title:q().optional(),description:q().optional(),minLength:p().optional(),maxLength:p().optional(),format:M0(["email","uri","date","date-time"]).optional(),default:q().optional()}),aU=P({type:M0(["number","integer"]),title:q().optional(),description:q().optional(),minimum:p().optional(),maximum:p().optional(),default:p().optional()}),sU=P({type:b("string"),title:q().optional(),description:q().optional(),enum:u(q()),default:q().optional()}),eU=P({type:b("string"),title:q().optional(),description:q().optional(),oneOf:u(P({const:q(),title:q()})),default:q().optional()}),QA=P({type:b("string"),title:q().optional(),description:q().optional(),enum:u(q()),enumNames:u(q()).optional(),default:q().optional()}),YA=d([sU,eU]),XA=P({type:b("array"),title:q().optional(),description:q().optional(),minItems:p().optional(),maxItems:p().optional(),items:P({type:b("string"),enum:u(q())}),default:u(q()).optional()}),WA=P({type:b("array"),title:q().optional(),description:q().optional(),minItems:p().optional(),maxItems:p().optional(),items:P({anyOf:u(P({const:q(),title:q()}))}),default:u(q()).optional()}),GA=d([XA,WA]),$A=d([QA,YA,GA]),zA=d([$A,oU,tU,aU]),JA=L6.extend({mode:b("form").optional(),message:q(),requestedSchema:P({type:b("object"),properties:Q0(q(),zA),required:u(q()).optional()})}),HA=L6.extend({mode:b("url"),message:q(),elicitationId:q(),url:q().url()}),UA=d([JA,HA]),AA=A0.extend({method:b("elicitation/create"),params:UA}),BA=E0.extend({elicitationId:q()}),KA=T0.extend({method:b("notifications/elicitation/complete"),params:BA}),v4=B0.extend({action:M0(["accept","decline","cancel"]),content:A9((Q)=>Q===null?void 0:Q,Q0(q(),d([q(),p(),z0(),u(q())])).optional())}),DA=P({type:b("ref/resource"),uri:q()});var LA=P({type:b("ref/prompt"),name:q()}),qA=b0.extend({ref:d([LA,DA]),argument:P({name:q(),value:q()}),context:P({arguments:Q0(q(),q()).optional()}).optional()}),FA=A0.extend({method:b("completion/complete"),params:qA});var OA=B0.extend({completion:q0({values:u(q()).max(100),total:Y0(p().int()),hasMore:Y0(z0())})}),MA=P({uri:q().startsWith("file://"),name:q().optional(),_meta:Q0(q(),e()).optional()}),VA=A0.extend({method:b("roots/list"),params:b0.optional()}),R9=B0.extend({roots:u(MA)}),NA=T0.extend({method:b("notifications/roots/list_changed"),params:E0.optional()}),rZ=d([P4,F9,FA,E9,IU,jU,V9,AU,Z9,FU,MU,w6,I9,I4,T4,S4,C4]),dZ=d([j4,b4,O9,NA,N6]),oZ=d([w4,T9,S9,v4,R9,E4,R4,y1]),tZ=d([P4,dU,AA,VA,I4,T4,S4,C4]),aZ=d([j4,b4,fU,NU,LU,yU,kU,N6,KA]),sZ=d([w4,XU,OA,CU,PU,UU,BU,DU,k4,_U,E4,R4,y1]);class _ extends Error{constructor(Q,Y,X){super(`MCP error ${Q}: ${Y}`);this.code=Q,this.data=X,this.name="McpError"}static fromError(Q,Y,X){if(Q===h.UrlElicitationRequired&&X){let W=X;if(W.elicitations)return new pG(W.elicitations,Y)}return new _(Q,Y,X)}}class pG extends _{constructor(Q,Y=`URL elicitation${Q.length>1?"s":""} required`){super(h.UrlElicitationRequired,Y,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function A1(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var ZA=Symbol("Let zodToJsonSchema decide on which parser to use");var Cw=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function C9(Q){let X=F4(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=eW(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function k9(Q,Y){let X=H1(Q,Y);if(!X.success)throw X.error;return X.data}var EA=60000;class v9{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(j4,(Y)=>{this._oncancel(Y)}),this.setNotificationHandler(b4,(Y)=>{this._onprogress(Y)}),this.setRequestHandler(P4,(Y)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(I4,async(Y,X)=>{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(T4,async(Y,X)=>{let W=async()=>{let G=Y.params.taskId;if(this._taskMessageQueue){let z;while(z=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(z.type==="response"||z.type==="error"){let J=z.message,H=J.id,U=this._requestResolvers.get(H);if(U)if(this._requestResolvers.delete(H),z.type==="response")U(J);else{let A=J,B=new _(A.error.code,A.error.message,A.error.data);U(B)}else{let A=z.type==="response"?"Response":"Error";this._onerror(Error(`${A} handler missing for request ${H}`))}continue}await this._transport?.send(z.message,{relatedRequestId:X.requestId})}}let $=await this._taskStore.getTask(G,X.sessionId);if(!$)throw new _(h.InvalidParams,`Task not found: ${G}`);if(!A1($.status))return await this._waitForTaskUpdate(G,X.signal),await W();if(A1($.status)){let z=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...z,_meta:{...z._meta,[U1]:{taskId:G}}}}return await W()};return await W()}),this.setRequestHandler(S4,async(Y,X)=>{try{let{tasks:W,nextCursor:G}=await this._taskStore.listTasks(Y.params?.cursor,X.sessionId);return{tasks:W,nextCursor:G,_meta:{}}}catch(W){throw new _(h.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(C4,async(Y,X)=>{try{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,`Task not found: ${Y.params.taskId}`);if(A1(W.status))throw new _(h.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(Y.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Y.params.taskId);let G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new _(h.InvalidParams,`Task not found after cancellation: ${Y.params.taskId}`);return{_meta:{},...G}}catch(W){if(W instanceof _)throw W;throw new _(h.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,Y,X,W,G=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,Y),startTime:Date.now(),timeout:Y,maxTotalTimeout:X,resetTimeoutOnProgress:G,onTimeout:W})}_resetTimeout(Q){let Y=this._timeoutInfo.get(Q);if(!Y)return!1;let X=Date.now()-Y.startTime;if(Y.maxTotalTimeout&&X>=Y.maxTotalTimeout)throw this._timeoutInfo.delete(Q),_.fromError(h.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Y.maxTotalTimeout,totalElapsed:X});return clearTimeout(Y.timeoutId),Y.timeoutId=setTimeout(Y.onTimeout,Y.timeout),!0}_cleanupTimeout(Q){let Y=this._timeoutInfo.get(Q);if(Y)clearTimeout(Y.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let Y=this.transport?.onclose;this._transport.onclose=()=>{Y?.(),this._onclose()};let X=this.transport?.onerror;this._transport.onerror=(G)=>{X?.(G),this._onerror(G)};let W=this._transport?.onmessage;this._transport.onmessage=(G,$)=>{if(W?.(G,$),q6(G)||gG(G))this._onresponse(G);else if(D9(G))this._onrequest(G,$);else if(_G(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let Y=_.fromError(h.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of Q.values())X(Y)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let Y=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(Y===void 0)return;Promise.resolve().then(()=>Y(Q)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(Q,Y){let X=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,G=Q.params?._meta?.[U1]?.taskId;if(X===void 0){let U={jsonrpc:"2.0",id:Q.id,error:{code:h.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId).catch((A)=>this._onerror(Error(`Failed to enqueue error response: ${A}`)));else W?.send(U).catch((A)=>this._onerror(Error(`Failed to send an error response: ${A}`)));return}let $=new AbortController;this._requestHandlerAbortControllers.set(Q.id,$);let z=kG(Q.params)?Q.params.task:void 0,J=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:$.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(U)=>{let A={relatedRequestId:Q.id};if(G)A.relatedTask={taskId:G};await this.notification(U,A)},sendRequest:async(U,A,B)=>{let K={...B,relatedRequestId:Q.id};if(G&&!K.relatedTask)K.relatedTask={taskId:G};let D=K.relatedTask?.taskId??G;if(D&&J)await J.updateTaskStatus(D,"input_required");return await this.request(U,A,K)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:J,taskRequestedTtl:z?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(z)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(U)=>{if($.signal.aborted)return;let A={result:U,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)},async(U)=>{if($.signal.aborted)return;let A={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(U.code)?U.code:h.InternalError,message:U.message??"Internal error",...U.data!==void 0&&{data:U.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)}).catch((U)=>this._onerror(Error(`Failed to send response: ${U}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:Y,...X}=Q.params,W=Number(Y),G=this._progressHandlers.get(W);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let $=this._responseHandlers.get(W),z=this._timeoutInfo.get(W);if(z&&$&&z.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(J){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),$(J);return}G(X)}_onresponse(Q){let Y=Number(Q.id),X=this._requestResolvers.get(Y);if(X){if(this._requestResolvers.delete(Y),q6(Q))X(Q);else{let $=new _(Q.error.code,Q.error.message,Q.error.data);X($)}return}let W=this._responseHandlers.get(Y);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(Y),this._cleanupTimeout(Y);let G=!1;if(q6(Q)&&Q.result&&typeof Q.result==="object"){let $=Q.result;if($.task&&typeof $.task==="object"){let z=$.task;if(typeof z.taskId==="string")G=!0,this._taskProgressTokens.set(z.taskId,Y)}}if(!G)this._progressHandlers.delete(Y);if(q6(Q))W(Q);else{let $=_.fromError(Q.error.code,Q.error.message,Q.error.data);W($)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,Y,X){let{task:W}=X??{};if(!W){try{yield{type:"result",result:await this.request(Q,Y,X)}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}return}let G;try{let $=await this.request(Q,y1,X);if($.task)G=$.task.taskId,yield{type:"taskCreated",task:$.task};else throw new _(h.InternalError,"Task creation did not return a task");while(!0){let z=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:z},A1(z.status)){if(z.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(z.status==="failed")yield{type:"error",error:new _(h.InternalError,`Task ${G} failed`)};else if(z.status==="cancelled")yield{type:"error",error:new _(h.InternalError,`Task ${G} was cancelled`)};return}if(z.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let J=z.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,J)),X?.signal?.throwIfAborted()}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$,task:z,relatedTask:J}=X??{};return new Promise((H,U)=>{let A=(V)=>{U(V)};if(!this._transport){A(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),z)this.assertTaskCapability(Q.method)}catch(V){A(V);return}X?.signal?.throwIfAborted();let B=this._requestMessageId++,K={...Q,jsonrpc:"2.0",id:B};if(X?.onprogress)this._progressHandlers.set(B,X.onprogress),K.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:B}};if(z)K.params={...K.params,task:z};if(J)K.params={...K.params,_meta:{...K.params?._meta||{},[U1]:J}};let D=(V)=>{this._responseHandlers.delete(B),this._progressHandlers.delete(B),this._cleanupTimeout(B),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:B,reason:String(V)}},{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((T)=>this._onerror(Error(`Failed to send cancellation: ${T}`)));let R=V instanceof _?V:new _(h.RequestTimeout,String(V));U(R)};this._responseHandlers.set(B,(V)=>{if(X?.signal?.aborted)return;if(V instanceof Error)return U(V);try{let R=H1(Y,V.result);if(!R.success)U(R.error);else H(R.data)}catch(R){U(R)}}),X?.signal?.addEventListener("abort",()=>{D(X?.signal?.reason)});let O=X?.timeout??EA,M=()=>D(_.fromError(h.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(B,O,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let Z=J?.taskId;if(Z){let V=(R)=>{let T=this._responseHandlers.get(B);if(T)T(R);else this._onerror(Error(`Response handler missing for side-channeled request ${B}`))};this._requestResolvers.set(B,V),this._enqueueTaskMessage(Z,{type:"request",message:K,timestamp:Date.now()}).catch((R)=>{this._cleanupTimeout(B),U(R)})}else this._transport.send(K,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((V)=>{this._cleanupTimeout(B),U(V)})})}async getTask(Q,Y){return this.request({method:"tasks/get",params:Q},E4,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},R4,Y)}async cancelTask(Q,Y){return this.request({method:"tasks/cancel",params:Q},uG,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let z={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[U1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:z,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!Y?.relatedRequestId&&!Y?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let z={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)z={...z,params:{...z.params,_meta:{...z.params?._meta||{},[U1]:Y.relatedTask}}};this._transport?.send(z,Y).catch((J)=>this._onerror(J))});return}let $={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)$={...$,params:{...$.params,_meta:{...$.params?._meta||{},[U1]:Y.relatedTask}}};await this._transport.send($,Y)}setRequestHandler(Q,Y){let X=C9(Q);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(W,G)=>{let $=k9(Q,W);return Promise.resolve(Y($,G))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,Y){let X=C9(Q);this._notificationHandlers.set(X,(W)=>{let G=k9(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"&&D9(W.message)){let G=W.message.id,$=this._requestResolvers.get(G);if($)$(new _(h.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,Y){let X=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)X=W.pollInterval}catch{}return new Promise((W,G)=>{if(Y.aborted){G(new _(h.InvalidRequest,"Request cancelled"));return}let $=setTimeout(W,X);Y.addEventListener("abort",()=>{clearTimeout($),G(new _(h.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,Y){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await X.createTask(W,Q.id,{method:Q.method,params:Q.params},Y)},getTask:async(W)=>{let G=await X.getTask(W,Y);if(!G)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(W,G,$)=>{await X.storeTaskResult(W,G,$,Y);let z=await X.getTask(W,Y);if(z){let J=N6.parse({method:"notifications/tasks/status",params:z});if(await this.notification(J),A1(z.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,$)=>{let z=await X.getTask(W,Y);if(!z)throw new _(h.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(A1(z.status))throw new _(h.InvalidParams,`Cannot update task "${W}" from terminal status "${z.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,$,Y);let J=await X.getTask(W,Y);if(J){let H=N6.parse({method:"notifications/tasks/status",params:J});if(await this.notification(H),A1(J.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function iG(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function nG(Q,Y){let X={...Q};for(let W in Y){let G=W,$=Y[G];if($===void 0)continue;let z=X[G];if(iG(z)&&iG($))X[G]={...z,...$};else X[G]=$}return X}var j5=sY(EY(),1),P5=sY(w5(),1);function gM(){let Q=new j5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return P5.default(Q),Q}class yY{constructor(Q){this._ajv=Q??gM()}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 uY{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 b5(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 I5(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 hY extends v9{constructor(Q,Y){super(Y);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(j6.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 yY,this.setRequestHandler(F9,(X)=>this._oninitialize(X)),this.setNotificationHandler(O9,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(E9,async(X,W)=>{let G=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:$}=X.params,z=j6.safeParse($);if(z.success)this._loggingLevels.set(G,z.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new uY(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=nG(this._capabilities,Q)}setRequestHandler(Q,Y){let W=F4(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let G;if(_1(W)){let z=W;G=z._zod?.def?.value??z.value}else{let z=W;G=z._def?.value??z.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let z=async(J,H)=>{let U=H1(w6,J);if(!U.success){let D=U.error instanceof Error?U.error.message:String(U.error);throw new _(h.InvalidParams,`Invalid tools/call request: ${D}`)}let{params:A}=U.data,B=await Promise.resolve(Y(J,H));if(A.task){let D=H1(y1,B);if(!D.success){let O=D.error instanceof Error?D.error.message:String(D.error);throw new _(h.InvalidParams,`Invalid task creation result: ${O}`)}return D.data}let K=H1(k4,B);if(!K.success){let D=K.error instanceof Error?K.error.message:String(K.error);throw new _(h.InvalidParams,`Invalid tools/call result: ${D}`)}return K.data};return super.setRequestHandler(Q,z)}return super.setRequestHandler(Q,Y)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){I5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;b5(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:SG.includes(Y)?Y:B9,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},w4)}async createMessage(Q,Y){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let X=Q.messages[Q.messages.length-1],W=Array.isArray(X.content)?X.content:[X.content],G=W.some((H)=>H.type==="tool_result"),$=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,z=$?Array.isArray($.content)?$.content:[$.content]:[],J=z.some((H)=>H.type==="tool_use");if(G){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!J)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(J){let H=new Set(z.filter((A)=>A.type==="tool_use").map((A)=>A.id)),U=new Set(W.filter((A)=>A.type==="tool_result").map((A)=>A.toolUseId));if(H.size!==U.size||![...H].every((A)=>U.has(A)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},S9,Y);return this.request({method:"sampling/createMessage",params:Q},T9,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},v4,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},v4,Y);if(G.action==="accept"&&G.content&&W.requestedSchema)try{let z=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!z.valid)throw new _(h.InvalidParams,`Elicitation response content does not match requested schema: ${z.errorMessage}`)}catch($){if($ instanceof _)throw $;throw new _(h.InternalError,`Error validating elicitation response: ${$ instanceof Error?$.message:String($)}`)}return G}}}createElicitationCompletionNotifier(Q,Y){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},Y)}async listRoots(Q,Y){return this.request({method:"roots/list",params:Q},R9,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 E5={name:"@sequenzy/mcp",version:"0.0.63",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 fY=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],T5={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",landingPages:"/dashboard/company/{companyId}/landing-pages",landingPage:"/dashboard/company/{companyId}/landing-pages/{landingPageId}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function uM(Q){let X=(Q??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return X.length>0?X:"https://sequenzy.com"}function f0(Q){let Y=Q?.trim();return Y?Y:void 0}function n0(Q){return encodeURIComponent(Q)}function G0(Q,Y){return`${Q}${Y}`}function $0(Q,Y=""){return`/dashboard/company/${n0(Q)}${Y}`}function S5(Q,Y,X){return G0(Q,`${$0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function hM(Q,Y){let X=fY.map((W)=>[W,Y?S5(Q,Y,W):""]);return Object.fromEntries(X)}function M1(Q={},Y){let X=uM(Y),W=f0(Q.companyId),G={},$=hM(X,W);if(!W)return{appUrl:X,routeTemplates:T5,settingsTabValues:fY,urls:G,settingsUrls:$};G.dashboard=G0(X,$0(W)),G.campaigns=G0(X,$0(W,"/campaign")),G.landingPages=G0(X,$0(W,"/landing-pages")),G.sequences=G0(X,$0(W,"/sequences")),G.settings=G0(X,$0(W,"/settings")),G.emails=G0(X,$0(W,"/emails")),G.subscribers=G0(X,$0(W,"/subscribers")),G.sentEmails=G0(X,$0(W,"/sent-emails")),G.segments=G0(X,$0(W,"/segments")),G.metrics=G0(X,$0(W,"/metrics")),G.transactional=G0(X,$0(W,"/transactional"));let z=f0(Q.campaignId);if(z)G.campaign=G0(X,$0(W,`/campaign/${n0(z)}`)),G.campaignPreview=`${G.campaign}?step=review`;let J=f0(Q.landingPageId);if(J)G.landingPage=G0(X,$0(W,`/landing-pages/${n0(J)}`));let H=f0(Q.sequenceId);if(H)G.sequence=G0(X,$0(W,`/sequences/${n0(H)}`));let U=f0(Q.emailId)??f0(Q.templateId);if(U)G.email=G0(X,$0(W,`/emails/${n0(U)}`)),G.template=G.email;let A=f0(Q.transactionalId);if(A)G.transactionalEmail=G0(X,$0(W,`/transactional/${n0(A)}`));let B=f0(Q.emailSendId);if(B)G.emailSend=G0(X,$0(W,`/sent-emails/${n0(B)}`));let K=f0(Q.domainId);if(K)G.domain=G0(X,$0(W,`/settings/domain/${n0(K)}`)),G.domainVerify=`${G.domain}/verify`;let D=f0(Q.status);if(D)G.campaignList=G0(X,$0(W,`/campaign/list/${n0(D)}`)),G.sequenceList=G0(X,$0(W,`/sequences/list/${n0(D)}`));let O=f0(Q.settingsTab);if(O)G.settingsTab=S5(X,W,O);return{appUrl:X,routeTemplates:T5,settingsTabValues:fY,urls:G,settingsUrls:$}}var R5=[{uri:"sequenzy://dashboard",name:"Dashboard Overview",description:"Live overview stats for the last 7 days",mimeType:"application/json"},{uri:"sequenzy://company",name:"Current Company",description:"The currently selected company, including localization settings",mimeType:"application/json"},{uri:"sequenzy://campaigns/recent",name:"Recent Campaigns",description:"Last 10 campaigns with status and basic stats",mimeType:"application/json"},{uri:"sequenzy://subscribers/recent",name:"Recent Subscribers",description:"Most recently added subscribers",mimeType:"application/json"},{uri:"sequenzy://subscribers/engaged",name:"Engaged Subscribers",description:"Most active/engaged subscribers",mimeType:"application/json"},{uri:"sequenzy://sequences",name:"Sequences",description:"All email sequences with status",mimeType:"application/json"},{uri:"sequenzy://templates",name:"Templates",description:"All available email templates with localization status",mimeType:"application/json"},{uri:"sequenzy://segments",name:"Segments",description:"All defined segments with subscriber counts",mimeType:"application/json"},{uri:"sequenzy://tags",name:"Tags",description:"All tags with usage counts",mimeType:"application/json"},{uri:"sequenzy://health",name:"Deliverability Health",description:"Email deliverability metrics and health status",mimeType:"application/json"},{uri:"sequenzy://app-routes",name:"Dashboard URL Routes",description:"Route templates and settings tabs for building Sequenzy dashboard links",mimeType:"application/json"}];async function C5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await L("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await L("GET","/api/v1/account"),W=N1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await L("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await L("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await L("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await L("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await L("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await L("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await L("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await L("GET","/api/v1/tags");break;case"sequenzy://health":Y=await L("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=M1();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:R1(Y)}]}}}import{readFileSync as fM,statSync as lM}from"node:fs";import{basename as mM}from"node:path";var d6="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: [...] }.",t1="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`.",c5="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.",MQ="Complete Sequenzy landing page content JSON. Use this when replacing the page structure. The content must be the editor-compatible landing page schema with version, template, seo, theme, and blocks. Landing pages must include exactly one footer block and at most one form block.",cM="Optional template key for default content, such as from-scratch, waitlist, lead-magnet, launch, demo-request, webinar, newsletter, product-hunt, pricing-offer, agency-lead-gen, or feature-announcement.",k5=500,v5=500,x5={type:"object",description:"Optional send window for every email step in the sequence. When set, email actions that become due outside the window wait until the next allowed local time. Omit days to allow every day.",properties:{enabled:{type:"boolean",description:"Set false to disable the sending window when creating a sequence. For updates, prefer clearSendingWindow."},timezone:{type:"string",description:"IANA timezone for the window, e.g. Europe/Kiev or America/New_York."},startTime:{type:"string",description:"Earliest local send time in 24-hour HH:mm format, e.g. 08:00."},endTime:{type:"string",description:"Latest local send cutoff in 24-hour HH:mm format, e.g. 20:00. Must be later than startTime."},days:{type:"array",description:"Allowed local days. Use full names or short names such as monday, tuesday, mon, tue. Omit for every day.",items:{type:"string"}}},additionalProperties:!1},ZQ=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],wQ=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.unsubscribed","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","sequence.finished","sequence.failed"],pM=new Set(["get_account","get_app_urls","get_company","list_websites","check_website","get_integration_guide","get_subscriber","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_email_send","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_transactional_emails","get_transactional_email","get_stats","get_campaign_stats","get_sequence_stats","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_sequence","generate_subject_lines"]),iM=new Set(["select_company","create_company","create_api_key","add_website","add_subscriber","update_subscriber","remove_subscriber","upsert_products","delete_product","attach_product_file","remove_product_file","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","delete_template","restart_ab_test","update_ab_test_variant","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","create_landing_page","update_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","update_sequence","enable_sequence","disable_sequence","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery"]),nM=new Set(["send_test_email","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","enable_sequence","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery"]),rM=new Set(["remove_subscriber","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","disable_sequence","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook"]);function dM(Q){let Y=pM.has(Q),X=iM.has(Q);if(Y===X)throw Error(`MCP tool "${Q}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:Y,destructiveHint:Y?!1:rM.has(Q),openWorldHint:nM.has(Q)}}function oM(Q){return{...Q,annotations:{...Q.annotations,...dM(Q.name)}}}var pY={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"],commerceProduct:["is","is_not","at_least","less_than_count"]},tM=Object.entries(pY).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),_5={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","commerceProduct"],description:"Filter field. Use `event` for custom subscriber events, `segment` for saved segment membership, `stripeProduct`/`stripeCurrentProduct`/`stripeTrialProduct` for Stripe product-based segments, and `commerceProduct` for products purchased through commerce orders - the value is `provider:productId` (provider one of `shopify`, `woocommerce`, `api`; product ids are provider-scoped), optionally with an order-count threshold (`provider:productId:count`) for at_least/less_than_count; a bare product id matches the id on any provider. Engagement fields (`emailSent`, `emailDelivered`, `emailOpened`, `emailClicked`, `emailBounced`, `emailComplained`) accept a time range as the value or a specific campaign via `campaign:<campaign_id>`."},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${tM}.`},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},g5={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 iY(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 nY(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=iY([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(nY):[]}}function aM(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function sM(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function y5(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 eM(Q,Y){let X=Y.split(":");if(Q==="at_least"||Q==="less_than_count"){if(X.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let $=X.slice(0,-2).join(":").trim(),z=X.at(-2),J=X.at(-1),H=z===void 0?Number.NaN:Number.parseInt(z,10);return $&&Number.isInteger(H)&&H>0&&J!==void 0&&y5(J)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(X.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=X.slice(0,-1).join(":").trim(),G=X.at(-1);return W&&G!==void 0&&y5(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function QV(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 YV(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function XV(Q){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(Q)}function WV(Q,Y){if(Y==="cancels_at"||Y==="cancel_at"||Y==="cancellation_at")return!0;if(Q==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(Y);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(Y)}function GV(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function $V(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let J=X.indexOf(":");if(J===-1)return null;let H=X.substring(0,J).trim(),U=Number.parseInt(X.substring(J+1).trim(),10);return H&&Number.isInteger(U)&&U>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(Q!=="stripeCurrentProduct"&&Q!=="stripeTrialProduct")return null;let{productId:W,subfilter:G,rawValue:$}=QV(X);if(!W.trim())return"Stripe product filters must include a product ID.";if(!G)return Y==="is"||Y==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let z=YV(G);if(XV(z))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!WV(Q,z))return`Unsupported Stripe product subfilter "${G}".`;if(!GV(Y))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return $?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var zV=new Set(["shopify","woocommerce","api"]);function JV(Q,Y){let X=Y.trim(),W=X.indexOf(":");if(W!==-1&&zV.has(X.substring(0,W).trim()))X=X.substring(W+1).trim();if(!X)return'Purchased Product filters must include a product ID, like "shopify:42".';if(Q!=="at_least"&&Q!=="less_than_count")return null;let G=X.lastIndexOf(":");if(G===-1)return null;let $=X.substring(0,G).trim(),z=Number.parseInt(X.substring(G+1).trim(),10);return $&&Number.isInteger(z)&&z>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function dY(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 pY))return`Unsupported segment filter field "${String(X)}".`;if(typeof W!=="string")return`Segment filter "${X}" must include an operator.`;let $=pY[X];if(!$.includes(W))return`Operator "${W}" is not supported for ${X} filters. Use one of: ${$.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${X}" must include a value.`;if(X==="attribute"&&typeof G==="string"){if(!aM(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!sM(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let z=eM(W,G);if(z)return z}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let z=$V(X,W,G);if(z)return z}if(X==="commerceProduct"&&typeof G==="string"){let z=JV(W,G);if(z)return z}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map((J)=>J.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function oY(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=dY(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap(oY);return[]}function S1(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 NQ(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 HV(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 $=dY(G);return $?[$]:[]}):oY(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function UV(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(Q.name===void 0&&Q.filterJoinOperator===void 0&&!Y&&!X)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=dY(G);return $?[$]:[]}):X?oY(Q.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}function AV(Q){if(Q.clearEnrollmentFieldPath===!0&&Q.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(Q.clearSendingWindow===!0&&Q.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");let Y={...Q};if(delete Y.clearEnrollmentFieldPath,delete Y.clearSendingWindow,Q.clearEnrollmentFieldPath===!0)Y.enrollmentFieldPath=null;if(Q.clearSendingWindow===!0)Y.sendingWindow=null;return Y}function BV(Q){let Y=w(Q,"subscriberId"),X=Q.fieldValues,W=X===void 0?void 0:Array.isArray(X)?X:void 0;if(X!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let G=W?.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0)??[];if(W?.some((J)=>typeof J!=="string")||W!==void 0&&G.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(Y!==void 0===G.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let $=w(Q,"fieldPath"),z=w(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...$!==void 0&&{fieldPath:$},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...z!==void 0&&{reason:z}}}function KV(Q){S1("create_campaign",Q),NQ("create_campaign",Q);let Y=w(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0,G=Q.templateId!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(Y&&(X||W||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function DV(Q){if(w(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!J0(Q.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(Q.sendTimeOptimization!==void 0){if(typeof Q.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(Q.spreadOverHours!==void 0){if(typeof Q.spreadOverHours!=="number"||!Number.isInteger(Q.spreadOverHours)||Q.spreadOverHours<1||Q.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}}function lY(Q,Y,X){let W=new Set(["companyId","landingPageId","name","slug","content"]),G=Object.keys(Y).filter(($)=>!W.has($));if(G.length>0)throw Error(`\`${Q}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map(($)=>`\`${$}\``).join(", ")}.`);if(X.requireUpdate&&Y.name===void 0&&Y.slug===void 0&&Y.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${Q}\`.`);return{...Y.name!==void 0&&{name:Y.name},...Y.slug!==void 0&&{slug:Y.slug},...Y.content!==void 0&&{content:Y.content}}}function LV(Q){let Y=new Set(["companyId","domain","verify"]),X=Object.keys(Q).filter((W)=>!Y.has(W));if(X.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${X.length===1?"":"s"}: ${X.map((W)=>`\`${W}\``).join(", ")}.`);if(Q.domain===void 0&&Q.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...Q.domain!==void 0&&{domain:Q.domain},...typeof Q.verify==="boolean"&&{verify:Q.verify}}}function qV(Q){S1("create_transactional_email",Q);let Y=w(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(Y&&(X||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!Y&&!X&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var u5={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:c5,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 FV(Q){if(!Q||typeof Q!=="object")return null;let Y=Q;if(Y.success!==!1)return null;if(typeof Y.error==="string")return Error(Y.error);if(Y.error&&typeof Y.error==="object"&&typeof Y.error.message==="string")return Error(Y.error.message);if(typeof Y.message==="string")return Error(Y.message);return Error("The tool returned an unsuccessful response.")}function J0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function h5(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function OV(Q){let Y=new URLSearchParams;if(typeof Q.query==="string"&&Q.query.trim()!=="")Y.set("query",Q.query.trim());if(Array.isArray(Q.tags)&&Q.tags.length>0)Y.set("tags",Q.tags.filter((X)=>typeof X==="string"&&X.trim()!=="").join(","));if(typeof Q.list==="string"&&Q.list.trim()!=="")Y.set("list",Q.list.trim());if(typeof Q.listId==="string"&&Q.listId.trim()!=="")Y.set("listId",Q.listId.trim());if(typeof Q.listName==="string"&&Q.listName.trim()!=="")Y.set("listName",Q.listName.trim());if(typeof Q.segmentId==="string"&&Q.segmentId.trim()!=="")Y.set("segmentId",Q.segmentId);if(typeof Q.status==="string"&&Q.status.trim()!=="")Y.set("status",Q.status.trim());return Y.set("page",String(Q.page)),Y.set("limit",String(Q.pageSize)),Y}async function MV(Q,Y){let X=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,W=Math.min(100,Math.max(1,X??100)),G=[],$=1,z=0,J=0,H=0;while(!0){let A=OV({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:$,pageSize:W}),B=await L("GET",`/api/v1/subscribers?${A.toString()}`,void 0,Y);z=B.pagination?.total??B.subscribers.length,J=B.pagination?.totalPages??1,H+=1,G.push(...B.subscribers??[]);let K=X!==void 0&&G.length>=X,D=B.pagination?$>=B.pagination.totalPages:(B.subscribers??[]).length<W;if(K||D)break;$+=1}let U=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:U,pagination:{page:1,limit:W,total:z,totalPages:J,fetchedPages:H},returned:U.length,truncated:X!==void 0&&z>0&&U.length<z}}function VV(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 o6(Q,Y){let X=VV(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function rY(Q){if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}`;return`/api/v1/subscribers/external?externalId=${encodeURIComponent(String(Q.externalId))}`}async function mY(Q,Y){return L("GET",rY(Q),void 0,Y)}function w(Q,Y){let X=Q[Y];if(typeof X!=="string")return;let W=X.trim();return W.length>0?W:void 0}function k(Q,Y,X){let W=w(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function W1(Q,Y,X,W){let G=w(Y,X);if(G===void 0)return;if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function cY(Q,Y,X,W){let G=k(Q,Y,X);if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function t6(Q,Y,X,W,G){let $=Y[X];if($===void 0)return;if(typeof $!=="number"||!Number.isInteger($)||$<W||$>G)throw Error(`\`${X}\` must be an integer between ${W} and ${G} when calling \`${Q}\`.`);return $}function f5(Q,Y){if(Y.events===void 0)return;if(!Array.isArray(Y.events))throw Error(`\`events\` must be an array when calling \`${Q}\`.`);let X=Y.events.map((W,G)=>{if(typeof W!=="string"||!wQ.includes(W))throw Error(`\`events\` item ${G+1} must be one of ${wQ.join(", ")} when calling \`${Q}\`.`);return W});if(X.length===0)throw Error(`\`events\` must include at least one event type when calling \`${Q}\`.`);return X}function l5(Q,Y){if(!Array.isArray(Y.emails))throw Error(`\`emails\` must be an array when calling \`${Q}\`.`);let X=[];if(Y.emails.forEach((W,G)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${Q}\`.`);let $=W.trim();if($.length>0)X.push($)}),X.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${Q}\`.`);if(X.length>k5)throw Error(`\`emails\` must include no more than ${k5} email addresses when calling \`${Q}\`. Split larger batches into multiple calls.`);return X}function m5(Q,Y,X,W){let G=Y[X];if(G===void 0)return;if(!Array.isArray(G))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`);let $=[];if(G.forEach((z,J)=>{if(typeof z!=="string")throw Error(`\`${X}\` item ${J+1} must be a string when calling \`${Q}\`.`);let H=z.trim();if(H.length>0)$.push(H)}),$.length===0)throw Error(`\`${X}\` must include at least one ${W} when calling \`${Q}\`.`);return $}function NV(Q){let X=m5("enroll_subscribers_in_sequence",Q,"emails","email address"),W=m5("enroll_subscribers_in_sequence",Q,"subscriberIds","subscriber ID"),G=(X?.length??0)+(W?.length??0);if(G===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(G>v5)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${v5} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let $=w(Q,"targetNodeId");return{...X!==void 0&&{emails:X},...W!==void 0&&{subscriberIds:W},...$!==void 0&&{targetNodeId:$}}}var ZV={pdf:"application/pdf",epub:"application/epub+zip",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",txt:"text/plain",csv:"text/csv"};function wV(Q){let Y=Q.split(".").pop()?.toLowerCase()??"";return ZV[Y]??null}var jV=104857600;async function PV(Q,Y){if(!YX())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let X=wV(Q);if(!X)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=lM(Q).size;if(W>jV)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=fM(Q),$=await L("POST","/api/v1/products/delivery/upload-url",{filename:mM(Q),contentType:X,fileSizeBytes:W},Y),z=await fetch($.uploadUrl,{method:"PUT",headers:{"Content-Type":X},body:G});if(!z.ok)throw Error(`File upload failed (${z.status})`);return{url:$.publicUrl,fileName:$.fileName,fileSizeBytes:W,mimeType:X}}async function p5(Q){let Y=w(Q,"companyId");if(Y)return Y;let X=N1();if(X)return X;try{return(await L("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}function a1(Q,Y){if(!J0(Q)||!Y)return Q;return{...Q,url:Y}}function i5(Q,Y){if(!J0(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(!J0(W))return W;let G=w(W,"id");if(!G)return W;let $=M1({companyId:Y,...X==="campaign"&&{campaignId:G},...X==="landingPage"&&{landingPageId:G},...X==="sequence"&&{sequenceId:G},...X==="template"&&{emailId:G},...X==="transactional"&&{transactionalId:G}});if(X==="campaign")return i5(W,$.urls);let z=X==="sequence"?$.urls.sequence:X==="landingPage"?$.urls.landingPage:X==="template"?$.urls.email:$.urls.transactionalEmail;return a1(W,z)})}function bV(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!J0(Y))return Y;let X=w(Y,"id");if(!X)return Y;let W=M1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var n5=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","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","update_sequence","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 IV(Q,Y,X){if(!J0(X)||!n5.has(Q))return X;let W=J0(X.company)?X.company:void 0,$=w(X,"selectedCompanyId")??w(X,"currentCompanyId")??w(X,"companyId")??(W?w(W,"id"):void 0)??(W?w(W,"companyId"):void 0)??await p5(Y);if(!$)return X;let z=J0(X.campaign)?X.campaign:void 0,J=J0(X.sequence)?X.sequence:void 0,H=J0(X.landingPage)?X.landingPage:void 0,U=J0(X.template)?X.template:void 0,A=J0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,B={companyId:$,campaignId:w(Y,"campaignId")??w(X,"campaignId")??(z?w(z,"id"):void 0),landingPageId:w(Y,"landingPageId")??w(X,"landingPageId")??(H?w(H,"id"):void 0),sequenceId:w(Y,"sequenceId")??w(X,"sequenceId")??(J?w(J,"id"):void 0),emailId:w(X,"templateId")??(U?w(U,"id"):void 0)??(A?w(A,"emailId"):void 0)??w(Y,"templateId"),transactionalId:w(Y,"transactionalId")??(A?w(A,"id"):void 0)??w(Y,"idOrSlug"),emailSendId:w(Y,"emailSendId")??w(X,"emailSendId")??(J0(X.emailSend)?w(X.emailSend,"id"):void 0),status:w(Y,"status")},K=M1(B),D=W?M1({companyId:$}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:bV(X.companies)},...Array.isArray(X.campaigns)&&{campaigns:a6(X.campaigns,$,"campaign")},...Array.isArray(X.landingPages)&&{landingPages:a6(X.landingPages,$,"landingPage")},...Array.isArray(X.sequences)&&{sequences:a6(X.sequences,$,"sequence")},...Array.isArray(X.templates)&&{templates:a6(X.templates,$,"template")},...Array.isArray(X.transactional)&&{transactional:a6(X.transactional,$,"transactional")},...W&&D!==void 0&&{company:{...W,url:D.urls.dashboard,settingsUrl:D.urls.settings}},...z&&K.urls.campaign!==void 0&&{campaign:i5(z,K.urls)},...J&&K.urls.sequence!==void 0&&{sequence:a1(J,K.urls.sequence)},...H&&K.urls.landingPage!==void 0&&{landingPage:a1(H,K.urls.landingPage)},...U&&K.urls.email!==void 0&&{template:a1(U,K.urls.email)},...A&&K.urls.transactionalEmail!==void 0&&{transactional:a1(A,K.urls.transactionalEmail)},...J0(X.emailSend)&&K.urls.emailSend!==void 0&&{emailSend:a1(X.emailSend,K.urls.emailSend)},appUrls:K.urls}}var EV={type:"boolean",description:"Whether the Sequenzy operation succeeded."},TV={type:"string",description:"Human-readable status, confirmation, or next-step message."},SV={type:"string",description:"Additional context about the result."};function l0(Q){return{type:"object",description:Q,additionalProperties:!0}}function RV(Q){return{type:"array",description:Q,items:l0("One item in the returned collection.")}}function v(Q){return{type:"string",description:Q}}function C0(Q){return{type:"number",description:Q}}function VQ(Q){return{type:"boolean",description:Q}}function N(Q){return l0(`The ${Q} record returned by Sequenzy.`)}function r(Q){return RV(`List of ${Q} records returned by Sequenzy.`)}var CV={appUrls:l0("Dashboard URLs for relevant Sequenzy resources."),url:v("Primary dashboard URL for this result."),settingsUrl:v("Company settings URL when available.")},kV={success:EV,message:TV,note:SV,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:l0("One returned item.")},value:l0("Fallback object wrapper used only when a tool returns a non-object value.")},vV={get_account:{account:N("account"),companies:r("company"),currentCompanyId:v("Company ID selected by the authenticated API key, when available."),selectedCompanyId:v("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:v("Selected company ID."),companyName:v("Selected company name.")},get_app_urls:{dashboard:v("Company dashboard URL."),settings:v("Company settings URL."),campaign:v("Campaign editor URL."),landingPage:v("Landing page editor URL."),sequence:v("Sequence editor URL."),email:v("Email editor URL."),transactionalEmail:v("Transactional email URL."),emailSend:v("Sent email detail URL."),domain:v("Sending domain settings URL."),urls:l0("All generated URLs keyed by resource type.")},create_company:{company:N("company"),autoSelected:VQ("Whether the new company was selected for subsequent MCP calls.")},get_company:{company:N("company")},create_api_key:{apiKey:v("Newly created API key. This secret is returned only once."),key:v("Newly created API key if the API response uses the short key field.")},list_websites:{websites:r("sender website")},add_website:{website:N("sender website")},check_website:{website:N("sender website"),ready:VQ("Whether the sender website is ready."),status:v("Current processing or verification status.")},get_integration_guide:{guide:N("integration guide"),code:v("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:l0("One setup step.")}},add_subscriber:{subscriber:N("subscriber")},update_subscriber:{subscriber:N("subscriber")},remove_subscriber:{subscriber:N("subscriber"),hardDeleted:VQ("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:N("subscriber")},search_subscribers:{subscribers:r("subscriber"),pagination:l0("Pagination metadata."),returned:C0("Number of subscribers returned."),truncated:VQ("Whether the result was truncated by the requested limit.")},list_products:{products:r("product")},upsert_products:{products:r("product"),created:C0("Number of products created."),updated:C0("Number of products updated.")},delete_product:{productId:v("Deleted product ID.")},attach_product_file:{product:N("product"),delivery:N("digital delivery file")},remove_product_file:{product:N("product")},sync_products:{job:N("product sync job"),jobId:v("Queued product sync job ID.")},list_tags:{tags:r("tag")},create_tag:{tag:N("tag")},update_tag:{tag:N("tag")},delete_tag:{tagId:v("Deleted tag ID.")},list_lists:{lists:r("list")},create_list:{list:N("list")},update_list:{list:N("list")},delete_list:{listId:v("Deleted list ID.")},add_subscribers_to_list:{list:N("list"),added:C0("Number of subscribers added to the list."),skipped:C0("Number of subscribers skipped.")},remove_subscribers_from_list:{list:N("list"),removed:C0("Number of subscribers removed from the list."),skipped:C0("Number of subscribers skipped.")},list_segments:{segments:r("segment")},create_segment:{segment:N("segment")},update_segment:{segment:N("segment")},delete_segment:{segmentId:v("Deleted segment ID.")},get_segment_count:{count:C0("Number of subscribers matching the segment."),segmentId:v("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:r("audience sync")},list_ad_accounts:{adAccounts:r("ad account")},create_audience_sync:{audienceSync:N("audience sync")},update_audience_sync:{audienceSync:N("audience sync")},delete_audience_sync:{audienceSyncId:v("Deleted audience sync ID.")},sync_audience_now:{audienceSync:N("audience sync"),job:N("audience sync job"),jobId:v("Queued audience sync job ID.")},list_templates:{templates:r("email template")},get_template:{template:N("email template")},create_template:{template:N("email template")},update_template:{template:N("email template")},delete_template:{templateId:v("Deleted template ID.")},list_ab_tests:{abTests:r("A/B test")},get_ab_test:{abTest:N("A/B test")},get_ab_test_stats:{abTest:N("A/B test"),stats:N("A/B test statistics")},restart_ab_test:{abTest:N("A/B test")},update_ab_test_variant:{abTest:N("A/B test"),variant:N("A/B test variant")},create_ab_test:{abTest:N("A/B test")},add_ab_test_variant:{abTest:N("A/B test"),variant:N("A/B test variant")},delete_ab_test_variant:{abTest:N("A/B test"),variantId:v("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:v("Deleted A/B test ID.")},list_campaigns:{campaigns:r("campaign")},get_campaign:{campaign:N("campaign")},get_email_send:{emailSend:N("email send")},create_campaign:{campaign:N("campaign")},update_campaign:{campaign:N("campaign")},schedule_campaign:{campaign:N("campaign"),scheduledAt:v("Scheduled send timestamp.")},send_test_email:{emailSend:N("test email send"),recipient:v("Test email recipient.")},cancel_campaign:{campaign:N("campaign")},pause_campaign:{campaign:N("campaign")},resume_campaign:{campaign:N("campaign")},delete_campaign:{campaignId:v("Deleted campaign ID.")},duplicate_campaign:{campaign:N("duplicated campaign")},list_landing_pages:{landingPages:r("landing page")},get_landing_page:{landingPage:N("landing page")},create_landing_page:{landingPage:N("landing page")},update_landing_page:{landingPage:N("landing page")},delete_landing_page:{landingPageId:v("Deleted landing page ID.")},publish_landing_page:{landingPage:N("landing page")},unpublish_landing_page:{landingPage:N("landing page")},connect_landing_page_domain:{landingPage:N("landing page"),domain:v("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:N("landing page"),domain:v("Landing page domain.")},list_sequences:{sequences:r("sequence")},get_sequence:{sequence:N("sequence")},create_sequence:{sequence:N("sequence")},update_sequence:{sequence:N("sequence")},enable_sequence:{sequence:N("sequence")},disable_sequence:{sequence:N("sequence")},enroll_subscribers_in_sequence:{sequence:N("sequence"),enrollments:r("sequence enrollment"),enrolled:C0("Number of subscribers enrolled."),skipped:C0("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:N("sequence"),cancelled:C0("Number of enrollments cancelled."),skipped:C0("Number of enrollments skipped.")},delete_sequence:{sequenceId:v("Deleted sequence ID.")},list_transactional_emails:{transactional:r("transactional email")},get_transactional_email:{transactional:N("transactional email")},create_transactional_email:{transactional:N("transactional email")},update_transactional_email:{transactional:N("transactional email")},send_email:{emailSend:N("transactional email send"),transactional:N("transactional email")},get_stats:{stats:N("account or company statistics")},get_campaign_stats:{campaign:N("campaign"),stats:N("campaign statistics")},get_sequence_stats:{sequence:N("sequence"),stats:N("sequence statistics")},get_subscriber_activity:{activity:r("subscriber activity event"),subscribers:r("subscriber"),pagination:l0("Pagination metadata.")},list_team_members:{members:r("team member"),invitations:r("team invitation")},invite_team_member:{invitation:N("team invitation")},cancel_team_invitation:{invitationId:v("Cancelled invitation ID.")},list_conversations:{conversations:r("inbox conversation"),pagination:l0("Pagination metadata.")},get_conversation:{conversation:N("inbox conversation"),messages:r("conversation message")},reply_to_conversation:{conversation:N("inbox conversation"),message:N("conversation message")},update_conversation_status:{conversation:N("inbox conversation")},mark_conversation_read:{conversation:N("inbox conversation")},list_webhooks:{webhooks:r("outbound webhook")},create_webhook:{webhook:N("outbound webhook")},update_webhook:{webhook:N("outbound webhook")},delete_webhook:{webhookId:v("Deleted outbound webhook ID.")},test_webhook:{webhook:N("outbound webhook"),delivery:N("test webhook delivery")},list_webhook_deliveries:{deliveries:r("webhook delivery")},replay_webhook_delivery:{delivery:N("webhook delivery"),job:N("webhook replay job")},generate_email:{email:N("generated email"),html:v("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks.",items:l0("One generated email block.")},subject:v("Generated subject line."),previewText:v("Generated inbox preview text.")},generate_sequence:{sequence:N("generated sequence"),steps:r("generated sequence step")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:v("One generated subject line.")},variants:r("generated subject line variant")}};function xV(Q){let Y=vV[Q];if(Y===void 0)throw Error(`MCP tool "${Q}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${Q}\` MCP tool.`,properties:{...kV,...Y,...n5.has(Q)?CV:{}},additionalProperties:!0}}function _V(Q){return{...Q,outputSchema:xV(Q.name)}}function gV(Q){if(J0(Q))return Q;if(Array.isArray(Q))return{items:Q};return{value:Q}}var yV=[{name:"get_account",description:`Get current account information including available companies. IMPORTANT: If you have access to multiple companies, you MUST either:
|
|
28
|
+
`)}D.write("payload.value = newResult;"),D.write("return payload;");let R=D.compile();return(T,y)=>R(K,T,y)},$,z=Z1,J=!s6.jitless,U=J&&CQ.value,A=Y.catchall,B;Q._zod.parse=(K,D)=>{B??(B=W.value);let O=K.value;if(!z(O))return K.issues.push({expected:"object",code:"invalid_type",input:O,inst:Q}),K;if(J&&U&&D?.async===!1&&D.jitless!==!0){if(!$)$=G(Y.shape);if(K=$(K,D),!A)return K;return e8([],O,K,D,B,Q)}return X(K,D)}});function q8(Q,Y,X,W){for(let $ of Q)if($.issues.length===0)return Y.value=$.value,Y;let G=Q.filter(($)=>!J1($));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map(($)=>$.issues.map((z)=>v0(z,W,I0())))}),Y}var cQ=F("$ZodUnion",(Q,Y)=>{o.init(Q,Y),i(Q._zod,"optin",()=>Y.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),i(Q._zod,"optout",()=>Y.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),i(Q._zod,"values",()=>{if(Y.options.every((G)=>G._zod.values))return new Set(Y.options.flatMap((G)=>Array.from(G._zod.values)));return}),i(Q._zod,"pattern",()=>{if(Y.options.every((G)=>G._zod.pattern)){let G=Y.options.map(($)=>$._zod.pattern);return new RegExp(`^(${G.map(($)=>W6($.source)).join("|")})$`)}return});let X=Y.options.length===1,W=Y.options[0]._zod.run;Q._zod.parse=(G,$)=>{if(X)return W(G,$);let z=!1,J=[];for(let H of Y.options){let U=H._zod.run({value:G.value,issues:[]},$);if(U instanceof Promise)J.push(U),z=!0;else{if(U.issues.length===0)return U;J.push(U)}}if(!z)return q8(J,G,Q,$);return Promise.all(J).then((H)=>{return q8(H,G,Q,$)})}}),YW=F("$ZodDiscriminatedUnion",(Q,Y)=>{cQ.init(Q,Y);let X=Q._zod.parse;i(Q._zod,"propValues",()=>{let G={};for(let $ of Y.options){let z=$._zod.propValues;if(!z||Object.keys(z).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf($)}"`);for(let[J,H]of Object.entries(z)){if(!G[J])G[J]=new Set;for(let U of H)G[J].add(U)}}return G});let W=k1(()=>{let G=Y.options,$=new Map;for(let z of G){let J=z._zod.propValues?.[Y.discriminator];if(!J||J.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(z)}"`);for(let H of J){if($.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);$.set(H,z)}}return $});Q._zod.parse=(G,$)=>{let z=G.value;if(!Z1(z))return G.issues.push({code:"invalid_type",expected:"object",input:z,inst:Q}),G;let J=W.value.get(z?.[Y.discriminator]);if(J)return J._zod.run(G,$);if(Y.unionFallback)return X(G,$);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,input:z,path:[Y.discriminator],inst:Q}),G}}),XW=F("$ZodIntersection",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value,$=Y.left._zod.run({value:G,issues:[]},W),z=Y.right._zod.run({value:G,issues:[]},W);if($ instanceof Promise||z instanceof Promise)return Promise.all([$,z]).then(([H,U])=>{return F8(X,H,U)});return F8(X,$,z)}});function lQ(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(z1(Q)&&z1(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter(($)=>X.indexOf($)!==-1),G={...Q,...Y};for(let $ of W){let z=lQ(Q[$],Y[$]);if(!z.valid)return{valid:!1,mergeErrorPath:[$,...z.mergeErrorPath]};G[$]=z.data}return{valid:!0,data:G}}if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let W=0;W<Q.length;W++){let G=Q[W],$=Y[W],z=lQ(G,$);if(!z.valid)return{valid:!1,mergeErrorPath:[W,...z.mergeErrorPath]};X.push(z.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function F8(Q,Y,X){if(Y.issues.length)Q.issues.push(...Y.issues);if(X.issues.length)Q.issues.push(...X.issues);if(J1(Q))return Q;let W=lQ(Y.value,X.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return Q.value=W.data,Q}var WW=F("$ZodRecord",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!z1(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let $=[];if(Y.keyType._zod.values){let z=Y.keyType._zod.values;X.value={};for(let H of z)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let U=Y.valueType._zod.run({value:G[H],issues:[]},W);if(U instanceof Promise)$.push(U.then((A)=>{if(A.issues.length)X.issues.push(...t0(H,A.issues));X.value[H]=A.value}));else{if(U.issues.length)X.issues.push(...t0(H,U.issues));X.value[H]=U.value}}let J;for(let H in G)if(!z.has(H))J=J??[],J.push(H);if(J&&J.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:J})}else{X.value={};for(let z of Reflect.ownKeys(G)){if(z==="__proto__")continue;let J=Y.keyType._zod.run({value:z,issues:[]},W);if(J instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(J.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:J.issues.map((U)=>v0(U,W,I0())),input:z,path:[z],inst:Q}),X.value[J.value]=J.value;continue}let H=Y.valueType._zod.run({value:G[z],issues:[]},W);if(H instanceof Promise)$.push(H.then((U)=>{if(U.issues.length)X.issues.push(...t0(z,U.issues));X.value[J.value]=U.value}));else{if(H.issues.length)X.issues.push(...t0(z,H.issues));X.value[J.value]=H.value}}}if($.length)return Promise.all($).then(()=>X);return X}});var GW=F("$ZodEnum",(Q,Y)=>{o.init(Q,Y);let X=SQ(Y.entries),W=new Set(X);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${X.filter((G)=>kQ.has(typeof G)).map((G)=>typeof G==="string"?o0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,$)=>{let z=G.value;if(W.has(z))return G;return G.issues.push({code:"invalid_value",values:X,input:z,inst:Q}),G}}),$W=F("$ZodLiteral",(Q,Y)=>{if(o.init(Q,Y),Y.values.length===0)throw Error("Cannot create literal schema with no valid values");Q._zod.values=new Set(Y.values),Q._zod.pattern=new RegExp(`^(${Y.values.map((X)=>typeof X==="string"?o0(X):X?o0(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 zW=F("$ZodTransform",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new Q6(Q.constructor.name);let G=Y.transform(X.value,X);if(W.async)return(G instanceof Promise?G:Promise.resolve(G)).then((z)=>{return X.value=z,X});if(G instanceof Promise)throw new d0;return X.value=G,X}});function O8(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var JW=F("$ZodOptional",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",i(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),i(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${W6(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(($)=>O8($,X.value));return O8(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),HW=F("$ZodNullable",(Q,Y)=>{o.init(Q,Y),i(Q._zod,"optin",()=>Y.innerType._zod.optin),i(Q._zod,"optout",()=>Y.innerType._zod.optout),i(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${W6(X.source)}|null)$`):void 0}),i(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)}}),UW=F("$ZodDefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",i(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(($)=>M8($,Y));return M8(G,Y)}});function M8(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var AW=F("$ZodPrefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",i(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)}}),BW=F("$ZodNonOptional",(Q,Y)=>{o.init(Q,Y),i(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(($)=>V8($,Q));return V8(G,Q)}});function V8(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 KW=F("$ZodCatch",(Q,Y)=>{o.init(Q,Y),i(Q._zod,"optin",()=>Y.innerType._zod.optin),i(Q._zod,"optout",()=>Y.innerType._zod.optout),i(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>{if(X.value=$.value,$.issues.length)X.value=Y.catchValue({...X,error:{issues:$.issues.map((z)=>v0(z,W,I0()))},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(($)=>v0($,W,I0()))},input:X.value}),X.issues=[];return X}});var DW=F("$ZodPipe",(Q,Y)=>{o.init(Q,Y),i(Q._zod,"values",()=>Y.in._zod.values),i(Q._zod,"optin",()=>Y.in._zod.optin),i(Q._zod,"optout",()=>Y.out._zod.optout),i(Q._zod,"propValues",()=>Y.in._zod.propValues),Q._zod.parse=(X,W)=>{if(W.direction==="backward"){let $=Y.out._zod.run(X,W);if($ instanceof Promise)return $.then((z)=>H4(z,Y.in,W));return H4($,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>H4($,Y.out,W));return H4(G,Y.out,W)}});function H4(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var LW=F("$ZodReadonly",(Q,Y)=>{o.init(Q,Y),i(Q._zod,"propValues",()=>Y.innerType._zod.propValues),i(Q._zod,"values",()=>Y.innerType._zod.values),i(Q._zod,"optin",()=>Y.innerType._zod.optin),i(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(N8);return N8(G)}});function N8(Q){return Q.value=Object.freeze(Q.value),Q}var qW=F("$ZodCustom",(Q,Y)=>{H0.init(Q,Y),o.init(Q,Y),Q._zod.parse=(X,W)=>{return X},Q._zod.check=(X)=>{let W=X.value,G=Y.fn(W);if(G instanceof Promise)return G.then(($)=>Z8($,X,W,Q));Z8(G,X,W,Q);return}});function Z8(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(v1(G))}}var pH=(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},iH=()=>{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 ${pH(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${X4(W.values[0])}`;return`Invalid option: expected one of ${e6(W.values,"|")}`;case"too_big":{let G=W.inclusive?"<=":"<",$=Y(W.origin);if($)return`Too big: expected ${W.origin??"value"} to have ${G}${W.maximum.toString()} ${$.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${G}${W.maximum.toString()}`}case"too_small":{let G=W.inclusive?">=":">",$=Y(W.origin);if($)return`Too small: expected ${W.origin} to have ${G}${W.minimum.toString()} ${$.unit}`;return`Too small: expected ${W.origin} to be ${G}${W.minimum.toString()}`}case"invalid_format":{let G=W;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${X[G.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${e6(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 pQ(){return{localeError:iH()}}var zN=Symbol("ZodOutput"),JN=Symbol("ZodInput");class FW{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 nH(){return new FW}var U6=nH();function OW(Q,Y){return new Q({type:"string",...E(Y)})}function MW(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...E(Y)})}function iQ(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...E(Y)})}function VW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...E(Y)})}function NW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...E(Y)})}function ZW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...E(Y)})}function wW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...E(Y)})}function jW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...E(Y)})}function PW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...E(Y)})}function bW(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...E(Y)})}function IW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...E(Y)})}function EW(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...E(Y)})}function TW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...E(Y)})}function SW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...E(Y)})}function RW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...E(Y)})}function CW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...E(Y)})}function kW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...E(Y)})}function vW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...E(Y)})}function xW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...E(Y)})}function _W(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...E(Y)})}function gW(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...E(Y)})}function yW(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...E(Y)})}function uW(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...E(Y)})}function hW(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...E(Y)})}function fW(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...E(Y)})}function lW(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...E(Y)})}function mW(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...E(Y)})}function cW(Q,Y){return new Q({type:"number",checks:[],...E(Y)})}function pW(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...E(Y)})}function iW(Q,Y){return new Q({type:"boolean",...E(Y)})}function nW(Q,Y){return new Q({type:"null",...E(Y)})}function rW(Q){return new Q({type:"unknown"})}function dW(Q,Y){return new Q({type:"never",...E(Y)})}function B4(Q,Y){return new uQ({check:"less_than",...E(Y),value:Q,inclusive:!1})}function A6(Q,Y){return new uQ({check:"less_than",...E(Y),value:Q,inclusive:!0})}function K4(Q,Y){return new hQ({check:"greater_than",...E(Y),value:Q,inclusive:!1})}function B6(Q,Y){return new hQ({check:"greater_than",...E(Y),value:Q,inclusive:!0})}function D4(Q,Y){return new Q8({check:"multiple_of",...E(Y),value:Q})}function L4(Q,Y){return new X8({check:"max_length",...E(Y),maximum:Q})}function x1(Q,Y){return new W8({check:"min_length",...E(Y),minimum:Q})}function q4(Q,Y){return new G8({check:"length_equals",...E(Y),length:Q})}function nQ(Q,Y){return new $8({check:"string_format",format:"regex",...E(Y),pattern:Q})}function rQ(Q){return new z8({check:"string_format",format:"lowercase",...E(Q)})}function dQ(Q){return new J8({check:"string_format",format:"uppercase",...E(Q)})}function oQ(Q,Y){return new H8({check:"string_format",format:"includes",...E(Y),includes:Q})}function tQ(Q,Y){return new U8({check:"string_format",format:"starts_with",...E(Y),prefix:Q})}function aQ(Q,Y){return new A8({check:"string_format",format:"ends_with",...E(Y),suffix:Q})}function w1(Q){return new B8({check:"overwrite",tx:Q})}function sQ(Q){return w1((Y)=>Y.normalize(Q))}function eQ(){return w1((Q)=>Q.trim())}function Q9(){return w1((Q)=>Q.toLowerCase())}function Y9(){return w1((Q)=>Q.toUpperCase())}function oW(Q,Y,X){return new Q({type:"array",element:Y,...E(X)})}function tW(Q,Y,X){let W=E(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function aW(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...E(X)})}function sW(Q){let Y=rH((X)=>{return X.addIssue=(W)=>{if(typeof W==="string")X.issues.push(v1(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(v1(G))}},Q(X.value,X)});return Y}function rH(Q,Y){let X=new H0({check:"custom",...E(Y)});return X._zod.check=Q,X}function _1(Q){return!!Q._zod}function H1(Q,Y){if(_1(Q))return z6(Q,Y);return Q.safeParse(Y)}function F4(Q){if(!Q)return;let Y;if(_1(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 eW(Q){if(_1(Q)){let $=Q._zod?.def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}}let X=Q._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let W=Q.value;if(W!==void 0)return W;return}var D6={};eY(D6,{time:()=>G9,duration:()=>$9,datetime:()=>X9,date:()=>W9,ZodISOTime:()=>XG,ZodISODuration:()=>WG,ZodISODateTime:()=>QG,ZodISODate:()=>YG});var QG=F("ZodISODateTime",(Q,Y)=>{v8.init(Q,Y),s.init(Q,Y)});function X9(Q){return hW(QG,Q)}var YG=F("ZodISODate",(Q,Y)=>{x8.init(Q,Y),s.init(Q,Y)});function W9(Q){return fW(YG,Q)}var XG=F("ZodISOTime",(Q,Y)=>{_8.init(Q,Y),s.init(Q,Y)});function G9(Q){return lW(XG,Q)}var WG=F("ZodISODuration",(Q,Y)=>{g8.init(Q,Y),s.init(Q,Y)});function $9(Q){return mW(WG,Q)}var GG=(Q,Y)=>{W4.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>qX(Q,X)},flatten:{value:(X)=>LX(Q,X)},addIssue:{value:(X)=>{Q.issues.push(X),Q.message=JSON.stringify(Q.issues,C1,2)}},addIssues:{value:(X)=>{Q.issues.push(...X),Q.message=JSON.stringify(Q.issues,C1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},nN=F("ZodError",GG),P0=F("ZodError",GG,{Parent:Error});var $G=G4(P0),zG=$4(P0),JG=$6(P0),HG=J6(P0),UG=FX(P0),AG=OX(P0),BG=MX(P0),KG=VX(P0),DG=NX(P0),LG=ZX(P0),qG=wX(P0),FG=jX(P0);var X0=F("ZodType",(Q,Y)=>{return o.init(Q,Y),Q.def=Y,Q.type=Y.type,Object.defineProperty(Q,"_def",{value:Y}),Q.check=(...X)=>{return Q.clone(m.mergeDefs(Y,{checks:[...Y.checks??[],...X.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},Q.clone=(X,W)=>k0(Q,X,W),Q.brand=()=>Q,Q.register=(X,W)=>{return X.add(Q,W),Q},Q.parse=(X,W)=>$G(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>JG(Q,X,W),Q.parseAsync=async(X,W)=>zG(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>HG(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>UG(Q,X,W),Q.decode=(X,W)=>AG(Q,X,W),Q.encodeAsync=async(X,W)=>BG(Q,X,W),Q.decodeAsync=async(X,W)=>KG(Q,X,W),Q.safeEncode=(X,W)=>DG(Q,X,W),Q.safeDecode=(X,W)=>LG(Q,X,W),Q.safeEncodeAsync=async(X,W)=>qG(Q,X,W),Q.safeDecodeAsync=async(X,W)=>FG(Q,X,W),Q.refine=(X,W)=>Q.check(c3(X,W)),Q.superRefine=(X)=>Q.check(p3(X)),Q.overwrite=(X)=>Q.check(w1(X)),Q.optional=()=>Y0(Q),Q.nullable=()=>VG(Q),Q.nullish=()=>Y0(VG(Q)),Q.nonoptional=(X)=>y3(Q,X),Q.array=()=>u(Q),Q.or=(X)=>d([Q,X]),Q.and=(X)=>M4(Q,X),Q.transform=(X)=>J9(Q,PG(X)),Q.default=(X)=>x3(Q,X),Q.prefault=(X)=>g3(Q,X),Q.catch=(X)=>h3(Q,X),Q.pipe=(X)=>J9(Q,X),Q.readonly=()=>m3(Q),Q.describe=(X)=>{let W=Q.clone();return U6.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return U6.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return U6.get(Q);let W=Q.clone();return U6.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),NG=F("_ZodString",(Q,Y)=>{A4.init(Q,Y),X0.init(Q,Y);let X=Q._zod.bag;Q.format=X.format??null,Q.minLength=X.minimum??null,Q.maxLength=X.maximum??null,Q.regex=(...W)=>Q.check(nQ(...W)),Q.includes=(...W)=>Q.check(oQ(...W)),Q.startsWith=(...W)=>Q.check(tQ(...W)),Q.endsWith=(...W)=>Q.check(aQ(...W)),Q.min=(...W)=>Q.check(x1(...W)),Q.max=(...W)=>Q.check(L4(...W)),Q.length=(...W)=>Q.check(q4(...W)),Q.nonempty=(...W)=>Q.check(x1(1,...W)),Q.lowercase=(W)=>Q.check(rQ(W)),Q.uppercase=(W)=>Q.check(dQ(W)),Q.trim=()=>Q.check(eQ()),Q.normalize=(...W)=>Q.check(sQ(...W)),Q.toLowerCase=()=>Q.check(Q9()),Q.toUpperCase=()=>Q.check(Y9())}),X3=F("ZodString",(Q,Y)=>{A4.init(Q,Y),NG.init(Q,Y),Q.email=(X)=>Q.check(MW(W3,X)),Q.url=(X)=>Q.check(jW(G3,X)),Q.jwt=(X)=>Q.check(uW(V3,X)),Q.emoji=(X)=>Q.check(PW($3,X)),Q.guid=(X)=>Q.check(iQ(OG,X)),Q.uuid=(X)=>Q.check(VW(O4,X)),Q.uuidv4=(X)=>Q.check(NW(O4,X)),Q.uuidv6=(X)=>Q.check(ZW(O4,X)),Q.uuidv7=(X)=>Q.check(wW(O4,X)),Q.nanoid=(X)=>Q.check(bW(z3,X)),Q.guid=(X)=>Q.check(iQ(OG,X)),Q.cuid=(X)=>Q.check(IW(J3,X)),Q.cuid2=(X)=>Q.check(EW(H3,X)),Q.ulid=(X)=>Q.check(TW(U3,X)),Q.base64=(X)=>Q.check(_W(F3,X)),Q.base64url=(X)=>Q.check(gW(O3,X)),Q.xid=(X)=>Q.check(SW(A3,X)),Q.ksuid=(X)=>Q.check(RW(B3,X)),Q.ipv4=(X)=>Q.check(CW(K3,X)),Q.ipv6=(X)=>Q.check(kW(D3,X)),Q.cidrv4=(X)=>Q.check(vW(L3,X)),Q.cidrv6=(X)=>Q.check(xW(q3,X)),Q.e164=(X)=>Q.check(yW(M3,X)),Q.datetime=(X)=>Q.check(X9(X)),Q.date=(X)=>Q.check(W9(X)),Q.time=(X)=>Q.check(G9(X)),Q.duration=(X)=>Q.check($9(X))});function q(Q){return OW(X3,Q)}var s=F("ZodStringFormat",(Q,Y)=>{t.init(Q,Y),NG.init(Q,Y)}),W3=F("ZodEmail",(Q,Y)=>{P8.init(Q,Y),s.init(Q,Y)});var OG=F("ZodGUID",(Q,Y)=>{w8.init(Q,Y),s.init(Q,Y)});var O4=F("ZodUUID",(Q,Y)=>{j8.init(Q,Y),s.init(Q,Y)});var G3=F("ZodURL",(Q,Y)=>{b8.init(Q,Y),s.init(Q,Y)});var $3=F("ZodEmoji",(Q,Y)=>{I8.init(Q,Y),s.init(Q,Y)});var z3=F("ZodNanoID",(Q,Y)=>{E8.init(Q,Y),s.init(Q,Y)});var J3=F("ZodCUID",(Q,Y)=>{T8.init(Q,Y),s.init(Q,Y)});var H3=F("ZodCUID2",(Q,Y)=>{S8.init(Q,Y),s.init(Q,Y)});var U3=F("ZodULID",(Q,Y)=>{R8.init(Q,Y),s.init(Q,Y)});var A3=F("ZodXID",(Q,Y)=>{C8.init(Q,Y),s.init(Q,Y)});var B3=F("ZodKSUID",(Q,Y)=>{k8.init(Q,Y),s.init(Q,Y)});var K3=F("ZodIPv4",(Q,Y)=>{y8.init(Q,Y),s.init(Q,Y)});var D3=F("ZodIPv6",(Q,Y)=>{u8.init(Q,Y),s.init(Q,Y)});var L3=F("ZodCIDRv4",(Q,Y)=>{h8.init(Q,Y),s.init(Q,Y)});var q3=F("ZodCIDRv6",(Q,Y)=>{f8.init(Q,Y),s.init(Q,Y)});var F3=F("ZodBase64",(Q,Y)=>{m8.init(Q,Y),s.init(Q,Y)});var O3=F("ZodBase64URL",(Q,Y)=>{c8.init(Q,Y),s.init(Q,Y)});var M3=F("ZodE164",(Q,Y)=>{p8.init(Q,Y),s.init(Q,Y)});var V3=F("ZodJWT",(Q,Y)=>{i8.init(Q,Y),s.init(Q,Y)});var ZG=F("ZodNumber",(Q,Y)=>{mQ.init(Q,Y),X0.init(Q,Y),Q.gt=(W,G)=>Q.check(K4(W,G)),Q.gte=(W,G)=>Q.check(B6(W,G)),Q.min=(W,G)=>Q.check(B6(W,G)),Q.lt=(W,G)=>Q.check(B4(W,G)),Q.lte=(W,G)=>Q.check(A6(W,G)),Q.max=(W,G)=>Q.check(A6(W,G)),Q.int=(W)=>Q.check(MG(W)),Q.safe=(W)=>Q.check(MG(W)),Q.positive=(W)=>Q.check(K4(0,W)),Q.nonnegative=(W)=>Q.check(B6(0,W)),Q.negative=(W)=>Q.check(B4(0,W)),Q.nonpositive=(W)=>Q.check(A6(0,W)),Q.multipleOf=(W,G)=>Q.check(D4(W,G)),Q.step=(W,G)=>Q.check(D4(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 p(Q){return cW(ZG,Q)}var N3=F("ZodNumberFormat",(Q,Y)=>{n8.init(Q,Y),ZG.init(Q,Y)});function MG(Q){return pW(N3,Q)}var Z3=F("ZodBoolean",(Q,Y)=>{r8.init(Q,Y),X0.init(Q,Y)});function z0(Q){return iW(Z3,Q)}var w3=F("ZodNull",(Q,Y)=>{d8.init(Q,Y),X0.init(Q,Y)});function H9(Q){return nW(w3,Q)}var j3=F("ZodUnknown",(Q,Y)=>{o8.init(Q,Y),X0.init(Q,Y)});function e(){return rW(j3)}var P3=F("ZodNever",(Q,Y)=>{t8.init(Q,Y),X0.init(Q,Y)});function b3(Q){return dW(P3,Q)}var I3=F("ZodArray",(Q,Y)=>{a8.init(Q,Y),X0.init(Q,Y),Q.element=Y.element,Q.min=(X,W)=>Q.check(x1(X,W)),Q.nonempty=(X)=>Q.check(x1(1,X)),Q.max=(X,W)=>Q.check(L4(X,W)),Q.length=(X,W)=>Q.check(q4(X,W)),Q.unwrap=()=>Q.element});function u(Q,Y){return oW(I3,Q,Y)}var wG=F("ZodObject",(Q,Y)=>{QW.init(Q,Y),X0.init(Q,Y),m.defineLazy(Q,"shape",()=>{return Y.shape}),Q.keyof=()=>M0(Object.keys(Q._zod.def.shape)),Q.catchall=(X)=>Q.clone({...Q._zod.def,catchall:X}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:b3()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(X)=>{return m.extend(Q,X)},Q.safeExtend=(X)=>{return m.safeExtend(Q,X)},Q.merge=(X)=>m.merge(Q,X),Q.pick=(X)=>m.pick(Q,X),Q.omit=(X)=>m.omit(Q,X),Q.partial=(...X)=>m.partial(bG,Q,X[0]),Q.required=(...X)=>m.required(IG,Q,X[0])});function P(Q,Y){let X={type:"object",shape:Q??{},...m.normalizeParams(Y)};return new wG(X)}function q0(Q,Y){return new wG({type:"object",shape:Q,catchall:e(),...m.normalizeParams(Y)})}var jG=F("ZodUnion",(Q,Y)=>{cQ.init(Q,Y),X0.init(Q,Y),Q.options=Y.options});function d(Q,Y){return new jG({type:"union",options:Q,...m.normalizeParams(Y)})}var E3=F("ZodDiscriminatedUnion",(Q,Y)=>{jG.init(Q,Y),YW.init(Q,Y)});function U9(Q,Y,X){return new E3({type:"union",options:Y,discriminator:Q,...m.normalizeParams(X)})}var T3=F("ZodIntersection",(Q,Y)=>{XW.init(Q,Y),X0.init(Q,Y)});function M4(Q,Y){return new T3({type:"intersection",left:Q,right:Y})}var S3=F("ZodRecord",(Q,Y)=>{WW.init(Q,Y),X0.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function Q0(Q,Y,X){return new S3({type:"record",keyType:Q,valueType:Y,...m.normalizeParams(X)})}var z9=F("ZodEnum",(Q,Y)=>{GW.init(Q,Y),X0.init(Q,Y),Q.enum=Y.entries,Q.options=Object.values(Y.entries);let X=new Set(Object.keys(Y.entries));Q.extract=(W,G)=>{let $={};for(let z of W)if(X.has(z))$[z]=Y.entries[z];else throw Error(`Key ${z} not found in enum`);return new z9({...Y,checks:[],...m.normalizeParams(G),entries:$})},Q.exclude=(W,G)=>{let $={...Y.entries};for(let z of W)if(X.has(z))delete $[z];else throw Error(`Key ${z} not found in enum`);return new z9({...Y,checks:[],...m.normalizeParams(G),entries:$})}});function M0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new z9({type:"enum",entries:X,...m.normalizeParams(Y)})}var R3=F("ZodLiteral",(Q,Y)=>{$W.init(Q,Y),X0.init(Q,Y),Q.values=new Set(Y.values),Object.defineProperty(Q,"value",{get(){if(Y.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return Y.values[0]}})});function b(Q,Y){return new R3({type:"literal",values:Array.isArray(Q)?Q:[Q],...m.normalizeParams(Y)})}var C3=F("ZodTransform",(Q,Y)=>{zW.init(Q,Y),X0.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new Q6(Q.constructor.name);X.addIssue=($)=>{if(typeof $==="string")X.issues.push(m.issue($,X.value,Y));else{let z=$;if(z.fatal)z.continue=!1;z.code??(z.code="custom"),z.input??(z.input=X.value),z.inst??(z.inst=Q),X.issues.push(m.issue(z))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then(($)=>{return X.value=$,X});return X.value=G,X}});function PG(Q){return new C3({type:"transform",transform:Q})}var bG=F("ZodOptional",(Q,Y)=>{JW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function Y0(Q){return new bG({type:"optional",innerType:Q})}var k3=F("ZodNullable",(Q,Y)=>{HW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function VG(Q){return new k3({type:"nullable",innerType:Q})}var v3=F("ZodDefault",(Q,Y)=>{UW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function x3(Q,Y){return new v3({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var _3=F("ZodPrefault",(Q,Y)=>{AW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function g3(Q,Y){return new _3({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var IG=F("ZodNonOptional",(Q,Y)=>{BW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function y3(Q,Y){return new IG({type:"nonoptional",innerType:Q,...m.normalizeParams(Y)})}var u3=F("ZodCatch",(Q,Y)=>{KW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function h3(Q,Y){return new u3({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var f3=F("ZodPipe",(Q,Y)=>{DW.init(Q,Y),X0.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function J9(Q,Y){return new f3({type:"pipe",in:Q,out:Y})}var l3=F("ZodReadonly",(Q,Y)=>{LW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function m3(Q){return new l3({type:"readonly",innerType:Q})}var EG=F("ZodCustom",(Q,Y)=>{qW.init(Q,Y),X0.init(Q,Y)});function TG(Q,Y){return tW(EG,Q??(()=>!0),Y)}function c3(Q,Y={}){return aW(EG,Q,Y)}function p3(Q){return sW(Q)}function A9(Q,Y){return J9(PG(Q),Y)}I0(pQ());var B9="2025-11-25";var SG=[B9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],U1="io.modelcontextprotocol/related-task",N4="2.0",U0=TG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),RG=d([q(),p().int()]),CG=q(),lZ=q0({ttl:d([p(),H9()]).optional(),pollInterval:p().optional()}),i3=P({ttl:p().optional()}),n3=P({taskId:q()}),K9=q0({progressToken:RG.optional(),[U1]:n3.optional()}),b0=P({_meta:K9.optional()}),L6=b0.extend({task:i3.optional()}),kG=(Q)=>L6.safeParse(Q).success,A0=P({method:q(),params:b0.loose().optional()}),E0=P({_meta:K9.optional()}),T0=P({method:q(),params:E0.loose().optional()}),B0=q0({_meta:K9.optional()}),Z4=d([q(),p().int()]),vG=P({jsonrpc:b(N4),id:Z4,...A0.shape}).strict(),D9=(Q)=>vG.safeParse(Q).success,xG=P({jsonrpc:b(N4),...T0.shape}).strict(),_G=(Q)=>xG.safeParse(Q).success,L9=P({jsonrpc:b(N4),id:Z4,result:B0}).strict(),q6=(Q)=>L9.safeParse(Q).success;var h;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(h||(h={}));var q9=P({jsonrpc:b(N4),id:Z4.optional(),error:P({code:p().int(),message:q(),data:e().optional()})}).strict();var gG=(Q)=>q9.safeParse(Q).success;var mZ=d([vG,xG,L9,q9]),cZ=d([L9,q9]),w4=B0.strict(),r3=E0.extend({requestId:Z4.optional(),reason:q().optional()}),j4=T0.extend({method:b("notifications/cancelled"),params:r3}),d3=P({src:q(),mimeType:q().optional(),sizes:u(q()).optional(),theme:M0(["light","dark"]).optional()}),F6=P({icons:u(d3).optional()}),g1=P({name:q(),title:q().optional()}),yG=g1.extend({...g1.shape,...F6.shape,version:q(),websiteUrl:q().optional(),description:q().optional()}),o3=M4(P({applyDefaults:z0().optional()}),Q0(q(),e())),t3=A9((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},M4(P({form:o3.optional(),url:U0.optional()}),Q0(q(),e()).optional())),a3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({sampling:q0({createMessage:U0.optional()}).optional(),elicitation:q0({create:U0.optional()}).optional()}).optional()}),s3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({tools:q0({call:U0.optional()}).optional()}).optional()}),e3=P({experimental:Q0(q(),U0).optional(),sampling:P({context:U0.optional(),tools:U0.optional()}).optional(),elicitation:t3.optional(),roots:P({listChanged:z0().optional()}).optional(),tasks:a3.optional()}),QU=b0.extend({protocolVersion:q(),capabilities:e3,clientInfo:yG}),F9=A0.extend({method:b("initialize"),params:QU});var YU=P({experimental:Q0(q(),U0).optional(),logging:U0.optional(),completions:U0.optional(),prompts:P({listChanged:z0().optional()}).optional(),resources:P({subscribe:z0().optional(),listChanged:z0().optional()}).optional(),tools:P({listChanged:z0().optional()}).optional(),tasks:s3.optional()}),XU=B0.extend({protocolVersion:q(),capabilities:YU,serverInfo:yG,instructions:q().optional()}),O9=T0.extend({method:b("notifications/initialized"),params:E0.optional()});var P4=A0.extend({method:b("ping"),params:b0.optional()}),WU=P({progress:p(),total:Y0(p()),message:Y0(q())}),GU=P({...E0.shape,...WU.shape,progressToken:RG}),b4=T0.extend({method:b("notifications/progress"),params:GU}),$U=b0.extend({cursor:CG.optional()}),O6=A0.extend({params:$U.optional()}),M6=B0.extend({nextCursor:CG.optional()}),zU=M0(["working","input_required","completed","failed","cancelled"]),V6=P({taskId:q(),status:zU,ttl:d([p(),H9()]),createdAt:q(),lastUpdatedAt:q(),pollInterval:Y0(p()),statusMessage:Y0(q())}),y1=B0.extend({task:V6}),JU=E0.merge(V6),N6=T0.extend({method:b("notifications/tasks/status"),params:JU}),I4=A0.extend({method:b("tasks/get"),params:b0.extend({taskId:q()})}),E4=B0.merge(V6),T4=A0.extend({method:b("tasks/result"),params:b0.extend({taskId:q()})}),pZ=B0.loose(),S4=O6.extend({method:b("tasks/list")}),R4=M6.extend({tasks:u(V6)}),C4=A0.extend({method:b("tasks/cancel"),params:b0.extend({taskId:q()})}),uG=B0.merge(V6),hG=P({uri:q(),mimeType:Y0(q()),_meta:Q0(q(),e()).optional()}),fG=hG.extend({text:q()}),M9=q().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),lG=hG.extend({blob:M9}),Z6=M0(["user","assistant"]),u1=P({audience:u(Z6).optional(),priority:p().min(0).max(1).optional(),lastModified:D6.datetime({offset:!0}).optional()}),mG=P({...g1.shape,...F6.shape,uri:q(),description:Y0(q()),mimeType:Y0(q()),annotations:u1.optional(),_meta:Y0(q0({}))}),HU=P({...g1.shape,...F6.shape,uriTemplate:q(),description:Y0(q()),mimeType:Y0(q()),annotations:u1.optional(),_meta:Y0(q0({}))}),V9=O6.extend({method:b("resources/list")}),UU=M6.extend({resources:u(mG)}),AU=O6.extend({method:b("resources/templates/list")}),BU=M6.extend({resourceTemplates:u(HU)}),N9=b0.extend({uri:q()}),KU=N9,Z9=A0.extend({method:b("resources/read"),params:KU}),DU=B0.extend({contents:u(d([fG,lG]))}),LU=T0.extend({method:b("notifications/resources/list_changed"),params:E0.optional()}),qU=N9,FU=A0.extend({method:b("resources/subscribe"),params:qU}),OU=N9,MU=A0.extend({method:b("resources/unsubscribe"),params:OU}),VU=E0.extend({uri:q()}),NU=T0.extend({method:b("notifications/resources/updated"),params:VU}),ZU=P({name:q(),description:Y0(q()),required:Y0(z0())}),wU=P({...g1.shape,...F6.shape,description:Y0(q()),arguments:Y0(u(ZU)),_meta:Y0(q0({}))}),jU=O6.extend({method:b("prompts/list")}),PU=M6.extend({prompts:u(wU)}),bU=b0.extend({name:q(),arguments:Q0(q(),q()).optional()}),IU=A0.extend({method:b("prompts/get"),params:bU}),w9=P({type:b("text"),text:q(),annotations:u1.optional(),_meta:Q0(q(),e()).optional()}),j9=P({type:b("image"),data:M9,mimeType:q(),annotations:u1.optional(),_meta:Q0(q(),e()).optional()}),P9=P({type:b("audio"),data:M9,mimeType:q(),annotations:u1.optional(),_meta:Q0(q(),e()).optional()}),EU=P({type:b("tool_use"),name:q(),id:q(),input:Q0(q(),e()),_meta:Q0(q(),e()).optional()}),TU=P({type:b("resource"),resource:d([fG,lG]),annotations:u1.optional(),_meta:Q0(q(),e()).optional()}),SU=mG.extend({type:b("resource_link")}),b9=d([w9,j9,P9,SU,TU]),RU=P({role:Z6,content:b9}),CU=B0.extend({description:q().optional(),messages:u(RU)}),kU=T0.extend({method:b("notifications/prompts/list_changed"),params:E0.optional()}),vU=P({title:q().optional(),readOnlyHint:z0().optional(),destructiveHint:z0().optional(),idempotentHint:z0().optional(),openWorldHint:z0().optional()}),xU=P({taskSupport:M0(["required","optional","forbidden"]).optional()}),cG=P({...g1.shape,...F6.shape,description:q().optional(),inputSchema:P({type:b("object"),properties:Q0(q(),U0).optional(),required:u(q()).optional()}).catchall(e()),outputSchema:P({type:b("object"),properties:Q0(q(),U0).optional(),required:u(q()).optional()}).catchall(e()).optional(),annotations:vU.optional(),execution:xU.optional(),_meta:Q0(q(),e()).optional()}),I9=O6.extend({method:b("tools/list")}),_U=M6.extend({tools:u(cG)}),k4=B0.extend({content:u(b9).default([]),structuredContent:Q0(q(),e()).optional(),isError:z0().optional()}),iZ=k4.or(B0.extend({toolResult:e()})),gU=L6.extend({name:q(),arguments:Q0(q(),e()).optional()}),w6=A0.extend({method:b("tools/call"),params:gU}),yU=T0.extend({method:b("notifications/tools/list_changed"),params:E0.optional()}),nZ=P({autoRefresh:z0().default(!0),debounceMs:p().int().nonnegative().default(300)}),j6=M0(["debug","info","notice","warning","error","critical","alert","emergency"]),uU=b0.extend({level:j6}),E9=A0.extend({method:b("logging/setLevel"),params:uU}),hU=E0.extend({level:j6,logger:q().optional(),data:e()}),fU=T0.extend({method:b("notifications/message"),params:hU}),lU=P({name:q().optional()}),mU=P({hints:u(lU).optional(),costPriority:p().min(0).max(1).optional(),speedPriority:p().min(0).max(1).optional(),intelligencePriority:p().min(0).max(1).optional()}),cU=P({mode:M0(["auto","required","none"]).optional()}),pU=P({type:b("tool_result"),toolUseId:q().describe("The unique identifier for the corresponding tool call."),content:u(b9).default([]),structuredContent:P({}).loose().optional(),isError:z0().optional(),_meta:Q0(q(),e()).optional()}),iU=U9("type",[w9,j9,P9]),V4=U9("type",[w9,j9,P9,EU,pU]),nU=P({role:Z6,content:d([V4,u(V4)]),_meta:Q0(q(),e()).optional()}),rU=L6.extend({messages:u(nU),modelPreferences:mU.optional(),systemPrompt:q().optional(),includeContext:M0(["none","thisServer","allServers"]).optional(),temperature:p().optional(),maxTokens:p().int(),stopSequences:u(q()).optional(),metadata:U0.optional(),tools:u(cG).optional(),toolChoice:cU.optional()}),dU=A0.extend({method:b("sampling/createMessage"),params:rU}),T9=B0.extend({model:q(),stopReason:Y0(M0(["endTurn","stopSequence","maxTokens"]).or(q())),role:Z6,content:iU}),S9=B0.extend({model:q(),stopReason:Y0(M0(["endTurn","stopSequence","maxTokens","toolUse"]).or(q())),role:Z6,content:d([V4,u(V4)])}),oU=P({type:b("boolean"),title:q().optional(),description:q().optional(),default:z0().optional()}),tU=P({type:b("string"),title:q().optional(),description:q().optional(),minLength:p().optional(),maxLength:p().optional(),format:M0(["email","uri","date","date-time"]).optional(),default:q().optional()}),aU=P({type:M0(["number","integer"]),title:q().optional(),description:q().optional(),minimum:p().optional(),maximum:p().optional(),default:p().optional()}),sU=P({type:b("string"),title:q().optional(),description:q().optional(),enum:u(q()),default:q().optional()}),eU=P({type:b("string"),title:q().optional(),description:q().optional(),oneOf:u(P({const:q(),title:q()})),default:q().optional()}),QA=P({type:b("string"),title:q().optional(),description:q().optional(),enum:u(q()),enumNames:u(q()).optional(),default:q().optional()}),YA=d([sU,eU]),XA=P({type:b("array"),title:q().optional(),description:q().optional(),minItems:p().optional(),maxItems:p().optional(),items:P({type:b("string"),enum:u(q())}),default:u(q()).optional()}),WA=P({type:b("array"),title:q().optional(),description:q().optional(),minItems:p().optional(),maxItems:p().optional(),items:P({anyOf:u(P({const:q(),title:q()}))}),default:u(q()).optional()}),GA=d([XA,WA]),$A=d([QA,YA,GA]),zA=d([$A,oU,tU,aU]),JA=L6.extend({mode:b("form").optional(),message:q(),requestedSchema:P({type:b("object"),properties:Q0(q(),zA),required:u(q()).optional()})}),HA=L6.extend({mode:b("url"),message:q(),elicitationId:q(),url:q().url()}),UA=d([JA,HA]),AA=A0.extend({method:b("elicitation/create"),params:UA}),BA=E0.extend({elicitationId:q()}),KA=T0.extend({method:b("notifications/elicitation/complete"),params:BA}),v4=B0.extend({action:M0(["accept","decline","cancel"]),content:A9((Q)=>Q===null?void 0:Q,Q0(q(),d([q(),p(),z0(),u(q())])).optional())}),DA=P({type:b("ref/resource"),uri:q()});var LA=P({type:b("ref/prompt"),name:q()}),qA=b0.extend({ref:d([LA,DA]),argument:P({name:q(),value:q()}),context:P({arguments:Q0(q(),q()).optional()}).optional()}),FA=A0.extend({method:b("completion/complete"),params:qA});var OA=B0.extend({completion:q0({values:u(q()).max(100),total:Y0(p().int()),hasMore:Y0(z0())})}),MA=P({uri:q().startsWith("file://"),name:q().optional(),_meta:Q0(q(),e()).optional()}),VA=A0.extend({method:b("roots/list"),params:b0.optional()}),R9=B0.extend({roots:u(MA)}),NA=T0.extend({method:b("notifications/roots/list_changed"),params:E0.optional()}),rZ=d([P4,F9,FA,E9,IU,jU,V9,AU,Z9,FU,MU,w6,I9,I4,T4,S4,C4]),dZ=d([j4,b4,O9,NA,N6]),oZ=d([w4,T9,S9,v4,R9,E4,R4,y1]),tZ=d([P4,dU,AA,VA,I4,T4,S4,C4]),aZ=d([j4,b4,fU,NU,LU,yU,kU,N6,KA]),sZ=d([w4,XU,OA,CU,PU,UU,BU,DU,k4,_U,E4,R4,y1]);class _ extends Error{constructor(Q,Y,X){super(`MCP error ${Q}: ${Y}`);this.code=Q,this.data=X,this.name="McpError"}static fromError(Q,Y,X){if(Q===h.UrlElicitationRequired&&X){let W=X;if(W.elicitations)return new pG(W.elicitations,Y)}return new _(Q,Y,X)}}class pG extends _{constructor(Q,Y=`URL elicitation${Q.length>1?"s":""} required`){super(h.UrlElicitationRequired,Y,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function A1(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var ZA=Symbol("Let zodToJsonSchema decide on which parser to use");var Cw=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function C9(Q){let X=F4(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=eW(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function k9(Q,Y){let X=H1(Q,Y);if(!X.success)throw X.error;return X.data}var EA=60000;class v9{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(j4,(Y)=>{this._oncancel(Y)}),this.setNotificationHandler(b4,(Y)=>{this._onprogress(Y)}),this.setRequestHandler(P4,(Y)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(I4,async(Y,X)=>{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(T4,async(Y,X)=>{let W=async()=>{let G=Y.params.taskId;if(this._taskMessageQueue){let z;while(z=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(z.type==="response"||z.type==="error"){let J=z.message,H=J.id,U=this._requestResolvers.get(H);if(U)if(this._requestResolvers.delete(H),z.type==="response")U(J);else{let A=J,B=new _(A.error.code,A.error.message,A.error.data);U(B)}else{let A=z.type==="response"?"Response":"Error";this._onerror(Error(`${A} handler missing for request ${H}`))}continue}await this._transport?.send(z.message,{relatedRequestId:X.requestId})}}let $=await this._taskStore.getTask(G,X.sessionId);if(!$)throw new _(h.InvalidParams,`Task not found: ${G}`);if(!A1($.status))return await this._waitForTaskUpdate(G,X.signal),await W();if(A1($.status)){let z=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...z,_meta:{...z._meta,[U1]:{taskId:G}}}}return await W()};return await W()}),this.setRequestHandler(S4,async(Y,X)=>{try{let{tasks:W,nextCursor:G}=await this._taskStore.listTasks(Y.params?.cursor,X.sessionId);return{tasks:W,nextCursor:G,_meta:{}}}catch(W){throw new _(h.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(C4,async(Y,X)=>{try{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,`Task not found: ${Y.params.taskId}`);if(A1(W.status))throw new _(h.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(Y.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Y.params.taskId);let G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new _(h.InvalidParams,`Task not found after cancellation: ${Y.params.taskId}`);return{_meta:{},...G}}catch(W){if(W instanceof _)throw W;throw new _(h.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,Y,X,W,G=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,Y),startTime:Date.now(),timeout:Y,maxTotalTimeout:X,resetTimeoutOnProgress:G,onTimeout:W})}_resetTimeout(Q){let Y=this._timeoutInfo.get(Q);if(!Y)return!1;let X=Date.now()-Y.startTime;if(Y.maxTotalTimeout&&X>=Y.maxTotalTimeout)throw this._timeoutInfo.delete(Q),_.fromError(h.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Y.maxTotalTimeout,totalElapsed:X});return clearTimeout(Y.timeoutId),Y.timeoutId=setTimeout(Y.onTimeout,Y.timeout),!0}_cleanupTimeout(Q){let Y=this._timeoutInfo.get(Q);if(Y)clearTimeout(Y.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let Y=this.transport?.onclose;this._transport.onclose=()=>{Y?.(),this._onclose()};let X=this.transport?.onerror;this._transport.onerror=(G)=>{X?.(G),this._onerror(G)};let W=this._transport?.onmessage;this._transport.onmessage=(G,$)=>{if(W?.(G,$),q6(G)||gG(G))this._onresponse(G);else if(D9(G))this._onrequest(G,$);else if(_G(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let Y=_.fromError(h.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of Q.values())X(Y)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let Y=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(Y===void 0)return;Promise.resolve().then(()=>Y(Q)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(Q,Y){let X=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,G=Q.params?._meta?.[U1]?.taskId;if(X===void 0){let U={jsonrpc:"2.0",id:Q.id,error:{code:h.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId).catch((A)=>this._onerror(Error(`Failed to enqueue error response: ${A}`)));else W?.send(U).catch((A)=>this._onerror(Error(`Failed to send an error response: ${A}`)));return}let $=new AbortController;this._requestHandlerAbortControllers.set(Q.id,$);let z=kG(Q.params)?Q.params.task:void 0,J=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:$.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(U)=>{let A={relatedRequestId:Q.id};if(G)A.relatedTask={taskId:G};await this.notification(U,A)},sendRequest:async(U,A,B)=>{let K={...B,relatedRequestId:Q.id};if(G&&!K.relatedTask)K.relatedTask={taskId:G};let D=K.relatedTask?.taskId??G;if(D&&J)await J.updateTaskStatus(D,"input_required");return await this.request(U,A,K)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:J,taskRequestedTtl:z?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(z)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(U)=>{if($.signal.aborted)return;let A={result:U,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)},async(U)=>{if($.signal.aborted)return;let A={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(U.code)?U.code:h.InternalError,message:U.message??"Internal error",...U.data!==void 0&&{data:U.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)}).catch((U)=>this._onerror(Error(`Failed to send response: ${U}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:Y,...X}=Q.params,W=Number(Y),G=this._progressHandlers.get(W);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let $=this._responseHandlers.get(W),z=this._timeoutInfo.get(W);if(z&&$&&z.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(J){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),$(J);return}G(X)}_onresponse(Q){let Y=Number(Q.id),X=this._requestResolvers.get(Y);if(X){if(this._requestResolvers.delete(Y),q6(Q))X(Q);else{let $=new _(Q.error.code,Q.error.message,Q.error.data);X($)}return}let W=this._responseHandlers.get(Y);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(Y),this._cleanupTimeout(Y);let G=!1;if(q6(Q)&&Q.result&&typeof Q.result==="object"){let $=Q.result;if($.task&&typeof $.task==="object"){let z=$.task;if(typeof z.taskId==="string")G=!0,this._taskProgressTokens.set(z.taskId,Y)}}if(!G)this._progressHandlers.delete(Y);if(q6(Q))W(Q);else{let $=_.fromError(Q.error.code,Q.error.message,Q.error.data);W($)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,Y,X){let{task:W}=X??{};if(!W){try{yield{type:"result",result:await this.request(Q,Y,X)}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}return}let G;try{let $=await this.request(Q,y1,X);if($.task)G=$.task.taskId,yield{type:"taskCreated",task:$.task};else throw new _(h.InternalError,"Task creation did not return a task");while(!0){let z=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:z},A1(z.status)){if(z.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(z.status==="failed")yield{type:"error",error:new _(h.InternalError,`Task ${G} failed`)};else if(z.status==="cancelled")yield{type:"error",error:new _(h.InternalError,`Task ${G} was cancelled`)};return}if(z.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let J=z.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,J)),X?.signal?.throwIfAborted()}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$,task:z,relatedTask:J}=X??{};return new Promise((H,U)=>{let A=(V)=>{U(V)};if(!this._transport){A(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),z)this.assertTaskCapability(Q.method)}catch(V){A(V);return}X?.signal?.throwIfAborted();let B=this._requestMessageId++,K={...Q,jsonrpc:"2.0",id:B};if(X?.onprogress)this._progressHandlers.set(B,X.onprogress),K.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:B}};if(z)K.params={...K.params,task:z};if(J)K.params={...K.params,_meta:{...K.params?._meta||{},[U1]:J}};let D=(V)=>{this._responseHandlers.delete(B),this._progressHandlers.delete(B),this._cleanupTimeout(B),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:B,reason:String(V)}},{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((T)=>this._onerror(Error(`Failed to send cancellation: ${T}`)));let R=V instanceof _?V:new _(h.RequestTimeout,String(V));U(R)};this._responseHandlers.set(B,(V)=>{if(X?.signal?.aborted)return;if(V instanceof Error)return U(V);try{let R=H1(Y,V.result);if(!R.success)U(R.error);else H(R.data)}catch(R){U(R)}}),X?.signal?.addEventListener("abort",()=>{D(X?.signal?.reason)});let O=X?.timeout??EA,M=()=>D(_.fromError(h.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(B,O,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let Z=J?.taskId;if(Z){let V=(R)=>{let T=this._responseHandlers.get(B);if(T)T(R);else this._onerror(Error(`Response handler missing for side-channeled request ${B}`))};this._requestResolvers.set(B,V),this._enqueueTaskMessage(Z,{type:"request",message:K,timestamp:Date.now()}).catch((R)=>{this._cleanupTimeout(B),U(R)})}else this._transport.send(K,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((V)=>{this._cleanupTimeout(B),U(V)})})}async getTask(Q,Y){return this.request({method:"tasks/get",params:Q},E4,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},R4,Y)}async cancelTask(Q,Y){return this.request({method:"tasks/cancel",params:Q},uG,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let z={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[U1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:z,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!Y?.relatedRequestId&&!Y?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let z={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)z={...z,params:{...z.params,_meta:{...z.params?._meta||{},[U1]:Y.relatedTask}}};this._transport?.send(z,Y).catch((J)=>this._onerror(J))});return}let $={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)$={...$,params:{...$.params,_meta:{...$.params?._meta||{},[U1]:Y.relatedTask}}};await this._transport.send($,Y)}setRequestHandler(Q,Y){let X=C9(Q);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(W,G)=>{let $=k9(Q,W);return Promise.resolve(Y($,G))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,Y){let X=C9(Q);this._notificationHandlers.set(X,(W)=>{let G=k9(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"&&D9(W.message)){let G=W.message.id,$=this._requestResolvers.get(G);if($)$(new _(h.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,Y){let X=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)X=W.pollInterval}catch{}return new Promise((W,G)=>{if(Y.aborted){G(new _(h.InvalidRequest,"Request cancelled"));return}let $=setTimeout(W,X);Y.addEventListener("abort",()=>{clearTimeout($),G(new _(h.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,Y){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await X.createTask(W,Q.id,{method:Q.method,params:Q.params},Y)},getTask:async(W)=>{let G=await X.getTask(W,Y);if(!G)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(W,G,$)=>{await X.storeTaskResult(W,G,$,Y);let z=await X.getTask(W,Y);if(z){let J=N6.parse({method:"notifications/tasks/status",params:z});if(await this.notification(J),A1(z.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,$)=>{let z=await X.getTask(W,Y);if(!z)throw new _(h.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(A1(z.status))throw new _(h.InvalidParams,`Cannot update task "${W}" from terminal status "${z.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,$,Y);let J=await X.getTask(W,Y);if(J){let H=N6.parse({method:"notifications/tasks/status",params:J});if(await this.notification(H),A1(J.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function iG(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function nG(Q,Y){let X={...Q};for(let W in Y){let G=W,$=Y[G];if($===void 0)continue;let z=X[G];if(iG(z)&&iG($))X[G]={...z,...$};else X[G]=$}return X}var j5=sY(EY(),1),P5=sY(w5(),1);function gM(){let Q=new j5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return P5.default(Q),Q}class yY{constructor(Q){this._ajv=Q??gM()}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 uY{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 b5(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 I5(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 hY extends v9{constructor(Q,Y){super(Y);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(j6.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 yY,this.setRequestHandler(F9,(X)=>this._oninitialize(X)),this.setNotificationHandler(O9,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(E9,async(X,W)=>{let G=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:$}=X.params,z=j6.safeParse($);if(z.success)this._loggingLevels.set(G,z.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new uY(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=nG(this._capabilities,Q)}setRequestHandler(Q,Y){let W=F4(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let G;if(_1(W)){let z=W;G=z._zod?.def?.value??z.value}else{let z=W;G=z._def?.value??z.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let z=async(J,H)=>{let U=H1(w6,J);if(!U.success){let D=U.error instanceof Error?U.error.message:String(U.error);throw new _(h.InvalidParams,`Invalid tools/call request: ${D}`)}let{params:A}=U.data,B=await Promise.resolve(Y(J,H));if(A.task){let D=H1(y1,B);if(!D.success){let O=D.error instanceof Error?D.error.message:String(D.error);throw new _(h.InvalidParams,`Invalid task creation result: ${O}`)}return D.data}let K=H1(k4,B);if(!K.success){let D=K.error instanceof Error?K.error.message:String(K.error);throw new _(h.InvalidParams,`Invalid tools/call result: ${D}`)}return K.data};return super.setRequestHandler(Q,z)}return super.setRequestHandler(Q,Y)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){I5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;b5(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:SG.includes(Y)?Y:B9,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},w4)}async createMessage(Q,Y){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let X=Q.messages[Q.messages.length-1],W=Array.isArray(X.content)?X.content:[X.content],G=W.some((H)=>H.type==="tool_result"),$=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,z=$?Array.isArray($.content)?$.content:[$.content]:[],J=z.some((H)=>H.type==="tool_use");if(G){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!J)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(J){let H=new Set(z.filter((A)=>A.type==="tool_use").map((A)=>A.id)),U=new Set(W.filter((A)=>A.type==="tool_result").map((A)=>A.toolUseId));if(H.size!==U.size||![...H].every((A)=>U.has(A)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},S9,Y);return this.request({method:"sampling/createMessage",params:Q},T9,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},v4,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},v4,Y);if(G.action==="accept"&&G.content&&W.requestedSchema)try{let z=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!z.valid)throw new _(h.InvalidParams,`Elicitation response content does not match requested schema: ${z.errorMessage}`)}catch($){if($ instanceof _)throw $;throw new _(h.InternalError,`Error validating elicitation response: ${$ instanceof Error?$.message:String($)}`)}return G}}}createElicitationCompletionNotifier(Q,Y){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},Y)}async listRoots(Q,Y){return this.request({method:"roots/list",params:Q},R9,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 E5={name:"@sequenzy/mcp",version:"0.0.65",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 fY=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],T5={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",landingPages:"/dashboard/company/{companyId}/landing-pages",landingPage:"/dashboard/company/{companyId}/landing-pages/{landingPageId}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function uM(Q){let X=(Q??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return X.length>0?X:"https://sequenzy.com"}function f0(Q){let Y=Q?.trim();return Y?Y:void 0}function n0(Q){return encodeURIComponent(Q)}function G0(Q,Y){return`${Q}${Y}`}function $0(Q,Y=""){return`/dashboard/company/${n0(Q)}${Y}`}function S5(Q,Y,X){return G0(Q,`${$0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function hM(Q,Y){let X=fY.map((W)=>[W,Y?S5(Q,Y,W):""]);return Object.fromEntries(X)}function M1(Q={},Y){let X=uM(Y),W=f0(Q.companyId),G={},$=hM(X,W);if(!W)return{appUrl:X,routeTemplates:T5,settingsTabValues:fY,urls:G,settingsUrls:$};G.dashboard=G0(X,$0(W)),G.campaigns=G0(X,$0(W,"/campaign")),G.landingPages=G0(X,$0(W,"/landing-pages")),G.sequences=G0(X,$0(W,"/sequences")),G.settings=G0(X,$0(W,"/settings")),G.emails=G0(X,$0(W,"/emails")),G.subscribers=G0(X,$0(W,"/subscribers")),G.sentEmails=G0(X,$0(W,"/sent-emails")),G.segments=G0(X,$0(W,"/segments")),G.metrics=G0(X,$0(W,"/metrics")),G.transactional=G0(X,$0(W,"/transactional"));let z=f0(Q.campaignId);if(z)G.campaign=G0(X,$0(W,`/campaign/${n0(z)}`)),G.campaignPreview=`${G.campaign}?step=review`;let J=f0(Q.landingPageId);if(J)G.landingPage=G0(X,$0(W,`/landing-pages/${n0(J)}`));let H=f0(Q.sequenceId);if(H)G.sequence=G0(X,$0(W,`/sequences/${n0(H)}`));let U=f0(Q.emailId)??f0(Q.templateId);if(U)G.email=G0(X,$0(W,`/emails/${n0(U)}`)),G.template=G.email;let A=f0(Q.transactionalId);if(A)G.transactionalEmail=G0(X,$0(W,`/transactional/${n0(A)}`));let B=f0(Q.emailSendId);if(B)G.emailSend=G0(X,$0(W,`/sent-emails/${n0(B)}`));let K=f0(Q.domainId);if(K)G.domain=G0(X,$0(W,`/settings/domain/${n0(K)}`)),G.domainVerify=`${G.domain}/verify`;let D=f0(Q.status);if(D)G.campaignList=G0(X,$0(W,`/campaign/list/${n0(D)}`)),G.sequenceList=G0(X,$0(W,`/sequences/list/${n0(D)}`));let O=f0(Q.settingsTab);if(O)G.settingsTab=S5(X,W,O);return{appUrl:X,routeTemplates:T5,settingsTabValues:fY,urls:G,settingsUrls:$}}var R5=[{uri:"sequenzy://dashboard",name:"Dashboard Overview",description:"Live overview stats for the last 7 days",mimeType:"application/json"},{uri:"sequenzy://company",name:"Current Company",description:"The currently selected company, including localization settings",mimeType:"application/json"},{uri:"sequenzy://campaigns/recent",name:"Recent Campaigns",description:"Last 10 campaigns with status and basic stats",mimeType:"application/json"},{uri:"sequenzy://subscribers/recent",name:"Recent Subscribers",description:"Most recently added subscribers",mimeType:"application/json"},{uri:"sequenzy://subscribers/engaged",name:"Engaged Subscribers",description:"Most active/engaged subscribers",mimeType:"application/json"},{uri:"sequenzy://sequences",name:"Sequences",description:"All email sequences with status",mimeType:"application/json"},{uri:"sequenzy://templates",name:"Templates",description:"All available email templates with localization status",mimeType:"application/json"},{uri:"sequenzy://segments",name:"Segments",description:"All defined segments with subscriber counts",mimeType:"application/json"},{uri:"sequenzy://tags",name:"Tags",description:"All tags with usage counts",mimeType:"application/json"},{uri:"sequenzy://health",name:"Deliverability Health",description:"Email deliverability metrics and health status",mimeType:"application/json"},{uri:"sequenzy://app-routes",name:"Dashboard URL Routes",description:"Route templates and settings tabs for building Sequenzy dashboard links",mimeType:"application/json"}];async function C5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await L("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await L("GET","/api/v1/account"),W=N1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await L("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await L("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await L("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await L("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await L("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await L("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await L("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await L("GET","/api/v1/tags");break;case"sequenzy://health":Y=await L("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=M1();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:R1(Y)}]}}}import{readFileSync as fM,statSync as lM}from"node:fs";import{basename as mM}from"node:path";var d6="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: [...] }.",t1="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`.",c5="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.",MQ="Complete Sequenzy landing page content JSON. Use this when replacing the page structure. The content must be the editor-compatible landing page schema with version, template, seo, theme, and blocks. Landing pages must include exactly one footer block and at most one form block.",cM="Optional template key for default content, such as from-scratch, waitlist, lead-magnet, launch, demo-request, webinar, newsletter, product-hunt, pricing-offer, agency-lead-gen, or feature-announcement.",k5=500,v5=500,x5={type:"object",description:"Optional send window for every email step in the sequence. When set, email actions that become due outside the window wait until the next allowed local time. Omit days to allow every day.",properties:{enabled:{type:"boolean",description:"Set false to disable the sending window when creating a sequence. For updates, prefer clearSendingWindow."},timezone:{type:"string",description:"IANA timezone for the window, e.g. Europe/Kiev or America/New_York."},startTime:{type:"string",description:"Earliest local send time in 24-hour HH:mm format, e.g. 08:00."},endTime:{type:"string",description:"Latest local send cutoff in 24-hour HH:mm format, e.g. 20:00. Must be later than startTime."},days:{type:"array",description:"Allowed local days. Use full names or short names such as monday, tuesday, mon, tue. Omit for every day.",items:{type:"string"}}},additionalProperties:!1},ZQ=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],wQ=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.unsubscribed","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","sequence.finished","sequence.failed"],pM=new Set(["get_account","get_app_urls","get_company","list_websites","check_website","get_integration_guide","get_subscriber","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_email_send","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_transactional_emails","get_transactional_email","get_stats","get_campaign_stats","get_sequence_stats","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_sequence","generate_subject_lines"]),iM=new Set(["select_company","create_company","create_api_key","add_website","add_subscriber","update_subscriber","remove_subscriber","upsert_products","delete_product","attach_product_file","remove_product_file","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","delete_template","restart_ab_test","update_ab_test_variant","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","create_landing_page","update_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","update_sequence","enable_sequence","disable_sequence","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery"]),nM=new Set(["send_test_email","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","enable_sequence","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery"]),rM=new Set(["remove_subscriber","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","disable_sequence","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook"]);function dM(Q){let Y=pM.has(Q),X=iM.has(Q);if(Y===X)throw Error(`MCP tool "${Q}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:Y,destructiveHint:Y?!1:rM.has(Q),openWorldHint:nM.has(Q)}}function oM(Q){return{...Q,annotations:{...Q.annotations,...dM(Q.name)}}}var pY={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"],commerceProduct:["is","is_not","at_least","less_than_count"]},tM=Object.entries(pY).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),_5={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","commerceProduct"],description:"Filter field. Use `event` for custom subscriber events, `segment` for saved segment membership, `stripeProduct`/`stripeCurrentProduct`/`stripeTrialProduct` for Stripe product-based segments, and `commerceProduct` for products purchased through commerce orders - the value is `provider:productId` (provider one of `shopify`, `woocommerce`, `api`; product ids are provider-scoped), optionally with an order-count threshold (`provider:productId:count`) for at_least/less_than_count; a bare product id matches the id on any provider. Engagement fields (`emailSent`, `emailDelivered`, `emailOpened`, `emailClicked`, `emailBounced`, `emailComplained`) accept a time range as the value or a specific campaign via `campaign:<campaign_id>`."},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${tM}.`},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},g5={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 iY(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 nY(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=iY([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(nY):[]}}function aM(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function sM(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function y5(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 eM(Q,Y){let X=Y.split(":");if(Q==="at_least"||Q==="less_than_count"){if(X.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let $=X.slice(0,-2).join(":").trim(),z=X.at(-2),J=X.at(-1),H=z===void 0?Number.NaN:Number.parseInt(z,10);return $&&Number.isInteger(H)&&H>0&&J!==void 0&&y5(J)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(X.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=X.slice(0,-1).join(":").trim(),G=X.at(-1);return W&&G!==void 0&&y5(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function QV(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 YV(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function XV(Q){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(Q)}function WV(Q,Y){if(Y==="cancels_at"||Y==="cancel_at"||Y==="cancellation_at")return!0;if(Q==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(Y);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(Y)}function GV(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function $V(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let J=X.indexOf(":");if(J===-1)return null;let H=X.substring(0,J).trim(),U=Number.parseInt(X.substring(J+1).trim(),10);return H&&Number.isInteger(U)&&U>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(Q!=="stripeCurrentProduct"&&Q!=="stripeTrialProduct")return null;let{productId:W,subfilter:G,rawValue:$}=QV(X);if(!W.trim())return"Stripe product filters must include a product ID.";if(!G)return Y==="is"||Y==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let z=YV(G);if(XV(z))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!WV(Q,z))return`Unsupported Stripe product subfilter "${G}".`;if(!GV(Y))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return $?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var zV=new Set(["shopify","woocommerce","api"]);function JV(Q,Y){let X=Y.trim(),W=X.indexOf(":");if(W!==-1&&zV.has(X.substring(0,W).trim()))X=X.substring(W+1).trim();if(!X)return'Purchased Product filters must include a product ID, like "shopify:42".';if(Q!=="at_least"&&Q!=="less_than_count")return null;let G=X.lastIndexOf(":");if(G===-1)return null;let $=X.substring(0,G).trim(),z=Number.parseInt(X.substring(G+1).trim(),10);return $&&Number.isInteger(z)&&z>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function dY(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 pY))return`Unsupported segment filter field "${String(X)}".`;if(typeof W!=="string")return`Segment filter "${X}" must include an operator.`;let $=pY[X];if(!$.includes(W))return`Operator "${W}" is not supported for ${X} filters. Use one of: ${$.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${X}" must include a value.`;if(X==="attribute"&&typeof G==="string"){if(!aM(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!sM(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let z=eM(W,G);if(z)return z}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let z=$V(X,W,G);if(z)return z}if(X==="commerceProduct"&&typeof G==="string"){let z=JV(W,G);if(z)return z}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map((J)=>J.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function oY(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=dY(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap(oY);return[]}function S1(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 NQ(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 HV(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 $=dY(G);return $?[$]:[]}):oY(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function UV(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(Q.name===void 0&&Q.filterJoinOperator===void 0&&!Y&&!X)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=dY(G);return $?[$]:[]}):X?oY(Q.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}function AV(Q){if(Q.clearEnrollmentFieldPath===!0&&Q.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(Q.clearSendingWindow===!0&&Q.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");let Y={...Q};if(delete Y.clearEnrollmentFieldPath,delete Y.clearSendingWindow,Q.clearEnrollmentFieldPath===!0)Y.enrollmentFieldPath=null;if(Q.clearSendingWindow===!0)Y.sendingWindow=null;return Y}function BV(Q){let Y=w(Q,"subscriberId"),X=Q.fieldValues,W=X===void 0?void 0:Array.isArray(X)?X:void 0;if(X!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let G=W?.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0)??[];if(W?.some((J)=>typeof J!=="string")||W!==void 0&&G.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(Y!==void 0===G.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let $=w(Q,"fieldPath"),z=w(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...$!==void 0&&{fieldPath:$},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...z!==void 0&&{reason:z}}}function KV(Q){S1("create_campaign",Q),NQ("create_campaign",Q);let Y=w(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0,G=Q.templateId!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(Y&&(X||W||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function DV(Q){if(w(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!J0(Q.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(Q.sendTimeOptimization!==void 0){if(typeof Q.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(Q.spreadOverHours!==void 0){if(typeof Q.spreadOverHours!=="number"||!Number.isInteger(Q.spreadOverHours)||Q.spreadOverHours<1||Q.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}}function lY(Q,Y,X){let W=new Set(["companyId","landingPageId","name","slug","content"]),G=Object.keys(Y).filter(($)=>!W.has($));if(G.length>0)throw Error(`\`${Q}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map(($)=>`\`${$}\``).join(", ")}.`);if(X.requireUpdate&&Y.name===void 0&&Y.slug===void 0&&Y.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${Q}\`.`);return{...Y.name!==void 0&&{name:Y.name},...Y.slug!==void 0&&{slug:Y.slug},...Y.content!==void 0&&{content:Y.content}}}function LV(Q){let Y=new Set(["companyId","domain","verify"]),X=Object.keys(Q).filter((W)=>!Y.has(W));if(X.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${X.length===1?"":"s"}: ${X.map((W)=>`\`${W}\``).join(", ")}.`);if(Q.domain===void 0&&Q.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...Q.domain!==void 0&&{domain:Q.domain},...typeof Q.verify==="boolean"&&{verify:Q.verify}}}function qV(Q){S1("create_transactional_email",Q);let Y=w(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(Y&&(X||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!Y&&!X&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var u5={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:c5,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 FV(Q){if(!Q||typeof Q!=="object")return null;let Y=Q;if(Y.success!==!1)return null;if(typeof Y.error==="string")return Error(Y.error);if(Y.error&&typeof Y.error==="object"&&typeof Y.error.message==="string")return Error(Y.error.message);if(typeof Y.message==="string")return Error(Y.message);return Error("The tool returned an unsuccessful response.")}function J0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function h5(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function OV(Q){let Y=new URLSearchParams;if(typeof Q.query==="string"&&Q.query.trim()!=="")Y.set("query",Q.query.trim());if(Array.isArray(Q.tags)&&Q.tags.length>0)Y.set("tags",Q.tags.filter((X)=>typeof X==="string"&&X.trim()!=="").join(","));if(typeof Q.list==="string"&&Q.list.trim()!=="")Y.set("list",Q.list.trim());if(typeof Q.listId==="string"&&Q.listId.trim()!=="")Y.set("listId",Q.listId.trim());if(typeof Q.listName==="string"&&Q.listName.trim()!=="")Y.set("listName",Q.listName.trim());if(typeof Q.segmentId==="string"&&Q.segmentId.trim()!=="")Y.set("segmentId",Q.segmentId);if(typeof Q.status==="string"&&Q.status.trim()!=="")Y.set("status",Q.status.trim());return Y.set("page",String(Q.page)),Y.set("limit",String(Q.pageSize)),Y}async function MV(Q,Y){let X=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,W=Math.min(100,Math.max(1,X??100)),G=[],$=1,z=0,J=0,H=0;while(!0){let A=OV({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:$,pageSize:W}),B=await L("GET",`/api/v1/subscribers?${A.toString()}`,void 0,Y);z=B.pagination?.total??B.subscribers.length,J=B.pagination?.totalPages??1,H+=1,G.push(...B.subscribers??[]);let K=X!==void 0&&G.length>=X,D=B.pagination?$>=B.pagination.totalPages:(B.subscribers??[]).length<W;if(K||D)break;$+=1}let U=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:U,pagination:{page:1,limit:W,total:z,totalPages:J,fetchedPages:H},returned:U.length,truncated:X!==void 0&&z>0&&U.length<z}}function VV(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 o6(Q,Y){let X=VV(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function rY(Q){if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}`;return`/api/v1/subscribers/external?externalId=${encodeURIComponent(String(Q.externalId))}`}async function mY(Q,Y){return L("GET",rY(Q),void 0,Y)}function w(Q,Y){let X=Q[Y];if(typeof X!=="string")return;let W=X.trim();return W.length>0?W:void 0}function k(Q,Y,X){let W=w(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function W1(Q,Y,X,W){let G=w(Y,X);if(G===void 0)return;if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function cY(Q,Y,X,W){let G=k(Q,Y,X);if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function t6(Q,Y,X,W,G){let $=Y[X];if($===void 0)return;if(typeof $!=="number"||!Number.isInteger($)||$<W||$>G)throw Error(`\`${X}\` must be an integer between ${W} and ${G} when calling \`${Q}\`.`);return $}function f5(Q,Y){if(Y.events===void 0)return;if(!Array.isArray(Y.events))throw Error(`\`events\` must be an array when calling \`${Q}\`.`);let X=Y.events.map((W,G)=>{if(typeof W!=="string"||!wQ.includes(W))throw Error(`\`events\` item ${G+1} must be one of ${wQ.join(", ")} when calling \`${Q}\`.`);return W});if(X.length===0)throw Error(`\`events\` must include at least one event type when calling \`${Q}\`.`);return X}function l5(Q,Y){if(!Array.isArray(Y.emails))throw Error(`\`emails\` must be an array when calling \`${Q}\`.`);let X=[];if(Y.emails.forEach((W,G)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${Q}\`.`);let $=W.trim();if($.length>0)X.push($)}),X.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${Q}\`.`);if(X.length>k5)throw Error(`\`emails\` must include no more than ${k5} email addresses when calling \`${Q}\`. Split larger batches into multiple calls.`);return X}function m5(Q,Y,X,W){let G=Y[X];if(G===void 0)return;if(!Array.isArray(G))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`);let $=[];if(G.forEach((z,J)=>{if(typeof z!=="string")throw Error(`\`${X}\` item ${J+1} must be a string when calling \`${Q}\`.`);let H=z.trim();if(H.length>0)$.push(H)}),$.length===0)throw Error(`\`${X}\` must include at least one ${W} when calling \`${Q}\`.`);return $}function NV(Q){let X=m5("enroll_subscribers_in_sequence",Q,"emails","email address"),W=m5("enroll_subscribers_in_sequence",Q,"subscriberIds","subscriber ID"),G=(X?.length??0)+(W?.length??0);if(G===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(G>v5)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${v5} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let $=w(Q,"targetNodeId");return{...X!==void 0&&{emails:X},...W!==void 0&&{subscriberIds:W},...$!==void 0&&{targetNodeId:$}}}var ZV={pdf:"application/pdf",epub:"application/epub+zip",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",txt:"text/plain",csv:"text/csv"};function wV(Q){let Y=Q.split(".").pop()?.toLowerCase()??"";return ZV[Y]??null}var jV=104857600;async function PV(Q,Y){if(!YX())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let X=wV(Q);if(!X)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=lM(Q).size;if(W>jV)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=fM(Q),$=await L("POST","/api/v1/products/delivery/upload-url",{filename:mM(Q),contentType:X,fileSizeBytes:W},Y),z=await fetch($.uploadUrl,{method:"PUT",headers:{"Content-Type":X},body:G});if(!z.ok)throw Error(`File upload failed (${z.status})`);return{url:$.publicUrl,fileName:$.fileName,fileSizeBytes:W,mimeType:X}}async function p5(Q){let Y=w(Q,"companyId");if(Y)return Y;let X=N1();if(X)return X;try{return(await L("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}function a1(Q,Y){if(!J0(Q)||!Y)return Q;return{...Q,url:Y}}function i5(Q,Y){if(!J0(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(!J0(W))return W;let G=w(W,"id");if(!G)return W;let $=M1({companyId:Y,...X==="campaign"&&{campaignId:G},...X==="landingPage"&&{landingPageId:G},...X==="sequence"&&{sequenceId:G},...X==="template"&&{emailId:G},...X==="transactional"&&{transactionalId:G}});if(X==="campaign")return i5(W,$.urls);let z=X==="sequence"?$.urls.sequence:X==="landingPage"?$.urls.landingPage:X==="template"?$.urls.email:$.urls.transactionalEmail;return a1(W,z)})}function bV(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!J0(Y))return Y;let X=w(Y,"id");if(!X)return Y;let W=M1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var n5=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","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","update_sequence","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 IV(Q,Y,X){if(!J0(X)||!n5.has(Q))return X;let W=J0(X.company)?X.company:void 0,$=w(X,"selectedCompanyId")??w(X,"currentCompanyId")??w(X,"companyId")??(W?w(W,"id"):void 0)??(W?w(W,"companyId"):void 0)??await p5(Y);if(!$)return X;let z=J0(X.campaign)?X.campaign:void 0,J=J0(X.sequence)?X.sequence:void 0,H=J0(X.landingPage)?X.landingPage:void 0,U=J0(X.template)?X.template:void 0,A=J0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,B={companyId:$,campaignId:w(Y,"campaignId")??w(X,"campaignId")??(z?w(z,"id"):void 0),landingPageId:w(Y,"landingPageId")??w(X,"landingPageId")??(H?w(H,"id"):void 0),sequenceId:w(Y,"sequenceId")??w(X,"sequenceId")??(J?w(J,"id"):void 0),emailId:w(X,"templateId")??(U?w(U,"id"):void 0)??(A?w(A,"emailId"):void 0)??w(Y,"templateId"),transactionalId:w(Y,"transactionalId")??(A?w(A,"id"):void 0)??w(Y,"idOrSlug"),emailSendId:w(Y,"emailSendId")??w(X,"emailSendId")??(J0(X.emailSend)?w(X.emailSend,"id"):void 0),status:w(Y,"status")},K=M1(B),D=W?M1({companyId:$}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:bV(X.companies)},...Array.isArray(X.campaigns)&&{campaigns:a6(X.campaigns,$,"campaign")},...Array.isArray(X.landingPages)&&{landingPages:a6(X.landingPages,$,"landingPage")},...Array.isArray(X.sequences)&&{sequences:a6(X.sequences,$,"sequence")},...Array.isArray(X.templates)&&{templates:a6(X.templates,$,"template")},...Array.isArray(X.transactional)&&{transactional:a6(X.transactional,$,"transactional")},...W&&D!==void 0&&{company:{...W,url:D.urls.dashboard,settingsUrl:D.urls.settings}},...z&&K.urls.campaign!==void 0&&{campaign:i5(z,K.urls)},...J&&K.urls.sequence!==void 0&&{sequence:a1(J,K.urls.sequence)},...H&&K.urls.landingPage!==void 0&&{landingPage:a1(H,K.urls.landingPage)},...U&&K.urls.email!==void 0&&{template:a1(U,K.urls.email)},...A&&K.urls.transactionalEmail!==void 0&&{transactional:a1(A,K.urls.transactionalEmail)},...J0(X.emailSend)&&K.urls.emailSend!==void 0&&{emailSend:a1(X.emailSend,K.urls.emailSend)},appUrls:K.urls}}var EV={type:"boolean",description:"Whether the Sequenzy operation succeeded."},TV={type:"string",description:"Human-readable status, confirmation, or next-step message."},SV={type:"string",description:"Additional context about the result."};function l0(Q){return{type:"object",description:Q,additionalProperties:!0}}function RV(Q){return{type:"array",description:Q,items:l0("One item in the returned collection.")}}function v(Q){return{type:"string",description:Q}}function C0(Q){return{type:"number",description:Q}}function VQ(Q){return{type:"boolean",description:Q}}function N(Q){return l0(`The ${Q} record returned by Sequenzy.`)}function r(Q){return RV(`List of ${Q} records returned by Sequenzy.`)}var CV={appUrls:l0("Dashboard URLs for relevant Sequenzy resources."),url:v("Primary dashboard URL for this result."),settingsUrl:v("Company settings URL when available.")},kV={success:EV,message:TV,note:SV,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:l0("One returned item.")},value:l0("Fallback object wrapper used only when a tool returns a non-object value.")},vV={get_account:{account:N("account"),companies:r("company"),currentCompanyId:v("Company ID selected by the authenticated API key, when available."),selectedCompanyId:v("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:v("Selected company ID."),companyName:v("Selected company name.")},get_app_urls:{dashboard:v("Company dashboard URL."),settings:v("Company settings URL."),campaign:v("Campaign editor URL."),landingPage:v("Landing page editor URL."),sequence:v("Sequence editor URL."),email:v("Email editor URL."),transactionalEmail:v("Transactional email URL."),emailSend:v("Sent email detail URL."),domain:v("Sending domain settings URL."),urls:l0("All generated URLs keyed by resource type.")},create_company:{company:N("company"),autoSelected:VQ("Whether the new company was selected for subsequent MCP calls.")},get_company:{company:N("company")},create_api_key:{apiKey:v("Newly created API key. This secret is returned only once."),key:v("Newly created API key if the API response uses the short key field.")},list_websites:{websites:r("sender website")},add_website:{website:N("sender website")},check_website:{website:N("sender website"),ready:VQ("Whether the sender website is ready."),status:v("Current processing or verification status.")},get_integration_guide:{guide:N("integration guide"),code:v("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:l0("One setup step.")}},add_subscriber:{subscriber:N("subscriber")},update_subscriber:{subscriber:N("subscriber")},remove_subscriber:{subscriber:N("subscriber"),hardDeleted:VQ("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:N("subscriber")},search_subscribers:{subscribers:r("subscriber"),pagination:l0("Pagination metadata."),returned:C0("Number of subscribers returned."),truncated:VQ("Whether the result was truncated by the requested limit.")},list_products:{products:r("product")},upsert_products:{products:r("product"),created:C0("Number of products created."),updated:C0("Number of products updated.")},delete_product:{productId:v("Deleted product ID.")},attach_product_file:{product:N("product"),delivery:N("digital delivery file")},remove_product_file:{product:N("product")},sync_products:{job:N("product sync job"),jobId:v("Queued product sync job ID.")},list_tags:{tags:r("tag")},create_tag:{tag:N("tag")},update_tag:{tag:N("tag")},delete_tag:{tagId:v("Deleted tag ID.")},list_lists:{lists:r("list")},create_list:{list:N("list")},update_list:{list:N("list")},delete_list:{listId:v("Deleted list ID.")},add_subscribers_to_list:{list:N("list"),added:C0("Number of subscribers added to the list."),skipped:C0("Number of subscribers skipped.")},remove_subscribers_from_list:{list:N("list"),removed:C0("Number of subscribers removed from the list."),skipped:C0("Number of subscribers skipped.")},list_segments:{segments:r("segment")},create_segment:{segment:N("segment")},update_segment:{segment:N("segment")},delete_segment:{segmentId:v("Deleted segment ID.")},get_segment_count:{count:C0("Number of subscribers matching the segment."),segmentId:v("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:r("audience sync")},list_ad_accounts:{adAccounts:r("ad account")},create_audience_sync:{audienceSync:N("audience sync")},update_audience_sync:{audienceSync:N("audience sync")},delete_audience_sync:{audienceSyncId:v("Deleted audience sync ID.")},sync_audience_now:{audienceSync:N("audience sync"),job:N("audience sync job"),jobId:v("Queued audience sync job ID.")},list_templates:{templates:r("email template")},get_template:{template:N("email template")},create_template:{template:N("email template")},update_template:{template:N("email template")},delete_template:{templateId:v("Deleted template ID.")},list_ab_tests:{abTests:r("A/B test")},get_ab_test:{abTest:N("A/B test")},get_ab_test_stats:{abTest:N("A/B test"),stats:N("A/B test statistics")},restart_ab_test:{abTest:N("A/B test")},update_ab_test_variant:{abTest:N("A/B test"),variant:N("A/B test variant")},create_ab_test:{abTest:N("A/B test")},add_ab_test_variant:{abTest:N("A/B test"),variant:N("A/B test variant")},delete_ab_test_variant:{abTest:N("A/B test"),variantId:v("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:v("Deleted A/B test ID.")},list_campaigns:{campaigns:r("campaign")},get_campaign:{campaign:N("campaign")},get_email_send:{emailSend:N("email send")},create_campaign:{campaign:N("campaign")},update_campaign:{campaign:N("campaign")},schedule_campaign:{campaign:N("campaign"),scheduledAt:v("Scheduled send timestamp.")},send_test_email:{emailSend:N("test email send"),recipient:v("Test email recipient.")},cancel_campaign:{campaign:N("campaign")},pause_campaign:{campaign:N("campaign")},resume_campaign:{campaign:N("campaign")},delete_campaign:{campaignId:v("Deleted campaign ID.")},duplicate_campaign:{campaign:N("duplicated campaign")},list_landing_pages:{landingPages:r("landing page")},get_landing_page:{landingPage:N("landing page")},create_landing_page:{landingPage:N("landing page")},update_landing_page:{landingPage:N("landing page")},delete_landing_page:{landingPageId:v("Deleted landing page ID.")},publish_landing_page:{landingPage:N("landing page")},unpublish_landing_page:{landingPage:N("landing page")},connect_landing_page_domain:{landingPage:N("landing page"),domain:v("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:N("landing page"),domain:v("Landing page domain.")},list_sequences:{sequences:r("sequence")},get_sequence:{sequence:N("sequence")},create_sequence:{sequence:N("sequence")},update_sequence:{sequence:N("sequence")},enable_sequence:{sequence:N("sequence")},disable_sequence:{sequence:N("sequence")},enroll_subscribers_in_sequence:{sequence:N("sequence"),enrollments:r("sequence enrollment"),enrolled:C0("Number of subscribers enrolled."),skipped:C0("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:N("sequence"),cancelled:C0("Number of enrollments cancelled."),skipped:C0("Number of enrollments skipped.")},delete_sequence:{sequenceId:v("Deleted sequence ID.")},list_transactional_emails:{transactional:r("transactional email")},get_transactional_email:{transactional:N("transactional email")},create_transactional_email:{transactional:N("transactional email")},update_transactional_email:{transactional:N("transactional email")},send_email:{emailSend:N("transactional email send"),transactional:N("transactional email")},get_stats:{stats:N("account or company statistics")},get_campaign_stats:{campaign:N("campaign"),stats:N("campaign statistics")},get_sequence_stats:{sequence:N("sequence"),stats:N("sequence statistics")},get_subscriber_activity:{activity:r("subscriber activity event"),subscribers:r("subscriber"),pagination:l0("Pagination metadata.")},list_team_members:{members:r("team member"),invitations:r("team invitation")},invite_team_member:{invitation:N("team invitation")},cancel_team_invitation:{invitationId:v("Cancelled invitation ID.")},list_conversations:{conversations:r("inbox conversation"),pagination:l0("Pagination metadata.")},get_conversation:{conversation:N("inbox conversation"),messages:r("conversation message")},reply_to_conversation:{conversation:N("inbox conversation"),message:N("conversation message")},update_conversation_status:{conversation:N("inbox conversation")},mark_conversation_read:{conversation:N("inbox conversation")},list_webhooks:{webhooks:r("outbound webhook")},create_webhook:{webhook:N("outbound webhook")},update_webhook:{webhook:N("outbound webhook")},delete_webhook:{webhookId:v("Deleted outbound webhook ID.")},test_webhook:{webhook:N("outbound webhook"),delivery:N("test webhook delivery")},list_webhook_deliveries:{deliveries:r("webhook delivery")},replay_webhook_delivery:{delivery:N("webhook delivery"),job:N("webhook replay job")},generate_email:{email:N("generated email"),html:v("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks.",items:l0("One generated email block.")},subject:v("Generated subject line."),previewText:v("Generated inbox preview text.")},generate_sequence:{sequence:N("generated sequence"),steps:r("generated sequence step")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:v("One generated subject line.")},variants:r("generated subject line variant")}};function xV(Q){let Y=vV[Q];if(Y===void 0)throw Error(`MCP tool "${Q}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${Q}\` MCP tool.`,properties:{...kV,...Y,...n5.has(Q)?CV:{}},additionalProperties:!0}}function _V(Q){return{...Q,outputSchema:xV(Q.name)}}function gV(Q){if(J0(Q))return Q;if(Array.isArray(Q))return{items:Q};return{value:Q}}var yV=[{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
|
|
|
@@ -47,7 +47,7 @@ Use cases:
|
|
|
47
47
|
- 'event_tracking': Tracking CUSTOM events only (not payment events - those come from the integration)
|
|
48
48
|
- 'ecommerce': Connecting a custom e-commerce platform via the Commerce API (sync products, push orders/checkouts, power abandoned cart + back-in-stock automations)
|
|
49
49
|
|
|
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_products",description:"List synced products (Stripe, Shopify, WooCommerce) including any attached digital delivery file. Useful before attaching a file or building a purchase sequence for a specific product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list products for. If not provided, uses the currently selected company."},provider:{type:"string",description:"Filter by provider: stripe, shopify, woocommerce, or manual."},search:{type:"string",description:"Filter products by title."}}}},{name:"upsert_products",description:"Create or update products in the catalog (Commerce API, keyed by your productId, stored under the api provider). Use this to add products that are not synced from Stripe/Shopify/WooCommerce, then attach a deliverable file with attach_product_file and build a purchase sequence for them.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},products:{type:"array",description:"Products to create or update (max 100).",items:{type:"object",properties:{productId:{type:"string",description:"Your stable product identifier (used for upserts and order line items)."},title:{type:"string",description:"Product title."},description:{type:"string",description:"Product description."},imageUrl:{type:"string",description:"Product image URL."},url:{type:"string",description:"Product page URL."},priceCents:{type:"number",description:"Price in the smallest currency unit."},currency:{type:"string",description:"ISO currency code, e.g. USD."},inStock:{type:"boolean",description:"Whether the product is in stock."}},required:["productId","title"]}}},required:["products"]}},{name:"delete_product",description:"Delete a product previously pushed via upsert_products (Commerce API products only), identified by your productId.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Your productId used when upserting the product."}},required:["productId"]}},{name:"attach_product_file",description:"Attach a distributable file to a product, either by public URL or by uploading a local file (filePath, local MCP server only). After a purchase of the product, sequence emails can link to it with {{event.download.url}} and {{event.download.name}}.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."},url:{type:"string",description:"Public http(s) URL of the file to deliver. Provide url or filePath, not both."},filePath:{type:"string",description:"Local path of a file to upload and attach (PDF, ePub, ZIP, image, audio, video, or text, up to 100MB). Only available when the MCP server runs locally on this machine."},fileName:{type:"string",description:"Display name for the file (e.g. guide.pdf). Used as {{event.download.name}}."}},required:["productId"]}},{name:"remove_product_file",description:"Remove the attached distributable file from a product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."}},required:["productId"]}},{name:"sync_products",description:"Queue a sync of the Stripe product catalog into the products list. Requires an active Stripe integration.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{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:"create_tag",description:"Create a new tag definition. The name is normalized to lowercase with hyphens (e.g. 'VIP Customer' becomes 'vip-customer'). Color defaults to gray.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Tag name. Normalized to lowercase with hyphens."},color:{type:"string",enum:[...ZQ],description:"Tag color. Defaults to gray."}},required:["name"]}},{name:"update_tag",description:"Update a tag's color. System tags cannot be updated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."},color:{type:"string",enum:[...ZQ],description:"New tag color."}},required:["tagId","color"]}},{name:"delete_tag",description:"Permanently delete a tag and remove it from all subscribers. This cannot be undone. System tags and tags used by sequences cannot be deleted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."}},required:["tagId"]}},{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:"update_list",description:"Update a subscriber list's name, description, or privacy. Only the provided fields are changed.",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 update."},name:{type:"string",description:"New list name."},description:{type:["string","null"],description:"New list description. Pass null to clear it."},isPrivate:{type:"boolean",description:"Whether the list is private."}},required:["listId"]}},{name:"delete_list",description:"Permanently delete a subscriber list and remove all of its memberships. Subscribers themselves are kept. This cannot be undone.",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 delete."}},required:["listId"]}},{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:"remove_subscribers_from_list",description:"Remove subscribers from a list by email address. Maximum 500 emails per call. Subscribers stay in the account; only the list membership is removed. Returns the removed count plus a notFound array of emails that did not match a subscriber.",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 remove subscribers from."},emails:{type:"array",items:{type:"string"},description:"Email addresses to remove from the list. Maximum 500 per call."}},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:_5,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 commerce product purchase filter (value is provider:productId since product ids are provider-scoped): [{"id":"filter-1","field":"commerceProduct","operator":"is","value":"api:prod-starter-kit"}]. Example repeat-buyer filter: [{"id":"filter-1","field":"commerceProduct","operator":"at_least","value":"shopify:42:2"}]. 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:{...g5,description:"Nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["name"]}},{name:"update_segment",description:"Update a segment's name and/or filter rules. Use the same `filters` plus `filterJoinOperator` or nested `root` shapes as create_segment; providing `filters` or `root` replaces the segment's existing rules.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to update."},name:{type:"string",description:"New 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:_5,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...g5,description:"Replacement nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["segmentId"]}},{name:"delete_segment",description:"Permanently delete a segment. This cannot be undone. Subscribers are not affected.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to delete."}},required:["segmentId"]}},{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_audience_syncs",description:"List Meta custom audience syncs (segment -> ad audience mappings) with their schedule and last sync status. Requires the Meta Ads integration to be connected in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"list_ad_accounts",description:"List the Meta ad accounts available through the connected Meta Ads integration. Use the returned account id as `adAccountId` when creating an audience sync.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_audience_sync",description:'Push a segment to a Meta custom audience and keep it synced on a schedule. Provide `segmentId` for an existing segment OR `predefinedSegmentId` for a ready-made template (for example "zero-ltv", "no-purchase-1y", "recent-buyers", "high-spenders-ecom", "non-buyers", "engaged") - the template segment is created automatically on first use. The first upload runs immediately. Note: audiences are add-only; subscribers who later leave the segment stay in the Meta audience.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Existing segment ID to sync. Mutually exclusive with `predefinedSegmentId`."},predefinedSegmentId:{type:"string",description:'Predefined segment template ID (for example "zero-ltv", "no-purchase-1y", "recent-buyers"). The segment is created automatically if it does not exist. Mutually exclusive with `segmentId`.'},adAccountId:{type:"string",description:"Meta ad account ID (act_...) from `list_ad_accounts`."},audienceName:{type:"string",description:"Name for the custom audience in Meta Ads Manager."},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"How often to re-upload the segment. Default: daily."}},required:["adAccountId","audienceName"]}},{name:"update_audience_sync",description:"Update an audience sync's frequency or pause/resume it (`isActive`).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID"},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"New sync frequency."},isActive:{type:"boolean",description:"Set false to pause the sync, true to resume it."}},required:["syncId"]}},{name:"delete_audience_sync",description:"Remove an audience sync mapping. The Meta audience itself is kept (running ads are not disrupted) - only future syncs stop.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to remove."}},required:["syncId"]}},{name:"sync_audience_now",description:"Trigger an immediate upload of the segment's subscribers to its Meta custom audience, outside the regular schedule.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to run."}},required:["syncId"]}},{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:d6,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:d6,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:`${t1} Mutually exclusive with html.`,items:{type:"object"}}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"create_ab_test",description:"Create a campaign A/B test. Control variant A is created automatically from the campaign's current email; optionally provide extra variants. The campaign must be in draft or rejected status, and each campaign can only have one A/B test.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Draft campaign ID to create the A/B test for."},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Percentage of the audience used for the test phase, from 5 to 50. Defaults to 20."},testDurationMinutes:{type:"number",description:"Test phase duration in minutes before the winner is selected, from 15 to 1440. Defaults to 240."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Defaults to open_rate."},variants:{type:"array",description:"Optional extra variants to create in addition to control variant A.",items:{type:"object",properties:{subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:t1,items:{type:"object"}}},required:["subject"]}}},required:["campaignId"]}},{name:"add_ab_test_variant",description:"Add a variant to a draft campaign A/B test. Variants cannot be added after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:t1,items:{type:"object"}}},required:["abTestId","subject"]}},{name:"delete_ab_test_variant",description:"Permanently delete a variant from a draft campaign A/B test. This cannot be undone. Variant A is the control and cannot be deleted, and the test must keep at least the minimum number of variants. Variants cannot be removed after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID to delete."}},required:["abTestId","variantId"]}},{name:"delete_ab_test",description:"Permanently delete a campaign A/B test and all of its variants. This cannot be undone. Running tests (testing or winner_selected) cannot be deleted, and the linked campaign must be in draft or rejected status.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to delete."}},required:["abTestId"]}},{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:d6,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:d6,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:"cancel_campaign",description:"Cancel a campaign. Stops scheduled and sending campaigns (also works for paused and approval-pending ones). Remaining emails will not be sent and the campaign cannot be restarted - this cannot be undone.",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 cancel."}},required:["campaignId"]}},{name:"pause_campaign",description:"Pause a campaign that is currently sending. Only campaigns in sending status can be paused. Use resume_campaign to continue delivery later.",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 pause."}},required:["campaignId"]}},{name:"resume_campaign",description:"Resume a paused campaign. Only campaigns in paused status can be resumed. Optionally spread the remaining delivery over a number of hours.",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 resume."},spreadOverHours:{type:"number",description:"Spread the remaining delivery over an integer number of hours from 1 to 72."}},required:["campaignId"]}},{name:"delete_campaign",description:"Permanently delete a campaign. This cannot be undone. Sending, scheduled, or paused campaigns must be cancelled with cancel_campaign first.",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 delete."}},required:["campaignId"]}},{name:"duplicate_campaign",description:"Duplicate a campaign as a new draft. mode 'campaign' (default) copies the campaign and its email, 'ab_test' also duplicates the campaign's A/B test with all variants, and 'variant' copies a single variant's content as the new campaign email (requires variantId).",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 duplicate."},mode:{type:"string",enum:["campaign","ab_test","variant"],description:"Duplication mode. Defaults to campaign."},variantId:{type:"string",description:"A/B test variant ID whose content becomes the new campaign email. Required when mode is variant."}},required:["campaignId"]}},{name:"list_landing_pages",description:"List all landing pages for a company",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list landing pages for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"get_landing_page",description:"Get landing page details, content, metrics, and URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"create_landing_page",description:"Create a draft landing page. Provide content for an exact page, or a template for generated starter content.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the landing page in. If not provided, uses the currently selected company."},name:{type:"string",description:"Landing page name. Optional; defaults to a template-specific name."},slug:{type:"string",description:"Optional URL slug. It will be normalized and made unique within the company."},template:{type:"string",description:cM},content:{type:"object",description:MQ,additionalProperties:!0}},additionalProperties:!1}},{name:"update_landing_page",description:"Edit a landing page's name, slug, or full content. Provide at least one update field.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Landing page name."},slug:{type:"string",description:"Landing page URL slug. It will be normalized and made unique within the company."},content:{type:"object",description:MQ,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"delete_landing_page",description:"Delete a landing page",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"publish_landing_page",description:"Publish a landing page. Optional name, slug, or content updates are saved before publishing.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before publishing."},content:{type:"object",description:MQ,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"unpublish_landing_page",description:"Unpublish a landing page and return it to draft status. Optional name, slug, or content updates are saved first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before unpublishing."},content:{type:"object",description:MQ,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"connect_landing_page_domain",description:"Connect a custom domain for published landing pages. Returns the DNS target and verification records.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Custom domain, for example pages.example.com."}},required:["domain"],additionalProperties:!1}},{name:"update_landing_page_domain_settings",description:"Update landing page domain settings. Provide domain to replace the custom domain, verify true to refresh verification, or both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Replacement custom domain."},verify:{type:"boolean",description:"Refresh domain verification after any domain update."}},additionalProperties:!1}},{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_products",description:"List synced products (Stripe, Shopify, WooCommerce) including any attached digital delivery file. Useful before attaching a file or building a purchase sequence for a specific product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list products for. If not provided, uses the currently selected company."},provider:{type:"string",description:"Filter by provider: stripe, shopify, woocommerce, or manual."},search:{type:"string",description:"Filter products by title."}}}},{name:"upsert_products",description:"Create or update products in the catalog (Commerce API, keyed by your productId, stored under the api provider). Use this to add products that are not synced from Stripe/Shopify/WooCommerce, then attach a deliverable file with attach_product_file and build a purchase sequence for them.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},products:{type:"array",description:"Products to create or update (max 100).",items:{type:"object",properties:{productId:{type:"string",description:"Your stable product identifier (used for upserts and order line items)."},title:{type:"string",description:"Product title."},description:{type:"string",description:"Product description."},imageUrl:{type:"string",description:"Product image URL."},url:{type:"string",description:"Product page URL."},priceCents:{type:"number",description:"Price in the smallest currency unit."},currency:{type:"string",description:"ISO currency code, e.g. USD."},inStock:{type:"boolean",description:"Whether the product is in stock."}},required:["productId","title"]}}},required:["products"]}},{name:"delete_product",description:"Delete a product previously pushed via upsert_products (Commerce API products only), identified by your productId.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Your productId used when upserting the product."}},required:["productId"]}},{name:"attach_product_file",description:"Attach a distributable file to a product, either by public URL or by uploading a local file (filePath, local MCP server only). After a purchase of the product, sequence emails can link to it with {{event.download.url}} and {{event.download.name}}.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."},url:{type:"string",description:"Public http(s) URL of the file to deliver. Provide url or filePath, not both."},filePath:{type:"string",description:"Local path of a file to upload and attach (PDF, ePub, ZIP, image, audio, video, or text, up to 100MB). Only available when the MCP server runs locally on this machine."},fileName:{type:"string",description:"Display name for the file (e.g. guide.pdf). Used as {{event.download.name}}."}},required:["productId"]}},{name:"remove_product_file",description:"Remove the attached distributable file from a product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."}},required:["productId"]}},{name:"sync_products",description:"Queue a sync of the Stripe product catalog into the products list. Requires an active Stripe integration.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{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:"create_tag",description:"Create a new tag definition. The name is normalized to lowercase with hyphens (e.g. 'VIP Customer' becomes 'vip-customer'). Color defaults to gray.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Tag name. Normalized to lowercase with hyphens."},color:{type:"string",enum:[...ZQ],description:"Tag color. Defaults to gray."}},required:["name"]}},{name:"update_tag",description:"Update a tag's color. System tags cannot be updated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."},color:{type:"string",enum:[...ZQ],description:"New tag color."}},required:["tagId","color"]}},{name:"delete_tag",description:"Permanently delete a tag and remove it from all subscribers. This cannot be undone. System tags and tags used by sequences cannot be deleted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."}},required:["tagId"]}},{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:"update_list",description:"Update a subscriber list's name, description, or privacy. Only the provided fields are changed.",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 update."},name:{type:"string",description:"New list name."},description:{type:["string","null"],description:"New list description. Pass null to clear it."},isPrivate:{type:"boolean",description:"Whether the list is private."}},required:["listId"]}},{name:"delete_list",description:"Permanently delete a subscriber list and remove all of its memberships. Subscribers themselves are kept. This cannot be undone.",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 delete."}},required:["listId"]}},{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:"remove_subscribers_from_list",description:"Remove subscribers from a list by email address. Maximum 500 emails per call. Subscribers stay in the account; only the list membership is removed. Returns the removed count plus a notFound array of emails that did not match a subscriber.",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 remove subscribers from."},emails:{type:"array",items:{type:"string"},description:"Email addresses to remove from the list. Maximum 500 per call."}},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:_5,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 commerce product purchase filter (value is provider:productId since product ids are provider-scoped): [{"id":"filter-1","field":"commerceProduct","operator":"is","value":"api:prod-starter-kit"}]. Example repeat-buyer filter: [{"id":"filter-1","field":"commerceProduct","operator":"at_least","value":"shopify:42:2"}]. 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:{...g5,description:"Nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["name"]}},{name:"update_segment",description:"Update a segment's name and/or filter rules. Use the same `filters` plus `filterJoinOperator` or nested `root` shapes as create_segment; providing `filters` or `root` replaces the segment's existing rules.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to update."},name:{type:"string",description:"New 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:_5,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...g5,description:"Replacement nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["segmentId"]}},{name:"delete_segment",description:"Permanently delete a segment. This cannot be undone. Subscribers are not affected.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to delete."}},required:["segmentId"]}},{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_audience_syncs",description:"List Meta custom audience syncs (segment -> ad audience mappings) with their schedule and last sync status. Requires the Meta Ads integration to be connected in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"list_ad_accounts",description:"List the Meta ad accounts available through the connected Meta Ads integration. Use the returned account id as `adAccountId` when creating an audience sync.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_audience_sync",description:'Push a segment to a Meta custom audience and keep it synced on a schedule. Provide `segmentId` for an existing segment OR `predefinedSegmentId` for a ready-made template (for example "zero-ltv", "no-purchase-1y", "recent-buyers", "high-spenders-ecom", "non-buyers", "engaged") - the template segment is created automatically on first use. The first upload runs immediately. Note: audiences are add-only; subscribers who later leave the segment stay in the Meta audience.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Existing segment ID to sync. Mutually exclusive with `predefinedSegmentId`."},predefinedSegmentId:{type:"string",description:'Predefined segment template ID (for example "zero-ltv", "no-purchase-1y", "recent-buyers"). The segment is created automatically if it does not exist. Mutually exclusive with `segmentId`.'},adAccountId:{type:"string",description:"Meta ad account ID (act_...) from `list_ad_accounts`."},audienceName:{type:"string",description:"Name for the custom audience in Meta Ads Manager."},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"How often to re-upload the segment. Default: daily."}},required:["adAccountId","audienceName"]}},{name:"update_audience_sync",description:"Update an audience sync's frequency or pause/resume it (`isActive`).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID"},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"New sync frequency."},isActive:{type:"boolean",description:"Set false to pause the sync, true to resume it."}},required:["syncId"]}},{name:"delete_audience_sync",description:"Remove an audience sync mapping. The Meta audience itself is kept (running ads are not disrupted) - only future syncs stop.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to remove."}},required:["syncId"]}},{name:"sync_audience_now",description:"Trigger an immediate upload of the segment's subscribers to its Meta custom audience, outside the regular schedule.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to run."}},required:["syncId"]}},{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:d6,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:d6,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:`${t1} Mutually exclusive with html.`,items:{type:"object"}}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"create_ab_test",description:"Create a campaign A/B test. Control variant A is created automatically from the campaign's current email; optionally provide extra variants. The campaign must be in draft or rejected status, and each campaign can only have one A/B test.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Draft campaign ID to create the A/B test for."},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Percentage of the audience used for the test phase, from 5 to 50. Defaults to 20."},testDurationMinutes:{type:"number",description:"Test phase duration in minutes before the winner is selected, from 15 to 1440. Defaults to 240."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Defaults to open_rate."},variants:{type:"array",description:"Optional extra variants to create in addition to control variant A.",items:{type:"object",properties:{subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:t1,items:{type:"object"}}},required:["subject"]}}},required:["campaignId"]}},{name:"add_ab_test_variant",description:"Add a variant to a draft campaign A/B test. Variants cannot be added after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:t1,items:{type:"object"}}},required:["abTestId","subject"]}},{name:"delete_ab_test_variant",description:"Permanently delete a variant from a draft campaign A/B test. This cannot be undone. Variant A is the control and cannot be deleted, and the test must keep at least the minimum number of variants. Variants cannot be removed after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID to delete."}},required:["abTestId","variantId"]}},{name:"delete_ab_test",description:"Permanently delete a campaign A/B test and all of its variants. This cannot be undone. Running tests (testing or winner_selected) cannot be deleted, and the linked campaign must be in draft or rejected status.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to delete."}},required:["abTestId"]}},{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. Defaults to draft; use status 'sent' only to archive an already-sent campaign without sending email.",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."},status:{type:"string",description:"Initial status: draft or sent. Defaults to draft. Use sent only for imported/already-sent campaigns; it does not send email or create delivery history."},sentAt:{type:"string",description:"ISO date-time for an imported/already-sent campaign. Only valid when status is sent; defaults to now if omitted."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:d6,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:d6,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:"cancel_campaign",description:"Cancel a campaign. Stops scheduled and sending campaigns (also works for paused and approval-pending ones). Remaining emails will not be sent and the campaign cannot be restarted - this cannot be undone.",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 cancel."}},required:["campaignId"]}},{name:"pause_campaign",description:"Pause a campaign that is currently sending. Only campaigns in sending status can be paused. Use resume_campaign to continue delivery later.",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 pause."}},required:["campaignId"]}},{name:"resume_campaign",description:"Resume a paused campaign. Only campaigns in paused status can be resumed. Optionally spread the remaining delivery over a number of hours.",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 resume."},spreadOverHours:{type:"number",description:"Spread the remaining delivery over an integer number of hours from 1 to 72."}},required:["campaignId"]}},{name:"delete_campaign",description:"Permanently delete a campaign. This cannot be undone. Sending, scheduled, or paused campaigns must be cancelled with cancel_campaign first.",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 delete."}},required:["campaignId"]}},{name:"duplicate_campaign",description:"Duplicate a campaign as a new draft. mode 'campaign' (default) copies the campaign and its email, 'ab_test' also duplicates the campaign's A/B test with all variants, and 'variant' copies a single variant's content as the new campaign email (requires variantId).",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 duplicate."},mode:{type:"string",enum:["campaign","ab_test","variant"],description:"Duplication mode. Defaults to campaign."},variantId:{type:"string",description:"A/B test variant ID whose content becomes the new campaign email. Required when mode is variant."}},required:["campaignId"]}},{name:"list_landing_pages",description:"List all landing pages for a company",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list landing pages for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"get_landing_page",description:"Get landing page details, content, metrics, and URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"create_landing_page",description:"Create a draft landing page. Provide content for an exact page, or a template for generated starter content.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the landing page in. If not provided, uses the currently selected company."},name:{type:"string",description:"Landing page name. Optional; defaults to a template-specific name."},slug:{type:"string",description:"Optional URL slug. It will be normalized and made unique within the company."},template:{type:"string",description:cM},content:{type:"object",description:MQ,additionalProperties:!0}},additionalProperties:!1}},{name:"update_landing_page",description:"Edit a landing page's name, slug, or full content. Provide at least one update field.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Landing page name."},slug:{type:"string",description:"Landing page URL slug. It will be normalized and made unique within the company."},content:{type:"object",description:MQ,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"delete_landing_page",description:"Delete a landing page",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"publish_landing_page",description:"Publish a landing page. Optional name, slug, or content updates are saved before publishing.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before publishing."},content:{type:"object",description:MQ,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"unpublish_landing_page",description:"Unpublish a landing page and return it to draft status. Optional name, slug, or content updates are saved first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before unpublishing."},content:{type:"object",description:MQ,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"connect_landing_page_domain",description:"Connect a custom domain for published landing pages. Returns the DNS target and verification records.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Custom domain, for example pages.example.com."}},required:["domain"],additionalProperties:!1}},{name:"update_landing_page_domain_settings",description:"Update landing page domain settings. Provide domain to replace the custom domain, verify true to refresh verification, or both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Replacement custom domain."},verify:{type:"boolean",description:"Refresh domain verification after any domain update."}},additionalProperties:!1}},{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).
|
|
51
51
|
|
|
52
52
|
IMPORTANT GUIDELINES:
|
|
53
53
|
|
|
@@ -182,4 +182,4 @@ BUILT-IN EVENTS (auto-fired by payment integrations):
|
|
|
182
182
|
|
|
183
183
|
OTHER BUILT-IN EVENTS:
|
|
184
184
|
- email.opened, email.clicked, email.replied, email.bounced, email.unsubscribed
|
|
185
|
-
- 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)"},propertyFilters:{type:"array",description:"Optional event property filters for event_received triggers. The sequence only starts when the triggering event's properties match ALL filters. Use a dot-path into the event properties; use [] to match inside arrays. Examples: scope a purchase sequence to one product with { path: 'lineItems[].providerProductId', operator: 'equals', value: 'prod_123' } (ecommerce.order_placed) or { path: 'productIds', operator: 'equals', value: 'prod_123' } (saas.purchase); to match any of several products use { path: 'lineItems[].providerProductId', operator: 'one_of', value: ['prod_123', 'prod_456'] }. Max 10 filters.",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the event properties, e.g. 'lineItems[].providerProductId' or 'plan'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"],description:"Comparison operator. one_of matches when the property equals any entry of the value array."},value:{type:["string","number","boolean","array"],items:{type:["string","number"]},maxItems:50,description:"Value to compare against. Required for every operator except exists/not_exists. For one_of, pass an array of strings or numbers (max 50 values); all other operators take a single value."}},required:["path","operator"]}},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."},sendingWindow:x5,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:c5,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."},sendingWindow:x5,clearSendingWindow:{type:"boolean",description:"Set true to remove the sequence sending window. Do not provide this together with sendingWindow."},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:u5}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:u5},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:t1,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:t1,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:"enroll_subscribers_in_sequence",description:"Manually enroll subscribers in a sequence by email address or subscriber ID. Maximum 500 total targets per call across emails and subscriberIds. Only active subscribers are enrolled: unknown emails are returned in `notFound`, while inactive, unavailable, and already actively enrolled subscribers are counted in `skipped`. By default enrollment starts at the first step after the trigger; pass targetNodeId to start at a specific step.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to enroll subscribers in."},emails:{type:"array",items:{type:"string"},description:"Email addresses of subscribers to enroll. Combined with subscriberIds, maximum 500 total targets per call."},subscriberIds:{type:"array",items:{type:"string"},description:"Subscriber IDs to enroll. Combined with emails, maximum 500 total targets per call."},targetNodeId:{type:"string",description:"Optional node ID to start enrollment at. Use a non-trigger nodeId from get_sequence. Defaults to the first step after the trigger."}},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:`${d6} 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:`${t1} 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. Maximum length: 255 characters."}},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, including attributed conversions and revenue (revenueCents)",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 attributed conversions and revenue (revenueCents) plus 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:"list_team_members",description:"List team members for the company, including the owner, members with their roles, and pending or expired invitations.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"invite_team_member",description:"Invite a team member by email with role admin or viewer. Existing Sequenzy users are added to the team immediately; others receive an email invitation. Billing access (canManageBilling) can only be granted by the company owner.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Email address of the person to invite."},role:{type:"string",enum:["admin","viewer"],description:"Team role. Admins can manage the workspace; viewers have read-only access."},canManageBilling:{type:"boolean",description:"Whether the member can manage billing. Only the company owner can grant billing access. Defaults to false."}},required:["email","role"]}},{name:"cancel_team_invitation",description:"Cancel a pending team invitation. Invitations that have already been accepted cannot be cancelled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},invitationId:{type:"string",description:"Invitation ID to cancel. Use list_team_members to find pending invitations."}},required:["invitationId"]}},{name:"list_conversations",description:"List inbox conversations (email replies from subscribers). Filter by status, free-text search, or unread state, with pagination.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},status:{type:"string",enum:["open","closed","all"],description:"Filter by conversation status. Defaults to all."},search:{type:"string",description:"Free-text search across conversation subjects and participants."},unread:{type:"boolean",description:"Set true to only return conversations with unread messages."},page:{type:"number",description:"Page number. Defaults to 1."},limit:{type:"number",description:"Results per page, from 1 to 100. Defaults to 20."}}}},{name:"get_conversation",description:"Get a conversation with its full message history, subscriber details, and context.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}},{name:"reply_to_conversation",description:"Send a reply in a conversation, or add an internal note. type 'outbound' (default) emails the subscriber and requires bodyText or bodyHtml; type 'note' adds a private team-only note. Replying to a closed conversation reopens it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID to reply in."},type:{type:"string",enum:["outbound","note"],description:"Message type: outbound emails the subscriber, note is internal-only. Defaults to outbound."},subject:{type:"string",description:"Optional subject override. Defaults to the conversation subject."},bodyText:{type:"string",description:"Plain-text message body."},bodyHtml:{type:"string",description:"HTML message body."}},required:["conversationId"]}},{name:"update_conversation_status",description:"Open or close a conversation.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."},status:{type:"string",enum:["open","closed"],description:"New conversation status."}},required:["conversationId","status"]}},{name:"mark_conversation_read",description:"Mark all unread inbound messages in a conversation as read.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}},{name:"list_webhooks",description:"List outbound webhook endpoints and their subscribed event types.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_webhook",description:"Create an outbound webhook endpoint. IMPORTANT: the response includes a signingSecret that is returned only once - show it to the user immediately so they can store it and verify webhook signatures. If events is omitted, a default set of event types is subscribed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Webhook endpoint name."},url:{type:"string",description:"HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...wQ]},description:"Event types to subscribe to. If omitted, a default set is used."}},required:["name","url"]}},{name:"update_webhook",description:"Update an outbound webhook endpoint's name, URL, subscribed events, or status (enabled/disabled). Providing events replaces the existing event list.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},name:{type:"string",description:"New webhook endpoint name."},url:{type:"string",description:"New HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...wQ]},description:"Replacement event type subscriptions."},status:{type:"string",enum:["enabled","disabled"],description:"Enable or disable deliveries to this endpoint."}},required:["webhookId"]}},{name:"delete_webhook",description:"Permanently delete an outbound webhook endpoint along with its delivery history. This cannot be undone. To keep the endpoint but stop deliveries, use update_webhook with status disabled instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to delete."}},required:["webhookId"]}},{name:"test_webhook",description:"Send a test event to an outbound webhook endpoint to verify it is reachable and signatures can be validated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to test."}},required:["webhookId"]}},{name:"list_webhook_deliveries",description:"List recent delivery attempts for an outbound webhook endpoint, including status and response codes.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},limit:{type:"number",description:"Maximum number of deliveries to return, from 1 to 100. Defaults to 20."}},required:["webhookId"]}},{name:"replay_webhook_delivery",description:"Replay a previous webhook delivery, re-sending the same event payload to the endpoint.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},deliveryId:{type:"string",description:"Delivery ID to replay. Use list_webhook_deliveries to find delivery IDs."}},required:["webhookId","deliveryId"]}},{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"]}}],r5=yV.map(_V).map(oM);async function d5(Q,Y){try{let X;switch(Q){case"get_account":{let G=await L("GET","/api/v1/account"),$=N1();X={...G,selectedCompanyId:$??G.currentCompanyId};break}case"select_company":{let G=Y.companyId,$=await L("GET","/api/v1/account"),z=$.companies?.find((J)=>J.id===G);if(!z)throw Error(`Company not found. Available companies: ${$.companies?.map((J)=>`${J.name} (${J.id})`).join(", ")??"none"}`);EQ(G),X={success:!0,message:`Switched to company: ${z.name}`,companyId:z.id,companyName:z.name};break}case"get_app_urls":{let G=await p5(Y);X={...M1({companyId:G,campaignId:w(Y,"campaignId"),landingPageId:w(Y,"landingPageId"),sequenceId:w(Y,"sequenceId"),emailId:w(Y,"emailId")??w(Y,"templateId"),transactionalId:w(Y,"transactionalId"),emailSendId:w(Y,"emailSendId"),domainId:w(Y,"domainId"),status:w(Y,"status"),settingsTab:w(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 L("POST","/api/v1/companies",{name:Y.name,domain:Y.domain});if(!G.success)throw Error("Failed to create company");let $=G.company.id,z=6,J=0,H=G.company.status;while(H==="processing"&&J<z){await new Promise((B)=>setTimeout(B,20000)),J++;let A=await L("GET",`/api/v1/companies/${$}`);if(A.success)H=A.company.status}EQ($);let U=await L("GET",`/api/v1/companies/${$}`);X={success:!0,company:U.company,message:H==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${U.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let G=Y.companyId;X=await L("GET",`/api/v1/companies/${G}`);break}case"create_api_key":{let G=Y.companyId;X=await L("POST","/api/v1/api-keys",{name:Y.name},G);break}case"list_websites":{let G=Y.companyId;X=await L("GET","/api/v1/websites",void 0,G);break}case"add_website":{let G=Y.companyId;X=await L("POST","/api/v1/websites",{domain:Y.domain},G);break}case"check_website":{let G=Y.companyId;X=await L("GET",`/api/v1/websites/${Y.domain}`,void 0,G);break}case"get_integration_guide":X=await L("POST","/api/v1/integration-guide",Y);break;case"add_subscriber":{let G=Y.companyId,$=o6("add_subscriber",Y);X=await L("POST","/api/v1/subscribers",{...$,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,$=o6("update_subscriber",Y),z=await mY($,G),J=Array.isArray(z.subscriber.tags)?z.subscriber.tags.filter((K)=>typeof K==="string"):[],H=Array.isArray(Y.addTags)?Y.addTags.filter((K)=>typeof K==="string"&&K.trim()!=="").map(h5):[],U=new Set(Array.isArray(Y.removeTags)?Y.removeTags.filter((K)=>typeof K==="string"&&K.trim()!=="").map(h5):[]),A=J.filter((K)=>!U.has(K));for(let K of H)if(!A.includes(K))A.push(K);let B={};if($.email&&$.externalId)B.externalId=$.externalId;if(J0(Y.attributes))B.customAttributes={...J0(z.subscriber.customAttributes)?z.subscriber.customAttributes:{},...Y.attributes};if(Y.addTags||Y.removeTags)B.tags=A;X=await L("PATCH",rY($),B,G);break}case"remove_subscriber":{let G=Y.companyId,$=o6("remove_subscriber",Y),z=rY($);if(Y.hardDelete===!0)X=await L("DELETE",z,void 0,G);else X=await L("PATCH",z,{status:"unsubscribed"},G);break}case"get_subscriber":{let G=Y.companyId,$=o6("get_subscriber",Y);X=await mY($,G);break}case"search_subscribers":{let G=Y.companyId;X=await MV(Y,G);break}case"list_products":{let G=Y.companyId,$=new URLSearchParams;if(typeof Y.provider==="string"&&Y.provider.trim())$.set("provider",Y.provider.trim());if(typeof Y.search==="string"&&Y.search.trim())$.set("search",Y.search.trim());let z=$.size>0?`?${$.toString()}`:"";X=await L("GET",`/api/v1/products${z}`,void 0,G);break}case"upsert_products":{let G=Y.companyId;if(!Array.isArray(Y.products)||Y.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");X=await L("POST","/api/v1/products",{products:Y.products},G);break}case"delete_product":{let G=Y.companyId,$=k("delete_product",Y,"productId");X=await L("DELETE",`/api/v1/products/${encodeURIComponent($)}`,void 0,G);break}case"attach_product_file":{let G=Y.companyId,$=k("attach_product_file",Y,"productId"),z=w(Y,"url"),J=w(Y,"filePath");if(z===void 0===(J===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let H;if(J!==void 0){let U=await PV(J,G);H={url:U.url,source:"upload",fileName:w(Y,"fileName")??U.fileName,fileSizeBytes:U.fileSizeBytes,mimeType:U.mimeType}}else{H={url:z};let U=w(Y,"fileName");if(U)H.fileName=U}X=await L("PUT",`/api/v1/products/${encodeURIComponent($)}/delivery`,H,G);break}case"remove_product_file":{let G=Y.companyId,$=k("remove_product_file",Y,"productId");X=await L("DELETE",`/api/v1/products/${encodeURIComponent($)}/delivery`,void 0,G);break}case"sync_products":{let G=Y.companyId;X=await L("POST","/api/v1/products/sync",void 0,G);break}case"list_tags":{let G=Y.companyId;X=await L("GET","/api/v1/tags",void 0,G);break}case"create_tag":{let G=Y.companyId,$=k("create_tag",Y,"name"),z=W1("create_tag",Y,"color",ZQ);X=await L("POST","/api/v1/tags",{name:$,...z!==void 0&&{color:z}},G);break}case"update_tag":{let G=Y.companyId,$=k("update_tag",Y,"tagId"),z=cY("update_tag",Y,"color",ZQ);X=await L("PATCH",`/api/v1/tags/${encodeURIComponent($)}`,{color:z},G);break}case"delete_tag":{let G=Y.companyId,$=k("delete_tag",Y,"tagId");X=await L("DELETE",`/api/v1/tags/${encodeURIComponent($)}`,void 0,G);break}case"list_lists":{let G=Y.companyId;X=await L("GET","/api/v1/lists",void 0,G);break}case"create_list":{let G=Y.companyId;X=await L("POST","/api/v1/lists",Y,G);break}case"update_list":{let G=Y.companyId,$=k("update_list",Y,"listId");if(Y.name===void 0&&Y.description===void 0&&Y.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(Y.name!==void 0&&w(Y,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(Y.description!==void 0&&Y.description!==null&&typeof Y.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(Y.isPrivate!==void 0&&typeof Y.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");X=await L("PATCH",`/api/v1/lists/${encodeURIComponent($)}`,{...Y.name!==void 0&&{name:w(Y,"name")},...Y.description!==void 0&&{description:Y.description},...Y.isPrivate!==void 0&&{isPrivate:Y.isPrivate}},G);break}case"delete_list":{let G=Y.companyId,$=k("delete_list",Y,"listId");X=await L("DELETE",`/api/v1/lists/${encodeURIComponent($)}`,void 0,G);break}case"add_subscribers_to_list":{let G=Y.companyId,$=k("add_subscribers_to_list",Y,"listId"),z=l5("add_subscribers_to_list",Y),J=W1("add_subscribers_to_list",Y,"duplicateStrategy",["skip","merge","overwrite"])??"skip",H=W1("add_subscribers_to_list",Y,"optInMode",["default","confirmed","double_opt_in"])??"default";X=await L("POST",`/api/v1/lists/${encodeURIComponent($)}/subscribers`,{emails:z,duplicateStrategy:J,enrollInSequences:Y.enrollInSequences===!0,optInMode:H},G);break}case"remove_subscribers_from_list":{let G=Y.companyId,$=k("remove_subscribers_from_list",Y,"listId"),z=l5("remove_subscribers_from_list",Y);X=await L("POST",`/api/v1/lists/${encodeURIComponent($)}/subscribers/remove`,{emails:z},G);break}case"list_segments":{let G=Y.companyId;X=await L("GET","/api/v1/segments",void 0,G);break}case"create_segment":{HV(Y);let G=Y.companyId;X=await L("POST","/api/v1/segments",{...Y,...Y.filters!==void 0?{filters:iY(Y.filters)}:{},...Y.root!==void 0?{root:nY(Y.root)}:{}},G);break}case"update_segment":{UV(Y);let G=Y.companyId,$=k("update_segment",Y,"segmentId"),z=w(Y,"name"),J=W1("update_segment",Y,"filterJoinOperator",["and","or"]);X=await L("PATCH",`/api/v1/segments/${encodeURIComponent($)}`,{...z!==void 0&&{name:z},...J!==void 0&&{filterJoinOperator:J},...Y.filters!==void 0?{filters:iY(Y.filters)}:{},...Y.root!==void 0?{root:nY(Y.root)}:{}},G);break}case"delete_segment":{let G=Y.companyId,$=k("delete_segment",Y,"segmentId");X=await L("DELETE",`/api/v1/segments/${encodeURIComponent($)}`,void 0,G);break}case"get_segment_count":{let G=Y.companyId;X=await L("GET",`/api/v1/segments/${Y.segmentId}/count`,void 0,G);break}case"list_audience_syncs":{let G=Y.companyId;X=await L("GET","/api/v1/audience-syncs",void 0,G);break}case"list_ad_accounts":{let G=Y.companyId;X=await L("GET","/api/v1/ad-accounts",void 0,G);break}case"create_audience_sync":{let G=Y.companyId,$=w(Y,"segmentId"),z=w(Y,"predefinedSegmentId");if($&&z)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!$&&!z)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");X=await L("POST","/api/v1/audience-syncs",{segmentId:$,predefinedSegmentId:z,adAccountId:k("create_audience_sync",Y,"adAccountId"),audienceName:k("create_audience_sync",Y,"audienceName"),...Y.frequency!==void 0?{frequency:Y.frequency}:{}},G);break}case"update_audience_sync":{let G=Y.companyId,$=k("update_audience_sync",Y,"syncId");X=await L("PATCH",`/api/v1/audience-syncs/${encodeURIComponent($)}`,{...Y.frequency!==void 0?{frequency:Y.frequency}:{},...Y.isActive!==void 0?{isActive:Y.isActive}:{}},G);break}case"delete_audience_sync":{let G=Y.companyId,$=k("delete_audience_sync",Y,"syncId");X=await L("DELETE",`/api/v1/audience-syncs/${encodeURIComponent($)}`,void 0,G);break}case"sync_audience_now":{let G=Y.companyId,$=k("sync_audience_now",Y,"syncId");X=await L("POST",`/api/v1/audience-syncs/${encodeURIComponent($)}/sync`,void 0,G);break}case"list_templates":{let G=Y.companyId,$=new URLSearchParams,z=w(Y,"label");if(z)$.set("label",z);X=await L("GET",`/api/v1/templates${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_template":{let G=Y.companyId;X=await L("GET",`/api/v1/templates/${Y.templateId}`,void 0,G);break}case"create_template":{let G=Y.companyId;S1("create_template",Y,{requireContent:!0}),NQ("create_template",Y),X=await L("POST","/api/v1/templates",Y,G);break}case"update_template":{let G=Y.companyId,$=new Set(["companyId","templateId","name","subject","html","blocks","labels"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);if(S1("update_template",Y),NQ("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 L("PUT",`/api/v1/templates/${Y.templateId}`,Y,G);break}case"delete_template":{let G=Y.companyId;X=await L("DELETE",`/api/v1/templates/${Y.templateId}`,void 0,G);break}case"list_ab_tests":{let G=Y.companyId,$=new URLSearchParams,z=w(Y,"sequenceId");if(z)$.set("sequenceId",z);X=await L("GET",`/api/v1/ab-tests${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_ab_test":{let G=Y.companyId;X=await L("GET",`/api/v1/ab-tests/${Y.abTestId}`,void 0,G);break}case"get_ab_test_stats":{let G=Y.companyId,$=new URLSearchParams,z=w(Y,"period"),J=w(Y,"start"),H=w(Y,"end");if(z)$.set("period",z);if(J)$.set("start",J);if(H)$.set("end",H);X=await L("GET",`/api/v1/ab-tests/${Y.abTestId}/stats${$.size>0?`?${$}`:""}`,void 0,G);break}case"restart_ab_test":{let G=Y.companyId,$=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),z=Object.keys(Y).filter((A)=>!$.has(A));if(z.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${z.length===1?"":"s"}: ${z.map((A)=>`\`${A}\``).join(", ")}.`);let J=w(Y,"testType");if(J!==void 0&&J!=="subject"&&J!=="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 U=Y.variantCount===void 0?void 0:Number(Y.variantCount);if(U!==void 0&&(!Number.isInteger(U)||U<2||U>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");X=await L("POST",`/api/v1/ab-tests/${Y.abTestId}/restart`,{sourceVariantId:w(Y,"sourceVariantId"),testType:J,winnerThreshold:H,variantCount:U},G);break}case"update_ab_test_variant":{let G=Y.companyId,$=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);if(S1("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 L("PATCH",`/api/v1/ab-tests/${Y.abTestId}/variants/${Y.variantId}`,Y,G);break}case"create_ab_test":{let G=Y.companyId,$=k("create_ab_test",Y,"campaignId"),z=w(Y,"name"),J=t6("create_ab_test",Y,"testPercentage",5,50),H=t6("create_ab_test",Y,"testDurationMinutes",15,1440),U=W1("create_ab_test",Y,"winnerCriteria",["open_rate","click_rate"]);if(Y.variants!==void 0){if(!Array.isArray(Y.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");Y.variants.forEach((A,B)=>{if(!J0(A)||typeof A.subject!=="string"||A.subject.trim()==="")throw Error(`\`variants\` item ${B+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(A.blocks!==void 0&&!Array.isArray(A.blocks))throw Error(`\`variants\` item ${B+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}X=await L("POST","/api/v1/ab-tests",{campaignId:$,...z!==void 0&&{name:z},...J!==void 0&&{testPercentage:J},...H!==void 0&&{testDurationMinutes:H},...U!==void 0&&{winnerCriteria:U},...Y.variants!==void 0&&{variants:Y.variants}},G);break}case"add_ab_test_variant":{let G=Y.companyId,$=k("add_ab_test_variant",Y,"abTestId"),z=k("add_ab_test_variant",Y,"subject"),J=w(Y,"previewText");if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");X=await L("POST",`/api/v1/ab-tests/${encodeURIComponent($)}/variants`,{subject:z,...J!==void 0&&{previewText:J},...Y.blocks!==void 0&&{blocks:Y.blocks}},G);break}case"delete_ab_test_variant":{let G=Y.companyId,$=k("delete_ab_test_variant",Y,"abTestId"),z=k("delete_ab_test_variant",Y,"variantId");X=await L("DELETE",`/api/v1/ab-tests/${encodeURIComponent($)}/variants/${encodeURIComponent(z)}`,void 0,G);break}case"delete_ab_test":{let G=Y.companyId,$=k("delete_ab_test",Y,"abTestId");X=await L("DELETE",`/api/v1/ab-tests/${encodeURIComponent($)}`,void 0,G);break}case"list_campaigns":{let G=Y.companyId,$=new URLSearchParams;if(Y.status)$.set("status",String(Y.status));let z=w(Y,"label");if(z)$.set("label",z);X=await L("GET",`/api/v1/campaigns?${$}`,void 0,G);break}case"get_campaign":{let G=Y.companyId;X=await L("GET",`/api/v1/campaigns/${Y.campaignId}`,void 0,G);break}case"get_email_send":{let G=Y.companyId;X=await L("GET",`/api/v1/email-sends/${encodeURIComponent(String(Y.emailSendId))}`,void 0,G);break}case"create_campaign":{let G=Y.companyId;KV(Y);let $=w(Y,"prompt");if($!==void 0){let z=await L("POST","/api/v1/generate/email",{prompt:$,...Y.style!==void 0&&{style:Y.style},...Y.tone!==void 0&&{tone:Y.tone}},G),J=w(Y,"subject")??(typeof z.subject==="string"&&z.subject.trim()!==""?z.subject.trim():void 0);if(!J)throw Error("`create_campaign` prompt generation did not return a subject. Provide `subject` explicitly.");let H=Array.isArray(z.blocks)&&z.blocks.length>0?z.blocks:void 0,U=typeof z.html==="string"&&z.html.trim()!==""?z.html:void 0;if(H===void 0&&U===void 0)throw Error("`create_campaign` prompt generation did not return email blocks. Try again or provide `html` or `blocks` explicitly.");X=await L("POST","/api/v1/campaigns",{name:Y.name,subject:J,...H!==void 0?{blocks:H}:{html:U},...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 L("POST","/api/v1/campaigns",Y,G);break}case"update_campaign":{let G=Y.companyId,$=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","replyTo","replyProfileId","campaignData","computedLists","labels"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`update_campaign\` accepts only \`name\`, \`subject\`, \`trackingCode\`, \`html\`, \`blocks\`, \`replyTo\`, \`replyProfileId\`, \`campaignData\`, \`computedLists\`, and \`labels\` update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);if(S1("update_campaign",Y),NQ("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 L("PUT",`/api/v1/campaigns/${Y.campaignId}`,Y,G);break}case"schedule_campaign":{let G=Y.companyId,$=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, and \`spreadOverHours\`. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);DV(Y),X=await L("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 L("POST",`/api/v1/campaigns/${Y.campaignId}/test`,{to:Y.to},G);break}case"cancel_campaign":{let G=Y.companyId,$=k("cancel_campaign",Y,"campaignId");X=await L("POST",`/api/v1/campaigns/${encodeURIComponent($)}/cancel`,void 0,G);break}case"pause_campaign":{let G=Y.companyId,$=k("pause_campaign",Y,"campaignId");X=await L("POST",`/api/v1/campaigns/${encodeURIComponent($)}/pause`,void 0,G);break}case"resume_campaign":{let G=Y.companyId,$=k("resume_campaign",Y,"campaignId"),z=t6("resume_campaign",Y,"spreadOverHours",1,72);X=await L("POST",`/api/v1/campaigns/${encodeURIComponent($)}/resume`,{...z!==void 0&&{spreadOverHours:z}},G);break}case"delete_campaign":{let G=Y.companyId,$=k("delete_campaign",Y,"campaignId");X=await L("DELETE",`/api/v1/campaigns/${encodeURIComponent($)}`,void 0,G);break}case"duplicate_campaign":{let G=Y.companyId,$=k("duplicate_campaign",Y,"campaignId"),z=W1("duplicate_campaign",Y,"mode",["campaign","ab_test","variant"]),J=w(Y,"variantId");if(z==="variant"&&J===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");X=await L("POST",`/api/v1/campaigns/${encodeURIComponent($)}/duplicate`,{...z!==void 0&&{mode:z},...J!==void 0&&{variantId:J}},G);break}case"list_landing_pages":{let G=Y.companyId;X=await L("GET","/api/v1/landing-pages",void 0,G);break}case"get_landing_page":{let G=Y.companyId;X=await L("GET",`/api/v1/landing-pages/${Y.landingPageId}`,void 0,G);break}case"create_landing_page":{let G=Y.companyId,$=new Set(["companyId","name","slug","template","content"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);X=await L("POST","/api/v1/landing-pages",{...Y.name!==void 0&&{name:Y.name},...Y.slug!==void 0&&{slug:Y.slug},...Y.template!==void 0&&{template:Y.template},...Y.content!==void 0&&{content:Y.content}},G);break}case"update_landing_page":{let G=Y.companyId,$=lY("update_landing_page",Y,{requireUpdate:!0});X=await L("PUT",`/api/v1/landing-pages/${Y.landingPageId}`,$,G);break}case"publish_landing_page":{let G=Y.companyId,$=lY("publish_landing_page",Y,{requireUpdate:!1});X=await L("POST",`/api/v1/landing-pages/${Y.landingPageId}/publish`,$,G);break}case"unpublish_landing_page":{let G=Y.companyId,$=lY("unpublish_landing_page",Y,{requireUpdate:!1});X=await L("POST",`/api/v1/landing-pages/${Y.landingPageId}/unpublish`,$,G);break}case"delete_landing_page":{let G=Y.companyId;X=await L("DELETE",`/api/v1/landing-pages/${Y.landingPageId}`,void 0,G);break}case"connect_landing_page_domain":{let G=Y.companyId;X=await L("POST","/api/v1/landing-pages/domain",{domain:Y.domain},G);break}case"update_landing_page_domain_settings":{let G=Y.companyId,$=LV(Y);X=await L("PUT","/api/v1/landing-pages/domain",$,G);break}case"list_sequences":{let G=Y.companyId;X=await L("GET","/api/v1/sequences",void 0,G);break}case"get_sequence":{let G=Y.companyId;X=await L("GET",`/api/v1/sequences/${Y.sequenceId}`,void 0,G);break}case"create_sequence":{let G=Y.companyId,$=Array.isArray(Y.steps)&&Y.steps.length>0,z=await L("POST","/api/v1/sequences",Y,G);if(!z.success){X=z;break}let J=z.sequence.id;if($){let K=await L("GET",`/api/v1/sequences/${J}`,void 0,G);if(K.success)X={success:!0,sequence:K.sequence,message:`Sequence "${K.sequence.name}" created with explicit steps. Review it before enabling.`};else X=K;break}let H=6,U=0,A="pending";while(A!=="complete"&&U<H){await new Promise((D)=>setTimeout(D,20000)),U++;let K=await L("GET",`/api/v1/sequences/${J}`,void 0,G);if(K.success)A=K.sequence.enrichmentStatus}let B=await L("GET",`/api/v1/sequences/${J}`,void 0,G);if(B.success)X={success:!0,sequence:B.sequence,message:B.sequence.enrichmentStatus==="complete"?`Sequence "${B.sequence.name}" created with ${B.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.`:`Sequence "${B.sequence.name}" created. Email enrichment is still in progress (${B.sequence.enrichedCount}/${B.sequence.emailCount} emails generated). You can check status with get_sequence.`};else X=B;break}case"update_sequence":{let G=Y.companyId,$=AV(Y);X=await L("PUT",`/api/v1/sequences/${Y.sequenceId}`,$,G);break}case"enable_sequence":{let G=Y.companyId;X=await L("POST",`/api/v1/sequences/${Y.sequenceId}/enable`,void 0,G);break}case"disable_sequence":{let G=Y.companyId;X=await L("POST",`/api/v1/sequences/${Y.sequenceId}/disable`,void 0,G);break}case"enroll_subscribers_in_sequence":{let G=Y.companyId,$=k("enroll_subscribers_in_sequence",Y,"sequenceId"),z=NV(Y);X=await L("POST",`/api/v1/sequences/${encodeURIComponent($)}/enroll`,z,G);break}case"cancel_sequence_enrollments":{let G=Y.companyId,$=BV(Y);X=await L("POST",`/api/v1/sequences/${Y.sequenceId}/enrollments/cancel`,$,G);break}case"delete_sequence":{let G=Y.companyId;X=await L("DELETE",`/api/v1/sequences/${Y.sequenceId}`,void 0,G);break}case"list_transactional_emails":{let G=Y.companyId;X=await L("GET","/api/v1/transactional",void 0,G);break}case"get_transactional_email":{let G=Y.companyId;X=await L("GET",`/api/v1/transactional/${Y.idOrSlug}`,void 0,G);break}case"create_transactional_email":{let G=Y.companyId,$=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),z=Object.keys(Y).filter((U)=>!$.has(U));if(z.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${z.length===1?"":"s"}: ${z.map((U)=>`\`${U}\``).join(", ")}.`);qV(Y);let J=w(Y,"prompt");if(J!==void 0){let U={companyId:G??N1()??"",name:typeof Y.name==="string"&&Y.name.trim()!==""?Y.name.trim():"",slug:typeof Y.slug==="string"&&Y.slug.trim()!==""?Y.slug.trim():"",promptLength:J.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",U);let A=await L("POST","/api/v1/generate/email",{prompt:J,...Y.style!==void 0&&{style:Y.style},...Y.tone!==void 0&&{tone:Y.tone}},G);console.error("[mcp:create_transactional_email] prompt generation complete",{...U,subject:A.subject??"",previewTextLength:typeof A.previewText==="string"?A.previewText.length:0,blockCount:Array.isArray(A.blocks)?A.blocks.length:0,htmlLength:typeof A.html==="string"?A.html.length:0});let B=w(Y,"subject")??(typeof A.subject==="string"&&A.subject.trim()!==""?A.subject.trim():void 0);if(!B)throw Error("`create_transactional_email` prompt generation did not return a subject. Provide `subject` explicitly.");let K=Array.isArray(A.blocks)&&A.blocks.length>0?A.blocks:void 0,D=typeof A.html==="string"&&A.html.trim()!==""?A.html:void 0,O=w(Y,"previewText")??(typeof A.previewText==="string"?A.previewText.trim():void 0);if(K===void 0&&D===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",{...U,subject:B,contentSource:K!==void 0?"blocks":"html",blockCount:K?.length??0,htmlLength:D?.length??0}),X=await L("POST","/api/v1/transactional",{name:Y.name,...Y.slug!==void 0&&{slug:Y.slug},subject:B,...O!==void 0&&{previewText:O},...K!==void 0?{blocks:K}:{html:D},...Y.enabled!==void 0&&{enabled:Y.enabled}},G),console.error("[mcp:create_transactional_email] generated transactional created",U)}catch(A){throw console.error("[mcp:create_transactional_email] prompt-based create failed",{...U,error:A instanceof Error?A.message:String(A)}),A}break}let H=Object.fromEntries(Object.entries(Y).filter(([U])=>U!=="companyId"));X=await L("POST","/api/v1/transactional",H,G);break}case"update_transactional_email":{let G=Y.companyId,$=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),z=Object.keys(Y).filter((H)=>!$.has(H));if(z.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((H)=>`\`${H}\``).join(", ")}.`);if(S1("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 J=Object.fromEntries(Object.entries(Y).filter(([H])=>H!=="companyId"&&H!=="idOrSlug"));X=await L("PATCH",`/api/v1/transactional/${Y.idOrSlug}`,J,G);break}case"send_email":{let G=Y.companyId;X=await L("POST","/api/v1/transactional/send",Y,G);break}case"get_stats":{let G=Y.companyId,$=Y.period??"7d";X=await L("GET",`/api/v1/metrics?period=${$}`,void 0,G);break}case"get_campaign_stats":{let G=Y.companyId;X=await L("GET",`/api/v1/metrics/campaigns/${Y.campaignId}`,void 0,G);break}case"get_sequence_stats":{let G=Y.companyId;X=await L("GET",`/api/v1/metrics/sequences/${Y.sequenceId}`,void 0,G);break}case"get_subscriber_activity":{let G=Y.companyId,$=o6("get_subscriber_activity",Y),z=await mY($,G);X={success:z.success,email:z.subscriber.email,emailStats:z.subscriber.emailStats??null,activity:z.subscriber.activity??[],sequenceEnrollments:z.subscriber.sequenceEnrollments??[]};break}case"list_team_members":{let G=Y.companyId;X=await L("GET","/api/v1/team",void 0,G);break}case"invite_team_member":{let G=Y.companyId,$=k("invite_team_member",Y,"email"),z=cY("invite_team_member",Y,"role",["admin","viewer"]);if(Y.canManageBilling!==void 0&&typeof Y.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");X=await L("POST","/api/v1/team/invitations",{email:$,role:z,...Y.canManageBilling!==void 0&&{canManageBilling:Y.canManageBilling}},G);break}case"cancel_team_invitation":{let G=Y.companyId,$=k("cancel_team_invitation",Y,"invitationId");X=await L("DELETE",`/api/v1/team/invitations/${encodeURIComponent($)}`,void 0,G);break}case"list_conversations":{let G=Y.companyId,$=new URLSearchParams,z=W1("list_conversations",Y,"status",["open","closed","all"]);if(z)$.set("status",z);let J=w(Y,"search");if(J)$.set("search",J);if(Y.unread!==void 0){if(typeof Y.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(Y.unread)$.set("unread","true")}if(Y.page!==void 0){if(typeof Y.page!=="number"||!Number.isInteger(Y.page)||Y.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");$.set("page",String(Y.page))}let H=t6("list_conversations",Y,"limit",1,100);if(H!==void 0)$.set("limit",String(H));X=await L("GET",`/api/v1/conversations${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_conversation":{let G=Y.companyId,$=k("get_conversation",Y,"conversationId");X=await L("GET",`/api/v1/conversations/${encodeURIComponent($)}`,void 0,G);break}case"reply_to_conversation":{let G=Y.companyId,$=k("reply_to_conversation",Y,"conversationId"),z=W1("reply_to_conversation",Y,"type",["outbound","note"])??"outbound",J=w(Y,"subject"),H=w(Y,"bodyText"),U=w(Y,"bodyHtml");if(z==="outbound"&&H===void 0&&U===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");X=await L("POST",`/api/v1/conversations/${encodeURIComponent($)}/messages`,{type:z,...J!==void 0&&{subject:J},...H!==void 0&&{bodyText:H},...U!==void 0&&{bodyHtml:U}},G);break}case"update_conversation_status":{let G=Y.companyId,$=k("update_conversation_status",Y,"conversationId"),z=cY("update_conversation_status",Y,"status",["open","closed"]);X=await L("POST",`/api/v1/conversations/${encodeURIComponent($)}/status`,{status:z},G);break}case"mark_conversation_read":{let G=Y.companyId,$=k("mark_conversation_read",Y,"conversationId");X=await L("POST",`/api/v1/conversations/${encodeURIComponent($)}/read`,void 0,G);break}case"list_webhooks":{let G=Y.companyId;X=await L("GET","/api/v1/webhooks",void 0,G);break}case"create_webhook":{let G=Y.companyId,$=k("create_webhook",Y,"name"),z=k("create_webhook",Y,"url"),J=f5("create_webhook",Y);X=await L("POST","/api/v1/webhooks",{name:$,url:z,...J!==void 0&&{events:J}},G);break}case"update_webhook":{let G=Y.companyId,$=k("update_webhook",Y,"webhookId"),z=w(Y,"name"),J=w(Y,"url"),H=f5("update_webhook",Y),U=W1("update_webhook",Y,"status",["enabled","disabled"]);if(z===void 0&&J===void 0&&H===void 0&&U===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");X=await L("PATCH",`/api/v1/webhooks/${encodeURIComponent($)}`,{...z!==void 0&&{name:z},...J!==void 0&&{url:J},...H!==void 0&&{events:H},...U!==void 0&&{status:U}},G);break}case"delete_webhook":{let G=Y.companyId,$=k("delete_webhook",Y,"webhookId");X=await L("DELETE",`/api/v1/webhooks/${encodeURIComponent($)}`,void 0,G);break}case"test_webhook":{let G=Y.companyId,$=k("test_webhook",Y,"webhookId");X=await L("POST",`/api/v1/webhooks/${encodeURIComponent($)}/test`,void 0,G);break}case"list_webhook_deliveries":{let G=Y.companyId,$=k("list_webhook_deliveries",Y,"webhookId"),z=t6("list_webhook_deliveries",Y,"limit",1,100),J=new URLSearchParams;if(z!==void 0)J.set("limit",String(z));X=await L("GET",`/api/v1/webhooks/${encodeURIComponent($)}/deliveries${J.size>0?`?${J}`:""}`,void 0,G);break}case"replay_webhook_delivery":{let G=Y.companyId,$=k("replay_webhook_delivery",Y,"webhookId"),z=k("replay_webhook_delivery",Y,"deliveryId");X=await L("POST",`/api/v1/webhooks/${encodeURIComponent($)}/deliveries/${encodeURIComponent(z)}/replay`,void 0,G);break}case"generate_email":{let G=Y.companyId;X=await L("POST","/api/v1/generate/email",Y,G);break}case"generate_sequence":{let G=Y.companyId;X=await L("POST","/api/v1/generate/sequence",Y,G);break}case"generate_subject_lines":{let G=Y.companyId;X=await L("POST","/api/v1/generate/subjects",Y,G);break}default:throw Error(`Unknown tool: ${Q}`)}let W=FV(X);if(W)throw W;return X=await IV(Q,Y,X),{structuredContent:gV(X),content:[{type:"text",text:JSON.stringify(X,null,2)}]}}catch(X){return{isError:!0,content:[{type:"text",text:R1(X)}]}}}async function o5(Q,Y,X){let W=Y.getRequestContext?.(Q)??{};try{return await WX(W,X)}finally{await Y.onRequestContextUpdated?.(W,Q)}}function pE(Q={}){let Y=new hY({name:"sequenzy",version:E5.version},{capabilities:{tools:{},resources:{}}});return Y.setRequestHandler(I9,async()=>{return{tools:r5}}),Y.setRequestHandler(w6,async(X,W)=>{let{name:G,arguments:$}=X.params;return o5(W,Q,()=>d5(G,$??{}))}),Y.setRequestHandler(V9,async()=>{return{resources:R5}}),Y.setRequestHandler(Z9,async(X,W)=>{let{uri:G}=X.params;return o5(W,Q,()=>C5(G))}),Y}export{pE as createSequenzyMcpServer};
|
|
185
|
+
- 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)"},propertyFilters:{type:"array",description:"Optional event property filters for event_received triggers. The sequence only starts when the triggering event's properties match ALL filters. Use a dot-path into the event properties; use [] to match inside arrays. Examples: scope a purchase sequence to one product with { path: 'lineItems[].providerProductId', operator: 'equals', value: 'prod_123' } (ecommerce.order_placed) or { path: 'productIds', operator: 'equals', value: 'prod_123' } (saas.purchase); to match any of several products use { path: 'lineItems[].providerProductId', operator: 'one_of', value: ['prod_123', 'prod_456'] }. Max 10 filters.",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the event properties, e.g. 'lineItems[].providerProductId' or 'plan'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"],description:"Comparison operator. one_of matches when the property equals any entry of the value array."},value:{type:["string","number","boolean","array"],items:{type:["string","number"]},maxItems:50,description:"Value to compare against. Required for every operator except exists/not_exists. For one_of, pass an array of strings or numbers (max 50 values); all other operators take a single value."}},required:["path","operator"]}},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."},sendingWindow:x5,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: 'entered_segment', value: 'segment_123' } when they enter a segment, { type: 'field_changed', value: 'plan' } when a subscriber field changes, { 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","entered_segment","field_changed","event_received"],description:"Stop condition type."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, 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:c5,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."},sendingWindow:x5,clearSendingWindow:{type:"boolean",description:"Set true to remove the sequence sending window. Do not provide this together with sendingWindow."},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: 'entered_segment', value: 'segment_123' } to stop when they enter a segment, { type: 'field_changed', value: 'plan' } to stop when a subscriber field changes, { 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","entered_segment","field_changed","event_received"]},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, 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:u5}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:u5},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:t1,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:t1,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:"enroll_subscribers_in_sequence",description:"Manually enroll subscribers in a sequence by email address or subscriber ID. Maximum 500 total targets per call across emails and subscriberIds. Only active subscribers are enrolled: unknown emails are returned in `notFound`, while inactive, unavailable, and already actively enrolled subscribers are counted in `skipped`. By default enrollment starts at the first step after the trigger; pass targetNodeId to start at a specific step.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to enroll subscribers in."},emails:{type:"array",items:{type:"string"},description:"Email addresses of subscribers to enroll. Combined with subscriberIds, maximum 500 total targets per call."},subscriberIds:{type:"array",items:{type:"string"},description:"Subscriber IDs to enroll. Combined with emails, maximum 500 total targets per call."},targetNodeId:{type:"string",description:"Optional node ID to start enrollment at. Use a non-trigger nodeId from get_sequence. Defaults to the first step after the trigger."}},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:`${d6} 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:`${t1} 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. Maximum length: 255 characters."}},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, including attributed conversions and revenue (revenueCents)",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 attributed conversions and revenue (revenueCents) plus 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:"list_team_members",description:"List team members for the company, including the owner, members with their roles, and pending or expired invitations.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"invite_team_member",description:"Invite a team member by email with role admin or viewer. Existing Sequenzy users are added to the team immediately; others receive an email invitation. Billing access (canManageBilling) can only be granted by the company owner.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Email address of the person to invite."},role:{type:"string",enum:["admin","viewer"],description:"Team role. Admins can manage the workspace; viewers have read-only access."},canManageBilling:{type:"boolean",description:"Whether the member can manage billing. Only the company owner can grant billing access. Defaults to false."}},required:["email","role"]}},{name:"cancel_team_invitation",description:"Cancel a pending team invitation. Invitations that have already been accepted cannot be cancelled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},invitationId:{type:"string",description:"Invitation ID to cancel. Use list_team_members to find pending invitations."}},required:["invitationId"]}},{name:"list_conversations",description:"List inbox conversations (email replies from subscribers). Filter by status, free-text search, or unread state, with pagination.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},status:{type:"string",enum:["open","closed","all"],description:"Filter by conversation status. Defaults to all."},search:{type:"string",description:"Free-text search across conversation subjects and participants."},unread:{type:"boolean",description:"Set true to only return conversations with unread messages."},page:{type:"number",description:"Page number. Defaults to 1."},limit:{type:"number",description:"Results per page, from 1 to 100. Defaults to 20."}}}},{name:"get_conversation",description:"Get a conversation with its full message history, subscriber details, and context.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}},{name:"reply_to_conversation",description:"Send a reply in a conversation, or add an internal note. type 'outbound' (default) emails the subscriber and requires bodyText or bodyHtml; type 'note' adds a private team-only note. Replying to a closed conversation reopens it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID to reply in."},type:{type:"string",enum:["outbound","note"],description:"Message type: outbound emails the subscriber, note is internal-only. Defaults to outbound."},subject:{type:"string",description:"Optional subject override. Defaults to the conversation subject."},bodyText:{type:"string",description:"Plain-text message body."},bodyHtml:{type:"string",description:"HTML message body."}},required:["conversationId"]}},{name:"update_conversation_status",description:"Open or close a conversation.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."},status:{type:"string",enum:["open","closed"],description:"New conversation status."}},required:["conversationId","status"]}},{name:"mark_conversation_read",description:"Mark all unread inbound messages in a conversation as read.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}},{name:"list_webhooks",description:"List outbound webhook endpoints and their subscribed event types.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_webhook",description:"Create an outbound webhook endpoint. IMPORTANT: the response includes a signingSecret that is returned only once - show it to the user immediately so they can store it and verify webhook signatures. If events is omitted, a default set of event types is subscribed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Webhook endpoint name."},url:{type:"string",description:"HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...wQ]},description:"Event types to subscribe to. If omitted, a default set is used."}},required:["name","url"]}},{name:"update_webhook",description:"Update an outbound webhook endpoint's name, URL, subscribed events, or status (enabled/disabled). Providing events replaces the existing event list.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},name:{type:"string",description:"New webhook endpoint name."},url:{type:"string",description:"New HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...wQ]},description:"Replacement event type subscriptions."},status:{type:"string",enum:["enabled","disabled"],description:"Enable or disable deliveries to this endpoint."}},required:["webhookId"]}},{name:"delete_webhook",description:"Permanently delete an outbound webhook endpoint along with its delivery history. This cannot be undone. To keep the endpoint but stop deliveries, use update_webhook with status disabled instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to delete."}},required:["webhookId"]}},{name:"test_webhook",description:"Send a test event to an outbound webhook endpoint to verify it is reachable and signatures can be validated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to test."}},required:["webhookId"]}},{name:"list_webhook_deliveries",description:"List recent delivery attempts for an outbound webhook endpoint, including status and response codes.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},limit:{type:"number",description:"Maximum number of deliveries to return, from 1 to 100. Defaults to 20."}},required:["webhookId"]}},{name:"replay_webhook_delivery",description:"Replay a previous webhook delivery, re-sending the same event payload to the endpoint.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},deliveryId:{type:"string",description:"Delivery ID to replay. Use list_webhook_deliveries to find delivery IDs."}},required:["webhookId","deliveryId"]}},{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"]}}],r5=yV.map(_V).map(oM);async function d5(Q,Y){try{let X;switch(Q){case"get_account":{let G=await L("GET","/api/v1/account"),$=N1();X={...G,selectedCompanyId:$??G.currentCompanyId};break}case"select_company":{let G=Y.companyId,$=await L("GET","/api/v1/account"),z=$.companies?.find((J)=>J.id===G);if(!z)throw Error(`Company not found. Available companies: ${$.companies?.map((J)=>`${J.name} (${J.id})`).join(", ")??"none"}`);EQ(G),X={success:!0,message:`Switched to company: ${z.name}`,companyId:z.id,companyName:z.name};break}case"get_app_urls":{let G=await p5(Y);X={...M1({companyId:G,campaignId:w(Y,"campaignId"),landingPageId:w(Y,"landingPageId"),sequenceId:w(Y,"sequenceId"),emailId:w(Y,"emailId")??w(Y,"templateId"),transactionalId:w(Y,"transactionalId"),emailSendId:w(Y,"emailSendId"),domainId:w(Y,"domainId"),status:w(Y,"status"),settingsTab:w(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 L("POST","/api/v1/companies",{name:Y.name,domain:Y.domain});if(!G.success)throw Error("Failed to create company");let $=G.company.id,z=6,J=0,H=G.company.status;while(H==="processing"&&J<z){await new Promise((B)=>setTimeout(B,20000)),J++;let A=await L("GET",`/api/v1/companies/${$}`);if(A.success)H=A.company.status}EQ($);let U=await L("GET",`/api/v1/companies/${$}`);X={success:!0,company:U.company,message:H==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${U.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let G=Y.companyId;X=await L("GET",`/api/v1/companies/${G}`);break}case"create_api_key":{let G=Y.companyId;X=await L("POST","/api/v1/api-keys",{name:Y.name},G);break}case"list_websites":{let G=Y.companyId;X=await L("GET","/api/v1/websites",void 0,G);break}case"add_website":{let G=Y.companyId;X=await L("POST","/api/v1/websites",{domain:Y.domain},G);break}case"check_website":{let G=Y.companyId;X=await L("GET",`/api/v1/websites/${Y.domain}`,void 0,G);break}case"get_integration_guide":X=await L("POST","/api/v1/integration-guide",Y);break;case"add_subscriber":{let G=Y.companyId,$=o6("add_subscriber",Y);X=await L("POST","/api/v1/subscribers",{...$,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,$=o6("update_subscriber",Y),z=await mY($,G),J=Array.isArray(z.subscriber.tags)?z.subscriber.tags.filter((K)=>typeof K==="string"):[],H=Array.isArray(Y.addTags)?Y.addTags.filter((K)=>typeof K==="string"&&K.trim()!=="").map(h5):[],U=new Set(Array.isArray(Y.removeTags)?Y.removeTags.filter((K)=>typeof K==="string"&&K.trim()!=="").map(h5):[]),A=J.filter((K)=>!U.has(K));for(let K of H)if(!A.includes(K))A.push(K);let B={};if($.email&&$.externalId)B.externalId=$.externalId;if(J0(Y.attributes))B.customAttributes={...J0(z.subscriber.customAttributes)?z.subscriber.customAttributes:{},...Y.attributes};if(Y.addTags||Y.removeTags)B.tags=A;X=await L("PATCH",rY($),B,G);break}case"remove_subscriber":{let G=Y.companyId,$=o6("remove_subscriber",Y),z=rY($);if(Y.hardDelete===!0)X=await L("DELETE",z,void 0,G);else X=await L("PATCH",z,{status:"unsubscribed"},G);break}case"get_subscriber":{let G=Y.companyId,$=o6("get_subscriber",Y);X=await mY($,G);break}case"search_subscribers":{let G=Y.companyId;X=await MV(Y,G);break}case"list_products":{let G=Y.companyId,$=new URLSearchParams;if(typeof Y.provider==="string"&&Y.provider.trim())$.set("provider",Y.provider.trim());if(typeof Y.search==="string"&&Y.search.trim())$.set("search",Y.search.trim());let z=$.size>0?`?${$.toString()}`:"";X=await L("GET",`/api/v1/products${z}`,void 0,G);break}case"upsert_products":{let G=Y.companyId;if(!Array.isArray(Y.products)||Y.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");X=await L("POST","/api/v1/products",{products:Y.products},G);break}case"delete_product":{let G=Y.companyId,$=k("delete_product",Y,"productId");X=await L("DELETE",`/api/v1/products/${encodeURIComponent($)}`,void 0,G);break}case"attach_product_file":{let G=Y.companyId,$=k("attach_product_file",Y,"productId"),z=w(Y,"url"),J=w(Y,"filePath");if(z===void 0===(J===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let H;if(J!==void 0){let U=await PV(J,G);H={url:U.url,source:"upload",fileName:w(Y,"fileName")??U.fileName,fileSizeBytes:U.fileSizeBytes,mimeType:U.mimeType}}else{H={url:z};let U=w(Y,"fileName");if(U)H.fileName=U}X=await L("PUT",`/api/v1/products/${encodeURIComponent($)}/delivery`,H,G);break}case"remove_product_file":{let G=Y.companyId,$=k("remove_product_file",Y,"productId");X=await L("DELETE",`/api/v1/products/${encodeURIComponent($)}/delivery`,void 0,G);break}case"sync_products":{let G=Y.companyId;X=await L("POST","/api/v1/products/sync",void 0,G);break}case"list_tags":{let G=Y.companyId;X=await L("GET","/api/v1/tags",void 0,G);break}case"create_tag":{let G=Y.companyId,$=k("create_tag",Y,"name"),z=W1("create_tag",Y,"color",ZQ);X=await L("POST","/api/v1/tags",{name:$,...z!==void 0&&{color:z}},G);break}case"update_tag":{let G=Y.companyId,$=k("update_tag",Y,"tagId"),z=cY("update_tag",Y,"color",ZQ);X=await L("PATCH",`/api/v1/tags/${encodeURIComponent($)}`,{color:z},G);break}case"delete_tag":{let G=Y.companyId,$=k("delete_tag",Y,"tagId");X=await L("DELETE",`/api/v1/tags/${encodeURIComponent($)}`,void 0,G);break}case"list_lists":{let G=Y.companyId;X=await L("GET","/api/v1/lists",void 0,G);break}case"create_list":{let G=Y.companyId;X=await L("POST","/api/v1/lists",Y,G);break}case"update_list":{let G=Y.companyId,$=k("update_list",Y,"listId");if(Y.name===void 0&&Y.description===void 0&&Y.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(Y.name!==void 0&&w(Y,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(Y.description!==void 0&&Y.description!==null&&typeof Y.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(Y.isPrivate!==void 0&&typeof Y.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");X=await L("PATCH",`/api/v1/lists/${encodeURIComponent($)}`,{...Y.name!==void 0&&{name:w(Y,"name")},...Y.description!==void 0&&{description:Y.description},...Y.isPrivate!==void 0&&{isPrivate:Y.isPrivate}},G);break}case"delete_list":{let G=Y.companyId,$=k("delete_list",Y,"listId");X=await L("DELETE",`/api/v1/lists/${encodeURIComponent($)}`,void 0,G);break}case"add_subscribers_to_list":{let G=Y.companyId,$=k("add_subscribers_to_list",Y,"listId"),z=l5("add_subscribers_to_list",Y),J=W1("add_subscribers_to_list",Y,"duplicateStrategy",["skip","merge","overwrite"])??"skip",H=W1("add_subscribers_to_list",Y,"optInMode",["default","confirmed","double_opt_in"])??"default";X=await L("POST",`/api/v1/lists/${encodeURIComponent($)}/subscribers`,{emails:z,duplicateStrategy:J,enrollInSequences:Y.enrollInSequences===!0,optInMode:H},G);break}case"remove_subscribers_from_list":{let G=Y.companyId,$=k("remove_subscribers_from_list",Y,"listId"),z=l5("remove_subscribers_from_list",Y);X=await L("POST",`/api/v1/lists/${encodeURIComponent($)}/subscribers/remove`,{emails:z},G);break}case"list_segments":{let G=Y.companyId;X=await L("GET","/api/v1/segments",void 0,G);break}case"create_segment":{HV(Y);let G=Y.companyId;X=await L("POST","/api/v1/segments",{...Y,...Y.filters!==void 0?{filters:iY(Y.filters)}:{},...Y.root!==void 0?{root:nY(Y.root)}:{}},G);break}case"update_segment":{UV(Y);let G=Y.companyId,$=k("update_segment",Y,"segmentId"),z=w(Y,"name"),J=W1("update_segment",Y,"filterJoinOperator",["and","or"]);X=await L("PATCH",`/api/v1/segments/${encodeURIComponent($)}`,{...z!==void 0&&{name:z},...J!==void 0&&{filterJoinOperator:J},...Y.filters!==void 0?{filters:iY(Y.filters)}:{},...Y.root!==void 0?{root:nY(Y.root)}:{}},G);break}case"delete_segment":{let G=Y.companyId,$=k("delete_segment",Y,"segmentId");X=await L("DELETE",`/api/v1/segments/${encodeURIComponent($)}`,void 0,G);break}case"get_segment_count":{let G=Y.companyId;X=await L("GET",`/api/v1/segments/${Y.segmentId}/count`,void 0,G);break}case"list_audience_syncs":{let G=Y.companyId;X=await L("GET","/api/v1/audience-syncs",void 0,G);break}case"list_ad_accounts":{let G=Y.companyId;X=await L("GET","/api/v1/ad-accounts",void 0,G);break}case"create_audience_sync":{let G=Y.companyId,$=w(Y,"segmentId"),z=w(Y,"predefinedSegmentId");if($&&z)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!$&&!z)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");X=await L("POST","/api/v1/audience-syncs",{segmentId:$,predefinedSegmentId:z,adAccountId:k("create_audience_sync",Y,"adAccountId"),audienceName:k("create_audience_sync",Y,"audienceName"),...Y.frequency!==void 0?{frequency:Y.frequency}:{}},G);break}case"update_audience_sync":{let G=Y.companyId,$=k("update_audience_sync",Y,"syncId");X=await L("PATCH",`/api/v1/audience-syncs/${encodeURIComponent($)}`,{...Y.frequency!==void 0?{frequency:Y.frequency}:{},...Y.isActive!==void 0?{isActive:Y.isActive}:{}},G);break}case"delete_audience_sync":{let G=Y.companyId,$=k("delete_audience_sync",Y,"syncId");X=await L("DELETE",`/api/v1/audience-syncs/${encodeURIComponent($)}`,void 0,G);break}case"sync_audience_now":{let G=Y.companyId,$=k("sync_audience_now",Y,"syncId");X=await L("POST",`/api/v1/audience-syncs/${encodeURIComponent($)}/sync`,void 0,G);break}case"list_templates":{let G=Y.companyId,$=new URLSearchParams,z=w(Y,"label");if(z)$.set("label",z);X=await L("GET",`/api/v1/templates${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_template":{let G=Y.companyId;X=await L("GET",`/api/v1/templates/${Y.templateId}`,void 0,G);break}case"create_template":{let G=Y.companyId;S1("create_template",Y,{requireContent:!0}),NQ("create_template",Y),X=await L("POST","/api/v1/templates",Y,G);break}case"update_template":{let G=Y.companyId,$=new Set(["companyId","templateId","name","subject","html","blocks","labels"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);if(S1("update_template",Y),NQ("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 L("PUT",`/api/v1/templates/${Y.templateId}`,Y,G);break}case"delete_template":{let G=Y.companyId;X=await L("DELETE",`/api/v1/templates/${Y.templateId}`,void 0,G);break}case"list_ab_tests":{let G=Y.companyId,$=new URLSearchParams,z=w(Y,"sequenceId");if(z)$.set("sequenceId",z);X=await L("GET",`/api/v1/ab-tests${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_ab_test":{let G=Y.companyId;X=await L("GET",`/api/v1/ab-tests/${Y.abTestId}`,void 0,G);break}case"get_ab_test_stats":{let G=Y.companyId,$=new URLSearchParams,z=w(Y,"period"),J=w(Y,"start"),H=w(Y,"end");if(z)$.set("period",z);if(J)$.set("start",J);if(H)$.set("end",H);X=await L("GET",`/api/v1/ab-tests/${Y.abTestId}/stats${$.size>0?`?${$}`:""}`,void 0,G);break}case"restart_ab_test":{let G=Y.companyId,$=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),z=Object.keys(Y).filter((A)=>!$.has(A));if(z.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${z.length===1?"":"s"}: ${z.map((A)=>`\`${A}\``).join(", ")}.`);let J=w(Y,"testType");if(J!==void 0&&J!=="subject"&&J!=="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 U=Y.variantCount===void 0?void 0:Number(Y.variantCount);if(U!==void 0&&(!Number.isInteger(U)||U<2||U>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");X=await L("POST",`/api/v1/ab-tests/${Y.abTestId}/restart`,{sourceVariantId:w(Y,"sourceVariantId"),testType:J,winnerThreshold:H,variantCount:U},G);break}case"update_ab_test_variant":{let G=Y.companyId,$=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);if(S1("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 L("PATCH",`/api/v1/ab-tests/${Y.abTestId}/variants/${Y.variantId}`,Y,G);break}case"create_ab_test":{let G=Y.companyId,$=k("create_ab_test",Y,"campaignId"),z=w(Y,"name"),J=t6("create_ab_test",Y,"testPercentage",5,50),H=t6("create_ab_test",Y,"testDurationMinutes",15,1440),U=W1("create_ab_test",Y,"winnerCriteria",["open_rate","click_rate"]);if(Y.variants!==void 0){if(!Array.isArray(Y.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");Y.variants.forEach((A,B)=>{if(!J0(A)||typeof A.subject!=="string"||A.subject.trim()==="")throw Error(`\`variants\` item ${B+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(A.blocks!==void 0&&!Array.isArray(A.blocks))throw Error(`\`variants\` item ${B+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}X=await L("POST","/api/v1/ab-tests",{campaignId:$,...z!==void 0&&{name:z},...J!==void 0&&{testPercentage:J},...H!==void 0&&{testDurationMinutes:H},...U!==void 0&&{winnerCriteria:U},...Y.variants!==void 0&&{variants:Y.variants}},G);break}case"add_ab_test_variant":{let G=Y.companyId,$=k("add_ab_test_variant",Y,"abTestId"),z=k("add_ab_test_variant",Y,"subject"),J=w(Y,"previewText");if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");X=await L("POST",`/api/v1/ab-tests/${encodeURIComponent($)}/variants`,{subject:z,...J!==void 0&&{previewText:J},...Y.blocks!==void 0&&{blocks:Y.blocks}},G);break}case"delete_ab_test_variant":{let G=Y.companyId,$=k("delete_ab_test_variant",Y,"abTestId"),z=k("delete_ab_test_variant",Y,"variantId");X=await L("DELETE",`/api/v1/ab-tests/${encodeURIComponent($)}/variants/${encodeURIComponent(z)}`,void 0,G);break}case"delete_ab_test":{let G=Y.companyId,$=k("delete_ab_test",Y,"abTestId");X=await L("DELETE",`/api/v1/ab-tests/${encodeURIComponent($)}`,void 0,G);break}case"list_campaigns":{let G=Y.companyId,$=new URLSearchParams;if(Y.status)$.set("status",String(Y.status));let z=w(Y,"label");if(z)$.set("label",z);X=await L("GET",`/api/v1/campaigns?${$}`,void 0,G);break}case"get_campaign":{let G=Y.companyId;X=await L("GET",`/api/v1/campaigns/${Y.campaignId}`,void 0,G);break}case"get_email_send":{let G=Y.companyId;X=await L("GET",`/api/v1/email-sends/${encodeURIComponent(String(Y.emailSendId))}`,void 0,G);break}case"create_campaign":{let G=Y.companyId;KV(Y);let $=w(Y,"prompt");if($!==void 0){let z=await L("POST","/api/v1/generate/email",{prompt:$,...Y.style!==void 0&&{style:Y.style},...Y.tone!==void 0&&{tone:Y.tone}},G),J=w(Y,"subject")??(typeof z.subject==="string"&&z.subject.trim()!==""?z.subject.trim():void 0);if(!J)throw Error("`create_campaign` prompt generation did not return a subject. Provide `subject` explicitly.");let H=Array.isArray(z.blocks)&&z.blocks.length>0?z.blocks:void 0,U=typeof z.html==="string"&&z.html.trim()!==""?z.html:void 0;if(H===void 0&&U===void 0)throw Error("`create_campaign` prompt generation did not return email blocks. Try again or provide `html` or `blocks` explicitly.");X=await L("POST","/api/v1/campaigns",{name:Y.name,subject:J,...H!==void 0?{blocks:H}:{html:U},...Y.segmentId!==void 0&&{segmentId:Y.segmentId},...Y.trackingCode!==void 0&&{trackingCode:Y.trackingCode},...Y.status!==void 0&&{status:Y.status},...Y.sentAt!==void 0&&{sentAt:Y.sentAt},...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 L("POST","/api/v1/campaigns",Y,G);break}case"update_campaign":{let G=Y.companyId,$=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","replyTo","replyProfileId","campaignData","computedLists","labels"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`update_campaign\` accepts only \`name\`, \`subject\`, \`trackingCode\`, \`html\`, \`blocks\`, \`replyTo\`, \`replyProfileId\`, \`campaignData\`, \`computedLists\`, and \`labels\` update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);if(S1("update_campaign",Y),NQ("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 L("PUT",`/api/v1/campaigns/${Y.campaignId}`,Y,G);break}case"schedule_campaign":{let G=Y.companyId,$=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, and \`spreadOverHours\`. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);DV(Y),X=await L("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 L("POST",`/api/v1/campaigns/${Y.campaignId}/test`,{to:Y.to},G);break}case"cancel_campaign":{let G=Y.companyId,$=k("cancel_campaign",Y,"campaignId");X=await L("POST",`/api/v1/campaigns/${encodeURIComponent($)}/cancel`,void 0,G);break}case"pause_campaign":{let G=Y.companyId,$=k("pause_campaign",Y,"campaignId");X=await L("POST",`/api/v1/campaigns/${encodeURIComponent($)}/pause`,void 0,G);break}case"resume_campaign":{let G=Y.companyId,$=k("resume_campaign",Y,"campaignId"),z=t6("resume_campaign",Y,"spreadOverHours",1,72);X=await L("POST",`/api/v1/campaigns/${encodeURIComponent($)}/resume`,{...z!==void 0&&{spreadOverHours:z}},G);break}case"delete_campaign":{let G=Y.companyId,$=k("delete_campaign",Y,"campaignId");X=await L("DELETE",`/api/v1/campaigns/${encodeURIComponent($)}`,void 0,G);break}case"duplicate_campaign":{let G=Y.companyId,$=k("duplicate_campaign",Y,"campaignId"),z=W1("duplicate_campaign",Y,"mode",["campaign","ab_test","variant"]),J=w(Y,"variantId");if(z==="variant"&&J===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");X=await L("POST",`/api/v1/campaigns/${encodeURIComponent($)}/duplicate`,{...z!==void 0&&{mode:z},...J!==void 0&&{variantId:J}},G);break}case"list_landing_pages":{let G=Y.companyId;X=await L("GET","/api/v1/landing-pages",void 0,G);break}case"get_landing_page":{let G=Y.companyId;X=await L("GET",`/api/v1/landing-pages/${Y.landingPageId}`,void 0,G);break}case"create_landing_page":{let G=Y.companyId,$=new Set(["companyId","name","slug","template","content"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);X=await L("POST","/api/v1/landing-pages",{...Y.name!==void 0&&{name:Y.name},...Y.slug!==void 0&&{slug:Y.slug},...Y.template!==void 0&&{template:Y.template},...Y.content!==void 0&&{content:Y.content}},G);break}case"update_landing_page":{let G=Y.companyId,$=lY("update_landing_page",Y,{requireUpdate:!0});X=await L("PUT",`/api/v1/landing-pages/${Y.landingPageId}`,$,G);break}case"publish_landing_page":{let G=Y.companyId,$=lY("publish_landing_page",Y,{requireUpdate:!1});X=await L("POST",`/api/v1/landing-pages/${Y.landingPageId}/publish`,$,G);break}case"unpublish_landing_page":{let G=Y.companyId,$=lY("unpublish_landing_page",Y,{requireUpdate:!1});X=await L("POST",`/api/v1/landing-pages/${Y.landingPageId}/unpublish`,$,G);break}case"delete_landing_page":{let G=Y.companyId;X=await L("DELETE",`/api/v1/landing-pages/${Y.landingPageId}`,void 0,G);break}case"connect_landing_page_domain":{let G=Y.companyId;X=await L("POST","/api/v1/landing-pages/domain",{domain:Y.domain},G);break}case"update_landing_page_domain_settings":{let G=Y.companyId,$=LV(Y);X=await L("PUT","/api/v1/landing-pages/domain",$,G);break}case"list_sequences":{let G=Y.companyId;X=await L("GET","/api/v1/sequences",void 0,G);break}case"get_sequence":{let G=Y.companyId;X=await L("GET",`/api/v1/sequences/${Y.sequenceId}`,void 0,G);break}case"create_sequence":{let G=Y.companyId,$=Array.isArray(Y.steps)&&Y.steps.length>0,z=await L("POST","/api/v1/sequences",Y,G);if(!z.success){X=z;break}let J=z.sequence.id;if($){let K=await L("GET",`/api/v1/sequences/${J}`,void 0,G);if(K.success)X={success:!0,sequence:K.sequence,message:`Sequence "${K.sequence.name}" created with explicit steps. Review it before enabling.`};else X=K;break}let H=6,U=0,A="pending";while(A!=="complete"&&U<H){await new Promise((D)=>setTimeout(D,20000)),U++;let K=await L("GET",`/api/v1/sequences/${J}`,void 0,G);if(K.success)A=K.sequence.enrichmentStatus}let B=await L("GET",`/api/v1/sequences/${J}`,void 0,G);if(B.success)X={success:!0,sequence:B.sequence,message:B.sequence.enrichmentStatus==="complete"?`Sequence "${B.sequence.name}" created with ${B.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.`:`Sequence "${B.sequence.name}" created. Email enrichment is still in progress (${B.sequence.enrichedCount}/${B.sequence.emailCount} emails generated). You can check status with get_sequence.`};else X=B;break}case"update_sequence":{let G=Y.companyId,$=AV(Y);X=await L("PUT",`/api/v1/sequences/${Y.sequenceId}`,$,G);break}case"enable_sequence":{let G=Y.companyId;X=await L("POST",`/api/v1/sequences/${Y.sequenceId}/enable`,void 0,G);break}case"disable_sequence":{let G=Y.companyId;X=await L("POST",`/api/v1/sequences/${Y.sequenceId}/disable`,void 0,G);break}case"enroll_subscribers_in_sequence":{let G=Y.companyId,$=k("enroll_subscribers_in_sequence",Y,"sequenceId"),z=NV(Y);X=await L("POST",`/api/v1/sequences/${encodeURIComponent($)}/enroll`,z,G);break}case"cancel_sequence_enrollments":{let G=Y.companyId,$=BV(Y);X=await L("POST",`/api/v1/sequences/${Y.sequenceId}/enrollments/cancel`,$,G);break}case"delete_sequence":{let G=Y.companyId;X=await L("DELETE",`/api/v1/sequences/${Y.sequenceId}`,void 0,G);break}case"list_transactional_emails":{let G=Y.companyId;X=await L("GET","/api/v1/transactional",void 0,G);break}case"get_transactional_email":{let G=Y.companyId;X=await L("GET",`/api/v1/transactional/${Y.idOrSlug}`,void 0,G);break}case"create_transactional_email":{let G=Y.companyId,$=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),z=Object.keys(Y).filter((U)=>!$.has(U));if(z.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${z.length===1?"":"s"}: ${z.map((U)=>`\`${U}\``).join(", ")}.`);qV(Y);let J=w(Y,"prompt");if(J!==void 0){let U={companyId:G??N1()??"",name:typeof Y.name==="string"&&Y.name.trim()!==""?Y.name.trim():"",slug:typeof Y.slug==="string"&&Y.slug.trim()!==""?Y.slug.trim():"",promptLength:J.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",U);let A=await L("POST","/api/v1/generate/email",{prompt:J,...Y.style!==void 0&&{style:Y.style},...Y.tone!==void 0&&{tone:Y.tone}},G);console.error("[mcp:create_transactional_email] prompt generation complete",{...U,subject:A.subject??"",previewTextLength:typeof A.previewText==="string"?A.previewText.length:0,blockCount:Array.isArray(A.blocks)?A.blocks.length:0,htmlLength:typeof A.html==="string"?A.html.length:0});let B=w(Y,"subject")??(typeof A.subject==="string"&&A.subject.trim()!==""?A.subject.trim():void 0);if(!B)throw Error("`create_transactional_email` prompt generation did not return a subject. Provide `subject` explicitly.");let K=Array.isArray(A.blocks)&&A.blocks.length>0?A.blocks:void 0,D=typeof A.html==="string"&&A.html.trim()!==""?A.html:void 0,O=w(Y,"previewText")??(typeof A.previewText==="string"?A.previewText.trim():void 0);if(K===void 0&&D===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",{...U,subject:B,contentSource:K!==void 0?"blocks":"html",blockCount:K?.length??0,htmlLength:D?.length??0}),X=await L("POST","/api/v1/transactional",{name:Y.name,...Y.slug!==void 0&&{slug:Y.slug},subject:B,...O!==void 0&&{previewText:O},...K!==void 0?{blocks:K}:{html:D},...Y.enabled!==void 0&&{enabled:Y.enabled}},G),console.error("[mcp:create_transactional_email] generated transactional created",U)}catch(A){throw console.error("[mcp:create_transactional_email] prompt-based create failed",{...U,error:A instanceof Error?A.message:String(A)}),A}break}let H=Object.fromEntries(Object.entries(Y).filter(([U])=>U!=="companyId"));X=await L("POST","/api/v1/transactional",H,G);break}case"update_transactional_email":{let G=Y.companyId,$=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),z=Object.keys(Y).filter((H)=>!$.has(H));if(z.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((H)=>`\`${H}\``).join(", ")}.`);if(S1("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 J=Object.fromEntries(Object.entries(Y).filter(([H])=>H!=="companyId"&&H!=="idOrSlug"));X=await L("PATCH",`/api/v1/transactional/${Y.idOrSlug}`,J,G);break}case"send_email":{let G=Y.companyId;X=await L("POST","/api/v1/transactional/send",Y,G);break}case"get_stats":{let G=Y.companyId,$=Y.period??"7d";X=await L("GET",`/api/v1/metrics?period=${$}`,void 0,G);break}case"get_campaign_stats":{let G=Y.companyId;X=await L("GET",`/api/v1/metrics/campaigns/${Y.campaignId}`,void 0,G);break}case"get_sequence_stats":{let G=Y.companyId;X=await L("GET",`/api/v1/metrics/sequences/${Y.sequenceId}`,void 0,G);break}case"get_subscriber_activity":{let G=Y.companyId,$=o6("get_subscriber_activity",Y),z=await mY($,G);X={success:z.success,email:z.subscriber.email,emailStats:z.subscriber.emailStats??null,activity:z.subscriber.activity??[],sequenceEnrollments:z.subscriber.sequenceEnrollments??[]};break}case"list_team_members":{let G=Y.companyId;X=await L("GET","/api/v1/team",void 0,G);break}case"invite_team_member":{let G=Y.companyId,$=k("invite_team_member",Y,"email"),z=cY("invite_team_member",Y,"role",["admin","viewer"]);if(Y.canManageBilling!==void 0&&typeof Y.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");X=await L("POST","/api/v1/team/invitations",{email:$,role:z,...Y.canManageBilling!==void 0&&{canManageBilling:Y.canManageBilling}},G);break}case"cancel_team_invitation":{let G=Y.companyId,$=k("cancel_team_invitation",Y,"invitationId");X=await L("DELETE",`/api/v1/team/invitations/${encodeURIComponent($)}`,void 0,G);break}case"list_conversations":{let G=Y.companyId,$=new URLSearchParams,z=W1("list_conversations",Y,"status",["open","closed","all"]);if(z)$.set("status",z);let J=w(Y,"search");if(J)$.set("search",J);if(Y.unread!==void 0){if(typeof Y.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(Y.unread)$.set("unread","true")}if(Y.page!==void 0){if(typeof Y.page!=="number"||!Number.isInteger(Y.page)||Y.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");$.set("page",String(Y.page))}let H=t6("list_conversations",Y,"limit",1,100);if(H!==void 0)$.set("limit",String(H));X=await L("GET",`/api/v1/conversations${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_conversation":{let G=Y.companyId,$=k("get_conversation",Y,"conversationId");X=await L("GET",`/api/v1/conversations/${encodeURIComponent($)}`,void 0,G);break}case"reply_to_conversation":{let G=Y.companyId,$=k("reply_to_conversation",Y,"conversationId"),z=W1("reply_to_conversation",Y,"type",["outbound","note"])??"outbound",J=w(Y,"subject"),H=w(Y,"bodyText"),U=w(Y,"bodyHtml");if(z==="outbound"&&H===void 0&&U===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");X=await L("POST",`/api/v1/conversations/${encodeURIComponent($)}/messages`,{type:z,...J!==void 0&&{subject:J},...H!==void 0&&{bodyText:H},...U!==void 0&&{bodyHtml:U}},G);break}case"update_conversation_status":{let G=Y.companyId,$=k("update_conversation_status",Y,"conversationId"),z=cY("update_conversation_status",Y,"status",["open","closed"]);X=await L("POST",`/api/v1/conversations/${encodeURIComponent($)}/status`,{status:z},G);break}case"mark_conversation_read":{let G=Y.companyId,$=k("mark_conversation_read",Y,"conversationId");X=await L("POST",`/api/v1/conversations/${encodeURIComponent($)}/read`,void 0,G);break}case"list_webhooks":{let G=Y.companyId;X=await L("GET","/api/v1/webhooks",void 0,G);break}case"create_webhook":{let G=Y.companyId,$=k("create_webhook",Y,"name"),z=k("create_webhook",Y,"url"),J=f5("create_webhook",Y);X=await L("POST","/api/v1/webhooks",{name:$,url:z,...J!==void 0&&{events:J}},G);break}case"update_webhook":{let G=Y.companyId,$=k("update_webhook",Y,"webhookId"),z=w(Y,"name"),J=w(Y,"url"),H=f5("update_webhook",Y),U=W1("update_webhook",Y,"status",["enabled","disabled"]);if(z===void 0&&J===void 0&&H===void 0&&U===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");X=await L("PATCH",`/api/v1/webhooks/${encodeURIComponent($)}`,{...z!==void 0&&{name:z},...J!==void 0&&{url:J},...H!==void 0&&{events:H},...U!==void 0&&{status:U}},G);break}case"delete_webhook":{let G=Y.companyId,$=k("delete_webhook",Y,"webhookId");X=await L("DELETE",`/api/v1/webhooks/${encodeURIComponent($)}`,void 0,G);break}case"test_webhook":{let G=Y.companyId,$=k("test_webhook",Y,"webhookId");X=await L("POST",`/api/v1/webhooks/${encodeURIComponent($)}/test`,void 0,G);break}case"list_webhook_deliveries":{let G=Y.companyId,$=k("list_webhook_deliveries",Y,"webhookId"),z=t6("list_webhook_deliveries",Y,"limit",1,100),J=new URLSearchParams;if(z!==void 0)J.set("limit",String(z));X=await L("GET",`/api/v1/webhooks/${encodeURIComponent($)}/deliveries${J.size>0?`?${J}`:""}`,void 0,G);break}case"replay_webhook_delivery":{let G=Y.companyId,$=k("replay_webhook_delivery",Y,"webhookId"),z=k("replay_webhook_delivery",Y,"deliveryId");X=await L("POST",`/api/v1/webhooks/${encodeURIComponent($)}/deliveries/${encodeURIComponent(z)}/replay`,void 0,G);break}case"generate_email":{let G=Y.companyId;X=await L("POST","/api/v1/generate/email",Y,G);break}case"generate_sequence":{let G=Y.companyId;X=await L("POST","/api/v1/generate/sequence",Y,G);break}case"generate_subject_lines":{let G=Y.companyId;X=await L("POST","/api/v1/generate/subjects",Y,G);break}default:throw Error(`Unknown tool: ${Q}`)}let W=FV(X);if(W)throw W;return X=await IV(Q,Y,X),{structuredContent:gV(X),content:[{type:"text",text:JSON.stringify(X,null,2)}]}}catch(X){return{isError:!0,content:[{type:"text",text:R1(X)}]}}}async function o5(Q,Y,X){let W=Y.getRequestContext?.(Q)??{};try{return await WX(W,X)}finally{await Y.onRequestContextUpdated?.(W,Q)}}function pE(Q={}){let Y=new hY({name:"sequenzy",version:E5.version},{capabilities:{tools:{},resources:{}}});return Y.setRequestHandler(I9,async()=>{return{tools:r5}}),Y.setRequestHandler(w6,async(X,W)=>{let{name:G,arguments:$}=X.params;return o5(W,Q,()=>d5(G,$??{}))}),Y.setRequestHandler(V9,async()=>{return{resources:R5}}),Y.setRequestHandler(Z9,async(X,W)=>{let{uri:G}=X.params;return o5(W,Q,()=>C5(G))}),Y}export{pE as createSequenzyMcpServer};
|