@sequenzy/mcp 0.0.99 → 0.0.100
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/index.js
CHANGED
|
@@ -26,11 +26,11 @@ var qH=Object.create;var{getPrototypeOf:OH,defineProperty:TQ,getOwnPropertyNames
|
|
|
26
26
|
newResult[${C}] = ${y}.value;
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
`)}L.write("payload.value = newResult;"),L.write("return payload;");let k=L.compile();return(S,y)=>k(D,S,y)},$,z=j1,J=!Y6.jitless,A=J&&vQ.value,U=Y.catchall,K;Q._zod.parse=(D,L)=>{K??(K=W.value);let O=D.value;if(!z(O))return D.issues.push({expected:"object",code:"invalid_type",input:O,inst:Q}),D;if(J&&A&&L?.async===!1&&L.jitless!==!0){if(!$)$=G(Y.shape);if(D=$(D,L),!U)return D;return FW([],O,D,L,K,Q)}return X(D,L)}});function C8(Q,Y,X,W){for(let $ of Q)if($.issues.length===0)return Y.value=$.value,Y;let G=Q.filter(($)=>!A1($));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map(($)=>$.issues.map((z)=>x0(z,W,T0())))}),Y}var iQ=q("$ZodUnion",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),n(Q._zod,"optout",()=>Y.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),n(Q._zod,"values",()=>{if(Y.options.every((G)=>G._zod.values))return new Set(Y.options.flatMap((G)=>Array.from(G._zod.values)));return}),n(Q._zod,"pattern",()=>{if(Y.options.every((G)=>G._zod.pattern)){let G=Y.options.map(($)=>$._zod.pattern);return new RegExp(`^(${G.map(($)=>J4($.source)).join("|")})$`)}return});let X=Y.options.length===1,W=Y.options[0]._zod.run;Q._zod.parse=(G,$)=>{if(X)return W(G,$);let z=!1,J=[];for(let H of Y.options){let A=H._zod.run({value:G.value,issues:[]},$);if(A instanceof Promise)J.push(A),z=!0;else{if(A.issues.length===0)return A;J.push(A)}}if(!z)return C8(J,G,Q,$);return Promise.all(J).then((H)=>{return C8(H,G,Q,$)})}}),OW=q("$ZodDiscriminatedUnion",(Q,Y)=>{iQ.init(Q,Y);let X=Q._zod.parse;n(Q._zod,"propValues",()=>{let G={};for(let $ of Y.options){let z=$._zod.propValues;if(!z||Object.keys(z).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf($)}"`);for(let[J,H]of Object.entries(z)){if(!G[J])G[J]=new Set;for(let A of H)G[J].add(A)}}return G});let W=g1(()=>{let G=Y.options,$=new Map;for(let z of G){let J=z._zod.propValues?.[Y.discriminator];if(!J||J.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(z)}"`);for(let H of J){if($.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);$.set(H,z)}}return $});Q._zod.parse=(G,$)=>{let z=G.value;if(!j1(z))return G.issues.push({code:"invalid_type",expected:"object",input:z,inst:Q}),G;let J=W.value.get(z?.[Y.discriminator]);if(J)return J._zod.run(G,$);if(Y.unionFallback)return X(G,$);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,input:z,path:[Y.discriminator],inst:Q}),G}}),MW=q("$ZodIntersection",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value,$=Y.left._zod.run({value:G,issues:[]},W),z=Y.right._zod.run({value:G,issues:[]},W);if($ instanceof Promise||z instanceof Promise)return Promise.all([$,z]).then(([H,A])=>{return k8(X,H,A)});return k8(X,$,z)}});function cQ(Q,Y){if(Q===Y)return{valid:!0,data:Q};if(Q instanceof Date&&Y instanceof Date&&+Q===+Y)return{valid:!0,data:Q};if(H1(Q)&&H1(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter(($)=>X.indexOf($)!==-1),G={...Q,...Y};for(let $ of W){let z=cQ(Q[$],Y[$]);if(!z.valid)return{valid:!1,mergeErrorPath:[$,...z.mergeErrorPath]};G[$]=z.data}return{valid:!0,data:G}}if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let W=0;W<Q.length;W++){let G=Q[W],$=Y[W],z=cQ(G,$);if(!z.valid)return{valid:!1,mergeErrorPath:[W,...z.mergeErrorPath]};X.push(z.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function k8(Q,Y,X){if(Y.issues.length)Q.issues.push(...Y.issues);if(X.issues.length)Q.issues.push(...X.issues);if(A1(Q))return Q;let W=cQ(Y.value,X.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return Q.value=W.data,Q}var VW=q("$ZodRecord",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!H1(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let $=[];if(Y.keyType._zod.values){let z=Y.keyType._zod.values;X.value={};for(let H of z)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let A=Y.valueType._zod.run({value:G[H],issues:[]},W);if(A instanceof Promise)$.push(A.then((U)=>{if(U.issues.length)X.issues.push(...s0(H,U.issues));X.value[H]=U.value}));else{if(A.issues.length)X.issues.push(...s0(H,A.issues));X.value[H]=A.value}}let J;for(let H in G)if(!z.has(H))J=J??[],J.push(H);if(J&&J.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:J})}else{X.value={};for(let z of Reflect.ownKeys(G)){if(z==="__proto__")continue;let J=Y.keyType._zod.run({value:z,issues:[]},W);if(J instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(J.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:J.issues.map((A)=>x0(A,W,T0())),input:z,path:[z],inst:Q}),X.value[J.value]=J.value;continue}let H=Y.valueType._zod.run({value:G[z],issues:[]},W);if(H instanceof Promise)$.push(H.then((A)=>{if(A.issues.length)X.issues.push(...s0(z,A.issues));X.value[J.value]=A.value}));else{if(H.issues.length)X.issues.push(...s0(z,H.issues));X.value[J.value]=H.value}}}if($.length)return Promise.all($).then(()=>X);return X}});var ZW=q("$ZodEnum",(Q,Y)=>{o.init(Q,Y);let X=CQ(Y.entries),W=new Set(X);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${X.filter((G)=>xQ.has(typeof G)).map((G)=>typeof G==="string"?a0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,$)=>{let z=G.value;if(W.has(z))return G;return G.issues.push({code:"invalid_value",values:X,input:z,inst:Q}),G}}),NW=q("$ZodLiteral",(Q,Y)=>{if(o.init(Q,Y),Y.values.length===0)throw Error("Cannot create literal schema with no valid values");Q._zod.values=new Set(Y.values),Q._zod.pattern=new RegExp(`^(${Y.values.map((X)=>typeof X==="string"?a0(X):X?a0(X.toString()):String(X)).join("|")})$`),Q._zod.parse=(X,W)=>{let G=X.value;if(Q._zod.values.has(G))return X;return X.issues.push({code:"invalid_value",values:Y.values,input:G,inst:Q}),X}});var wW=q("$ZodTransform",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new G4(Q.constructor.name);let G=Y.transform(X.value,X);if(W.async)return(G instanceof Promise?G:Promise.resolve(G)).then((z)=>{return X.value=z,X});if(G instanceof Promise)throw new t0;return X.value=G,X}});function v8(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var PW=q("$ZodOptional",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",n(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),n(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${J4(X.source)})?$`):void 0}),Q._zod.parse=(X,W)=>{if(Y.innerType._zod.optin==="optional"){let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>v8($,X.value));return v8(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),bW=q("$ZodNullable",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),n(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${J4(X.source)}|null)$`):void 0}),n(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,null]):void 0}),Q._zod.parse=(X,W)=>{if(X.value===null)return X;return Y.innerType._zod.run(X,W)}}),jW=q("$ZodDefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)return X.value=Y.defaultValue,X;let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>x8($,Y));return x8(G,Y)}});function x8(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var IW=q("$ZodPrefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)X.value=Y.defaultValue;return Y.innerType._zod.run(X,W)}}),EW=q("$ZodNonOptional",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"values",()=>{let X=Y.innerType._zod.values;return X?new Set([...X].filter((W)=>W!==void 0)):void 0}),Q._zod.parse=(X,W)=>{let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>_8($,Q));return _8(G,Q)}});function _8(Q,Y){if(!Q.issues.length&&Q.value===void 0)Q.issues.push({code:"invalid_type",expected:"nonoptional",input:Q.value,inst:Y});return Q}var TW=q("$ZodCatch",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>{if(X.value=$.value,$.issues.length)X.value=Y.catchValue({...X,error:{issues:$.issues.map((z)=>x0(z,W,T0()))},input:X.value}),X.issues=[];return X});if(X.value=G.value,G.issues.length)X.value=Y.catchValue({...X,error:{issues:G.issues.map(($)=>x0($,W,T0()))},input:X.value}),X.issues=[];return X}});var SW=q("$ZodPipe",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"values",()=>Y.in._zod.values),n(Q._zod,"optin",()=>Y.in._zod.optin),n(Q._zod,"optout",()=>Y.out._zod.optout),n(Q._zod,"propValues",()=>Y.in._zod.propValues),Q._zod.parse=(X,W)=>{if(W.direction==="backward"){let $=Y.out._zod.run(X,W);if($ instanceof Promise)return $.then((z)=>K6(z,Y.in,W));return K6($,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>K6($,Y.out,W));return K6(G,Y.out,W)}});function K6(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var RW=q("$ZodReadonly",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"propValues",()=>Y.innerType._zod.propValues),n(Q._zod,"values",()=>Y.innerType._zod.values),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(g8);return g8(G)}});function g8(Q){return Q.value=Object.freeze(Q.value),Q}var CW=q("$ZodCustom",(Q,Y)=>{A0.init(Q,Y),o.init(Q,Y),Q._zod.parse=(X,W)=>{return X},Q._zod.check=(X)=>{let W=X.value,G=Y.fn(W);if(G instanceof Promise)return G.then(($)=>y8($,X,W,Q));y8(G,X,W,Q);return}});function y8(Q,Y,X,W){if(!Q){let G={code:"custom",input:X,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)G.params=W._zod.def.params;Y.issues.push(y1(G))}}var UA=(Q)=>{let Y=typeof Q;switch(Y){case"number":return Number.isNaN(Q)?"NaN":"number";case"object":{if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Object.getPrototypeOf(Q)!==Object.prototype&&Q.constructor)return Q.constructor.name}}return Y},KA=()=>{let Q={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function Y(W){return Q[W]??null}let X={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${UA(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${$6(W.values[0])}`;return`Invalid option: expected one of ${X6(W.values,"|")}`;case"too_big":{let G=W.inclusive?"<=":"<",$=Y(W.origin);if($)return`Too big: expected ${W.origin??"value"} to have ${G}${W.maximum.toString()} ${$.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${G}${W.maximum.toString()}`}case"too_small":{let G=W.inclusive?">=":">",$=Y(W.origin);if($)return`Too small: expected ${W.origin} to have ${G}${W.minimum.toString()} ${$.unit}`;return`Too small: expected ${W.origin} to be ${G}${W.minimum.toString()}`}case"invalid_format":{let G=W;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${X[G.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${X6(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};function nQ(){return{localeError:KA()}}var kZ=Symbol("ZodOutput"),vZ=Symbol("ZodInput");class kW{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Q,...Y){let X=Y[0];if(this._map.set(Q,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.id,Q)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Q){let Y=this._map.get(Q);if(Y&&typeof Y==="object"&&"id"in Y)this._idmap.delete(Y.id);return this._map.delete(Q),this}get(Q){let Y=Q._zod.parent;if(Y){let X={...this.get(Y)??{}};delete X.id;let W={...X,...this._map.get(Q)};return Object.keys(W).length?W:void 0}return this._map.get(Q)}has(Q){return this._map.has(Q)}}function DA(){return new kW}var B4=DA();function vW(Q,Y){return new Q({type:"string",...T(Y)})}function xW(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...T(Y)})}function rQ(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...T(Y)})}function _W(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...T(Y)})}function gW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...T(Y)})}function yW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...T(Y)})}function uW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...T(Y)})}function hW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...T(Y)})}function fW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...T(Y)})}function lW(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...T(Y)})}function mW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...T(Y)})}function cW(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...T(Y)})}function pW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...T(Y)})}function iW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...T(Y)})}function nW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...T(Y)})}function rW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...T(Y)})}function dW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...T(Y)})}function oW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...T(Y)})}function tW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...T(Y)})}function aW(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...T(Y)})}function sW(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...T(Y)})}function eW(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...T(Y)})}function QG(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...T(Y)})}function YG(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...T(Y)})}function XG(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...T(Y)})}function WG(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...T(Y)})}function GG(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...T(Y)})}function $G(Q,Y){return new Q({type:"number",checks:[],...T(Y)})}function zG(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...T(Y)})}function JG(Q,Y){return new Q({type:"boolean",...T(Y)})}function HG(Q,Y){return new Q({type:"null",...T(Y)})}function AG(Q){return new Q({type:"unknown"})}function UG(Q,Y){return new Q({type:"never",...T(Y)})}function L6(Q,Y){return new fQ({check:"less_than",...T(Y),value:Q,inclusive:!1})}function L4(Q,Y){return new fQ({check:"less_than",...T(Y),value:Q,inclusive:!0})}function F6(Q,Y){return new lQ({check:"greater_than",...T(Y),value:Q,inclusive:!1})}function F4(Q,Y){return new lQ({check:"greater_than",...T(Y),value:Q,inclusive:!0})}function q6(Q,Y){return new q8({check:"multiple_of",...T(Y),value:Q})}function O6(Q,Y){return new M8({check:"max_length",...T(Y),maximum:Q})}function u1(Q,Y){return new V8({check:"min_length",...T(Y),minimum:Q})}function M6(Q,Y){return new Z8({check:"length_equals",...T(Y),length:Q})}function dQ(Q,Y){return new N8({check:"string_format",format:"regex",...T(Y),pattern:Q})}function oQ(Q){return new w8({check:"string_format",format:"lowercase",...T(Q)})}function tQ(Q){return new P8({check:"string_format",format:"uppercase",...T(Q)})}function aQ(Q,Y){return new b8({check:"string_format",format:"includes",...T(Y),includes:Q})}function sQ(Q,Y){return new j8({check:"string_format",format:"starts_with",...T(Y),prefix:Q})}function eQ(Q,Y){return new I8({check:"string_format",format:"ends_with",...T(Y),suffix:Q})}function I1(Q){return new E8({check:"overwrite",tx:Q})}function Q9(Q){return I1((Y)=>Y.normalize(Q))}function Y9(){return I1((Q)=>Q.trim())}function X9(){return I1((Q)=>Q.toLowerCase())}function W9(){return I1((Q)=>Q.toUpperCase())}function KG(Q,Y,X){return new Q({type:"array",element:Y,...T(X)})}function DG(Q,Y,X){let W=T(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function BG(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...T(X)})}function LG(Q){let Y=BA((X)=>{return X.addIssue=(W)=>{if(typeof W==="string")X.issues.push(y1(W,X.value,Y._zod.def));else{let G=W;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=X.value),G.inst??(G.inst=Y),G.continue??(G.continue=!Y._zod.def.abort),X.issues.push(y1(G))}},Q(X.value,X)});return Y}function BA(Q,Y){let X=new A0({check:"custom",...T(Y)});return X._zod.check=Q,X}function h1(Q){return!!Q._zod}function U1(Q,Y){if(h1(Q))return U4(Q,Y);return Q.safeParse(Y)}function V6(Q){if(!Q)return;let Y;if(h1(Q))Y=Q._zod?.def?.shape;else Y=Q.shape;if(!Y)return;if(typeof Y==="function")try{return Y()}catch{return}return Y}function FG(Q){if(h1(Q)){let $=Q._zod?.def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}}let X=Q._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let W=Q.value;if(W!==void 0)return W;return}var O4={};LX(O4,{time:()=>z9,duration:()=>J9,datetime:()=>G9,date:()=>$9,ZodISOTime:()=>MG,ZodISODuration:()=>VG,ZodISODateTime:()=>qG,ZodISODate:()=>OG});var qG=q("ZodISODateTime",(Q,Y)=>{o8.init(Q,Y),s.init(Q,Y)});function G9(Q){return YG(qG,Q)}var OG=q("ZodISODate",(Q,Y)=>{t8.init(Q,Y),s.init(Q,Y)});function $9(Q){return XG(OG,Q)}var MG=q("ZodISOTime",(Q,Y)=>{a8.init(Q,Y),s.init(Q,Y)});function z9(Q){return WG(MG,Q)}var VG=q("ZodISODuration",(Q,Y)=>{s8.init(Q,Y),s.init(Q,Y)});function J9(Q){return GG(VG,Q)}var ZG=(Q,Y)=>{z6.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>CX(Q,X)},flatten:{value:(X)=>RX(Q,X)},addIssue:{value:(X)=>{Q.issues.push(X),Q.message=JSON.stringify(Q.issues,_1,2)}},addIssues:{value:(X)=>{Q.issues.push(...X),Q.message=JSON.stringify(Q.issues,_1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},MN=q("ZodError",ZG),I0=q("ZodError",ZG,{Parent:Error});var NG=J6(I0),wG=H6(I0),PG=A4(I0),bG=K4(I0),jG=kX(I0),IG=vX(I0),EG=xX(I0),TG=_X(I0),SG=gX(I0),RG=yX(I0),CG=uX(I0),kG=hX(I0);var X0=q("ZodType",(Q,Y)=>{return o.init(Q,Y),Q.def=Y,Q.type=Y.type,Object.defineProperty(Q,"_def",{value:Y}),Q.check=(...X)=>{return Q.clone(m.mergeDefs(Y,{checks:[...Y.checks??[],...X.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},Q.clone=(X,W)=>v0(Q,X,W),Q.brand=()=>Q,Q.register=(X,W)=>{return X.add(Q,W),Q},Q.parse=(X,W)=>NG(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>PG(Q,X,W),Q.parseAsync=async(X,W)=>wG(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>bG(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>jG(Q,X,W),Q.decode=(X,W)=>IG(Q,X,W),Q.encodeAsync=async(X,W)=>EG(Q,X,W),Q.decodeAsync=async(X,W)=>TG(Q,X,W),Q.safeEncode=(X,W)=>SG(Q,X,W),Q.safeDecode=(X,W)=>RG(Q,X,W),Q.safeEncodeAsync=async(X,W)=>CG(Q,X,W),Q.safeDecodeAsync=async(X,W)=>kG(Q,X,W),Q.refine=(X,W)=>Q.check(A3(X,W)),Q.superRefine=(X)=>Q.check(U3(X)),Q.overwrite=(X)=>Q.check(I1(X)),Q.optional=()=>Y0(Q),Q.nullable=()=>_G(Q),Q.nullish=()=>Y0(_G(Q)),Q.nonoptional=(X)=>W3(Q,X),Q.array=()=>u(Q),Q.or=(X)=>d([Q,X]),Q.and=(X)=>N6(Q,X),Q.transform=(X)=>A9(Q,fG(X)),Q.default=(X)=>Q3(Q,X),Q.prefault=(X)=>X3(Q,X),Q.catch=(X)=>$3(Q,X),Q.pipe=(X)=>A9(Q,X),Q.readonly=()=>H3(Q),Q.describe=(X)=>{let W=Q.clone();return B4.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return B4.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return B4.get(Q);let W=Q.clone();return B4.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),gG=q("_ZodString",(Q,Y)=>{B6.init(Q,Y),X0.init(Q,Y);let X=Q._zod.bag;Q.format=X.format??null,Q.minLength=X.minimum??null,Q.maxLength=X.maximum??null,Q.regex=(...W)=>Q.check(dQ(...W)),Q.includes=(...W)=>Q.check(aQ(...W)),Q.startsWith=(...W)=>Q.check(sQ(...W)),Q.endsWith=(...W)=>Q.check(eQ(...W)),Q.min=(...W)=>Q.check(u1(...W)),Q.max=(...W)=>Q.check(O6(...W)),Q.length=(...W)=>Q.check(M6(...W)),Q.nonempty=(...W)=>Q.check(u1(1,...W)),Q.lowercase=(W)=>Q.check(oQ(W)),Q.uppercase=(W)=>Q.check(tQ(W)),Q.trim=()=>Q.check(Y9()),Q.normalize=(...W)=>Q.check(Q9(...W)),Q.toLowerCase=()=>Q.check(X9()),Q.toUpperCase=()=>Q.check(W9())}),wA=q("ZodString",(Q,Y)=>{B6.init(Q,Y),gG.init(Q,Y),Q.email=(X)=>Q.check(xW(PA,X)),Q.url=(X)=>Q.check(hW(bA,X)),Q.jwt=(X)=>Q.check(QG(hA,X)),Q.emoji=(X)=>Q.check(fW(jA,X)),Q.guid=(X)=>Q.check(rQ(vG,X)),Q.uuid=(X)=>Q.check(_W(Z6,X)),Q.uuidv4=(X)=>Q.check(gW(Z6,X)),Q.uuidv6=(X)=>Q.check(yW(Z6,X)),Q.uuidv7=(X)=>Q.check(uW(Z6,X)),Q.nanoid=(X)=>Q.check(lW(IA,X)),Q.guid=(X)=>Q.check(rQ(vG,X)),Q.cuid=(X)=>Q.check(mW(EA,X)),Q.cuid2=(X)=>Q.check(cW(TA,X)),Q.ulid=(X)=>Q.check(pW(SA,X)),Q.base64=(X)=>Q.check(aW(gA,X)),Q.base64url=(X)=>Q.check(sW(yA,X)),Q.xid=(X)=>Q.check(iW(RA,X)),Q.ksuid=(X)=>Q.check(nW(CA,X)),Q.ipv4=(X)=>Q.check(rW(kA,X)),Q.ipv6=(X)=>Q.check(dW(vA,X)),Q.cidrv4=(X)=>Q.check(oW(xA,X)),Q.cidrv6=(X)=>Q.check(tW(_A,X)),Q.e164=(X)=>Q.check(eW(uA,X)),Q.datetime=(X)=>Q.check(G9(X)),Q.date=(X)=>Q.check($9(X)),Q.time=(X)=>Q.check(z9(X)),Q.duration=(X)=>Q.check(J9(X))});function F(Q){return vW(wA,Q)}var s=q("ZodStringFormat",(Q,Y)=>{t.init(Q,Y),gG.init(Q,Y)}),PA=q("ZodEmail",(Q,Y)=>{f8.init(Q,Y),s.init(Q,Y)});var vG=q("ZodGUID",(Q,Y)=>{u8.init(Q,Y),s.init(Q,Y)});var Z6=q("ZodUUID",(Q,Y)=>{h8.init(Q,Y),s.init(Q,Y)});var bA=q("ZodURL",(Q,Y)=>{l8.init(Q,Y),s.init(Q,Y)});var jA=q("ZodEmoji",(Q,Y)=>{m8.init(Q,Y),s.init(Q,Y)});var IA=q("ZodNanoID",(Q,Y)=>{c8.init(Q,Y),s.init(Q,Y)});var EA=q("ZodCUID",(Q,Y)=>{p8.init(Q,Y),s.init(Q,Y)});var TA=q("ZodCUID2",(Q,Y)=>{i8.init(Q,Y),s.init(Q,Y)});var SA=q("ZodULID",(Q,Y)=>{n8.init(Q,Y),s.init(Q,Y)});var RA=q("ZodXID",(Q,Y)=>{r8.init(Q,Y),s.init(Q,Y)});var CA=q("ZodKSUID",(Q,Y)=>{d8.init(Q,Y),s.init(Q,Y)});var kA=q("ZodIPv4",(Q,Y)=>{e8.init(Q,Y),s.init(Q,Y)});var vA=q("ZodIPv6",(Q,Y)=>{QW.init(Q,Y),s.init(Q,Y)});var xA=q("ZodCIDRv4",(Q,Y)=>{YW.init(Q,Y),s.init(Q,Y)});var _A=q("ZodCIDRv6",(Q,Y)=>{XW.init(Q,Y),s.init(Q,Y)});var gA=q("ZodBase64",(Q,Y)=>{GW.init(Q,Y),s.init(Q,Y)});var yA=q("ZodBase64URL",(Q,Y)=>{$W.init(Q,Y),s.init(Q,Y)});var uA=q("ZodE164",(Q,Y)=>{zW.init(Q,Y),s.init(Q,Y)});var hA=q("ZodJWT",(Q,Y)=>{JW.init(Q,Y),s.init(Q,Y)});var yG=q("ZodNumber",(Q,Y)=>{pQ.init(Q,Y),X0.init(Q,Y),Q.gt=(W,G)=>Q.check(F6(W,G)),Q.gte=(W,G)=>Q.check(F4(W,G)),Q.min=(W,G)=>Q.check(F4(W,G)),Q.lt=(W,G)=>Q.check(L6(W,G)),Q.lte=(W,G)=>Q.check(L4(W,G)),Q.max=(W,G)=>Q.check(L4(W,G)),Q.int=(W)=>Q.check(xG(W)),Q.safe=(W)=>Q.check(xG(W)),Q.positive=(W)=>Q.check(F6(0,W)),Q.nonnegative=(W)=>Q.check(F4(0,W)),Q.negative=(W)=>Q.check(L6(0,W)),Q.nonpositive=(W)=>Q.check(L4(0,W)),Q.multipleOf=(W,G)=>Q.check(q6(W,G)),Q.step=(W,G)=>Q.check(q6(W,G)),Q.finite=()=>Q;let X=Q._zod.bag;Q.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Q.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Q.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Q.isFinite=!0,Q.format=X.format??null});function i(Q){return $G(yG,Q)}var fA=q("ZodNumberFormat",(Q,Y)=>{HW.init(Q,Y),yG.init(Q,Y)});function xG(Q){return zG(fA,Q)}var lA=q("ZodBoolean",(Q,Y)=>{AW.init(Q,Y),X0.init(Q,Y)});function H0(Q){return JG(lA,Q)}var mA=q("ZodNull",(Q,Y)=>{UW.init(Q,Y),X0.init(Q,Y)});function U9(Q){return HG(mA,Q)}var cA=q("ZodUnknown",(Q,Y)=>{KW.init(Q,Y),X0.init(Q,Y)});function e(){return AG(cA)}var pA=q("ZodNever",(Q,Y)=>{DW.init(Q,Y),X0.init(Q,Y)});function iA(Q){return UG(pA,Q)}var nA=q("ZodArray",(Q,Y)=>{BW.init(Q,Y),X0.init(Q,Y),Q.element=Y.element,Q.min=(X,W)=>Q.check(u1(X,W)),Q.nonempty=(X)=>Q.check(u1(1,X)),Q.max=(X,W)=>Q.check(O6(X,W)),Q.length=(X,W)=>Q.check(M6(X,W)),Q.unwrap=()=>Q.element});function u(Q,Y){return KG(nA,Q,Y)}var uG=q("ZodObject",(Q,Y)=>{qW.init(Q,Y),X0.init(Q,Y),m.defineLazy(Q,"shape",()=>{return Y.shape}),Q.keyof=()=>V0(Object.keys(Q._zod.def.shape)),Q.catchall=(X)=>Q.clone({...Q._zod.def,catchall:X}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:iA()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(X)=>{return m.extend(Q,X)},Q.safeExtend=(X)=>{return m.safeExtend(Q,X)},Q.merge=(X)=>m.merge(Q,X),Q.pick=(X)=>m.pick(Q,X),Q.omit=(X)=>m.omit(Q,X),Q.partial=(...X)=>m.partial(lG,Q,X[0]),Q.required=(...X)=>m.required(mG,Q,X[0])});function b(Q,Y){let X={type:"object",shape:Q??{},...m.normalizeParams(Y)};return new uG(X)}function q0(Q,Y){return new uG({type:"object",shape:Q,catchall:e(),...m.normalizeParams(Y)})}var hG=q("ZodUnion",(Q,Y)=>{iQ.init(Q,Y),X0.init(Q,Y),Q.options=Y.options});function d(Q,Y){return new hG({type:"union",options:Q,...m.normalizeParams(Y)})}var rA=q("ZodDiscriminatedUnion",(Q,Y)=>{hG.init(Q,Y),OW.init(Q,Y)});function K9(Q,Y,X){return new rA({type:"union",options:Y,discriminator:Q,...m.normalizeParams(X)})}var dA=q("ZodIntersection",(Q,Y)=>{MW.init(Q,Y),X0.init(Q,Y)});function N6(Q,Y){return new dA({type:"intersection",left:Q,right:Y})}var oA=q("ZodRecord",(Q,Y)=>{VW.init(Q,Y),X0.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function Q0(Q,Y,X){return new oA({type:"record",keyType:Q,valueType:Y,...m.normalizeParams(X)})}var H9=q("ZodEnum",(Q,Y)=>{ZW.init(Q,Y),X0.init(Q,Y),Q.enum=Y.entries,Q.options=Object.values(Y.entries);let X=new Set(Object.keys(Y.entries));Q.extract=(W,G)=>{let $={};for(let z of W)if(X.has(z))$[z]=Y.entries[z];else throw Error(`Key ${z} not found in enum`);return new H9({...Y,checks:[],...m.normalizeParams(G),entries:$})},Q.exclude=(W,G)=>{let $={...Y.entries};for(let z of W)if(X.has(z))delete $[z];else throw Error(`Key ${z} not found in enum`);return new H9({...Y,checks:[],...m.normalizeParams(G),entries:$})}});function V0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new H9({type:"enum",entries:X,...m.normalizeParams(Y)})}var tA=q("ZodLiteral",(Q,Y)=>{NW.init(Q,Y),X0.init(Q,Y),Q.values=new Set(Y.values),Object.defineProperty(Q,"value",{get(){if(Y.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return Y.values[0]}})});function j(Q,Y){return new tA({type:"literal",values:Array.isArray(Q)?Q:[Q],...m.normalizeParams(Y)})}var aA=q("ZodTransform",(Q,Y)=>{wW.init(Q,Y),X0.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new G4(Q.constructor.name);X.addIssue=($)=>{if(typeof $==="string")X.issues.push(m.issue($,X.value,Y));else{let z=$;if(z.fatal)z.continue=!1;z.code??(z.code="custom"),z.input??(z.input=X.value),z.inst??(z.inst=Q),X.issues.push(m.issue(z))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then(($)=>{return X.value=$,X});return X.value=G,X}});function fG(Q){return new aA({type:"transform",transform:Q})}var lG=q("ZodOptional",(Q,Y)=>{PW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function Y0(Q){return new lG({type:"optional",innerType:Q})}var sA=q("ZodNullable",(Q,Y)=>{bW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function _G(Q){return new sA({type:"nullable",innerType:Q})}var eA=q("ZodDefault",(Q,Y)=>{jW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function Q3(Q,Y){return new eA({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var Y3=q("ZodPrefault",(Q,Y)=>{IW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function X3(Q,Y){return new Y3({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var mG=q("ZodNonOptional",(Q,Y)=>{EW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function W3(Q,Y){return new mG({type:"nonoptional",innerType:Q,...m.normalizeParams(Y)})}var G3=q("ZodCatch",(Q,Y)=>{TW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function $3(Q,Y){return new G3({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var z3=q("ZodPipe",(Q,Y)=>{SW.init(Q,Y),X0.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function A9(Q,Y){return new z3({type:"pipe",in:Q,out:Y})}var J3=q("ZodReadonly",(Q,Y)=>{RW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function H3(Q){return new J3({type:"readonly",innerType:Q})}var cG=q("ZodCustom",(Q,Y)=>{CW.init(Q,Y),X0.init(Q,Y)});function pG(Q,Y){return DG(cG,Q??(()=>!0),Y)}function A3(Q,Y={}){return BG(cG,Q,Y)}function U3(Q){return LG(Q)}function D9(Q,Y){return A9(fG(Q),Y)}T0(nQ());var B9="2025-11-25";var iG=[B9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],K1="io.modelcontextprotocol/related-task",P6="2.0",U0=pG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),nG=d([F(),i().int()]),rG=F(),Bw=q0({ttl:d([i(),U9()]).optional(),pollInterval:i().optional()}),K3=b({ttl:i().optional()}),D3=b({taskId:F()}),L9=q0({progressToken:nG.optional(),[K1]:D3.optional()}),E0=b({_meta:L9.optional()}),M4=E0.extend({task:K3.optional()}),dG=(Q)=>M4.safeParse(Q).success,K0=b({method:F(),params:E0.loose().optional()}),S0=b({_meta:L9.optional()}),R0=b({method:F(),params:S0.loose().optional()}),D0=q0({_meta:L9.optional()}),b6=d([F(),i().int()]),oG=b({jsonrpc:j(P6),id:b6,...K0.shape}).strict(),F9=(Q)=>oG.safeParse(Q).success,tG=b({jsonrpc:j(P6),...R0.shape}).strict(),aG=(Q)=>tG.safeParse(Q).success,q9=b({jsonrpc:j(P6),id:b6,result:D0}).strict(),V4=(Q)=>q9.safeParse(Q).success;var h;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(h||(h={}));var O9=b({jsonrpc:j(P6),id:b6.optional(),error:b({code:i().int(),message:F(),data:e().optional()})}).strict();var sG=(Q)=>O9.safeParse(Q).success;var eG=d([oG,tG,q9,O9]),Lw=d([q9,O9]),j6=D0.strict(),B3=S0.extend({requestId:b6.optional(),reason:F().optional()}),I6=R0.extend({method:j("notifications/cancelled"),params:B3}),L3=b({src:F(),mimeType:F().optional(),sizes:u(F()).optional(),theme:V0(["light","dark"]).optional()}),Z4=b({icons:u(L3).optional()}),f1=b({name:F(),title:F().optional()}),Q$=f1.extend({...f1.shape,...Z4.shape,version:F(),websiteUrl:F().optional(),description:F().optional()}),F3=N6(b({applyDefaults:H0().optional()}),Q0(F(),e())),q3=D9((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},N6(b({form:F3.optional(),url:U0.optional()}),Q0(F(),e()).optional())),O3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({sampling:q0({createMessage:U0.optional()}).optional(),elicitation:q0({create:U0.optional()}).optional()}).optional()}),M3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({tools:q0({call:U0.optional()}).optional()}).optional()}),V3=b({experimental:Q0(F(),U0).optional(),sampling:b({context:U0.optional(),tools:U0.optional()}).optional(),elicitation:q3.optional(),roots:b({listChanged:H0().optional()}).optional(),tasks:O3.optional()}),Z3=E0.extend({protocolVersion:F(),capabilities:V3,clientInfo:Q$}),M9=K0.extend({method:j("initialize"),params:Z3});var N3=b({experimental:Q0(F(),U0).optional(),logging:U0.optional(),completions:U0.optional(),prompts:b({listChanged:H0().optional()}).optional(),resources:b({subscribe:H0().optional(),listChanged:H0().optional()}).optional(),tools:b({listChanged:H0().optional()}).optional(),tasks:M3.optional()}),w3=D0.extend({protocolVersion:F(),capabilities:N3,serverInfo:Q$,instructions:F().optional()}),V9=R0.extend({method:j("notifications/initialized"),params:S0.optional()});var E6=K0.extend({method:j("ping"),params:E0.optional()}),P3=b({progress:i(),total:Y0(i()),message:Y0(F())}),b3=b({...S0.shape,...P3.shape,progressToken:nG}),T6=R0.extend({method:j("notifications/progress"),params:b3}),j3=E0.extend({cursor:rG.optional()}),N4=K0.extend({params:j3.optional()}),w4=D0.extend({nextCursor:rG.optional()}),I3=V0(["working","input_required","completed","failed","cancelled"]),P4=b({taskId:F(),status:I3,ttl:d([i(),U9()]),createdAt:F(),lastUpdatedAt:F(),pollInterval:Y0(i()),statusMessage:Y0(F())}),l1=D0.extend({task:P4}),E3=S0.merge(P4),b4=R0.extend({method:j("notifications/tasks/status"),params:E3}),S6=K0.extend({method:j("tasks/get"),params:E0.extend({taskId:F()})}),R6=D0.merge(P4),C6=K0.extend({method:j("tasks/result"),params:E0.extend({taskId:F()})}),Fw=D0.loose(),k6=N4.extend({method:j("tasks/list")}),v6=w4.extend({tasks:u(P4)}),x6=K0.extend({method:j("tasks/cancel"),params:E0.extend({taskId:F()})}),Y$=D0.merge(P4),X$=b({uri:F(),mimeType:Y0(F()),_meta:Q0(F(),e()).optional()}),W$=X$.extend({text:F()}),Z9=F().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),G$=X$.extend({blob:Z9}),j4=V0(["user","assistant"]),m1=b({audience:u(j4).optional(),priority:i().min(0).max(1).optional(),lastModified:O4.datetime({offset:!0}).optional()}),$$=b({...f1.shape,...Z4.shape,uri:F(),description:Y0(F()),mimeType:Y0(F()),annotations:m1.optional(),_meta:Y0(q0({}))}),T3=b({...f1.shape,...Z4.shape,uriTemplate:F(),description:Y0(F()),mimeType:Y0(F()),annotations:m1.optional(),_meta:Y0(q0({}))}),N9=N4.extend({method:j("resources/list")}),S3=w4.extend({resources:u($$)}),R3=N4.extend({method:j("resources/templates/list")}),C3=w4.extend({resourceTemplates:u(T3)}),w9=E0.extend({uri:F()}),k3=w9,P9=K0.extend({method:j("resources/read"),params:k3}),v3=D0.extend({contents:u(d([W$,G$]))}),x3=R0.extend({method:j("notifications/resources/list_changed"),params:S0.optional()}),_3=w9,g3=K0.extend({method:j("resources/subscribe"),params:_3}),y3=w9,u3=K0.extend({method:j("resources/unsubscribe"),params:y3}),h3=S0.extend({uri:F()}),f3=R0.extend({method:j("notifications/resources/updated"),params:h3}),l3=b({name:F(),description:Y0(F()),required:Y0(H0())}),m3=b({...f1.shape,...Z4.shape,description:Y0(F()),arguments:Y0(u(l3)),_meta:Y0(q0({}))}),c3=N4.extend({method:j("prompts/list")}),p3=w4.extend({prompts:u(m3)}),i3=E0.extend({name:F(),arguments:Q0(F(),F()).optional()}),n3=K0.extend({method:j("prompts/get"),params:i3}),b9=b({type:j("text"),text:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),j9=b({type:j("image"),data:Z9,mimeType:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),I9=b({type:j("audio"),data:Z9,mimeType:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),r3=b({type:j("tool_use"),name:F(),id:F(),input:Q0(F(),e()),_meta:Q0(F(),e()).optional()}),d3=b({type:j("resource"),resource:d([W$,G$]),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),o3=$$.extend({type:j("resource_link")}),E9=d([b9,j9,I9,o3,d3]),t3=b({role:j4,content:E9}),a3=D0.extend({description:F().optional(),messages:u(t3)}),s3=R0.extend({method:j("notifications/prompts/list_changed"),params:S0.optional()}),e3=b({title:F().optional(),readOnlyHint:H0().optional(),destructiveHint:H0().optional(),idempotentHint:H0().optional(),openWorldHint:H0().optional()}),QU=b({taskSupport:V0(["required","optional","forbidden"]).optional()}),z$=b({...f1.shape,...Z4.shape,description:F().optional(),inputSchema:b({type:j("object"),properties:Q0(F(),U0).optional(),required:u(F()).optional()}).catchall(e()),outputSchema:b({type:j("object"),properties:Q0(F(),U0).optional(),required:u(F()).optional()}).catchall(e()).optional(),annotations:e3.optional(),execution:QU.optional(),_meta:Q0(F(),e()).optional()}),T9=N4.extend({method:j("tools/list")}),YU=w4.extend({tools:u(z$)}),_6=D0.extend({content:u(E9).default([]),structuredContent:Q0(F(),e()).optional(),isError:H0().optional()}),qw=_6.or(D0.extend({toolResult:e()})),XU=M4.extend({name:F(),arguments:Q0(F(),e()).optional()}),I4=K0.extend({method:j("tools/call"),params:XU}),WU=R0.extend({method:j("notifications/tools/list_changed"),params:S0.optional()}),Ow=b({autoRefresh:H0().default(!0),debounceMs:i().int().nonnegative().default(300)}),E4=V0(["debug","info","notice","warning","error","critical","alert","emergency"]),GU=E0.extend({level:E4}),S9=K0.extend({method:j("logging/setLevel"),params:GU}),$U=S0.extend({level:E4,logger:F().optional(),data:e()}),zU=R0.extend({method:j("notifications/message"),params:$U}),JU=b({name:F().optional()}),HU=b({hints:u(JU).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),AU=b({mode:V0(["auto","required","none"]).optional()}),UU=b({type:j("tool_result"),toolUseId:F().describe("The unique identifier for the corresponding tool call."),content:u(E9).default([]),structuredContent:b({}).loose().optional(),isError:H0().optional(),_meta:Q0(F(),e()).optional()}),KU=K9("type",[b9,j9,I9]),w6=K9("type",[b9,j9,I9,r3,UU]),DU=b({role:j4,content:d([w6,u(w6)]),_meta:Q0(F(),e()).optional()}),BU=M4.extend({messages:u(DU),modelPreferences:HU.optional(),systemPrompt:F().optional(),includeContext:V0(["none","thisServer","allServers"]).optional(),temperature:i().optional(),maxTokens:i().int(),stopSequences:u(F()).optional(),metadata:U0.optional(),tools:u(z$).optional(),toolChoice:AU.optional()}),LU=K0.extend({method:j("sampling/createMessage"),params:BU}),R9=D0.extend({model:F(),stopReason:Y0(V0(["endTurn","stopSequence","maxTokens"]).or(F())),role:j4,content:KU}),C9=D0.extend({model:F(),stopReason:Y0(V0(["endTurn","stopSequence","maxTokens","toolUse"]).or(F())),role:j4,content:d([w6,u(w6)])}),FU=b({type:j("boolean"),title:F().optional(),description:F().optional(),default:H0().optional()}),qU=b({type:j("string"),title:F().optional(),description:F().optional(),minLength:i().optional(),maxLength:i().optional(),format:V0(["email","uri","date","date-time"]).optional(),default:F().optional()}),OU=b({type:V0(["number","integer"]),title:F().optional(),description:F().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),MU=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),default:F().optional()}),VU=b({type:j("string"),title:F().optional(),description:F().optional(),oneOf:u(b({const:F(),title:F()})),default:F().optional()}),ZU=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),enumNames:u(F()).optional(),default:F().optional()}),NU=d([MU,VU]),wU=b({type:j("array"),title:F().optional(),description:F().optional(),minItems:i().optional(),maxItems:i().optional(),items:b({type:j("string"),enum:u(F())}),default:u(F()).optional()}),PU=b({type:j("array"),title:F().optional(),description:F().optional(),minItems:i().optional(),maxItems:i().optional(),items:b({anyOf:u(b({const:F(),title:F()}))}),default:u(F()).optional()}),bU=d([wU,PU]),jU=d([ZU,NU,bU]),IU=d([jU,FU,qU,OU]),EU=M4.extend({mode:j("form").optional(),message:F(),requestedSchema:b({type:j("object"),properties:Q0(F(),IU),required:u(F()).optional()})}),TU=M4.extend({mode:j("url"),message:F(),elicitationId:F(),url:F().url()}),SU=d([EU,TU]),RU=K0.extend({method:j("elicitation/create"),params:SU}),CU=S0.extend({elicitationId:F()}),kU=R0.extend({method:j("notifications/elicitation/complete"),params:CU}),g6=D0.extend({action:V0(["accept","decline","cancel"]),content:D9((Q)=>Q===null?void 0:Q,Q0(F(),d([F(),i(),H0(),u(F())])).optional())}),vU=b({type:j("ref/resource"),uri:F()});var xU=b({type:j("ref/prompt"),name:F()}),_U=E0.extend({ref:d([xU,vU]),argument:b({name:F(),value:F()}),context:b({arguments:Q0(F(),F()).optional()}).optional()}),gU=K0.extend({method:j("completion/complete"),params:_U});var yU=D0.extend({completion:q0({values:u(F()).max(100),total:Y0(i().int()),hasMore:Y0(H0())})}),uU=b({uri:F().startsWith("file://"),name:F().optional(),_meta:Q0(F(),e()).optional()}),hU=K0.extend({method:j("roots/list"),params:E0.optional()}),k9=D0.extend({roots:u(uU)}),fU=R0.extend({method:j("notifications/roots/list_changed"),params:S0.optional()}),Mw=d([E6,M9,gU,S9,n3,c3,N9,R3,P9,g3,u3,I4,T9,S6,C6,k6,x6]),Vw=d([I6,T6,V9,fU,b4]),Zw=d([j6,R9,C9,g6,k9,R6,v6,l1]),Nw=d([E6,LU,RU,hU,S6,C6,k6,x6]),ww=d([I6,T6,zU,f3,x3,WU,s3,b4,kU]),Pw=d([j6,w3,yU,a3,p3,S3,C3,v3,_6,YU,R6,v6,l1]);class _ extends Error{constructor(Q,Y,X){super(`MCP error ${Q}: ${Y}`);this.code=Q,this.data=X,this.name="McpError"}static fromError(Q,Y,X){if(Q===h.UrlElicitationRequired&&X){let W=X;if(W.elicitations)return new J$(W.elicitations,Y)}return new _(Q,Y,X)}}class J$ extends _{constructor(Q,Y=`URL elicitation${Q.length>1?"s":""} required`){super(h.UrlElicitationRequired,Y,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function D1(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var lU=Symbol("Let zodToJsonSchema decide on which parser to use");var XP=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function v9(Q){let X=V6(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=FG(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function x9(Q,Y){let X=U1(Q,Y);if(!X.success)throw X.error;return X.data}var rU=60000;class _9{constructor(Q){if(this._options=Q,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(I6,(Y)=>{this._oncancel(Y)}),this.setNotificationHandler(T6,(Y)=>{this._onprogress(Y)}),this.setRequestHandler(E6,(Y)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(S6,async(Y,X)=>{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(C6,async(Y,X)=>{let W=async()=>{let G=Y.params.taskId;if(this._taskMessageQueue){let z;while(z=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(z.type==="response"||z.type==="error"){let J=z.message,H=J.id,A=this._requestResolvers.get(H);if(A)if(this._requestResolvers.delete(H),z.type==="response")A(J);else{let U=J,K=new _(U.error.code,U.error.message,U.error.data);A(K)}else{let U=z.type==="response"?"Response":"Error";this._onerror(Error(`${U} handler missing for request ${H}`))}continue}await this._transport?.send(z.message,{relatedRequestId:X.requestId})}}let $=await this._taskStore.getTask(G,X.sessionId);if(!$)throw new _(h.InvalidParams,`Task not found: ${G}`);if(!D1($.status))return await this._waitForTaskUpdate(G,X.signal),await W();if(D1($.status)){let z=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...z,_meta:{...z._meta,[K1]:{taskId:G}}}}return await W()};return await W()}),this.setRequestHandler(k6,async(Y,X)=>{try{let{tasks:W,nextCursor:G}=await this._taskStore.listTasks(Y.params?.cursor,X.sessionId);return{tasks:W,nextCursor:G,_meta:{}}}catch(W){throw new _(h.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(x6,async(Y,X)=>{try{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,`Task not found: ${Y.params.taskId}`);if(D1(W.status))throw new _(h.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(Y.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Y.params.taskId);let G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new _(h.InvalidParams,`Task not found after cancellation: ${Y.params.taskId}`);return{_meta:{},...G}}catch(W){if(W instanceof _)throw W;throw new _(h.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,Y,X,W,G=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,Y),startTime:Date.now(),timeout:Y,maxTotalTimeout:X,resetTimeoutOnProgress:G,onTimeout:W})}_resetTimeout(Q){let Y=this._timeoutInfo.get(Q);if(!Y)return!1;let X=Date.now()-Y.startTime;if(Y.maxTotalTimeout&&X>=Y.maxTotalTimeout)throw this._timeoutInfo.delete(Q),_.fromError(h.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Y.maxTotalTimeout,totalElapsed:X});return clearTimeout(Y.timeoutId),Y.timeoutId=setTimeout(Y.onTimeout,Y.timeout),!0}_cleanupTimeout(Q){let Y=this._timeoutInfo.get(Q);if(Y)clearTimeout(Y.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let Y=this.transport?.onclose;this._transport.onclose=()=>{Y?.(),this._onclose()};let X=this.transport?.onerror;this._transport.onerror=(G)=>{X?.(G),this._onerror(G)};let W=this._transport?.onmessage;this._transport.onmessage=(G,$)=>{if(W?.(G,$),V4(G)||sG(G))this._onresponse(G);else if(F9(G))this._onrequest(G,$);else if(aG(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let Y=_.fromError(h.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of Q.values())X(Y)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let Y=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(Y===void 0)return;Promise.resolve().then(()=>Y(Q)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(Q,Y){let X=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,G=Q.params?._meta?.[K1]?.taskId;if(X===void 0){let A={jsonrpc:"2.0",id:Q.id,error:{code:h.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId).catch((U)=>this._onerror(Error(`Failed to enqueue error response: ${U}`)));else W?.send(A).catch((U)=>this._onerror(Error(`Failed to send an error response: ${U}`)));return}let $=new AbortController;this._requestHandlerAbortControllers.set(Q.id,$);let z=dG(Q.params)?Q.params.task:void 0,J=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:$.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(A)=>{let U={relatedRequestId:Q.id};if(G)U.relatedTask={taskId:G};await this.notification(A,U)},sendRequest:async(A,U,K)=>{let D={...K,relatedRequestId:Q.id};if(G&&!D.relatedTask)D.relatedTask={taskId:G};let L=D.relatedTask?.taskId??G;if(L&&J)await J.updateTaskStatus(L,"input_required");return await this.request(A,U,D)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:J,taskRequestedTtl:z?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(z)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(A)=>{if($.signal.aborted)return;let U={result:A,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:U,timestamp:Date.now()},W?.sessionId);else await W?.send(U)},async(A)=>{if($.signal.aborted)return;let U={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(A.code)?A.code:h.InternalError,message:A.message??"Internal error",...A.data!==void 0&&{data:A.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId);else await W?.send(U)}).catch((A)=>this._onerror(Error(`Failed to send response: ${A}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:Y,...X}=Q.params,W=Number(Y),G=this._progressHandlers.get(W);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let $=this._responseHandlers.get(W),z=this._timeoutInfo.get(W);if(z&&$&&z.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(J){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),$(J);return}G(X)}_onresponse(Q){let Y=Number(Q.id),X=this._requestResolvers.get(Y);if(X){if(this._requestResolvers.delete(Y),V4(Q))X(Q);else{let $=new _(Q.error.code,Q.error.message,Q.error.data);X($)}return}let W=this._responseHandlers.get(Y);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(Y),this._cleanupTimeout(Y);let G=!1;if(V4(Q)&&Q.result&&typeof Q.result==="object"){let $=Q.result;if($.task&&typeof $.task==="object"){let z=$.task;if(typeof z.taskId==="string")G=!0,this._taskProgressTokens.set(z.taskId,Y)}}if(!G)this._progressHandlers.delete(Y);if(V4(Q))W(Q);else{let $=_.fromError(Q.error.code,Q.error.message,Q.error.data);W($)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,Y,X){let{task:W}=X??{};if(!W){try{yield{type:"result",result:await this.request(Q,Y,X)}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}return}let G;try{let $=await this.request(Q,l1,X);if($.task)G=$.task.taskId,yield{type:"taskCreated",task:$.task};else throw new _(h.InternalError,"Task creation did not return a task");while(!0){let z=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:z},D1(z.status)){if(z.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(z.status==="failed")yield{type:"error",error:new _(h.InternalError,`Task ${G} failed`)};else if(z.status==="cancelled")yield{type:"error",error:new _(h.InternalError,`Task ${G} was cancelled`)};return}if(z.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let J=z.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,J)),X?.signal?.throwIfAborted()}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$,task:z,relatedTask:J}=X??{};return new Promise((H,A)=>{let U=(Z)=>{A(Z)};if(!this._transport){U(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),z)this.assertTaskCapability(Q.method)}catch(Z){U(Z);return}X?.signal?.throwIfAborted();let K=this._requestMessageId++,D={...Q,jsonrpc:"2.0",id:K};if(X?.onprogress)this._progressHandlers.set(K,X.onprogress),D.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:K}};if(z)D.params={...D.params,task:z};if(J)D.params={...D.params,_meta:{...D.params?._meta||{},[K1]:J}};let L=(Z)=>{this._responseHandlers.delete(K),this._progressHandlers.delete(K),this._cleanupTimeout(K),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:K,reason:String(Z)}},{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let k=Z instanceof _?Z:new _(h.RequestTimeout,String(Z));A(k)};this._responseHandlers.set(K,(Z)=>{if(X?.signal?.aborted)return;if(Z instanceof Error)return A(Z);try{let k=U1(Y,Z.result);if(!k.success)A(k.error);else H(k.data)}catch(k){A(k)}}),X?.signal?.addEventListener("abort",()=>{L(X?.signal?.reason)});let O=X?.timeout??rU,M=()=>L(_.fromError(h.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(K,O,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let N=J?.taskId;if(N){let Z=(k)=>{let S=this._responseHandlers.get(K);if(S)S(k);else this._onerror(Error(`Response handler missing for side-channeled request ${K}`))};this._requestResolvers.set(K,Z),this._enqueueTaskMessage(N,{type:"request",message:D,timestamp:Date.now()}).catch((k)=>{this._cleanupTimeout(K),A(k)})}else this._transport.send(D,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((Z)=>{this._cleanupTimeout(K),A(Z)})})}async getTask(Q,Y){return this.request({method:"tasks/get",params:Q},R6,Y)}async getTaskResult(Q,Y,X){return this.request({method:"tasks/result",params:Q},Y,X)}async listTasks(Q,Y){return this.request({method:"tasks/list",params:Q},v6,Y)}async cancelTask(Q,Y){return this.request({method:"tasks/cancel",params:Q},Y$,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let z={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[K1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:z,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!Y?.relatedRequestId&&!Y?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let z={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)z={...z,params:{...z.params,_meta:{...z.params?._meta||{},[K1]:Y.relatedTask}}};this._transport?.send(z,Y).catch((J)=>this._onerror(J))});return}let $={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)$={...$,params:{...$.params,_meta:{...$.params?._meta||{},[K1]:Y.relatedTask}}};await this._transport.send($,Y)}setRequestHandler(Q,Y){let X=v9(Q);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(W,G)=>{let $=x9(Q,W);return Promise.resolve(Y($,G))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,Y){let X=v9(Q);this._notificationHandlers.set(X,(W)=>{let G=x9(Q,W);return Promise.resolve(Y(G))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let Y=this._taskProgressTokens.get(Q);if(Y!==void 0)this._progressHandlers.delete(Y),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,Y,X){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,Y,X,W)}async _clearTaskQueue(Q,Y){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll(Q,Y);for(let W of X)if(W.type==="request"&&F9(W.message)){let G=W.message.id,$=this._requestResolvers.get(G);if($)$(new _(h.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,Y){let X=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)X=W.pollInterval}catch{}return new Promise((W,G)=>{if(Y.aborted){G(new _(h.InvalidRequest,"Request cancelled"));return}let $=setTimeout(W,X);Y.addEventListener("abort",()=>{clearTimeout($),G(new _(h.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,Y){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await X.createTask(W,Q.id,{method:Q.method,params:Q.params},Y)},getTask:async(W)=>{let G=await X.getTask(W,Y);if(!G)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(W,G,$)=>{await X.storeTaskResult(W,G,$,Y);let z=await X.getTask(W,Y);if(z){let J=b4.parse({method:"notifications/tasks/status",params:z});if(await this.notification(J),D1(z.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,$)=>{let z=await X.getTask(W,Y);if(!z)throw new _(h.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(D1(z.status))throw new _(h.InvalidParams,`Cannot update task "${W}" from terminal status "${z.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,$,Y);let J=await X.getTask(W,Y);if(J){let H=b4.parse({method:"notifications/tasks/status",params:J});if(await this.notification(H),D1(J.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function H$(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function A$(Q,Y){let X={...Q};for(let W in Y){let G=W,$=Y[G];if($===void 0)continue;let z=X[G];if(H$(z)&&H$($))X[G]={...z,...$};else X[G]=$}return X}var f5=BX(SY(),1),l5=BX(h5(),1);function XV(){let Q=new f5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return l5.default(Q),Q}class hY{constructor(Q){this._ajv=Q??XV()}getValidator(Q){let Y="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(X)=>{if(Y(X))return{valid:!0,data:X,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(Y.errors)}}}}class fY{constructor(Q){this._server=Q}requestStream(Q,Y,X){return this._server.requestStream(Q,Y,X)}async getTask(Q,Y){return this._server.getTask({taskId:Q},Y)}async getTaskResult(Q,Y,X){return this._server.getTaskResult({taskId:Q},Y,X)}async listTasks(Q,Y){return this._server.listTasks(Q?{cursor:Q}:void 0,Y)}async cancelTask(Q,Y){return this._server.cancelTask({taskId:Q},Y)}}function m5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"tools/call":if(!Q.tools?.call)throw Error(`${X} does not support task creation for tools/call (required for ${Y})`);break;default:break}}function c5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${X} does not support task creation for sampling/createMessage (required for ${Y})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${X} does not support task creation for elicitation/create (required for ${Y})`);break;default:break}}class lY extends _9{constructor(Q,Y){super(Y);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(E4.options.map((X,W)=>[X,W])),this.isMessageIgnored=(X,W)=>{let G=this._loggingLevels.get(W);return G?this.LOG_LEVEL_SEVERITY.get(X)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=Y?.capabilities??{},this._instructions=Y?.instructions,this._jsonSchemaValidator=Y?.jsonSchemaValidator??new hY,this.setRequestHandler(M9,(X)=>this._oninitialize(X)),this.setNotificationHandler(V9,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(S9,async(X,W)=>{let G=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:$}=X.params,z=E4.safeParse($);if(z.success)this._loggingLevels.set(G,z.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new fY(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=A$(this._capabilities,Q)}setRequestHandler(Q,Y){let W=V6(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let G;if(h1(W)){let z=W;G=z._zod?.def?.value??z.value}else{let z=W;G=z._def?.value??z.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let z=async(J,H)=>{let A=U1(I4,J);if(!A.success){let L=A.error instanceof Error?A.error.message:String(A.error);throw new _(h.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:U}=A.data,K=await Promise.resolve(Y(J,H));if(U.task){let L=U1(l1,K);if(!L.success){let O=L.error instanceof Error?L.error.message:String(L.error);throw new _(h.InvalidParams,`Invalid task creation result: ${O}`)}return L.data}let D=U1(_6,K);if(!D.success){let L=D.error instanceof Error?D.error.message:String(D.error);throw new _(h.InvalidParams,`Invalid tools/call result: ${L}`)}return D.data};return super.setRequestHandler(Q,z)}return super.setRequestHandler(Q,Y)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){c5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;m5(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let Y=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:iG.includes(Y)?Y:B9,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},j6)}async createMessage(Q,Y){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let X=Q.messages[Q.messages.length-1],W=Array.isArray(X.content)?X.content:[X.content],G=W.some((H)=>H.type==="tool_result"),$=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,z=$?Array.isArray($.content)?$.content:[$.content]:[],J=z.some((H)=>H.type==="tool_use");if(G){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!J)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(J){let H=new Set(z.filter((U)=>U.type==="tool_use").map((U)=>U.id)),A=new Set(W.filter((U)=>U.type==="tool_result").map((U)=>U.toolUseId));if(H.size!==A.size||![...H].every((U)=>A.has(U)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},C9,Y);return this.request({method:"sampling/createMessage",params:Q},R9,Y)}async elicitInput(Q,Y){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},g6,Y)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},G=await this.request({method:"elicitation/create",params:W},g6,Y);if(G.action==="accept"&&G.content&&W.requestedSchema)try{let z=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!z.valid)throw new _(h.InvalidParams,`Elicitation response content does not match requested schema: ${z.errorMessage}`)}catch($){if($ instanceof _)throw $;throw new _(h.InternalError,`Error validating elicitation response: ${$ instanceof Error?$.message:String($)}`)}return G}}}createElicitationCompletionNotifier(Q,Y){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},Y)}async listRoots(Q,Y){return this.request({method:"roots/list",params:Q},k9,Y)}async sendLoggingMessage(Q,Y){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,Y))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var p5={name:"@sequenzy/mcp",version:"0.0.99",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"bunx --bun tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^7.0.2"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var mY=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],i5={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",landingPages:"/dashboard/company/{companyId}/landing-pages",landingPage:"/dashboard/company/{companyId}/landing-pages/{landingPageId}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function GV(Q){let X=(Q??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return X.length>0?X:"https://sequenzy.com"}function l0(Q){let Y=Q?.trim();return Y?Y:void 0}function r0(Q){return encodeURIComponent(Q)}function $0(Q,Y){return`${Q}${Y}`}function z0(Q,Y=""){return`/dashboard/company/${r0(Q)}${Y}`}function n5(Q,Y,X){return $0(Q,`${z0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function $V(Q,Y){let X=mY.map((W)=>[W,Y?n5(Q,Y,W):""]);return Object.fromEntries(X)}function Z1(Q={},Y){let X=GV(Y),W=l0(Q.companyId),G={},$=$V(X,W);if(!W)return{appUrl:X,routeTemplates:i5,settingsTabValues:mY,urls:G,settingsUrls:$};G.dashboard=$0(X,z0(W)),G.campaigns=$0(X,z0(W,"/campaign")),G.landingPages=$0(X,z0(W,"/landing-pages")),G.sequences=$0(X,z0(W,"/sequences")),G.settings=$0(X,z0(W,"/settings")),G.emails=$0(X,z0(W,"/emails")),G.subscribers=$0(X,z0(W,"/subscribers")),G.sentEmails=$0(X,z0(W,"/sent-emails")),G.segments=$0(X,z0(W,"/segments")),G.metrics=$0(X,z0(W,"/metrics")),G.transactional=$0(X,z0(W,"/transactional"));let z=l0(Q.campaignId);if(z)G.campaign=$0(X,z0(W,`/campaign/${r0(z)}`)),G.campaignPreview=`${G.campaign}?step=review`;let J=l0(Q.landingPageId);if(J)G.landingPage=$0(X,z0(W,`/landing-pages/${r0(J)}`));let H=l0(Q.sequenceId);if(H)G.sequence=$0(X,z0(W,`/sequences/${r0(H)}`));let A=l0(Q.emailId)??l0(Q.templateId);if(A)G.email=$0(X,z0(W,`/emails/${r0(A)}`)),G.template=G.email;let U=l0(Q.transactionalId);if(U)G.transactionalEmail=$0(X,z0(W,`/transactional/${r0(U)}`));let K=l0(Q.emailSendId);if(K)G.emailSend=$0(X,z0(W,`/sent-emails/${r0(K)}`));let D=l0(Q.domainId);if(D)G.domain=$0(X,z0(W,`/settings/domain/${r0(D)}`)),G.domainVerify=`${G.domain}/verify`;let L=l0(Q.status);if(L)G.campaignList=$0(X,z0(W,`/campaign/list/${r0(L)}`)),G.sequenceList=$0(X,z0(W,`/sequences/list/${r0(L)}`));let O=l0(Q.settingsTab);if(O)G.settingsTab=n5(X,W,O);return{appUrl:X,routeTemplates:i5,settingsTabValues:mY,urls:G,settingsUrls:$}}var r5=[{uri:"sequenzy://dashboard",name:"Dashboard Overview",description:"Live overview stats for the last 7 days",mimeType:"application/json"},{uri:"sequenzy://company",name:"Current Company",description:"The currently selected company, including localization settings",mimeType:"application/json"},{uri:"sequenzy://campaigns/recent",name:"Recent Campaigns",description:"Last 10 campaigns with status and basic stats",mimeType:"application/json"},{uri:"sequenzy://subscribers/recent",name:"Recent Subscribers",description:"Most recently added subscribers",mimeType:"application/json"},{uri:"sequenzy://subscribers/engaged",name:"Engaged Subscribers",description:"Most active/engaged subscribers",mimeType:"application/json"},{uri:"sequenzy://sequences",name:"Sequences",description:"All email sequences with status",mimeType:"application/json"},{uri:"sequenzy://templates",name:"Templates",description:"All available email templates with localization status",mimeType:"application/json"},{uri:"sequenzy://segments",name:"Segments",description:"All defined segments with subscriber counts",mimeType:"application/json"},{uri:"sequenzy://tags",name:"Tags",description:"All tags with usage counts",mimeType:"application/json"},{uri:"sequenzy://health",name:"Deliverability Health",description:"Email deliverability metrics and health status",mimeType:"application/json"},{uri:"sequenzy://app-routes",name:"Dashboard URL Routes",description:"Route templates and settings tabs for building Sequenzy dashboard links",mimeType:"application/json"}];async function d5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await B("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await B("GET","/api/v1/account"),W=b1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await B("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await B("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await B("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await B("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await B("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await B("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await B("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await B("GET","/api/v1/tags");break;case"sequenzy://health":Y=await B("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=Z1();break;default:throw Error(`Unknown resource: ${Q}`)}return{contents:[{uri:Q,mimeType:"application/json",text:JSON.stringify(Y,null,2)}]}}catch(Y){return{contents:[{uri:Q,mimeType:"text/plain",text:$1(Y)}]}}}import{readFileSync as zV,statSync as JV}from"node:fs";import{basename as HV}from"node:path";var GX=' Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in the transactional send `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" } where the text before the colon is a {{merge tag}} path (nested paths like "order.total" or "event.plan" work) and the text after it is the comparison value. `field` may also be "attribute" (same "name:value" form) or "email"/"firstName"/"lastName" (the value is the plain comparison string). Operators: is, is_not, contains, not_contains, gt, gte, lt, lte, is_empty, is_not_empty. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block.',s4=`Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. For provider-migrated HTML from another email platform, prefer the \`html\` field instead; Sequenzy stores it as one raw HTML block to preserve the original design. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.${GX}`,Q4=`Replacement Sequenzy email blocks. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`.${GX}`,tY=`Sequenzy email blocks. Provide blocks or html for email steps. For migrated provider HTML, prefer \`html\`; Sequenzy stores it as one raw HTML block and does not recreate it as native blocks. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Blocks can include repeat blocks over array variables such as items.${GX}`,NQ="Complete Sequenzy landing page content JSON. Use this when replacing the page structure. The content must be the editor-compatible landing page schema with version, template, seo, theme, and blocks. Landing pages must include exactly one footer block and at most one form block.",AV="Optional template key for default content, such as from-scratch, waitlist, lead-magnet, launch, demo-request, webinar, newsletter, product-hunt, pricing-offer, agency-lead-gen, or feature-announcement.",o5=500,t5=500,N1={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},cY=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay"],a5={type:"object",description:"Optional send window for every email step in the sequence. When set, email actions that become due outside the window wait until the next allowed local time. Omit days to allow every day.",properties:{enabled:{type:"boolean",description:"Set false to disable the sending window when creating a sequence. For updates, prefer clearSendingWindow."},timezone:{type:"string",description:"IANA timezone for the window, e.g. Europe/Kiev or America/New_York."},startTime:{type:"string",description:"Earliest local send time in 24-hour HH:mm format, e.g. 08:00."},endTime:{type:"string",description:"Latest local send cutoff in 24-hour HH:mm format, e.g. 20:00. Must be later than startTime."},days:{type:"array",description:"Allowed local days. Use full names or short names such as monday, tuesday, mon, tue. Omit for every day.",items:{type:"string"}}},additionalProperties:!1},UV={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},aY={type:"object",description:"Wait until a date from the trigger event before this step. Use this for renewal reminders, appointment follow-ups, trial-expiry nudges, and other subscriber-specific dates. The field value must be an ISO date string or Unix timestamp.",properties:{field:{type:"string",description:"Dot-path into the trigger event properties, e.g. renews_at or booking.startsAt."},untilDateField:{type:"string",description:"Alias for field."},offset:UV,days:{type:"number",description:"Offset days shorthand. Ignored when offset is provided."},hours:{type:"number",description:"Offset hours shorthand. Ignored when offset is provided."},minutes:{type:"number",description:"Offset minutes shorthand. Ignored when offset is provided."},direction:{type:"string",enum:["before","after"],description:"Whether the offset applies before or after the resolved date. Defaults to after."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"Alias for direction."},missingAction:{type:"string",enum:["continue","exit"],description:"What to do if the event field is missing or invalid. Defaults to continue."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"Alias for missingAction."}},additionalProperties:!1},sY={type:"object",description:"Fixed delay before this step. For a dynamic wait-until-date delay, either set mode:'until_date' plus untilDateField here, or use waitUntil.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"},mode:{type:"string",enum:["duration","until_date"],description:"Use duration for a fixed wait, or until_date to resolve a date from the trigger event."},untilDateField:{type:"string",description:"For mode:'until_date', dot-path into the trigger event properties."},field:{type:"string",description:"Alias for untilDateField."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"For mode:'until_date', whether days/hours/minutes are before or after the event date. Defaults to after."},direction:{type:"string",enum:["before","after"],description:"Alias for untilOffsetDirection."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"For mode:'until_date', what to do when the field is missing or invalid. Defaults to continue."},missingAction:{type:"string",enum:["continue","exit"],description:"Alias for untilMissingAction."}},additionalProperties:!1},wQ=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],PQ=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","sequence.finished","sequence.failed"],KV=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_websites","check_website","get_integration_guide","get_subscriber","list_subscriber_notes","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_email_send","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_transactional_emails","get_transactional_email","get_stats","get_campaign_stats","get_sequence_stats","list_campaign_events","list_sequence_events","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_sequence","generate_subject_lines","generate_sms","get_sms_settings"]),DV=new Set(["select_company","create_company","update_company","update_sync_rules","update_shopify_automation_settings","create_api_key","add_website","verify_sending_domain","add_subscriber","update_subscriber","add_subscriber_note","remove_subscriber","delete_subscriber_note","upsert_products","delete_product","attach_product_file","remove_product_file","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","delete_template","restart_ab_test","update_ab_test_variant","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","send_test_sms","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_landing_page","update_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","update_sequence","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery","submit_feedback"]),BV=new Set(["send_test_email","send_test_sms","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","verify_sending_domain","enable_sequence","resume_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery"]),LV=new Set(["remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","disable_sequence","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook"]);function FV(Q){let Y=KV.has(Q),X=DV.has(Q);if(Y===X)throw Error(`MCP tool "${Q}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:Y,destructiveHint:Y?!1:LV.has(Q),openWorldHint:BV.has(Q)}}function qV(Q){return{...Q,annotations:{...Q.annotations,...FV(Q.name)}}}var eY={status:["is","is_not"],phone:["is_not_empty","is_empty"],smsStatus:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"],commerceProduct:["is","is_not","at_least","less_than_count"]},OV=Object.entries(eY).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),s5={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","phone","smsStatus","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct","commerceProduct"],description:"Filter field. Use `phone` with is_not_empty/is_empty to check whether a subscriber has a phone number, and `smsStatus` (is/is_not one of `subscribed`, `unsubscribed`, `not_subscribed`) for SMS marketing consent. Use `event` for custom subscriber events, `segment` for saved segment membership, `stripeProduct`/`stripeCurrentProduct`/`stripeTrialProduct` for Stripe product-based segments, and `commerceProduct` for products purchased through commerce orders - the value is `provider:productId` (provider one of `shopify`, `woocommerce`, `api`; product ids are provider-scoped), optionally with an order-count threshold (`provider:productId:count`) for at_least/less_than_count; a bare product id matches the id on any provider. Engagement fields (`emailSent`, `emailDelivered`, `emailOpened`, `emailClicked`, `emailBounced`, `emailComplained`) accept a time range as the value or a specific campaign via `campaign:<campaign_id>`."},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${OV}.`},value:{type:"string",description:"Filter value. For custom attribute empty checks, use `attributeName:` such as `last_logged_in:`. Event examples: `saas.purchase:30d`, `saas.purchase:all`, or `saas.purchase:5:30d` for thresholds. Segment values are segment IDs. Stripe product examples: `prod_123` for bought/didn't buy/current/trialing, `prod_123:3` for payment thresholds, `prod_123:is_canceled` for products set to cancel, `prod_123:cancels_at:2026-05-26`, `prod_123:end_at:2026-05-26`, or `prod_123:start_at:7 days ago` for product-scoped dates. Engagement examples: `7d`, `30d`, `90d`, `180d`, `all` for rolling time windows, or `campaign:<campaign_id>` to scope to a specific sent campaign (use `list_campaigns` to find IDs)."}},required:["field","operator","value"],additionalProperties:!1},e5={type:"object",properties:{kind:{type:"string",enum:["group"]},id:{type:"string",description:"Stable group ID. Any string works; one will be generated if omitted."},joinOperator:{type:"string",enum:["and","or"],description:"How children in this group combine."},children:{type:"array",minItems:1,items:{type:"object",description:'Either a filter leaf (`kind: "filter"`) or another group (`kind: "group"`).'}}},required:["kind","joinOperator","children"],additionalProperties:!0};function QX(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(typeof Y!=="object"||Y===null)return Y;let X=Y;if(typeof X.id==="string"&&X.id.trim()!=="")return X;return{...X,id:crypto.randomUUID()}})}function YX(Q){if(typeof Q!=="object"||Q===null)return Q;let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=QX([Y]);return Array.isArray(X)?X[0]:Y}if(Y.kind!=="group")return Q;return{...Y,id:typeof Y.id==="string"&&Y.id.trim()!==""?Y.id:crypto.randomUUID(),children:Array.isArray(Y.children)?Y.children.map(YX):[]}}function MV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function VV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function QH(Q){if(Q==="all")return!0;let Y=Q.match(/^(\d+)d$/);if(!Y?.[1])return!1;let X=Number.parseInt(Y[1],10);return Number.isInteger(X)&&X>0}function ZV(Q,Y){let X=Y.split(":");if(Q==="at_least"||Q==="less_than_count"){if(X.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let $=X.slice(0,-2).join(":").trim(),z=X.at(-2),J=X.at(-1),H=z===void 0?Number.NaN:Number.parseInt(z,10);return $&&Number.isInteger(H)&&H>0&&J!==void 0&&QH(J)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(X.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=X.slice(0,-1).join(":").trim(),G=X.at(-1);return W&&G!==void 0&&QH(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function NV(Q){let Y=Q.indexOf(":");if(Y===-1)return{productId:Q,subfilter:null,rawValue:null};let X=Q.substring(0,Y),W=Q.substring(Y+1),G=W.indexOf(":");if(G===-1)return{productId:X,subfilter:W,rawValue:null};return{productId:X,subfilter:W.substring(0,G),rawValue:W.substring(G+1)}}function wV(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function PV(Q){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(Q)}function bV(Q,Y){if(Y==="cancels_at"||Y==="cancel_at"||Y==="cancellation_at")return!0;if(Q==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(Y);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(Y)}function jV(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function IV(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let J=X.indexOf(":");if(J===-1)return null;let H=X.substring(0,J).trim(),A=Number.parseInt(X.substring(J+1).trim(),10);return H&&Number.isInteger(A)&&A>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(Q!=="stripeCurrentProduct"&&Q!=="stripeTrialProduct")return null;let{productId:W,subfilter:G,rawValue:$}=NV(X);if(!W.trim())return"Stripe product filters must include a product ID.";if(!G)return Y==="is"||Y==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let z=wV(G);if(PV(z))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!bV(Q,z))return`Unsupported Stripe product subfilter "${G}".`;if(!jV(Y))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return $?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var EV=new Set(["shopify","woocommerce","api"]);function TV(Q,Y){let X=Y.trim(),W=X.indexOf(":");if(W!==-1&&EV.has(X.substring(0,W).trim()))X=X.substring(W+1).trim();if(!X)return'Purchased Product filters must include a product ID, like "shopify:42".';if(Q!=="at_least"&&Q!=="less_than_count")return null;let G=X.lastIndexOf(":");if(G===-1)return null;let $=X.substring(0,G).trim(),z=Number.parseInt(X.substring(G+1).trim(),10);return $&&Number.isInteger(z)&&z>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function $X(Q){if(typeof Q!=="object"||Q===null)return"Segment filters must be objects.";let Y=Q,X=Y.field,W=Y.operator,G=Y.value;if(typeof X!=="string"||!(X in eY))return`Unsupported segment filter field "${String(X)}".`;if(typeof W!=="string")return`Segment filter "${X}" must include an operator.`;let $=eY[X];if(!$.includes(W))return`Operator "${W}" is not supported for ${X} filters. Use one of: ${$.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${X}" must include a value.`;if(X==="attribute"&&typeof G==="string"){if(!MV(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!VV(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let z=ZV(W,G);if(z)return z}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let z=IV(X,W,G);if(z)return z}if(X==="commerceProduct"&&typeof G==="string"){let z=TV(W,G);if(z)return z}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map((J)=>J.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function zX(Q){if(typeof Q!=="object"||Q===null)return[];let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=$X(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap(zX);return[]}function w1(Q,Y,X){if(Y.html!==void 0&&Y.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`, not both.`);if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error(`\`blocks\` must be an array when calling \`${Q}\`.`);if(X?.requireContent&&Y.html===void 0&&Y.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`.`)}function bQ(Q,Y){if(Y.labels===void 0)return;if(!Array.isArray(Y.labels))throw Error(`\`labels\` must be an array when calling \`${Q}\`.`);if(Y.labels.some((X)=>typeof X!=="string"||X.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${Q}\`.`)}function SV(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!Y&&!X)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=$X(G);return $?[$]:[]}):zX(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function RV(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(Q.name===void 0&&Q.filterJoinOperator===void 0&&!Y&&!X)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=$X(G);return $?[$]:[]}):X?zX(Q.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var pY=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"];function iY(Q,Y,X){if(Y[X]!==void 0&&!J0(Y[X]))throw Error(`\`${X}\` must be an object when calling \`${Q}\`.`)}function YH(Q,Y,X){if(Y[X]!==void 0&&!Array.isArray(Y[X]))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`)}function CV(Q){let Y=new Set(["companyId",...pY]),X=Object.keys(Q).filter((G)=>!Y.has(G));if(X.length>0)throw Error(`\`update_company\` accepts only company product-info fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);let W={};for(let G of pY)if(Q[G]!==void 0)W[G]=Q[G];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${pY.map((G)=>`\`${G}\``).join(", ")} when calling \`update_company\`.`);for(let G of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"])if(Q[G]!==void 0&&typeof Q[G]!=="string")throw Error(`\`${G}\` must be a string when calling \`update_company\`.`);if(iY("update_company",Q,"brandColors"),iY("update_company",Q,"socialLinks"),iY("update_company",Q,"pricing"),YH("update_company",Q,"valueProps"),YH("update_company",Q,"testimonials"),typeof Q.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(Q.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let G of["fromEmail","replyTo"]){let $=Q[G];if(typeof $==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($.trim()))throw Error(`\`${G}\` must be a valid email address when calling \`update_company\`.`)}if(Q.fromName!==void 0&&Q.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_company`.");if(Q.replyToName!==void 0&&Q.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_company`.");return W}function kV(Q){if(Q.fromEmail!==void 0&&Q.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_sequence`, not both.");if(Q.replyTo!==void 0&&Q.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_sequence`, not both.");if(Q.fromName!==void 0&&Q.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_sequence`.");if(Q.replyToName!==void 0&&Q.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_sequence`.");if(Q.clearEnrollmentFieldPath===!0&&Q.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(Q.clearSendingWindow===!0&&Q.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(Q.clearBccEmails===!0&&Q.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(Q.branch!==void 0&&Q.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");let Y={...Q};if(delete Y.clearEnrollmentFieldPath,delete Y.clearSendingWindow,delete Y.clearBccEmails,Q.clearEnrollmentFieldPath===!0)Y.enrollmentFieldPath=null;if(Q.clearSendingWindow===!0)Y.sendingWindow=null;if(Q.clearBccEmails===!0)Y.bccEmails=null;return Y}function vV(Q){let Y=Q.type==="sms",X;if(Y){let G=w(Q,"text"),$=Array.isArray(Q.blocks)&&Q.blocks.length>0;if(G===void 0&&!$)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");X={type:"sms"};for(let z of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(Q[z]!==void 0)X[z]=Q[z]}else{w1("insert_sequence_step",Q,{requireContent:!0}),X={subject:R("insert_sequence_step",Q,"subject")};for(let G of["name","previewText","html","blocks","delay","delayMs","waitUntil"])if(Q[G]!==void 0)X[G]=Q[G]}let W={steps:[X]};if(Q.afterNodeId!==void 0)W.afterNodeId=Q.afterNodeId;return{...Q.confirmStructuralChange!==void 0&&{confirmStructuralChange:Q.confirmStructuralChange},insertSteps:W}}function xV(Q){let Y=w(Q,"subscriberId"),X=Q.fieldValues,W=X===void 0?void 0:Array.isArray(X)?X:void 0;if(X!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let G=W?.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0)??[];if(W?.some((J)=>typeof J!=="string")||W!==void 0&&G.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(Y!==void 0===G.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let $=w(Q,"fieldPath"),z=w(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...$!==void 0&&{fieldPath:$},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...z!==void 0&&{reason:z}}}function _V(Q){w1("create_campaign",Q),bQ("create_campaign",Q);let Y=w(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0,G=Q.templateId!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(Y&&(X||W||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function gV(Q){w1("create_template",Q),bQ("create_template",Q);let Y=w(Q,"prompt")!==void 0,X=[Y,Q.html!==void 0,Q.blocks!==void 0].filter(Boolean).length;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_template`.");if(X!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function yV(Q){if(w(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!J0(Q.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(Q.sendTimeOptimization!==void 0){if(typeof Q.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(Q.spreadOverHours!==void 0){if(typeof Q.spreadOverHours!=="number"||!Number.isInteger(Q.spreadOverHours)||Q.spreadOverHours<1||Q.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(Q.recurringInterval!==void 0&&Q.recurringInterval!=="weekly"&&Q.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function nY(Q,Y,X){let W=new Set(["companyId","landingPageId","name","slug","content"]),G=Object.keys(Y).filter(($)=>!W.has($));if(G.length>0)throw Error(`\`${Q}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map(($)=>`\`${$}\``).join(", ")}.`);if(X.requireUpdate&&Y.name===void 0&&Y.slug===void 0&&Y.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${Q}\`.`);return{...Y.name!==void 0&&{name:Y.name},...Y.slug!==void 0&&{slug:Y.slug},...Y.content!==void 0&&{content:Y.content}}}function uV(Q){let Y=new Set(["companyId","domain","verify"]),X=Object.keys(Q).filter((W)=>!Y.has(W));if(X.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${X.length===1?"":"s"}: ${X.map((W)=>`\`${W}\``).join(", ")}.`);if(Q.domain===void 0&&Q.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...Q.domain!==void 0&&{domain:Q.domain},...typeof Q.verify==="boolean"&&{verify:Q.verify}}}function hV(Q){w1("create_transactional_email",Q);let Y=w(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(Y&&(X||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!Y&&!X&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var XX={type:"object",description:"Update Subscriber config. firstName, lastName, and customAttributeUpdates values may use trigger-event merge tags such as {{event.plan}}. Number and boolean values must be a literal or one standalone merge tag and are coerced after resolution.",properties:{label:{type:"string"},firstName:{type:["string","null"],description:"First name literal or merge tag; null clears the field."},lastName:{type:["string","null"],description:"Last name literal or merge tag; null clears the field."},status:{type:"string",enum:["active","unsubscribed","bounced"]},customAttributeUpdates:{type:"array",items:{type:"object",properties:{name:{type:"string"},value:{type:["string","number","boolean","null"],description:"Literal scalar, null to delete, or a standalone merge tag such as {{event.plan}}, {{event.amount}}, or {{event.active}}."},valueType:{type:"string",enum:["text","number","boolean"]}},required:["name","value"]}}},additionalProperties:!0},rY={type:"object",description:"A step to create inside a sequence path. Use type:'delay' for a standalone delay, type:'email' for an email, type:'create_discount' for a discount action, or type:'condition' for a condition gate.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","update_subscriber","condition","webhook"],description:"Sequence path step type. Omit for email steps; use delay for standalone waits or update_subscriber for action_update_attributes."},nodeType:{type:"string",enum:["logic_delay","action_email","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","logic_condition","action_webhook"],description:"Advanced sequence path node type. Prefer type unless creating a non-email action."},config:{...XX,description:"Config for advanced nodeType steps. For action_update_attributes, use the documented Update Subscriber fields and trigger-event merge tags; other node types accept their normal config fields.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:tY,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},delay:sY,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:aY,name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use stripe to dynamically create a Stripe coupon plus promotion code, or shopify to dynamically create a Shopify Admin discount code."},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"}},additionalProperties:!1};function fV(Q){if(!Q||typeof Q!=="object")return null;let Y=Q;if(Y.success!==!1)return null;if(typeof Y.error==="string")return Error(Y.error);if(Y.error&&typeof Y.error==="object"&&typeof Y.error.message==="string")return Error(Y.error.message);if(typeof Y.message==="string")return Error(Y.message);return Error("The tool returned an unsuccessful response.")}function J0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function XH(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function lV(Q){let Y=new URLSearchParams;if(typeof Q.query==="string"&&Q.query.trim()!=="")Y.set("query",Q.query.trim());if(Array.isArray(Q.tags)&&Q.tags.length>0)Y.set("tags",Q.tags.filter((X)=>typeof X==="string"&&X.trim()!=="").join(","));if(typeof Q.list==="string"&&Q.list.trim()!=="")Y.set("list",Q.list.trim());if(typeof Q.listId==="string"&&Q.listId.trim()!=="")Y.set("listId",Q.listId.trim());if(typeof Q.listName==="string"&&Q.listName.trim()!=="")Y.set("listName",Q.listName.trim());if(typeof Q.segmentId==="string"&&Q.segmentId.trim()!=="")Y.set("segmentId",Q.segmentId);if(typeof Q.status==="string"&&Q.status.trim()!=="")Y.set("status",Q.status.trim());return Y.set("page",String(Q.page)),Y.set("limit",String(Q.pageSize)),Y}async function mV(Q,Y){let X=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,W=Math.min(100,Math.max(1,X??100)),G=[],$=1,z=0,J=0,H=0;while(!0){let U=lV({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:$,pageSize:W}),K=await B("GET",`/api/v1/subscribers?${U.toString()}`,void 0,Y);z=K.pagination?.total??K.subscribers.length,J=K.pagination?.totalPages??1,H+=1,G.push(...K.subscribers??[]);let D=X!==void 0&&G.length>=X,L=K.pagination?$>=K.pagination.totalPages:(K.subscribers??[]).length<W;if(D||L)break;$+=1}let A=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:A,pagination:{page:1,limit:W,total:z,totalPages:J,fetchedPages:H},returned:A.length,truncated:X!==void 0&&z>0&&A.length<z}}function cV(Q){let Y=typeof Q.email==="string"&&Q.email.trim()!==""?Q.email.trim():void 0,X=typeof Q.externalId==="string"&&Q.externalId.trim()!==""?Q.externalId.trim():void 0;return{...Y?{email:Y}:{},...X?{externalId:X}:{}}}function v1(Q,Y){let X=cV(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function WX(Q,Y){let X=new URLSearchParams;if(Y?.includeMachineEngagement)X.set("includeMachineEngagement","true");let W=X.toString(),G=W?`?${W}`:"";if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}${G}`;return X.set("externalId",String(Q.externalId)),`/api/v1/subscribers/external?${X.toString()}`}function WH(Q){if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}/notes`;let Y=new URLSearchParams;return Y.set("externalId",String(Q.externalId)),`/api/v1/subscribers/external/notes?${Y.toString()}`}async function dY(Q,Y,X){return B("GET",WX(Q,X),void 0,Y)}function w(Q,Y){let X=Q[Y];if(typeof X!=="string")return;let W=X.trim();return W.length>0?W:void 0}function R(Q,Y,X){let W=w(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function m0(Q,Y,X,W){let G=w(Y,X);if(G===void 0)return;if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function oY(Q,Y,X,W){let G=R(Q,Y,X);if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function x1(Q,Y,X,W,G){let $=Y[X];if($===void 0)return;if(typeof $!=="number"||!Number.isInteger($)||$<W||$>G)throw Error(`\`${X}\` must be an integer between ${W} and ${G} when calling \`${Q}\`.`);return $}function pV(Q,Y){let X=[],W=m0(Q,Y,"eventType",cY);if(W)X.push(W);if(Y.eventTypes!==void 0){if(!Array.isArray(Y.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${Q}\`.`);Y.eventTypes.forEach((G,$)=>{if(typeof G!=="string")throw Error(`\`eventTypes\` item ${$+1} must be a string when calling \`${Q}\`.`);let z=G.trim();if(!cY.includes(z))throw Error(`\`eventTypes\` item ${$+1} must be one of ${cY.join(", ")} when calling \`${Q}\`.`);X.push(z)})}return[...new Set(X)]}function GH(Q,Y){let X=new URLSearchParams,W=pV(Q,Y);if(W.length>0)X.set("eventTypes",W.join(","));let G=m0(Q,Y,"period",["1h","24h","7d","30d","90d"]);if(G)X.set("period",G);let $=w(Y,"start");if($)X.set("start",$);let z=w(Y,"end");if(z)X.set("end",z);let J=x1(Q,Y,"page",1,1e6);if(J!==void 0)X.set("page",String(J));let H=x1(Q,Y,"limit",1,500);if(H!==void 0)X.set("limit",String(H));if(Y.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");return X}function $H(Q,Y){if(Y.events===void 0)return;if(!Array.isArray(Y.events))throw Error(`\`events\` must be an array when calling \`${Q}\`.`);let X=Y.events.map((W,G)=>{if(typeof W!=="string"||!PQ.includes(W))throw Error(`\`events\` item ${G+1} must be one of ${PQ.join(", ")} when calling \`${Q}\`.`);return W});if(X.length===0)throw Error(`\`events\` must include at least one event type when calling \`${Q}\`.`);return X}function zH(Q,Y){if(!Array.isArray(Y.emails))throw Error(`\`emails\` must be an array when calling \`${Q}\`.`);let X=[];if(Y.emails.forEach((W,G)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${Q}\`.`);let $=W.trim();if($.length>0)X.push($)}),X.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${Q}\`.`);if(X.length>o5)throw Error(`\`emails\` must include no more than ${o5} email addresses when calling \`${Q}\`. Split larger batches into multiple calls.`);return X}function JH(Q,Y,X,W){let G=Y[X];if(G===void 0)return;if(!Array.isArray(G))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`);let $=[];if(G.forEach((z,J)=>{if(typeof z!=="string")throw Error(`\`${X}\` item ${J+1} must be a string when calling \`${Q}\`.`);let H=z.trim();if(H.length>0)$.push(H)}),$.length===0)throw Error(`\`${X}\` must include at least one ${W} when calling \`${Q}\`.`);return $}function iV(Q){let X=JH("enroll_subscribers_in_sequence",Q,"emails","email address"),W=JH("enroll_subscribers_in_sequence",Q,"subscriberIds","subscriber ID"),G=(X?.length??0)+(W?.length??0);if(G===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(G>t5)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${t5} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let $=w(Q,"targetNodeId");return{...X!==void 0&&{emails:X},...W!==void 0&&{subscriberIds:W},...$!==void 0&&{targetNodeId:$}}}var nV={pdf:"application/pdf",epub:"application/epub+zip",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",txt:"text/plain",csv:"text/csv"};function rV(Q){let Y=Q.split(".").pop()?.toLowerCase()??"";return nV[Y]??null}var dV=104857600;async function oV(Q,Y){if(!OX())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let X=rV(Q);if(!X)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=JV(Q).size;if(W>dV)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=zV(Q),$=await B("POST","/api/v1/products/delivery/upload-url",{filename:HV(Q),contentType:X,fileSizeBytes:W},Y),z=await fetch($.uploadUrl,{method:"PUT",headers:{"Content-Type":X},body:G});if(!z.ok)throw Error(`File upload failed (${z.status})`);return{url:$.publicUrl,fileName:$.fileName,fileSizeBytes:W,mimeType:X}}async function JX(Q){let Y=w(Q,"companyId");if(Y)return Y;let X=b1();if(X)return X;try{return(await B("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function tV(Q,Y){let X=await JX(Y);if(!X)throw Error(`A company is required when calling \`${Q}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return X}function Y4(Q,Y){if(!J0(Q)||!Y)return Q;return{...Q,url:Y}}function HH(Q,Y){if(!J0(Q))return Q;return{...Q,...Y.campaign!==void 0&&{url:Y.campaign},...Y.campaignPreview!==void 0&&{previewUrl:Y.campaignPreview}}}function e4(Q,Y,X){if(!Array.isArray(Q)||!Y)return Q;return Q.map((W)=>{if(!J0(W))return W;let G=w(W,"id");if(!G)return W;let $=Z1({companyId:Y,...X==="campaign"&&{campaignId:G},...X==="landingPage"&&{landingPageId:G},...X==="sequence"&&{sequenceId:G},...X==="template"&&{emailId:G},...X==="transactional"&&{transactionalId:G}});if(X==="campaign")return HH(W,$.urls);let z=X==="sequence"?$.urls.sequence:X==="landingPage"?$.urls.landingPage:X==="template"?$.urls.email:$.urls.transactionalEmail;return Y4(W,z)})}function aV(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!J0(Y))return Y;let X=w(Y,"id");if(!X)return Y;let W=Z1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var AH=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","update_sequence","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function sV(Q,Y,X){if(!J0(X)||!AH.has(Q))return X;let W=J0(X.company)?X.company:void 0,$=w(X,"selectedCompanyId")??w(X,"currentCompanyId")??w(X,"companyId")??(W?w(W,"id"):void 0)??(W?w(W,"companyId"):void 0)??await JX(Y);if(!$)return X;let z=J0(X.campaign)?X.campaign:void 0,J=J0(X.sequence)?X.sequence:void 0,H=J0(X.landingPage)?X.landingPage:void 0,A=J0(X.template)?X.template:void 0,U=J0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,K={companyId:$,campaignId:w(Y,"campaignId")??w(X,"campaignId")??(z?w(z,"id"):void 0),landingPageId:w(Y,"landingPageId")??w(X,"landingPageId")??(H?w(H,"id"):void 0),sequenceId:w(Y,"sequenceId")??w(X,"sequenceId")??(J?w(J,"id"):void 0),emailId:w(X,"templateId")??(A?w(A,"id"):void 0)??(U?w(U,"emailId"):void 0)??w(Y,"templateId"),transactionalId:w(Y,"transactionalId")??(U?w(U,"id"):void 0)??w(Y,"idOrSlug"),emailSendId:w(Y,"emailSendId")??w(X,"emailSendId")??(J0(X.emailSend)?w(X.emailSend,"id"):void 0),status:w(Y,"status")},D=Z1(K),L=W?Z1({companyId:$}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:aV(X.companies)},...Array.isArray(X.campaigns)&&{campaigns:e4(X.campaigns,$,"campaign")},...Array.isArray(X.landingPages)&&{landingPages:e4(X.landingPages,$,"landingPage")},...Array.isArray(X.sequences)&&{sequences:e4(X.sequences,$,"sequence")},...Array.isArray(X.templates)&&{templates:e4(X.templates,$,"template")},...Array.isArray(X.transactional)&&{transactional:e4(X.transactional,$,"transactional")},...W&&L!==void 0&&{company:{...W,url:L.urls.dashboard,settingsUrl:L.urls.settings}},...z&&D.urls.campaign!==void 0&&{campaign:HH(z,D.urls)},...J&&D.urls.sequence!==void 0&&{sequence:Y4(J,D.urls.sequence)},...H&&D.urls.landingPage!==void 0&&{landingPage:Y4(H,D.urls.landingPage)},...A&&D.urls.email!==void 0&&{template:Y4(A,D.urls.email)},...U&&D.urls.transactionalEmail!==void 0&&{transactional:Y4(U,D.urls.transactionalEmail)},...J0(X.emailSend)&&D.urls.emailSend!==void 0&&{emailSend:Y4(X.emailSend,D.urls.emailSend)},appUrls:D.urls}}var eV={type:"boolean",description:"Whether the Sequenzy operation succeeded."},QZ={type:"string",description:"Human-readable status, confirmation, or next-step message."},YZ={type:"string",description:"Additional context about the result."};function W0(Q){return{type:"object",description:Q,additionalProperties:!0}}function XZ(Q){return{type:"array",description:Q,items:W0("One item in the returned collection.")}}function E(Q){return{type:"string",description:Q}}function b0(Q){return{type:"number",description:Q}}function d0(Q){return{type:"boolean",description:Q}}function V(Q){return W0(`The ${Q} record returned by Sequenzy.`)}function p(Q){return XZ(`List of ${Q} records returned by Sequenzy.`)}var WZ={appUrls:W0("Dashboard URLs for relevant Sequenzy resources."),url:E("Primary dashboard URL for this result."),settingsUrl:E("Company settings URL when available.")},GZ={success:eV,message:QZ,note:YZ,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:W0("One returned item.")},value:W0("Fallback object wrapper used only when a tool returns a non-object value.")},$Z={get_account:{account:V("account"),companies:p("company"),apiKeyPermissions:W0("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:E("Company ID selected by the authenticated API key, when available."),selectedCompanyId:E("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:E("Selected company ID."),companyName:E("Selected company name.")},get_app_urls:{dashboard:E("Company dashboard URL."),settings:E("Company settings URL."),campaign:E("Campaign editor URL."),landingPage:E("Landing page editor URL."),sequence:E("Sequence editor URL."),email:E("Email editor URL."),transactionalEmail:E("Transactional email URL."),emailSend:E("Sent email detail URL."),domain:E("Sending domain settings URL."),urls:W0("All generated URLs keyed by resource type.")},create_company:{company:V("company"),autoSelected:d0("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:V("company")},get_company:{company:V("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:W0("One sync rule.")},isDefault:d0("Whether the company still uses the platform default rules.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:W0("One sync rule.")},isDefault:d0("Whether the company now uses the platform default rules.")},get_shopify_automation_settings:{browseAbandonment:W0("Effective browse-abandonment settings (defaults applied)."),priceDrop:W0("Effective price-drop settings (defaults applied)."),shopDomain:E("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:W0("Effective browse-abandonment settings after the update."),priceDrop:W0("Effective price-drop settings after the update."),shopDomain:E("Connected Shopify store domain.")},create_api_key:{apiKey:W0("Created API key metadata: the newly created secret in `key`, plus `scopes` listing the assigned permission scopes (null when the key has full access)."),key:E("Newly created API key if the API response uses the short key field.")},list_websites:{websites:p("sender website")},add_website:{website:V("sender website")},check_website:{website:V("sender website"),ready:d0("Whether the sender website is ready."),status:E("Current processing or verification status.")},verify_sending_domain:{website:V("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:d0("Whether the sending domain passed the fresh verification check."),message:E("Verification result summary.")},get_integration_guide:{guide:V("integration guide"),code:E("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:W0("One setup step.")}},add_subscriber:{subscriber:V("subscriber")},update_subscriber:{subscriber:V("subscriber")},remove_subscriber:{subscriber:V("subscriber"),hardDeleted:d0("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:V("subscriber")},list_subscriber_notes:{notes:p("subscriber note")},add_subscriber_note:{note:V("subscriber note")},delete_subscriber_note:{id:E("Deleted subscriber note ID."),deleted:d0("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:p("subscriber"),pagination:W0("Pagination metadata."),returned:b0("Number of subscribers returned."),truncated:d0("Whether the result was truncated by the requested limit.")},list_products:{products:p("product")},upsert_products:{products:p("product"),created:b0("Number of products created."),updated:b0("Number of products updated.")},delete_product:{productId:E("Deleted product ID.")},attach_product_file:{product:V("product"),delivery:V("digital delivery file")},remove_product_file:{product:V("product")},sync_products:{job:V("product sync job"),jobId:E("Queued product sync job ID.")},list_tags:{tags:p("tag")},create_tag:{tag:V("tag")},update_tag:{tag:V("tag")},delete_tag:{tagId:E("Deleted tag ID.")},list_lists:{lists:p("list")},create_list:{list:V("list")},update_list:{list:V("list")},delete_list:{listId:E("Deleted list ID.")},add_subscribers_to_list:{list:V("list"),added:b0("Number of subscribers added to the list."),skipped:b0("Number of subscribers skipped.")},remove_subscribers_from_list:{list:V("list"),removed:b0("Number of subscribers removed from the list."),skipped:b0("Number of subscribers skipped.")},list_segments:{segments:p("segment")},create_segment:{segment:V("segment")},update_segment:{segment:V("segment")},delete_segment:{segmentId:E("Deleted segment ID.")},get_segment_count:{count:b0("Number of subscribers matching the segment."),segmentId:E("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:p("audience sync")},list_ad_accounts:{adAccounts:p("ad account")},create_audience_sync:{audienceSync:V("audience sync")},update_audience_sync:{audienceSync:V("audience sync")},delete_audience_sync:{audienceSyncId:E("Deleted audience sync ID.")},sync_audience_now:{audienceSync:V("audience sync"),job:V("audience sync job"),jobId:E("Queued audience sync job ID.")},list_templates:{templates:p("email template")},get_template:{template:V("email template")},create_template:{template:V("email template")},update_template:{template:V("email template")},delete_template:{templateId:E("Deleted template ID.")},list_ab_tests:{abTests:p("A/B test")},get_ab_test:{abTest:V("A/B test")},get_ab_test_stats:{abTest:V("A/B test"),stats:V("A/B test statistics")},restart_ab_test:{abTest:V("A/B test")},update_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},create_ab_test:{abTest:V("A/B test")},add_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},delete_ab_test_variant:{abTest:V("A/B test"),variantId:E("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:E("Deleted A/B test ID.")},list_campaigns:{campaigns:p("campaign")},get_campaign:{campaign:V("campaign")},get_email_send:{emailSend:V("email send")},create_campaign:{campaign:V("campaign")},update_campaign:{campaign:V("campaign")},schedule_campaign:{campaign:V("campaign"),scheduledAt:E("Scheduled send timestamp.")},send_test_email:{emailSend:V("test email send"),recipient:E("Test email recipient.")},send_test_sms:{smsSendId:E("Created test SMS send ID."),toPhone:E("Normalized E.164 destination phone.")},cancel_campaign:{campaign:V("campaign")},pause_campaign:{campaign:V("campaign")},resume_campaign:{campaign:V("campaign")},delete_campaign:{campaignId:E("Deleted campaign ID.")},duplicate_campaign:{campaign:V("duplicated campaign")},resend_campaign_to_non_openers:{campaign:V("non-opener resend draft campaign"),estimatedNonOpenerCount:b0("Estimated number of subscribers who haven't opened the original campaign.")},list_landing_pages:{landingPages:p("landing page")},get_landing_page:{landingPage:V("landing page")},create_landing_page:{landingPage:V("landing page")},update_landing_page:{landingPage:V("landing page")},delete_landing_page:{landingPageId:E("Deleted landing page ID.")},publish_landing_page:{landingPage:V("landing page")},unpublish_landing_page:{landingPage:V("landing page")},connect_landing_page_domain:{landingPage:V("landing page"),domain:E("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:V("landing page"),domain:E("Landing page domain.")},list_sequences:{sequences:p("sequence")},get_sequence:{sequence:V("sequence")},create_sequence:{sequence:V("sequence")},update_sequence:{sequence:V("sequence")},insert_sequence_step:{sequence:V("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for the inserted step, including any delay node.",items:E("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:E("Inserted email template ID.")},insertedEmailCount:b0("Number of email steps inserted.")},enable_sequence:{sequence:V("sequence")},disable_sequence:{sequence:V("sequence")},pause_sequence_enrollments:{sequenceId:E("Sequence ID."),enrollmentPaused:d0("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:E("Sequence ID."),enrollmentPaused:d0("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:V("sequence"),enrollments:p("sequence enrollment"),enrolled:b0("Number of subscribers enrolled."),skipped:b0("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:V("sequence"),cancelled:b0("Number of enrollments cancelled."),skipped:b0("Number of enrollments skipped.")},delete_sequence:{sequenceId:E("Deleted sequence ID.")},list_transactional_emails:{transactional:p("transactional email")},get_transactional_email:{transactional:V("transactional email")},create_transactional_email:{transactional:V("transactional email")},update_transactional_email:{transactional:V("transactional email")},send_email:{emailSend:V("transactional email send"),transactional:V("transactional email")},get_stats:{stats:V("account or company statistics")},get_campaign_stats:{campaign:V("campaign"),stats:V("campaign statistics")},get_sequence_stats:{sequence:V("sequence"),stats:V("sequence statistics")},list_campaign_events:{events:p("campaign email event"),pagination:W0("Pagination metadata.")},list_sequence_events:{events:p("sequence email event"),pagination:W0("Pagination metadata.")},get_subscriber_activity:{activity:p("subscriber activity event"),subscribers:p("subscriber"),pagination:W0("Pagination metadata.")},list_team_members:{members:p("team member"),invitations:p("team invitation")},invite_team_member:{invitation:V("team invitation")},cancel_team_invitation:{invitationId:E("Cancelled invitation ID.")},list_conversations:{conversations:p("inbox conversation"),pagination:W0("Pagination metadata.")},get_conversation:{conversation:V("inbox conversation"),messages:p("conversation message")},reply_to_conversation:{conversation:V("inbox conversation"),message:V("conversation message")},update_conversation_status:{conversation:V("inbox conversation")},mark_conversation_read:{conversation:V("inbox conversation")},list_webhooks:{webhooks:p("outbound webhook")},create_webhook:{webhook:V("outbound webhook")},update_webhook:{webhook:V("outbound webhook")},delete_webhook:{webhookId:E("Deleted outbound webhook ID.")},test_webhook:{webhook:V("outbound webhook"),delivery:V("test webhook delivery")},list_webhook_deliveries:{deliveries:p("webhook delivery")},replay_webhook_delivery:{delivery:V("webhook delivery"),job:V("webhook replay job")},generate_email:{email:V("generated email"),html:E("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:W0("One generated email block.")},subject:E("Generated subject line."),previewText:E("Generated inbox preview text.")},generate_sequence:{sequence:V("generated sequence"),steps:p("generated sequence step")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:E("One generated subject line.")},variants:p("generated subject line variant")},generate_sms:{prompt:E("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:W0("One generated SMS message.")}},get_sms_settings:{sms:W0("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{}};function zZ(Q){let Y=$Z[Q];if(Y===void 0)throw Error(`MCP tool "${Q}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${Q}\` MCP tool.`,properties:{...GZ,...Y,...AH.has(Q)?WZ:{}},additionalProperties:!0}}function JZ(Q){return{...Q,outputSchema:zZ(Q.name)}}function HZ(Q){if(J0(Q))return Q;if(Array.isArray(Q))return{items:Q};return{value:Q}}var AZ=[{name:"get_account",description:`Get current account information including available companies, the current API key's permission scopes, and the API Keys management URL. Call this after a missing-scope error to inspect access and find the replacement-key settings. IMPORTANT: If you have access to multiple companies, you MUST either:
|
|
29
|
+
`)}L.write("payload.value = newResult;"),L.write("return payload;");let k=L.compile();return(S,y)=>k(D,S,y)},$,z=j1,J=!Y6.jitless,A=J&&vQ.value,U=Y.catchall,K;Q._zod.parse=(D,L)=>{K??(K=W.value);let O=D.value;if(!z(O))return D.issues.push({expected:"object",code:"invalid_type",input:O,inst:Q}),D;if(J&&A&&L?.async===!1&&L.jitless!==!0){if(!$)$=G(Y.shape);if(D=$(D,L),!U)return D;return FW([],O,D,L,K,Q)}return X(D,L)}});function C8(Q,Y,X,W){for(let $ of Q)if($.issues.length===0)return Y.value=$.value,Y;let G=Q.filter(($)=>!A1($));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map(($)=>$.issues.map((z)=>x0(z,W,T0())))}),Y}var iQ=q("$ZodUnion",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),n(Q._zod,"optout",()=>Y.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),n(Q._zod,"values",()=>{if(Y.options.every((G)=>G._zod.values))return new Set(Y.options.flatMap((G)=>Array.from(G._zod.values)));return}),n(Q._zod,"pattern",()=>{if(Y.options.every((G)=>G._zod.pattern)){let G=Y.options.map(($)=>$._zod.pattern);return new RegExp(`^(${G.map(($)=>J4($.source)).join("|")})$`)}return});let X=Y.options.length===1,W=Y.options[0]._zod.run;Q._zod.parse=(G,$)=>{if(X)return W(G,$);let z=!1,J=[];for(let H of Y.options){let A=H._zod.run({value:G.value,issues:[]},$);if(A instanceof Promise)J.push(A),z=!0;else{if(A.issues.length===0)return A;J.push(A)}}if(!z)return C8(J,G,Q,$);return Promise.all(J).then((H)=>{return C8(H,G,Q,$)})}}),OW=q("$ZodDiscriminatedUnion",(Q,Y)=>{iQ.init(Q,Y);let X=Q._zod.parse;n(Q._zod,"propValues",()=>{let G={};for(let $ of Y.options){let z=$._zod.propValues;if(!z||Object.keys(z).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf($)}"`);for(let[J,H]of Object.entries(z)){if(!G[J])G[J]=new Set;for(let A of H)G[J].add(A)}}return G});let W=g1(()=>{let G=Y.options,$=new Map;for(let z of G){let J=z._zod.propValues?.[Y.discriminator];if(!J||J.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(z)}"`);for(let H of J){if($.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);$.set(H,z)}}return $});Q._zod.parse=(G,$)=>{let z=G.value;if(!j1(z))return G.issues.push({code:"invalid_type",expected:"object",input:z,inst:Q}),G;let J=W.value.get(z?.[Y.discriminator]);if(J)return J._zod.run(G,$);if(Y.unionFallback)return X(G,$);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,input:z,path:[Y.discriminator],inst:Q}),G}}),MW=q("$ZodIntersection",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value,$=Y.left._zod.run({value:G,issues:[]},W),z=Y.right._zod.run({value:G,issues:[]},W);if($ instanceof Promise||z instanceof Promise)return Promise.all([$,z]).then(([H,A])=>{return k8(X,H,A)});return k8(X,$,z)}});function cQ(Q,Y){if(Q===Y)return{valid:!0,data:Q};if(Q instanceof Date&&Y instanceof Date&&+Q===+Y)return{valid:!0,data:Q};if(H1(Q)&&H1(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter(($)=>X.indexOf($)!==-1),G={...Q,...Y};for(let $ of W){let z=cQ(Q[$],Y[$]);if(!z.valid)return{valid:!1,mergeErrorPath:[$,...z.mergeErrorPath]};G[$]=z.data}return{valid:!0,data:G}}if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let W=0;W<Q.length;W++){let G=Q[W],$=Y[W],z=cQ(G,$);if(!z.valid)return{valid:!1,mergeErrorPath:[W,...z.mergeErrorPath]};X.push(z.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function k8(Q,Y,X){if(Y.issues.length)Q.issues.push(...Y.issues);if(X.issues.length)Q.issues.push(...X.issues);if(A1(Q))return Q;let W=cQ(Y.value,X.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return Q.value=W.data,Q}var VW=q("$ZodRecord",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!H1(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let $=[];if(Y.keyType._zod.values){let z=Y.keyType._zod.values;X.value={};for(let H of z)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let A=Y.valueType._zod.run({value:G[H],issues:[]},W);if(A instanceof Promise)$.push(A.then((U)=>{if(U.issues.length)X.issues.push(...s0(H,U.issues));X.value[H]=U.value}));else{if(A.issues.length)X.issues.push(...s0(H,A.issues));X.value[H]=A.value}}let J;for(let H in G)if(!z.has(H))J=J??[],J.push(H);if(J&&J.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:J})}else{X.value={};for(let z of Reflect.ownKeys(G)){if(z==="__proto__")continue;let J=Y.keyType._zod.run({value:z,issues:[]},W);if(J instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(J.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:J.issues.map((A)=>x0(A,W,T0())),input:z,path:[z],inst:Q}),X.value[J.value]=J.value;continue}let H=Y.valueType._zod.run({value:G[z],issues:[]},W);if(H instanceof Promise)$.push(H.then((A)=>{if(A.issues.length)X.issues.push(...s0(z,A.issues));X.value[J.value]=A.value}));else{if(H.issues.length)X.issues.push(...s0(z,H.issues));X.value[J.value]=H.value}}}if($.length)return Promise.all($).then(()=>X);return X}});var ZW=q("$ZodEnum",(Q,Y)=>{o.init(Q,Y);let X=CQ(Y.entries),W=new Set(X);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${X.filter((G)=>xQ.has(typeof G)).map((G)=>typeof G==="string"?a0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,$)=>{let z=G.value;if(W.has(z))return G;return G.issues.push({code:"invalid_value",values:X,input:z,inst:Q}),G}}),NW=q("$ZodLiteral",(Q,Y)=>{if(o.init(Q,Y),Y.values.length===0)throw Error("Cannot create literal schema with no valid values");Q._zod.values=new Set(Y.values),Q._zod.pattern=new RegExp(`^(${Y.values.map((X)=>typeof X==="string"?a0(X):X?a0(X.toString()):String(X)).join("|")})$`),Q._zod.parse=(X,W)=>{let G=X.value;if(Q._zod.values.has(G))return X;return X.issues.push({code:"invalid_value",values:Y.values,input:G,inst:Q}),X}});var wW=q("$ZodTransform",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new G4(Q.constructor.name);let G=Y.transform(X.value,X);if(W.async)return(G instanceof Promise?G:Promise.resolve(G)).then((z)=>{return X.value=z,X});if(G instanceof Promise)throw new t0;return X.value=G,X}});function v8(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var PW=q("$ZodOptional",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",n(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),n(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${J4(X.source)})?$`):void 0}),Q._zod.parse=(X,W)=>{if(Y.innerType._zod.optin==="optional"){let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>v8($,X.value));return v8(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),bW=q("$ZodNullable",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),n(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${J4(X.source)}|null)$`):void 0}),n(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,null]):void 0}),Q._zod.parse=(X,W)=>{if(X.value===null)return X;return Y.innerType._zod.run(X,W)}}),jW=q("$ZodDefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)return X.value=Y.defaultValue,X;let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>x8($,Y));return x8(G,Y)}});function x8(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var IW=q("$ZodPrefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)X.value=Y.defaultValue;return Y.innerType._zod.run(X,W)}}),EW=q("$ZodNonOptional",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"values",()=>{let X=Y.innerType._zod.values;return X?new Set([...X].filter((W)=>W!==void 0)):void 0}),Q._zod.parse=(X,W)=>{let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>_8($,Q));return _8(G,Q)}});function _8(Q,Y){if(!Q.issues.length&&Q.value===void 0)Q.issues.push({code:"invalid_type",expected:"nonoptional",input:Q.value,inst:Y});return Q}var TW=q("$ZodCatch",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>{if(X.value=$.value,$.issues.length)X.value=Y.catchValue({...X,error:{issues:$.issues.map((z)=>x0(z,W,T0()))},input:X.value}),X.issues=[];return X});if(X.value=G.value,G.issues.length)X.value=Y.catchValue({...X,error:{issues:G.issues.map(($)=>x0($,W,T0()))},input:X.value}),X.issues=[];return X}});var SW=q("$ZodPipe",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"values",()=>Y.in._zod.values),n(Q._zod,"optin",()=>Y.in._zod.optin),n(Q._zod,"optout",()=>Y.out._zod.optout),n(Q._zod,"propValues",()=>Y.in._zod.propValues),Q._zod.parse=(X,W)=>{if(W.direction==="backward"){let $=Y.out._zod.run(X,W);if($ instanceof Promise)return $.then((z)=>K6(z,Y.in,W));return K6($,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>K6($,Y.out,W));return K6(G,Y.out,W)}});function K6(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var RW=q("$ZodReadonly",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"propValues",()=>Y.innerType._zod.propValues),n(Q._zod,"values",()=>Y.innerType._zod.values),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(g8);return g8(G)}});function g8(Q){return Q.value=Object.freeze(Q.value),Q}var CW=q("$ZodCustom",(Q,Y)=>{A0.init(Q,Y),o.init(Q,Y),Q._zod.parse=(X,W)=>{return X},Q._zod.check=(X)=>{let W=X.value,G=Y.fn(W);if(G instanceof Promise)return G.then(($)=>y8($,X,W,Q));y8(G,X,W,Q);return}});function y8(Q,Y,X,W){if(!Q){let G={code:"custom",input:X,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)G.params=W._zod.def.params;Y.issues.push(y1(G))}}var UA=(Q)=>{let Y=typeof Q;switch(Y){case"number":return Number.isNaN(Q)?"NaN":"number";case"object":{if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Object.getPrototypeOf(Q)!==Object.prototype&&Q.constructor)return Q.constructor.name}}return Y},KA=()=>{let Q={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function Y(W){return Q[W]??null}let X={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${UA(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${$6(W.values[0])}`;return`Invalid option: expected one of ${X6(W.values,"|")}`;case"too_big":{let G=W.inclusive?"<=":"<",$=Y(W.origin);if($)return`Too big: expected ${W.origin??"value"} to have ${G}${W.maximum.toString()} ${$.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${G}${W.maximum.toString()}`}case"too_small":{let G=W.inclusive?">=":">",$=Y(W.origin);if($)return`Too small: expected ${W.origin} to have ${G}${W.minimum.toString()} ${$.unit}`;return`Too small: expected ${W.origin} to be ${G}${W.minimum.toString()}`}case"invalid_format":{let G=W;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${X[G.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${X6(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};function nQ(){return{localeError:KA()}}var kZ=Symbol("ZodOutput"),vZ=Symbol("ZodInput");class kW{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Q,...Y){let X=Y[0];if(this._map.set(Q,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.id,Q)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Q){let Y=this._map.get(Q);if(Y&&typeof Y==="object"&&"id"in Y)this._idmap.delete(Y.id);return this._map.delete(Q),this}get(Q){let Y=Q._zod.parent;if(Y){let X={...this.get(Y)??{}};delete X.id;let W={...X,...this._map.get(Q)};return Object.keys(W).length?W:void 0}return this._map.get(Q)}has(Q){return this._map.has(Q)}}function DA(){return new kW}var B4=DA();function vW(Q,Y){return new Q({type:"string",...T(Y)})}function xW(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...T(Y)})}function rQ(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...T(Y)})}function _W(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...T(Y)})}function gW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...T(Y)})}function yW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...T(Y)})}function uW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...T(Y)})}function hW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...T(Y)})}function fW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...T(Y)})}function lW(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...T(Y)})}function mW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...T(Y)})}function cW(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...T(Y)})}function pW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...T(Y)})}function iW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...T(Y)})}function nW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...T(Y)})}function rW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...T(Y)})}function dW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...T(Y)})}function oW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...T(Y)})}function tW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...T(Y)})}function aW(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...T(Y)})}function sW(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...T(Y)})}function eW(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...T(Y)})}function QG(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...T(Y)})}function YG(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...T(Y)})}function XG(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...T(Y)})}function WG(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...T(Y)})}function GG(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...T(Y)})}function $G(Q,Y){return new Q({type:"number",checks:[],...T(Y)})}function zG(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...T(Y)})}function JG(Q,Y){return new Q({type:"boolean",...T(Y)})}function HG(Q,Y){return new Q({type:"null",...T(Y)})}function AG(Q){return new Q({type:"unknown"})}function UG(Q,Y){return new Q({type:"never",...T(Y)})}function L6(Q,Y){return new fQ({check:"less_than",...T(Y),value:Q,inclusive:!1})}function L4(Q,Y){return new fQ({check:"less_than",...T(Y),value:Q,inclusive:!0})}function F6(Q,Y){return new lQ({check:"greater_than",...T(Y),value:Q,inclusive:!1})}function F4(Q,Y){return new lQ({check:"greater_than",...T(Y),value:Q,inclusive:!0})}function q6(Q,Y){return new q8({check:"multiple_of",...T(Y),value:Q})}function O6(Q,Y){return new M8({check:"max_length",...T(Y),maximum:Q})}function u1(Q,Y){return new V8({check:"min_length",...T(Y),minimum:Q})}function M6(Q,Y){return new Z8({check:"length_equals",...T(Y),length:Q})}function dQ(Q,Y){return new N8({check:"string_format",format:"regex",...T(Y),pattern:Q})}function oQ(Q){return new w8({check:"string_format",format:"lowercase",...T(Q)})}function tQ(Q){return new P8({check:"string_format",format:"uppercase",...T(Q)})}function aQ(Q,Y){return new b8({check:"string_format",format:"includes",...T(Y),includes:Q})}function sQ(Q,Y){return new j8({check:"string_format",format:"starts_with",...T(Y),prefix:Q})}function eQ(Q,Y){return new I8({check:"string_format",format:"ends_with",...T(Y),suffix:Q})}function I1(Q){return new E8({check:"overwrite",tx:Q})}function Q9(Q){return I1((Y)=>Y.normalize(Q))}function Y9(){return I1((Q)=>Q.trim())}function X9(){return I1((Q)=>Q.toLowerCase())}function W9(){return I1((Q)=>Q.toUpperCase())}function KG(Q,Y,X){return new Q({type:"array",element:Y,...T(X)})}function DG(Q,Y,X){let W=T(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function BG(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...T(X)})}function LG(Q){let Y=BA((X)=>{return X.addIssue=(W)=>{if(typeof W==="string")X.issues.push(y1(W,X.value,Y._zod.def));else{let G=W;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=X.value),G.inst??(G.inst=Y),G.continue??(G.continue=!Y._zod.def.abort),X.issues.push(y1(G))}},Q(X.value,X)});return Y}function BA(Q,Y){let X=new A0({check:"custom",...T(Y)});return X._zod.check=Q,X}function h1(Q){return!!Q._zod}function U1(Q,Y){if(h1(Q))return U4(Q,Y);return Q.safeParse(Y)}function V6(Q){if(!Q)return;let Y;if(h1(Q))Y=Q._zod?.def?.shape;else Y=Q.shape;if(!Y)return;if(typeof Y==="function")try{return Y()}catch{return}return Y}function FG(Q){if(h1(Q)){let $=Q._zod?.def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}}let X=Q._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let W=Q.value;if(W!==void 0)return W;return}var O4={};LX(O4,{time:()=>z9,duration:()=>J9,datetime:()=>G9,date:()=>$9,ZodISOTime:()=>MG,ZodISODuration:()=>VG,ZodISODateTime:()=>qG,ZodISODate:()=>OG});var qG=q("ZodISODateTime",(Q,Y)=>{o8.init(Q,Y),s.init(Q,Y)});function G9(Q){return YG(qG,Q)}var OG=q("ZodISODate",(Q,Y)=>{t8.init(Q,Y),s.init(Q,Y)});function $9(Q){return XG(OG,Q)}var MG=q("ZodISOTime",(Q,Y)=>{a8.init(Q,Y),s.init(Q,Y)});function z9(Q){return WG(MG,Q)}var VG=q("ZodISODuration",(Q,Y)=>{s8.init(Q,Y),s.init(Q,Y)});function J9(Q){return GG(VG,Q)}var ZG=(Q,Y)=>{z6.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>CX(Q,X)},flatten:{value:(X)=>RX(Q,X)},addIssue:{value:(X)=>{Q.issues.push(X),Q.message=JSON.stringify(Q.issues,_1,2)}},addIssues:{value:(X)=>{Q.issues.push(...X),Q.message=JSON.stringify(Q.issues,_1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},MN=q("ZodError",ZG),I0=q("ZodError",ZG,{Parent:Error});var NG=J6(I0),wG=H6(I0),PG=A4(I0),bG=K4(I0),jG=kX(I0),IG=vX(I0),EG=xX(I0),TG=_X(I0),SG=gX(I0),RG=yX(I0),CG=uX(I0),kG=hX(I0);var X0=q("ZodType",(Q,Y)=>{return o.init(Q,Y),Q.def=Y,Q.type=Y.type,Object.defineProperty(Q,"_def",{value:Y}),Q.check=(...X)=>{return Q.clone(m.mergeDefs(Y,{checks:[...Y.checks??[],...X.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},Q.clone=(X,W)=>v0(Q,X,W),Q.brand=()=>Q,Q.register=(X,W)=>{return X.add(Q,W),Q},Q.parse=(X,W)=>NG(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>PG(Q,X,W),Q.parseAsync=async(X,W)=>wG(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>bG(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>jG(Q,X,W),Q.decode=(X,W)=>IG(Q,X,W),Q.encodeAsync=async(X,W)=>EG(Q,X,W),Q.decodeAsync=async(X,W)=>TG(Q,X,W),Q.safeEncode=(X,W)=>SG(Q,X,W),Q.safeDecode=(X,W)=>RG(Q,X,W),Q.safeEncodeAsync=async(X,W)=>CG(Q,X,W),Q.safeDecodeAsync=async(X,W)=>kG(Q,X,W),Q.refine=(X,W)=>Q.check(A3(X,W)),Q.superRefine=(X)=>Q.check(U3(X)),Q.overwrite=(X)=>Q.check(I1(X)),Q.optional=()=>Y0(Q),Q.nullable=()=>_G(Q),Q.nullish=()=>Y0(_G(Q)),Q.nonoptional=(X)=>W3(Q,X),Q.array=()=>u(Q),Q.or=(X)=>d([Q,X]),Q.and=(X)=>N6(Q,X),Q.transform=(X)=>A9(Q,fG(X)),Q.default=(X)=>Q3(Q,X),Q.prefault=(X)=>X3(Q,X),Q.catch=(X)=>$3(Q,X),Q.pipe=(X)=>A9(Q,X),Q.readonly=()=>H3(Q),Q.describe=(X)=>{let W=Q.clone();return B4.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return B4.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return B4.get(Q);let W=Q.clone();return B4.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),gG=q("_ZodString",(Q,Y)=>{B6.init(Q,Y),X0.init(Q,Y);let X=Q._zod.bag;Q.format=X.format??null,Q.minLength=X.minimum??null,Q.maxLength=X.maximum??null,Q.regex=(...W)=>Q.check(dQ(...W)),Q.includes=(...W)=>Q.check(aQ(...W)),Q.startsWith=(...W)=>Q.check(sQ(...W)),Q.endsWith=(...W)=>Q.check(eQ(...W)),Q.min=(...W)=>Q.check(u1(...W)),Q.max=(...W)=>Q.check(O6(...W)),Q.length=(...W)=>Q.check(M6(...W)),Q.nonempty=(...W)=>Q.check(u1(1,...W)),Q.lowercase=(W)=>Q.check(oQ(W)),Q.uppercase=(W)=>Q.check(tQ(W)),Q.trim=()=>Q.check(Y9()),Q.normalize=(...W)=>Q.check(Q9(...W)),Q.toLowerCase=()=>Q.check(X9()),Q.toUpperCase=()=>Q.check(W9())}),wA=q("ZodString",(Q,Y)=>{B6.init(Q,Y),gG.init(Q,Y),Q.email=(X)=>Q.check(xW(PA,X)),Q.url=(X)=>Q.check(hW(bA,X)),Q.jwt=(X)=>Q.check(QG(hA,X)),Q.emoji=(X)=>Q.check(fW(jA,X)),Q.guid=(X)=>Q.check(rQ(vG,X)),Q.uuid=(X)=>Q.check(_W(Z6,X)),Q.uuidv4=(X)=>Q.check(gW(Z6,X)),Q.uuidv6=(X)=>Q.check(yW(Z6,X)),Q.uuidv7=(X)=>Q.check(uW(Z6,X)),Q.nanoid=(X)=>Q.check(lW(IA,X)),Q.guid=(X)=>Q.check(rQ(vG,X)),Q.cuid=(X)=>Q.check(mW(EA,X)),Q.cuid2=(X)=>Q.check(cW(TA,X)),Q.ulid=(X)=>Q.check(pW(SA,X)),Q.base64=(X)=>Q.check(aW(gA,X)),Q.base64url=(X)=>Q.check(sW(yA,X)),Q.xid=(X)=>Q.check(iW(RA,X)),Q.ksuid=(X)=>Q.check(nW(CA,X)),Q.ipv4=(X)=>Q.check(rW(kA,X)),Q.ipv6=(X)=>Q.check(dW(vA,X)),Q.cidrv4=(X)=>Q.check(oW(xA,X)),Q.cidrv6=(X)=>Q.check(tW(_A,X)),Q.e164=(X)=>Q.check(eW(uA,X)),Q.datetime=(X)=>Q.check(G9(X)),Q.date=(X)=>Q.check($9(X)),Q.time=(X)=>Q.check(z9(X)),Q.duration=(X)=>Q.check(J9(X))});function F(Q){return vW(wA,Q)}var s=q("ZodStringFormat",(Q,Y)=>{t.init(Q,Y),gG.init(Q,Y)}),PA=q("ZodEmail",(Q,Y)=>{f8.init(Q,Y),s.init(Q,Y)});var vG=q("ZodGUID",(Q,Y)=>{u8.init(Q,Y),s.init(Q,Y)});var Z6=q("ZodUUID",(Q,Y)=>{h8.init(Q,Y),s.init(Q,Y)});var bA=q("ZodURL",(Q,Y)=>{l8.init(Q,Y),s.init(Q,Y)});var jA=q("ZodEmoji",(Q,Y)=>{m8.init(Q,Y),s.init(Q,Y)});var IA=q("ZodNanoID",(Q,Y)=>{c8.init(Q,Y),s.init(Q,Y)});var EA=q("ZodCUID",(Q,Y)=>{p8.init(Q,Y),s.init(Q,Y)});var TA=q("ZodCUID2",(Q,Y)=>{i8.init(Q,Y),s.init(Q,Y)});var SA=q("ZodULID",(Q,Y)=>{n8.init(Q,Y),s.init(Q,Y)});var RA=q("ZodXID",(Q,Y)=>{r8.init(Q,Y),s.init(Q,Y)});var CA=q("ZodKSUID",(Q,Y)=>{d8.init(Q,Y),s.init(Q,Y)});var kA=q("ZodIPv4",(Q,Y)=>{e8.init(Q,Y),s.init(Q,Y)});var vA=q("ZodIPv6",(Q,Y)=>{QW.init(Q,Y),s.init(Q,Y)});var xA=q("ZodCIDRv4",(Q,Y)=>{YW.init(Q,Y),s.init(Q,Y)});var _A=q("ZodCIDRv6",(Q,Y)=>{XW.init(Q,Y),s.init(Q,Y)});var gA=q("ZodBase64",(Q,Y)=>{GW.init(Q,Y),s.init(Q,Y)});var yA=q("ZodBase64URL",(Q,Y)=>{$W.init(Q,Y),s.init(Q,Y)});var uA=q("ZodE164",(Q,Y)=>{zW.init(Q,Y),s.init(Q,Y)});var hA=q("ZodJWT",(Q,Y)=>{JW.init(Q,Y),s.init(Q,Y)});var yG=q("ZodNumber",(Q,Y)=>{pQ.init(Q,Y),X0.init(Q,Y),Q.gt=(W,G)=>Q.check(F6(W,G)),Q.gte=(W,G)=>Q.check(F4(W,G)),Q.min=(W,G)=>Q.check(F4(W,G)),Q.lt=(W,G)=>Q.check(L6(W,G)),Q.lte=(W,G)=>Q.check(L4(W,G)),Q.max=(W,G)=>Q.check(L4(W,G)),Q.int=(W)=>Q.check(xG(W)),Q.safe=(W)=>Q.check(xG(W)),Q.positive=(W)=>Q.check(F6(0,W)),Q.nonnegative=(W)=>Q.check(F4(0,W)),Q.negative=(W)=>Q.check(L6(0,W)),Q.nonpositive=(W)=>Q.check(L4(0,W)),Q.multipleOf=(W,G)=>Q.check(q6(W,G)),Q.step=(W,G)=>Q.check(q6(W,G)),Q.finite=()=>Q;let X=Q._zod.bag;Q.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Q.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Q.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Q.isFinite=!0,Q.format=X.format??null});function i(Q){return $G(yG,Q)}var fA=q("ZodNumberFormat",(Q,Y)=>{HW.init(Q,Y),yG.init(Q,Y)});function xG(Q){return zG(fA,Q)}var lA=q("ZodBoolean",(Q,Y)=>{AW.init(Q,Y),X0.init(Q,Y)});function H0(Q){return JG(lA,Q)}var mA=q("ZodNull",(Q,Y)=>{UW.init(Q,Y),X0.init(Q,Y)});function U9(Q){return HG(mA,Q)}var cA=q("ZodUnknown",(Q,Y)=>{KW.init(Q,Y),X0.init(Q,Y)});function e(){return AG(cA)}var pA=q("ZodNever",(Q,Y)=>{DW.init(Q,Y),X0.init(Q,Y)});function iA(Q){return UG(pA,Q)}var nA=q("ZodArray",(Q,Y)=>{BW.init(Q,Y),X0.init(Q,Y),Q.element=Y.element,Q.min=(X,W)=>Q.check(u1(X,W)),Q.nonempty=(X)=>Q.check(u1(1,X)),Q.max=(X,W)=>Q.check(O6(X,W)),Q.length=(X,W)=>Q.check(M6(X,W)),Q.unwrap=()=>Q.element});function u(Q,Y){return KG(nA,Q,Y)}var uG=q("ZodObject",(Q,Y)=>{qW.init(Q,Y),X0.init(Q,Y),m.defineLazy(Q,"shape",()=>{return Y.shape}),Q.keyof=()=>V0(Object.keys(Q._zod.def.shape)),Q.catchall=(X)=>Q.clone({...Q._zod.def,catchall:X}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:iA()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(X)=>{return m.extend(Q,X)},Q.safeExtend=(X)=>{return m.safeExtend(Q,X)},Q.merge=(X)=>m.merge(Q,X),Q.pick=(X)=>m.pick(Q,X),Q.omit=(X)=>m.omit(Q,X),Q.partial=(...X)=>m.partial(lG,Q,X[0]),Q.required=(...X)=>m.required(mG,Q,X[0])});function b(Q,Y){let X={type:"object",shape:Q??{},...m.normalizeParams(Y)};return new uG(X)}function q0(Q,Y){return new uG({type:"object",shape:Q,catchall:e(),...m.normalizeParams(Y)})}var hG=q("ZodUnion",(Q,Y)=>{iQ.init(Q,Y),X0.init(Q,Y),Q.options=Y.options});function d(Q,Y){return new hG({type:"union",options:Q,...m.normalizeParams(Y)})}var rA=q("ZodDiscriminatedUnion",(Q,Y)=>{hG.init(Q,Y),OW.init(Q,Y)});function K9(Q,Y,X){return new rA({type:"union",options:Y,discriminator:Q,...m.normalizeParams(X)})}var dA=q("ZodIntersection",(Q,Y)=>{MW.init(Q,Y),X0.init(Q,Y)});function N6(Q,Y){return new dA({type:"intersection",left:Q,right:Y})}var oA=q("ZodRecord",(Q,Y)=>{VW.init(Q,Y),X0.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function Q0(Q,Y,X){return new oA({type:"record",keyType:Q,valueType:Y,...m.normalizeParams(X)})}var H9=q("ZodEnum",(Q,Y)=>{ZW.init(Q,Y),X0.init(Q,Y),Q.enum=Y.entries,Q.options=Object.values(Y.entries);let X=new Set(Object.keys(Y.entries));Q.extract=(W,G)=>{let $={};for(let z of W)if(X.has(z))$[z]=Y.entries[z];else throw Error(`Key ${z} not found in enum`);return new H9({...Y,checks:[],...m.normalizeParams(G),entries:$})},Q.exclude=(W,G)=>{let $={...Y.entries};for(let z of W)if(X.has(z))delete $[z];else throw Error(`Key ${z} not found in enum`);return new H9({...Y,checks:[],...m.normalizeParams(G),entries:$})}});function V0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new H9({type:"enum",entries:X,...m.normalizeParams(Y)})}var tA=q("ZodLiteral",(Q,Y)=>{NW.init(Q,Y),X0.init(Q,Y),Q.values=new Set(Y.values),Object.defineProperty(Q,"value",{get(){if(Y.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return Y.values[0]}})});function j(Q,Y){return new tA({type:"literal",values:Array.isArray(Q)?Q:[Q],...m.normalizeParams(Y)})}var aA=q("ZodTransform",(Q,Y)=>{wW.init(Q,Y),X0.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new G4(Q.constructor.name);X.addIssue=($)=>{if(typeof $==="string")X.issues.push(m.issue($,X.value,Y));else{let z=$;if(z.fatal)z.continue=!1;z.code??(z.code="custom"),z.input??(z.input=X.value),z.inst??(z.inst=Q),X.issues.push(m.issue(z))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then(($)=>{return X.value=$,X});return X.value=G,X}});function fG(Q){return new aA({type:"transform",transform:Q})}var lG=q("ZodOptional",(Q,Y)=>{PW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function Y0(Q){return new lG({type:"optional",innerType:Q})}var sA=q("ZodNullable",(Q,Y)=>{bW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function _G(Q){return new sA({type:"nullable",innerType:Q})}var eA=q("ZodDefault",(Q,Y)=>{jW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function Q3(Q,Y){return new eA({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var Y3=q("ZodPrefault",(Q,Y)=>{IW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function X3(Q,Y){return new Y3({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var mG=q("ZodNonOptional",(Q,Y)=>{EW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function W3(Q,Y){return new mG({type:"nonoptional",innerType:Q,...m.normalizeParams(Y)})}var G3=q("ZodCatch",(Q,Y)=>{TW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function $3(Q,Y){return new G3({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var z3=q("ZodPipe",(Q,Y)=>{SW.init(Q,Y),X0.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function A9(Q,Y){return new z3({type:"pipe",in:Q,out:Y})}var J3=q("ZodReadonly",(Q,Y)=>{RW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function H3(Q){return new J3({type:"readonly",innerType:Q})}var cG=q("ZodCustom",(Q,Y)=>{CW.init(Q,Y),X0.init(Q,Y)});function pG(Q,Y){return DG(cG,Q??(()=>!0),Y)}function A3(Q,Y={}){return BG(cG,Q,Y)}function U3(Q){return LG(Q)}function D9(Q,Y){return A9(fG(Q),Y)}T0(nQ());var B9="2025-11-25";var iG=[B9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],K1="io.modelcontextprotocol/related-task",P6="2.0",U0=pG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),nG=d([F(),i().int()]),rG=F(),Bw=q0({ttl:d([i(),U9()]).optional(),pollInterval:i().optional()}),K3=b({ttl:i().optional()}),D3=b({taskId:F()}),L9=q0({progressToken:nG.optional(),[K1]:D3.optional()}),E0=b({_meta:L9.optional()}),M4=E0.extend({task:K3.optional()}),dG=(Q)=>M4.safeParse(Q).success,K0=b({method:F(),params:E0.loose().optional()}),S0=b({_meta:L9.optional()}),R0=b({method:F(),params:S0.loose().optional()}),D0=q0({_meta:L9.optional()}),b6=d([F(),i().int()]),oG=b({jsonrpc:j(P6),id:b6,...K0.shape}).strict(),F9=(Q)=>oG.safeParse(Q).success,tG=b({jsonrpc:j(P6),...R0.shape}).strict(),aG=(Q)=>tG.safeParse(Q).success,q9=b({jsonrpc:j(P6),id:b6,result:D0}).strict(),V4=(Q)=>q9.safeParse(Q).success;var h;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(h||(h={}));var O9=b({jsonrpc:j(P6),id:b6.optional(),error:b({code:i().int(),message:F(),data:e().optional()})}).strict();var sG=(Q)=>O9.safeParse(Q).success;var eG=d([oG,tG,q9,O9]),Lw=d([q9,O9]),j6=D0.strict(),B3=S0.extend({requestId:b6.optional(),reason:F().optional()}),I6=R0.extend({method:j("notifications/cancelled"),params:B3}),L3=b({src:F(),mimeType:F().optional(),sizes:u(F()).optional(),theme:V0(["light","dark"]).optional()}),Z4=b({icons:u(L3).optional()}),f1=b({name:F(),title:F().optional()}),Q$=f1.extend({...f1.shape,...Z4.shape,version:F(),websiteUrl:F().optional(),description:F().optional()}),F3=N6(b({applyDefaults:H0().optional()}),Q0(F(),e())),q3=D9((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},N6(b({form:F3.optional(),url:U0.optional()}),Q0(F(),e()).optional())),O3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({sampling:q0({createMessage:U0.optional()}).optional(),elicitation:q0({create:U0.optional()}).optional()}).optional()}),M3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({tools:q0({call:U0.optional()}).optional()}).optional()}),V3=b({experimental:Q0(F(),U0).optional(),sampling:b({context:U0.optional(),tools:U0.optional()}).optional(),elicitation:q3.optional(),roots:b({listChanged:H0().optional()}).optional(),tasks:O3.optional()}),Z3=E0.extend({protocolVersion:F(),capabilities:V3,clientInfo:Q$}),M9=K0.extend({method:j("initialize"),params:Z3});var N3=b({experimental:Q0(F(),U0).optional(),logging:U0.optional(),completions:U0.optional(),prompts:b({listChanged:H0().optional()}).optional(),resources:b({subscribe:H0().optional(),listChanged:H0().optional()}).optional(),tools:b({listChanged:H0().optional()}).optional(),tasks:M3.optional()}),w3=D0.extend({protocolVersion:F(),capabilities:N3,serverInfo:Q$,instructions:F().optional()}),V9=R0.extend({method:j("notifications/initialized"),params:S0.optional()});var E6=K0.extend({method:j("ping"),params:E0.optional()}),P3=b({progress:i(),total:Y0(i()),message:Y0(F())}),b3=b({...S0.shape,...P3.shape,progressToken:nG}),T6=R0.extend({method:j("notifications/progress"),params:b3}),j3=E0.extend({cursor:rG.optional()}),N4=K0.extend({params:j3.optional()}),w4=D0.extend({nextCursor:rG.optional()}),I3=V0(["working","input_required","completed","failed","cancelled"]),P4=b({taskId:F(),status:I3,ttl:d([i(),U9()]),createdAt:F(),lastUpdatedAt:F(),pollInterval:Y0(i()),statusMessage:Y0(F())}),l1=D0.extend({task:P4}),E3=S0.merge(P4),b4=R0.extend({method:j("notifications/tasks/status"),params:E3}),S6=K0.extend({method:j("tasks/get"),params:E0.extend({taskId:F()})}),R6=D0.merge(P4),C6=K0.extend({method:j("tasks/result"),params:E0.extend({taskId:F()})}),Fw=D0.loose(),k6=N4.extend({method:j("tasks/list")}),v6=w4.extend({tasks:u(P4)}),x6=K0.extend({method:j("tasks/cancel"),params:E0.extend({taskId:F()})}),Y$=D0.merge(P4),X$=b({uri:F(),mimeType:Y0(F()),_meta:Q0(F(),e()).optional()}),W$=X$.extend({text:F()}),Z9=F().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),G$=X$.extend({blob:Z9}),j4=V0(["user","assistant"]),m1=b({audience:u(j4).optional(),priority:i().min(0).max(1).optional(),lastModified:O4.datetime({offset:!0}).optional()}),$$=b({...f1.shape,...Z4.shape,uri:F(),description:Y0(F()),mimeType:Y0(F()),annotations:m1.optional(),_meta:Y0(q0({}))}),T3=b({...f1.shape,...Z4.shape,uriTemplate:F(),description:Y0(F()),mimeType:Y0(F()),annotations:m1.optional(),_meta:Y0(q0({}))}),N9=N4.extend({method:j("resources/list")}),S3=w4.extend({resources:u($$)}),R3=N4.extend({method:j("resources/templates/list")}),C3=w4.extend({resourceTemplates:u(T3)}),w9=E0.extend({uri:F()}),k3=w9,P9=K0.extend({method:j("resources/read"),params:k3}),v3=D0.extend({contents:u(d([W$,G$]))}),x3=R0.extend({method:j("notifications/resources/list_changed"),params:S0.optional()}),_3=w9,g3=K0.extend({method:j("resources/subscribe"),params:_3}),y3=w9,u3=K0.extend({method:j("resources/unsubscribe"),params:y3}),h3=S0.extend({uri:F()}),f3=R0.extend({method:j("notifications/resources/updated"),params:h3}),l3=b({name:F(),description:Y0(F()),required:Y0(H0())}),m3=b({...f1.shape,...Z4.shape,description:Y0(F()),arguments:Y0(u(l3)),_meta:Y0(q0({}))}),c3=N4.extend({method:j("prompts/list")}),p3=w4.extend({prompts:u(m3)}),i3=E0.extend({name:F(),arguments:Q0(F(),F()).optional()}),n3=K0.extend({method:j("prompts/get"),params:i3}),b9=b({type:j("text"),text:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),j9=b({type:j("image"),data:Z9,mimeType:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),I9=b({type:j("audio"),data:Z9,mimeType:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),r3=b({type:j("tool_use"),name:F(),id:F(),input:Q0(F(),e()),_meta:Q0(F(),e()).optional()}),d3=b({type:j("resource"),resource:d([W$,G$]),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),o3=$$.extend({type:j("resource_link")}),E9=d([b9,j9,I9,o3,d3]),t3=b({role:j4,content:E9}),a3=D0.extend({description:F().optional(),messages:u(t3)}),s3=R0.extend({method:j("notifications/prompts/list_changed"),params:S0.optional()}),e3=b({title:F().optional(),readOnlyHint:H0().optional(),destructiveHint:H0().optional(),idempotentHint:H0().optional(),openWorldHint:H0().optional()}),QU=b({taskSupport:V0(["required","optional","forbidden"]).optional()}),z$=b({...f1.shape,...Z4.shape,description:F().optional(),inputSchema:b({type:j("object"),properties:Q0(F(),U0).optional(),required:u(F()).optional()}).catchall(e()),outputSchema:b({type:j("object"),properties:Q0(F(),U0).optional(),required:u(F()).optional()}).catchall(e()).optional(),annotations:e3.optional(),execution:QU.optional(),_meta:Q0(F(),e()).optional()}),T9=N4.extend({method:j("tools/list")}),YU=w4.extend({tools:u(z$)}),_6=D0.extend({content:u(E9).default([]),structuredContent:Q0(F(),e()).optional(),isError:H0().optional()}),qw=_6.or(D0.extend({toolResult:e()})),XU=M4.extend({name:F(),arguments:Q0(F(),e()).optional()}),I4=K0.extend({method:j("tools/call"),params:XU}),WU=R0.extend({method:j("notifications/tools/list_changed"),params:S0.optional()}),Ow=b({autoRefresh:H0().default(!0),debounceMs:i().int().nonnegative().default(300)}),E4=V0(["debug","info","notice","warning","error","critical","alert","emergency"]),GU=E0.extend({level:E4}),S9=K0.extend({method:j("logging/setLevel"),params:GU}),$U=S0.extend({level:E4,logger:F().optional(),data:e()}),zU=R0.extend({method:j("notifications/message"),params:$U}),JU=b({name:F().optional()}),HU=b({hints:u(JU).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),AU=b({mode:V0(["auto","required","none"]).optional()}),UU=b({type:j("tool_result"),toolUseId:F().describe("The unique identifier for the corresponding tool call."),content:u(E9).default([]),structuredContent:b({}).loose().optional(),isError:H0().optional(),_meta:Q0(F(),e()).optional()}),KU=K9("type",[b9,j9,I9]),w6=K9("type",[b9,j9,I9,r3,UU]),DU=b({role:j4,content:d([w6,u(w6)]),_meta:Q0(F(),e()).optional()}),BU=M4.extend({messages:u(DU),modelPreferences:HU.optional(),systemPrompt:F().optional(),includeContext:V0(["none","thisServer","allServers"]).optional(),temperature:i().optional(),maxTokens:i().int(),stopSequences:u(F()).optional(),metadata:U0.optional(),tools:u(z$).optional(),toolChoice:AU.optional()}),LU=K0.extend({method:j("sampling/createMessage"),params:BU}),R9=D0.extend({model:F(),stopReason:Y0(V0(["endTurn","stopSequence","maxTokens"]).or(F())),role:j4,content:KU}),C9=D0.extend({model:F(),stopReason:Y0(V0(["endTurn","stopSequence","maxTokens","toolUse"]).or(F())),role:j4,content:d([w6,u(w6)])}),FU=b({type:j("boolean"),title:F().optional(),description:F().optional(),default:H0().optional()}),qU=b({type:j("string"),title:F().optional(),description:F().optional(),minLength:i().optional(),maxLength:i().optional(),format:V0(["email","uri","date","date-time"]).optional(),default:F().optional()}),OU=b({type:V0(["number","integer"]),title:F().optional(),description:F().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),MU=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),default:F().optional()}),VU=b({type:j("string"),title:F().optional(),description:F().optional(),oneOf:u(b({const:F(),title:F()})),default:F().optional()}),ZU=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),enumNames:u(F()).optional(),default:F().optional()}),NU=d([MU,VU]),wU=b({type:j("array"),title:F().optional(),description:F().optional(),minItems:i().optional(),maxItems:i().optional(),items:b({type:j("string"),enum:u(F())}),default:u(F()).optional()}),PU=b({type:j("array"),title:F().optional(),description:F().optional(),minItems:i().optional(),maxItems:i().optional(),items:b({anyOf:u(b({const:F(),title:F()}))}),default:u(F()).optional()}),bU=d([wU,PU]),jU=d([ZU,NU,bU]),IU=d([jU,FU,qU,OU]),EU=M4.extend({mode:j("form").optional(),message:F(),requestedSchema:b({type:j("object"),properties:Q0(F(),IU),required:u(F()).optional()})}),TU=M4.extend({mode:j("url"),message:F(),elicitationId:F(),url:F().url()}),SU=d([EU,TU]),RU=K0.extend({method:j("elicitation/create"),params:SU}),CU=S0.extend({elicitationId:F()}),kU=R0.extend({method:j("notifications/elicitation/complete"),params:CU}),g6=D0.extend({action:V0(["accept","decline","cancel"]),content:D9((Q)=>Q===null?void 0:Q,Q0(F(),d([F(),i(),H0(),u(F())])).optional())}),vU=b({type:j("ref/resource"),uri:F()});var xU=b({type:j("ref/prompt"),name:F()}),_U=E0.extend({ref:d([xU,vU]),argument:b({name:F(),value:F()}),context:b({arguments:Q0(F(),F()).optional()}).optional()}),gU=K0.extend({method:j("completion/complete"),params:_U});var yU=D0.extend({completion:q0({values:u(F()).max(100),total:Y0(i().int()),hasMore:Y0(H0())})}),uU=b({uri:F().startsWith("file://"),name:F().optional(),_meta:Q0(F(),e()).optional()}),hU=K0.extend({method:j("roots/list"),params:E0.optional()}),k9=D0.extend({roots:u(uU)}),fU=R0.extend({method:j("notifications/roots/list_changed"),params:S0.optional()}),Mw=d([E6,M9,gU,S9,n3,c3,N9,R3,P9,g3,u3,I4,T9,S6,C6,k6,x6]),Vw=d([I6,T6,V9,fU,b4]),Zw=d([j6,R9,C9,g6,k9,R6,v6,l1]),Nw=d([E6,LU,RU,hU,S6,C6,k6,x6]),ww=d([I6,T6,zU,f3,x3,WU,s3,b4,kU]),Pw=d([j6,w3,yU,a3,p3,S3,C3,v3,_6,YU,R6,v6,l1]);class _ extends Error{constructor(Q,Y,X){super(`MCP error ${Q}: ${Y}`);this.code=Q,this.data=X,this.name="McpError"}static fromError(Q,Y,X){if(Q===h.UrlElicitationRequired&&X){let W=X;if(W.elicitations)return new J$(W.elicitations,Y)}return new _(Q,Y,X)}}class J$ extends _{constructor(Q,Y=`URL elicitation${Q.length>1?"s":""} required`){super(h.UrlElicitationRequired,Y,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function D1(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var lU=Symbol("Let zodToJsonSchema decide on which parser to use");var XP=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function v9(Q){let X=V6(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=FG(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function x9(Q,Y){let X=U1(Q,Y);if(!X.success)throw X.error;return X.data}var rU=60000;class _9{constructor(Q){if(this._options=Q,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(I6,(Y)=>{this._oncancel(Y)}),this.setNotificationHandler(T6,(Y)=>{this._onprogress(Y)}),this.setRequestHandler(E6,(Y)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(S6,async(Y,X)=>{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(C6,async(Y,X)=>{let W=async()=>{let G=Y.params.taskId;if(this._taskMessageQueue){let z;while(z=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(z.type==="response"||z.type==="error"){let J=z.message,H=J.id,A=this._requestResolvers.get(H);if(A)if(this._requestResolvers.delete(H),z.type==="response")A(J);else{let U=J,K=new _(U.error.code,U.error.message,U.error.data);A(K)}else{let U=z.type==="response"?"Response":"Error";this._onerror(Error(`${U} handler missing for request ${H}`))}continue}await this._transport?.send(z.message,{relatedRequestId:X.requestId})}}let $=await this._taskStore.getTask(G,X.sessionId);if(!$)throw new _(h.InvalidParams,`Task not found: ${G}`);if(!D1($.status))return await this._waitForTaskUpdate(G,X.signal),await W();if(D1($.status)){let z=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...z,_meta:{...z._meta,[K1]:{taskId:G}}}}return await W()};return await W()}),this.setRequestHandler(k6,async(Y,X)=>{try{let{tasks:W,nextCursor:G}=await this._taskStore.listTasks(Y.params?.cursor,X.sessionId);return{tasks:W,nextCursor:G,_meta:{}}}catch(W){throw new _(h.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(x6,async(Y,X)=>{try{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,`Task not found: ${Y.params.taskId}`);if(D1(W.status))throw new _(h.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(Y.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Y.params.taskId);let G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new _(h.InvalidParams,`Task not found after cancellation: ${Y.params.taskId}`);return{_meta:{},...G}}catch(W){if(W instanceof _)throw W;throw new _(h.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,Y,X,W,G=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,Y),startTime:Date.now(),timeout:Y,maxTotalTimeout:X,resetTimeoutOnProgress:G,onTimeout:W})}_resetTimeout(Q){let Y=this._timeoutInfo.get(Q);if(!Y)return!1;let X=Date.now()-Y.startTime;if(Y.maxTotalTimeout&&X>=Y.maxTotalTimeout)throw this._timeoutInfo.delete(Q),_.fromError(h.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Y.maxTotalTimeout,totalElapsed:X});return clearTimeout(Y.timeoutId),Y.timeoutId=setTimeout(Y.onTimeout,Y.timeout),!0}_cleanupTimeout(Q){let Y=this._timeoutInfo.get(Q);if(Y)clearTimeout(Y.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let Y=this.transport?.onclose;this._transport.onclose=()=>{Y?.(),this._onclose()};let X=this.transport?.onerror;this._transport.onerror=(G)=>{X?.(G),this._onerror(G)};let W=this._transport?.onmessage;this._transport.onmessage=(G,$)=>{if(W?.(G,$),V4(G)||sG(G))this._onresponse(G);else if(F9(G))this._onrequest(G,$);else if(aG(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let Y=_.fromError(h.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of Q.values())X(Y)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let Y=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(Y===void 0)return;Promise.resolve().then(()=>Y(Q)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(Q,Y){let X=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,G=Q.params?._meta?.[K1]?.taskId;if(X===void 0){let A={jsonrpc:"2.0",id:Q.id,error:{code:h.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId).catch((U)=>this._onerror(Error(`Failed to enqueue error response: ${U}`)));else W?.send(A).catch((U)=>this._onerror(Error(`Failed to send an error response: ${U}`)));return}let $=new AbortController;this._requestHandlerAbortControllers.set(Q.id,$);let z=dG(Q.params)?Q.params.task:void 0,J=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:$.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(A)=>{let U={relatedRequestId:Q.id};if(G)U.relatedTask={taskId:G};await this.notification(A,U)},sendRequest:async(A,U,K)=>{let D={...K,relatedRequestId:Q.id};if(G&&!D.relatedTask)D.relatedTask={taskId:G};let L=D.relatedTask?.taskId??G;if(L&&J)await J.updateTaskStatus(L,"input_required");return await this.request(A,U,D)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:J,taskRequestedTtl:z?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(z)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(A)=>{if($.signal.aborted)return;let U={result:A,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:U,timestamp:Date.now()},W?.sessionId);else await W?.send(U)},async(A)=>{if($.signal.aborted)return;let U={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(A.code)?A.code:h.InternalError,message:A.message??"Internal error",...A.data!==void 0&&{data:A.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId);else await W?.send(U)}).catch((A)=>this._onerror(Error(`Failed to send response: ${A}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:Y,...X}=Q.params,W=Number(Y),G=this._progressHandlers.get(W);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let $=this._responseHandlers.get(W),z=this._timeoutInfo.get(W);if(z&&$&&z.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(J){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),$(J);return}G(X)}_onresponse(Q){let Y=Number(Q.id),X=this._requestResolvers.get(Y);if(X){if(this._requestResolvers.delete(Y),V4(Q))X(Q);else{let $=new _(Q.error.code,Q.error.message,Q.error.data);X($)}return}let W=this._responseHandlers.get(Y);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(Y),this._cleanupTimeout(Y);let G=!1;if(V4(Q)&&Q.result&&typeof Q.result==="object"){let $=Q.result;if($.task&&typeof $.task==="object"){let z=$.task;if(typeof z.taskId==="string")G=!0,this._taskProgressTokens.set(z.taskId,Y)}}if(!G)this._progressHandlers.delete(Y);if(V4(Q))W(Q);else{let $=_.fromError(Q.error.code,Q.error.message,Q.error.data);W($)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,Y,X){let{task:W}=X??{};if(!W){try{yield{type:"result",result:await this.request(Q,Y,X)}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}return}let G;try{let $=await this.request(Q,l1,X);if($.task)G=$.task.taskId,yield{type:"taskCreated",task:$.task};else throw new _(h.InternalError,"Task creation did not return a task");while(!0){let z=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:z},D1(z.status)){if(z.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(z.status==="failed")yield{type:"error",error:new _(h.InternalError,`Task ${G} failed`)};else if(z.status==="cancelled")yield{type:"error",error:new _(h.InternalError,`Task ${G} was cancelled`)};return}if(z.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let J=z.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,J)),X?.signal?.throwIfAborted()}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$,task:z,relatedTask:J}=X??{};return new Promise((H,A)=>{let U=(Z)=>{A(Z)};if(!this._transport){U(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),z)this.assertTaskCapability(Q.method)}catch(Z){U(Z);return}X?.signal?.throwIfAborted();let K=this._requestMessageId++,D={...Q,jsonrpc:"2.0",id:K};if(X?.onprogress)this._progressHandlers.set(K,X.onprogress),D.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:K}};if(z)D.params={...D.params,task:z};if(J)D.params={...D.params,_meta:{...D.params?._meta||{},[K1]:J}};let L=(Z)=>{this._responseHandlers.delete(K),this._progressHandlers.delete(K),this._cleanupTimeout(K),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:K,reason:String(Z)}},{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let k=Z instanceof _?Z:new _(h.RequestTimeout,String(Z));A(k)};this._responseHandlers.set(K,(Z)=>{if(X?.signal?.aborted)return;if(Z instanceof Error)return A(Z);try{let k=U1(Y,Z.result);if(!k.success)A(k.error);else H(k.data)}catch(k){A(k)}}),X?.signal?.addEventListener("abort",()=>{L(X?.signal?.reason)});let O=X?.timeout??rU,M=()=>L(_.fromError(h.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(K,O,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let N=J?.taskId;if(N){let Z=(k)=>{let S=this._responseHandlers.get(K);if(S)S(k);else this._onerror(Error(`Response handler missing for side-channeled request ${K}`))};this._requestResolvers.set(K,Z),this._enqueueTaskMessage(N,{type:"request",message:D,timestamp:Date.now()}).catch((k)=>{this._cleanupTimeout(K),A(k)})}else this._transport.send(D,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((Z)=>{this._cleanupTimeout(K),A(Z)})})}async getTask(Q,Y){return this.request({method:"tasks/get",params:Q},R6,Y)}async getTaskResult(Q,Y,X){return this.request({method:"tasks/result",params:Q},Y,X)}async listTasks(Q,Y){return this.request({method:"tasks/list",params:Q},v6,Y)}async cancelTask(Q,Y){return this.request({method:"tasks/cancel",params:Q},Y$,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let z={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[K1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:z,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!Y?.relatedRequestId&&!Y?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let z={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)z={...z,params:{...z.params,_meta:{...z.params?._meta||{},[K1]:Y.relatedTask}}};this._transport?.send(z,Y).catch((J)=>this._onerror(J))});return}let $={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)$={...$,params:{...$.params,_meta:{...$.params?._meta||{},[K1]:Y.relatedTask}}};await this._transport.send($,Y)}setRequestHandler(Q,Y){let X=v9(Q);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(W,G)=>{let $=x9(Q,W);return Promise.resolve(Y($,G))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,Y){let X=v9(Q);this._notificationHandlers.set(X,(W)=>{let G=x9(Q,W);return Promise.resolve(Y(G))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let Y=this._taskProgressTokens.get(Q);if(Y!==void 0)this._progressHandlers.delete(Y),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,Y,X){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,Y,X,W)}async _clearTaskQueue(Q,Y){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll(Q,Y);for(let W of X)if(W.type==="request"&&F9(W.message)){let G=W.message.id,$=this._requestResolvers.get(G);if($)$(new _(h.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,Y){let X=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)X=W.pollInterval}catch{}return new Promise((W,G)=>{if(Y.aborted){G(new _(h.InvalidRequest,"Request cancelled"));return}let $=setTimeout(W,X);Y.addEventListener("abort",()=>{clearTimeout($),G(new _(h.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,Y){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await X.createTask(W,Q.id,{method:Q.method,params:Q.params},Y)},getTask:async(W)=>{let G=await X.getTask(W,Y);if(!G)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(W,G,$)=>{await X.storeTaskResult(W,G,$,Y);let z=await X.getTask(W,Y);if(z){let J=b4.parse({method:"notifications/tasks/status",params:z});if(await this.notification(J),D1(z.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,$)=>{let z=await X.getTask(W,Y);if(!z)throw new _(h.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(D1(z.status))throw new _(h.InvalidParams,`Cannot update task "${W}" from terminal status "${z.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,$,Y);let J=await X.getTask(W,Y);if(J){let H=b4.parse({method:"notifications/tasks/status",params:J});if(await this.notification(H),D1(J.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function H$(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function A$(Q,Y){let X={...Q};for(let W in Y){let G=W,$=Y[G];if($===void 0)continue;let z=X[G];if(H$(z)&&H$($))X[G]={...z,...$};else X[G]=$}return X}var f5=BX(SY(),1),l5=BX(h5(),1);function XV(){let Q=new f5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return l5.default(Q),Q}class hY{constructor(Q){this._ajv=Q??XV()}getValidator(Q){let Y="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(X)=>{if(Y(X))return{valid:!0,data:X,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(Y.errors)}}}}class fY{constructor(Q){this._server=Q}requestStream(Q,Y,X){return this._server.requestStream(Q,Y,X)}async getTask(Q,Y){return this._server.getTask({taskId:Q},Y)}async getTaskResult(Q,Y,X){return this._server.getTaskResult({taskId:Q},Y,X)}async listTasks(Q,Y){return this._server.listTasks(Q?{cursor:Q}:void 0,Y)}async cancelTask(Q,Y){return this._server.cancelTask({taskId:Q},Y)}}function m5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"tools/call":if(!Q.tools?.call)throw Error(`${X} does not support task creation for tools/call (required for ${Y})`);break;default:break}}function c5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${X} does not support task creation for sampling/createMessage (required for ${Y})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${X} does not support task creation for elicitation/create (required for ${Y})`);break;default:break}}class lY extends _9{constructor(Q,Y){super(Y);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(E4.options.map((X,W)=>[X,W])),this.isMessageIgnored=(X,W)=>{let G=this._loggingLevels.get(W);return G?this.LOG_LEVEL_SEVERITY.get(X)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=Y?.capabilities??{},this._instructions=Y?.instructions,this._jsonSchemaValidator=Y?.jsonSchemaValidator??new hY,this.setRequestHandler(M9,(X)=>this._oninitialize(X)),this.setNotificationHandler(V9,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(S9,async(X,W)=>{let G=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:$}=X.params,z=E4.safeParse($);if(z.success)this._loggingLevels.set(G,z.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new fY(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=A$(this._capabilities,Q)}setRequestHandler(Q,Y){let W=V6(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let G;if(h1(W)){let z=W;G=z._zod?.def?.value??z.value}else{let z=W;G=z._def?.value??z.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let z=async(J,H)=>{let A=U1(I4,J);if(!A.success){let L=A.error instanceof Error?A.error.message:String(A.error);throw new _(h.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:U}=A.data,K=await Promise.resolve(Y(J,H));if(U.task){let L=U1(l1,K);if(!L.success){let O=L.error instanceof Error?L.error.message:String(L.error);throw new _(h.InvalidParams,`Invalid task creation result: ${O}`)}return L.data}let D=U1(_6,K);if(!D.success){let L=D.error instanceof Error?D.error.message:String(D.error);throw new _(h.InvalidParams,`Invalid tools/call result: ${L}`)}return D.data};return super.setRequestHandler(Q,z)}return super.setRequestHandler(Q,Y)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){c5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;m5(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let Y=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:iG.includes(Y)?Y:B9,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},j6)}async createMessage(Q,Y){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let X=Q.messages[Q.messages.length-1],W=Array.isArray(X.content)?X.content:[X.content],G=W.some((H)=>H.type==="tool_result"),$=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,z=$?Array.isArray($.content)?$.content:[$.content]:[],J=z.some((H)=>H.type==="tool_use");if(G){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!J)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(J){let H=new Set(z.filter((U)=>U.type==="tool_use").map((U)=>U.id)),A=new Set(W.filter((U)=>U.type==="tool_result").map((U)=>U.toolUseId));if(H.size!==A.size||![...H].every((U)=>A.has(U)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},C9,Y);return this.request({method:"sampling/createMessage",params:Q},R9,Y)}async elicitInput(Q,Y){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},g6,Y)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},G=await this.request({method:"elicitation/create",params:W},g6,Y);if(G.action==="accept"&&G.content&&W.requestedSchema)try{let z=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!z.valid)throw new _(h.InvalidParams,`Elicitation response content does not match requested schema: ${z.errorMessage}`)}catch($){if($ instanceof _)throw $;throw new _(h.InternalError,`Error validating elicitation response: ${$ instanceof Error?$.message:String($)}`)}return G}}}createElicitationCompletionNotifier(Q,Y){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},Y)}async listRoots(Q,Y){return this.request({method:"roots/list",params:Q},k9,Y)}async sendLoggingMessage(Q,Y){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,Y))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var p5={name:"@sequenzy/mcp",version:"0.0.100",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"bunx --bun tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^7.0.2"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var mY=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],i5={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",landingPages:"/dashboard/company/{companyId}/landing-pages",landingPage:"/dashboard/company/{companyId}/landing-pages/{landingPageId}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function GV(Q){let X=(Q??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return X.length>0?X:"https://sequenzy.com"}function l0(Q){let Y=Q?.trim();return Y?Y:void 0}function r0(Q){return encodeURIComponent(Q)}function $0(Q,Y){return`${Q}${Y}`}function z0(Q,Y=""){return`/dashboard/company/${r0(Q)}${Y}`}function n5(Q,Y,X){return $0(Q,`${z0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function $V(Q,Y){let X=mY.map((W)=>[W,Y?n5(Q,Y,W):""]);return Object.fromEntries(X)}function Z1(Q={},Y){let X=GV(Y),W=l0(Q.companyId),G={},$=$V(X,W);if(!W)return{appUrl:X,routeTemplates:i5,settingsTabValues:mY,urls:G,settingsUrls:$};G.dashboard=$0(X,z0(W)),G.campaigns=$0(X,z0(W,"/campaign")),G.landingPages=$0(X,z0(W,"/landing-pages")),G.sequences=$0(X,z0(W,"/sequences")),G.settings=$0(X,z0(W,"/settings")),G.emails=$0(X,z0(W,"/emails")),G.subscribers=$0(X,z0(W,"/subscribers")),G.sentEmails=$0(X,z0(W,"/sent-emails")),G.segments=$0(X,z0(W,"/segments")),G.metrics=$0(X,z0(W,"/metrics")),G.transactional=$0(X,z0(W,"/transactional"));let z=l0(Q.campaignId);if(z)G.campaign=$0(X,z0(W,`/campaign/${r0(z)}`)),G.campaignPreview=`${G.campaign}?step=review`;let J=l0(Q.landingPageId);if(J)G.landingPage=$0(X,z0(W,`/landing-pages/${r0(J)}`));let H=l0(Q.sequenceId);if(H)G.sequence=$0(X,z0(W,`/sequences/${r0(H)}`));let A=l0(Q.emailId)??l0(Q.templateId);if(A)G.email=$0(X,z0(W,`/emails/${r0(A)}`)),G.template=G.email;let U=l0(Q.transactionalId);if(U)G.transactionalEmail=$0(X,z0(W,`/transactional/${r0(U)}`));let K=l0(Q.emailSendId);if(K)G.emailSend=$0(X,z0(W,`/sent-emails/${r0(K)}`));let D=l0(Q.domainId);if(D)G.domain=$0(X,z0(W,`/settings/domain/${r0(D)}`)),G.domainVerify=`${G.domain}/verify`;let L=l0(Q.status);if(L)G.campaignList=$0(X,z0(W,`/campaign/list/${r0(L)}`)),G.sequenceList=$0(X,z0(W,`/sequences/list/${r0(L)}`));let O=l0(Q.settingsTab);if(O)G.settingsTab=n5(X,W,O);return{appUrl:X,routeTemplates:i5,settingsTabValues:mY,urls:G,settingsUrls:$}}var r5=[{uri:"sequenzy://dashboard",name:"Dashboard Overview",description:"Live overview stats for the last 7 days",mimeType:"application/json"},{uri:"sequenzy://company",name:"Current Company",description:"The currently selected company, including localization settings",mimeType:"application/json"},{uri:"sequenzy://campaigns/recent",name:"Recent Campaigns",description:"Last 10 campaigns with status and basic stats",mimeType:"application/json"},{uri:"sequenzy://subscribers/recent",name:"Recent Subscribers",description:"Most recently added subscribers",mimeType:"application/json"},{uri:"sequenzy://subscribers/engaged",name:"Engaged Subscribers",description:"Most active/engaged subscribers",mimeType:"application/json"},{uri:"sequenzy://sequences",name:"Sequences",description:"All email sequences with status",mimeType:"application/json"},{uri:"sequenzy://templates",name:"Templates",description:"All available email templates with localization status",mimeType:"application/json"},{uri:"sequenzy://segments",name:"Segments",description:"All defined segments with subscriber counts",mimeType:"application/json"},{uri:"sequenzy://tags",name:"Tags",description:"All tags with usage counts",mimeType:"application/json"},{uri:"sequenzy://health",name:"Deliverability Health",description:"Email deliverability metrics and health status",mimeType:"application/json"},{uri:"sequenzy://app-routes",name:"Dashboard URL Routes",description:"Route templates and settings tabs for building Sequenzy dashboard links",mimeType:"application/json"}];async function d5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await B("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await B("GET","/api/v1/account"),W=b1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await B("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await B("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await B("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await B("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await B("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await B("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await B("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await B("GET","/api/v1/tags");break;case"sequenzy://health":Y=await B("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=Z1();break;default:throw Error(`Unknown resource: ${Q}`)}return{contents:[{uri:Q,mimeType:"application/json",text:JSON.stringify(Y,null,2)}]}}catch(Y){return{contents:[{uri:Q,mimeType:"text/plain",text:$1(Y)}]}}}import{readFileSync as zV,statSync as JV}from"node:fs";import{basename as HV}from"node:path";var GX=' Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in the transactional send `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" } where the text before the colon is a {{merge tag}} path (nested paths like "order.total" or "event.plan" work) and the text after it is the comparison value. `field` may also be "attribute" (same "name:value" form) or "email"/"firstName"/"lastName" (the value is the plain comparison string). Operators: is, is_not, contains, not_contains, gt, gte, lt, lte, is_empty, is_not_empty. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block.',s4=`Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. For provider-migrated HTML from another email platform, prefer the \`html\` field instead; Sequenzy stores it as one raw HTML block to preserve the original design. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.${GX}`,Q4=`Replacement Sequenzy email blocks. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`.${GX}`,tY=`Sequenzy email blocks. Provide blocks or html for email steps. For migrated provider HTML, prefer \`html\`; Sequenzy stores it as one raw HTML block and does not recreate it as native blocks. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Blocks can include repeat blocks over array variables such as items.${GX}`,NQ="Complete Sequenzy landing page content JSON. Use this when replacing the page structure. The content must be the editor-compatible landing page schema with version, template, seo, theme, and blocks. Landing pages must include exactly one footer block and at most one form block.",AV="Optional template key for default content, such as from-scratch, waitlist, lead-magnet, launch, demo-request, webinar, newsletter, product-hunt, pricing-offer, agency-lead-gen, or feature-announcement.",o5=500,t5=500,N1={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},cY=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay"],a5={type:"object",description:"Optional send window for every email step in the sequence. When set, email actions that become due outside the window wait until the next allowed local time. Omit days to allow every day.",properties:{enabled:{type:"boolean",description:"Set false to disable the sending window when creating a sequence. For updates, prefer clearSendingWindow."},timezone:{type:"string",description:"IANA timezone for the window, e.g. Europe/Kiev or America/New_York."},startTime:{type:"string",description:"Earliest local send time in 24-hour HH:mm format, e.g. 08:00."},endTime:{type:"string",description:"Latest local send cutoff in 24-hour HH:mm format, e.g. 20:00. Must be later than startTime."},days:{type:"array",description:"Allowed local days. Use full names or short names such as monday, tuesday, mon, tue. Omit for every day.",items:{type:"string"}}},additionalProperties:!1},UV={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},aY={type:"object",description:"Wait until a date from the trigger event before this step. Use this for renewal reminders, appointment follow-ups, trial-expiry nudges, and other subscriber-specific dates. The field value must be an ISO date string or Unix timestamp.",properties:{field:{type:"string",description:"Dot-path into the trigger event properties, e.g. renews_at or booking.startsAt."},untilDateField:{type:"string",description:"Alias for field."},offset:UV,days:{type:"number",description:"Offset days shorthand. Ignored when offset is provided."},hours:{type:"number",description:"Offset hours shorthand. Ignored when offset is provided."},minutes:{type:"number",description:"Offset minutes shorthand. Ignored when offset is provided."},direction:{type:"string",enum:["before","after"],description:"Whether the offset applies before or after the resolved date. Defaults to after."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"Alias for direction."},missingAction:{type:"string",enum:["continue","exit"],description:"What to do if the event field is missing or invalid. Defaults to continue."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"Alias for missingAction."}},additionalProperties:!1},sY={type:"object",description:"Fixed delay before this step. For a dynamic wait-until-date delay, either set mode:'until_date' plus untilDateField here, or use waitUntil.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"},mode:{type:"string",enum:["duration","until_date"],description:"Use duration for a fixed wait, or until_date to resolve a date from the trigger event."},untilDateField:{type:"string",description:"For mode:'until_date', dot-path into the trigger event properties."},field:{type:"string",description:"Alias for untilDateField."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"For mode:'until_date', whether days/hours/minutes are before or after the event date. Defaults to after."},direction:{type:"string",enum:["before","after"],description:"Alias for untilOffsetDirection."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"For mode:'until_date', what to do when the field is missing or invalid. Defaults to continue."},missingAction:{type:"string",enum:["continue","exit"],description:"Alias for untilMissingAction."}},additionalProperties:!1},wQ=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],PQ=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","sequence.finished","sequence.failed"],KV=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_websites","check_website","get_integration_guide","get_subscriber","list_subscriber_notes","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_email_send","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_transactional_emails","get_transactional_email","get_stats","get_campaign_stats","get_sequence_stats","list_campaign_events","list_sequence_events","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_sequence","generate_subject_lines","generate_sms","get_sms_settings"]),DV=new Set(["select_company","create_company","update_company","update_sync_rules","update_shopify_automation_settings","create_api_key","add_sending_domain","add_website","verify_sending_domain","add_subscriber","update_subscriber","add_subscriber_note","remove_subscriber","delete_subscriber_note","upsert_products","delete_product","attach_product_file","remove_product_file","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","delete_template","restart_ab_test","update_ab_test_variant","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","send_test_sms","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_landing_page","update_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","update_sequence","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery","submit_feedback"]),BV=new Set(["send_test_email","send_test_sms","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","add_sending_domain","add_website","verify_sending_domain","enable_sequence","resume_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery"]),LV=new Set(["remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","disable_sequence","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook"]);function FV(Q){let Y=KV.has(Q),X=DV.has(Q);if(Y===X)throw Error(`MCP tool "${Q}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:Y,destructiveHint:Y?!1:LV.has(Q),openWorldHint:BV.has(Q)}}function qV(Q){return{...Q,annotations:{...Q.annotations,...FV(Q.name)}}}var eY={status:["is","is_not"],phone:["is_not_empty","is_empty"],smsStatus:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"],commerceProduct:["is","is_not","at_least","less_than_count"]},OV=Object.entries(eY).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),s5={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","phone","smsStatus","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct","commerceProduct"],description:"Filter field. Use `phone` with is_not_empty/is_empty to check whether a subscriber has a phone number, and `smsStatus` (is/is_not one of `subscribed`, `unsubscribed`, `not_subscribed`) for SMS marketing consent. Use `event` for custom subscriber events, `segment` for saved segment membership, `stripeProduct`/`stripeCurrentProduct`/`stripeTrialProduct` for Stripe product-based segments, and `commerceProduct` for products purchased through commerce orders - the value is `provider:productId` (provider one of `shopify`, `woocommerce`, `api`; product ids are provider-scoped), optionally with an order-count threshold (`provider:productId:count`) for at_least/less_than_count; a bare product id matches the id on any provider. Engagement fields (`emailSent`, `emailDelivered`, `emailOpened`, `emailClicked`, `emailBounced`, `emailComplained`) accept a time range as the value or a specific campaign via `campaign:<campaign_id>`."},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${OV}.`},value:{type:"string",description:"Filter value. For custom attribute empty checks, use `attributeName:` such as `last_logged_in:`. Event examples: `saas.purchase:30d`, `saas.purchase:all`, or `saas.purchase:5:30d` for thresholds. Segment values are segment IDs. Stripe product examples: `prod_123` for bought/didn't buy/current/trialing, `prod_123:3` for payment thresholds, `prod_123:is_canceled` for products set to cancel, `prod_123:cancels_at:2026-05-26`, `prod_123:end_at:2026-05-26`, or `prod_123:start_at:7 days ago` for product-scoped dates. Engagement examples: `7d`, `30d`, `90d`, `180d`, `all` for rolling time windows, or `campaign:<campaign_id>` to scope to a specific sent campaign (use `list_campaigns` to find IDs)."}},required:["field","operator","value"],additionalProperties:!1},e5={type:"object",properties:{kind:{type:"string",enum:["group"]},id:{type:"string",description:"Stable group ID. Any string works; one will be generated if omitted."},joinOperator:{type:"string",enum:["and","or"],description:"How children in this group combine."},children:{type:"array",minItems:1,items:{type:"object",description:'Either a filter leaf (`kind: "filter"`) or another group (`kind: "group"`).'}}},required:["kind","joinOperator","children"],additionalProperties:!0};function QX(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(typeof Y!=="object"||Y===null)return Y;let X=Y;if(typeof X.id==="string"&&X.id.trim()!=="")return X;return{...X,id:crypto.randomUUID()}})}function YX(Q){if(typeof Q!=="object"||Q===null)return Q;let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=QX([Y]);return Array.isArray(X)?X[0]:Y}if(Y.kind!=="group")return Q;return{...Y,id:typeof Y.id==="string"&&Y.id.trim()!==""?Y.id:crypto.randomUUID(),children:Array.isArray(Y.children)?Y.children.map(YX):[]}}function MV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function VV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function QH(Q){if(Q==="all")return!0;let Y=Q.match(/^(\d+)d$/);if(!Y?.[1])return!1;let X=Number.parseInt(Y[1],10);return Number.isInteger(X)&&X>0}function ZV(Q,Y){let X=Y.split(":");if(Q==="at_least"||Q==="less_than_count"){if(X.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let $=X.slice(0,-2).join(":").trim(),z=X.at(-2),J=X.at(-1),H=z===void 0?Number.NaN:Number.parseInt(z,10);return $&&Number.isInteger(H)&&H>0&&J!==void 0&&QH(J)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(X.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=X.slice(0,-1).join(":").trim(),G=X.at(-1);return W&&G!==void 0&&QH(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function NV(Q){let Y=Q.indexOf(":");if(Y===-1)return{productId:Q,subfilter:null,rawValue:null};let X=Q.substring(0,Y),W=Q.substring(Y+1),G=W.indexOf(":");if(G===-1)return{productId:X,subfilter:W,rawValue:null};return{productId:X,subfilter:W.substring(0,G),rawValue:W.substring(G+1)}}function wV(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function PV(Q){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(Q)}function bV(Q,Y){if(Y==="cancels_at"||Y==="cancel_at"||Y==="cancellation_at")return!0;if(Q==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(Y);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(Y)}function jV(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function IV(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let J=X.indexOf(":");if(J===-1)return null;let H=X.substring(0,J).trim(),A=Number.parseInt(X.substring(J+1).trim(),10);return H&&Number.isInteger(A)&&A>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(Q!=="stripeCurrentProduct"&&Q!=="stripeTrialProduct")return null;let{productId:W,subfilter:G,rawValue:$}=NV(X);if(!W.trim())return"Stripe product filters must include a product ID.";if(!G)return Y==="is"||Y==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let z=wV(G);if(PV(z))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!bV(Q,z))return`Unsupported Stripe product subfilter "${G}".`;if(!jV(Y))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return $?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var EV=new Set(["shopify","woocommerce","api"]);function TV(Q,Y){let X=Y.trim(),W=X.indexOf(":");if(W!==-1&&EV.has(X.substring(0,W).trim()))X=X.substring(W+1).trim();if(!X)return'Purchased Product filters must include a product ID, like "shopify:42".';if(Q!=="at_least"&&Q!=="less_than_count")return null;let G=X.lastIndexOf(":");if(G===-1)return null;let $=X.substring(0,G).trim(),z=Number.parseInt(X.substring(G+1).trim(),10);return $&&Number.isInteger(z)&&z>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function $X(Q){if(typeof Q!=="object"||Q===null)return"Segment filters must be objects.";let Y=Q,X=Y.field,W=Y.operator,G=Y.value;if(typeof X!=="string"||!(X in eY))return`Unsupported segment filter field "${String(X)}".`;if(typeof W!=="string")return`Segment filter "${X}" must include an operator.`;let $=eY[X];if(!$.includes(W))return`Operator "${W}" is not supported for ${X} filters. Use one of: ${$.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${X}" must include a value.`;if(X==="attribute"&&typeof G==="string"){if(!MV(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!VV(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let z=ZV(W,G);if(z)return z}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let z=IV(X,W,G);if(z)return z}if(X==="commerceProduct"&&typeof G==="string"){let z=TV(W,G);if(z)return z}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map((J)=>J.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function zX(Q){if(typeof Q!=="object"||Q===null)return[];let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=$X(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap(zX);return[]}function w1(Q,Y,X){if(Y.html!==void 0&&Y.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`, not both.`);if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error(`\`blocks\` must be an array when calling \`${Q}\`.`);if(X?.requireContent&&Y.html===void 0&&Y.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`.`)}function bQ(Q,Y){if(Y.labels===void 0)return;if(!Array.isArray(Y.labels))throw Error(`\`labels\` must be an array when calling \`${Q}\`.`);if(Y.labels.some((X)=>typeof X!=="string"||X.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${Q}\`.`)}function SV(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!Y&&!X)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=$X(G);return $?[$]:[]}):zX(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function RV(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(Q.name===void 0&&Q.filterJoinOperator===void 0&&!Y&&!X)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=$X(G);return $?[$]:[]}):X?zX(Q.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var pY=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"];function iY(Q,Y,X){if(Y[X]!==void 0&&!J0(Y[X]))throw Error(`\`${X}\` must be an object when calling \`${Q}\`.`)}function YH(Q,Y,X){if(Y[X]!==void 0&&!Array.isArray(Y[X]))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`)}function CV(Q){let Y=new Set(["companyId",...pY]),X=Object.keys(Q).filter((G)=>!Y.has(G));if(X.length>0)throw Error(`\`update_company\` accepts only company product-info fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);let W={};for(let G of pY)if(Q[G]!==void 0)W[G]=Q[G];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${pY.map((G)=>`\`${G}\``).join(", ")} when calling \`update_company\`.`);for(let G of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"])if(Q[G]!==void 0&&typeof Q[G]!=="string")throw Error(`\`${G}\` must be a string when calling \`update_company\`.`);if(iY("update_company",Q,"brandColors"),iY("update_company",Q,"socialLinks"),iY("update_company",Q,"pricing"),YH("update_company",Q,"valueProps"),YH("update_company",Q,"testimonials"),typeof Q.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(Q.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let G of["fromEmail","replyTo"]){let $=Q[G];if(typeof $==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($.trim()))throw Error(`\`${G}\` must be a valid email address when calling \`update_company\`.`)}if(Q.fromName!==void 0&&Q.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_company`.");if(Q.replyToName!==void 0&&Q.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_company`.");return W}function kV(Q){if(Q.fromEmail!==void 0&&Q.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_sequence`, not both.");if(Q.replyTo!==void 0&&Q.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_sequence`, not both.");if(Q.fromName!==void 0&&Q.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_sequence`.");if(Q.replyToName!==void 0&&Q.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_sequence`.");if(Q.clearEnrollmentFieldPath===!0&&Q.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(Q.clearSendingWindow===!0&&Q.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(Q.clearBccEmails===!0&&Q.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(Q.branch!==void 0&&Q.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");let Y={...Q};if(delete Y.clearEnrollmentFieldPath,delete Y.clearSendingWindow,delete Y.clearBccEmails,Q.clearEnrollmentFieldPath===!0)Y.enrollmentFieldPath=null;if(Q.clearSendingWindow===!0)Y.sendingWindow=null;if(Q.clearBccEmails===!0)Y.bccEmails=null;return Y}function vV(Q){let Y=Q.type==="sms",X;if(Y){let G=w(Q,"text"),$=Array.isArray(Q.blocks)&&Q.blocks.length>0;if(G===void 0&&!$)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");X={type:"sms"};for(let z of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(Q[z]!==void 0)X[z]=Q[z]}else{w1("insert_sequence_step",Q,{requireContent:!0}),X={subject:R("insert_sequence_step",Q,"subject")};for(let G of["name","previewText","html","blocks","delay","delayMs","waitUntil"])if(Q[G]!==void 0)X[G]=Q[G]}let W={steps:[X]};if(Q.afterNodeId!==void 0)W.afterNodeId=Q.afterNodeId;return{...Q.confirmStructuralChange!==void 0&&{confirmStructuralChange:Q.confirmStructuralChange},insertSteps:W}}function xV(Q){let Y=w(Q,"subscriberId"),X=Q.fieldValues,W=X===void 0?void 0:Array.isArray(X)?X:void 0;if(X!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let G=W?.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0)??[];if(W?.some((J)=>typeof J!=="string")||W!==void 0&&G.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(Y!==void 0===G.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let $=w(Q,"fieldPath"),z=w(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...$!==void 0&&{fieldPath:$},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...z!==void 0&&{reason:z}}}function _V(Q){w1("create_campaign",Q),bQ("create_campaign",Q);let Y=w(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0,G=Q.templateId!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(Y&&(X||W||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function gV(Q){w1("create_template",Q),bQ("create_template",Q);let Y=w(Q,"prompt")!==void 0,X=[Y,Q.html!==void 0,Q.blocks!==void 0].filter(Boolean).length;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_template`.");if(X!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function yV(Q){if(w(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!J0(Q.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(Q.sendTimeOptimization!==void 0){if(typeof Q.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(Q.spreadOverHours!==void 0){if(typeof Q.spreadOverHours!=="number"||!Number.isInteger(Q.spreadOverHours)||Q.spreadOverHours<1||Q.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(Q.recurringInterval!==void 0&&Q.recurringInterval!=="weekly"&&Q.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function nY(Q,Y,X){let W=new Set(["companyId","landingPageId","name","slug","content"]),G=Object.keys(Y).filter(($)=>!W.has($));if(G.length>0)throw Error(`\`${Q}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map(($)=>`\`${$}\``).join(", ")}.`);if(X.requireUpdate&&Y.name===void 0&&Y.slug===void 0&&Y.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${Q}\`.`);return{...Y.name!==void 0&&{name:Y.name},...Y.slug!==void 0&&{slug:Y.slug},...Y.content!==void 0&&{content:Y.content}}}function uV(Q){let Y=new Set(["companyId","domain","verify"]),X=Object.keys(Q).filter((W)=>!Y.has(W));if(X.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${X.length===1?"":"s"}: ${X.map((W)=>`\`${W}\``).join(", ")}.`);if(Q.domain===void 0&&Q.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...Q.domain!==void 0&&{domain:Q.domain},...typeof Q.verify==="boolean"&&{verify:Q.verify}}}function hV(Q){w1("create_transactional_email",Q);let Y=w(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(Y&&(X||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!Y&&!X&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var XX={type:"object",description:"Update Subscriber config. firstName, lastName, and customAttributeUpdates values may use trigger-event merge tags such as {{event.plan}}. Number and boolean values must be a literal or one standalone merge tag and are coerced after resolution.",properties:{label:{type:"string"},firstName:{type:["string","null"],description:"First name literal or merge tag; null clears the field."},lastName:{type:["string","null"],description:"Last name literal or merge tag; null clears the field."},status:{type:"string",enum:["active","unsubscribed","bounced"]},customAttributeUpdates:{type:"array",items:{type:"object",properties:{name:{type:"string"},value:{type:["string","number","boolean","null"],description:"Literal scalar, null to delete, or a standalone merge tag such as {{event.plan}}, {{event.amount}}, or {{event.active}}."},valueType:{type:"string",enum:["text","number","boolean"]}},required:["name","value"]}}},additionalProperties:!0},rY={type:"object",description:"A step to create inside a sequence path. Use type:'delay' for a standalone delay, type:'email' for an email, type:'create_discount' for a discount action, or type:'condition' for a condition gate.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","update_subscriber","condition","webhook"],description:"Sequence path step type. Omit for email steps; use delay for standalone waits or update_subscriber for action_update_attributes."},nodeType:{type:"string",enum:["logic_delay","action_email","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","logic_condition","action_webhook"],description:"Advanced sequence path node type. Prefer type unless creating a non-email action."},config:{...XX,description:"Config for advanced nodeType steps. For action_update_attributes, use the documented Update Subscriber fields and trigger-event merge tags; other node types accept their normal config fields.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:tY,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},delay:sY,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:aY,name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use stripe to dynamically create a Stripe coupon plus promotion code, or shopify to dynamically create a Shopify Admin discount code."},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"}},additionalProperties:!1};function fV(Q){if(!Q||typeof Q!=="object")return null;let Y=Q;if(Y.success!==!1)return null;if(typeof Y.error==="string")return Error(Y.error);if(Y.error&&typeof Y.error==="object"&&typeof Y.error.message==="string")return Error(Y.error.message);if(typeof Y.message==="string")return Error(Y.message);return Error("The tool returned an unsuccessful response.")}function J0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function XH(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function lV(Q){let Y=new URLSearchParams;if(typeof Q.query==="string"&&Q.query.trim()!=="")Y.set("query",Q.query.trim());if(Array.isArray(Q.tags)&&Q.tags.length>0)Y.set("tags",Q.tags.filter((X)=>typeof X==="string"&&X.trim()!=="").join(","));if(typeof Q.list==="string"&&Q.list.trim()!=="")Y.set("list",Q.list.trim());if(typeof Q.listId==="string"&&Q.listId.trim()!=="")Y.set("listId",Q.listId.trim());if(typeof Q.listName==="string"&&Q.listName.trim()!=="")Y.set("listName",Q.listName.trim());if(typeof Q.segmentId==="string"&&Q.segmentId.trim()!=="")Y.set("segmentId",Q.segmentId);if(typeof Q.status==="string"&&Q.status.trim()!=="")Y.set("status",Q.status.trim());return Y.set("page",String(Q.page)),Y.set("limit",String(Q.pageSize)),Y}async function mV(Q,Y){let X=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,W=Math.min(100,Math.max(1,X??100)),G=[],$=1,z=0,J=0,H=0;while(!0){let U=lV({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:$,pageSize:W}),K=await B("GET",`/api/v1/subscribers?${U.toString()}`,void 0,Y);z=K.pagination?.total??K.subscribers.length,J=K.pagination?.totalPages??1,H+=1,G.push(...K.subscribers??[]);let D=X!==void 0&&G.length>=X,L=K.pagination?$>=K.pagination.totalPages:(K.subscribers??[]).length<W;if(D||L)break;$+=1}let A=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:A,pagination:{page:1,limit:W,total:z,totalPages:J,fetchedPages:H},returned:A.length,truncated:X!==void 0&&z>0&&A.length<z}}function cV(Q){let Y=typeof Q.email==="string"&&Q.email.trim()!==""?Q.email.trim():void 0,X=typeof Q.externalId==="string"&&Q.externalId.trim()!==""?Q.externalId.trim():void 0;return{...Y?{email:Y}:{},...X?{externalId:X}:{}}}function v1(Q,Y){let X=cV(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function WX(Q,Y){let X=new URLSearchParams;if(Y?.includeMachineEngagement)X.set("includeMachineEngagement","true");let W=X.toString(),G=W?`?${W}`:"";if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}${G}`;return X.set("externalId",String(Q.externalId)),`/api/v1/subscribers/external?${X.toString()}`}function WH(Q){if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}/notes`;let Y=new URLSearchParams;return Y.set("externalId",String(Q.externalId)),`/api/v1/subscribers/external/notes?${Y.toString()}`}async function dY(Q,Y,X){return B("GET",WX(Q,X),void 0,Y)}function w(Q,Y){let X=Q[Y];if(typeof X!=="string")return;let W=X.trim();return W.length>0?W:void 0}function R(Q,Y,X){let W=w(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function m0(Q,Y,X,W){let G=w(Y,X);if(G===void 0)return;if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function oY(Q,Y,X,W){let G=R(Q,Y,X);if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function x1(Q,Y,X,W,G){let $=Y[X];if($===void 0)return;if(typeof $!=="number"||!Number.isInteger($)||$<W||$>G)throw Error(`\`${X}\` must be an integer between ${W} and ${G} when calling \`${Q}\`.`);return $}function pV(Q,Y){let X=[],W=m0(Q,Y,"eventType",cY);if(W)X.push(W);if(Y.eventTypes!==void 0){if(!Array.isArray(Y.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${Q}\`.`);Y.eventTypes.forEach((G,$)=>{if(typeof G!=="string")throw Error(`\`eventTypes\` item ${$+1} must be a string when calling \`${Q}\`.`);let z=G.trim();if(!cY.includes(z))throw Error(`\`eventTypes\` item ${$+1} must be one of ${cY.join(", ")} when calling \`${Q}\`.`);X.push(z)})}return[...new Set(X)]}function GH(Q,Y){let X=new URLSearchParams,W=pV(Q,Y);if(W.length>0)X.set("eventTypes",W.join(","));let G=m0(Q,Y,"period",["1h","24h","7d","30d","90d"]);if(G)X.set("period",G);let $=w(Y,"start");if($)X.set("start",$);let z=w(Y,"end");if(z)X.set("end",z);let J=x1(Q,Y,"page",1,1e6);if(J!==void 0)X.set("page",String(J));let H=x1(Q,Y,"limit",1,500);if(H!==void 0)X.set("limit",String(H));if(Y.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");return X}function $H(Q,Y){if(Y.events===void 0)return;if(!Array.isArray(Y.events))throw Error(`\`events\` must be an array when calling \`${Q}\`.`);let X=Y.events.map((W,G)=>{if(typeof W!=="string"||!PQ.includes(W))throw Error(`\`events\` item ${G+1} must be one of ${PQ.join(", ")} when calling \`${Q}\`.`);return W});if(X.length===0)throw Error(`\`events\` must include at least one event type when calling \`${Q}\`.`);return X}function zH(Q,Y){if(!Array.isArray(Y.emails))throw Error(`\`emails\` must be an array when calling \`${Q}\`.`);let X=[];if(Y.emails.forEach((W,G)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${Q}\`.`);let $=W.trim();if($.length>0)X.push($)}),X.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${Q}\`.`);if(X.length>o5)throw Error(`\`emails\` must include no more than ${o5} email addresses when calling \`${Q}\`. Split larger batches into multiple calls.`);return X}function JH(Q,Y,X,W){let G=Y[X];if(G===void 0)return;if(!Array.isArray(G))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`);let $=[];if(G.forEach((z,J)=>{if(typeof z!=="string")throw Error(`\`${X}\` item ${J+1} must be a string when calling \`${Q}\`.`);let H=z.trim();if(H.length>0)$.push(H)}),$.length===0)throw Error(`\`${X}\` must include at least one ${W} when calling \`${Q}\`.`);return $}function iV(Q){let X=JH("enroll_subscribers_in_sequence",Q,"emails","email address"),W=JH("enroll_subscribers_in_sequence",Q,"subscriberIds","subscriber ID"),G=(X?.length??0)+(W?.length??0);if(G===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(G>t5)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${t5} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let $=w(Q,"targetNodeId");return{...X!==void 0&&{emails:X},...W!==void 0&&{subscriberIds:W},...$!==void 0&&{targetNodeId:$}}}var nV={pdf:"application/pdf",epub:"application/epub+zip",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",txt:"text/plain",csv:"text/csv"};function rV(Q){let Y=Q.split(".").pop()?.toLowerCase()??"";return nV[Y]??null}var dV=104857600;async function oV(Q,Y){if(!OX())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let X=rV(Q);if(!X)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=JV(Q).size;if(W>dV)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=zV(Q),$=await B("POST","/api/v1/products/delivery/upload-url",{filename:HV(Q),contentType:X,fileSizeBytes:W},Y),z=await fetch($.uploadUrl,{method:"PUT",headers:{"Content-Type":X},body:G});if(!z.ok)throw Error(`File upload failed (${z.status})`);return{url:$.publicUrl,fileName:$.fileName,fileSizeBytes:W,mimeType:X}}async function JX(Q){let Y=w(Q,"companyId");if(Y)return Y;let X=b1();if(X)return X;try{return(await B("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function tV(Q,Y){let X=await JX(Y);if(!X)throw Error(`A company is required when calling \`${Q}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return X}function Y4(Q,Y){if(!J0(Q)||!Y)return Q;return{...Q,url:Y}}function HH(Q,Y){if(!J0(Q))return Q;return{...Q,...Y.campaign!==void 0&&{url:Y.campaign},...Y.campaignPreview!==void 0&&{previewUrl:Y.campaignPreview}}}function e4(Q,Y,X){if(!Array.isArray(Q)||!Y)return Q;return Q.map((W)=>{if(!J0(W))return W;let G=w(W,"id");if(!G)return W;let $=Z1({companyId:Y,...X==="campaign"&&{campaignId:G},...X==="landingPage"&&{landingPageId:G},...X==="sequence"&&{sequenceId:G},...X==="template"&&{emailId:G},...X==="transactional"&&{transactionalId:G}});if(X==="campaign")return HH(W,$.urls);let z=X==="sequence"?$.urls.sequence:X==="landingPage"?$.urls.landingPage:X==="template"?$.urls.email:$.urls.transactionalEmail;return Y4(W,z)})}function aV(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!J0(Y))return Y;let X=w(Y,"id");if(!X)return Y;let W=Z1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var AH=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","update_sequence","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function sV(Q,Y,X){if(!J0(X)||!AH.has(Q))return X;let W=J0(X.company)?X.company:void 0,$=w(X,"selectedCompanyId")??w(X,"currentCompanyId")??w(X,"companyId")??(W?w(W,"id"):void 0)??(W?w(W,"companyId"):void 0)??await JX(Y);if(!$)return X;let z=J0(X.campaign)?X.campaign:void 0,J=J0(X.sequence)?X.sequence:void 0,H=J0(X.landingPage)?X.landingPage:void 0,A=J0(X.template)?X.template:void 0,U=J0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,K={companyId:$,campaignId:w(Y,"campaignId")??w(X,"campaignId")??(z?w(z,"id"):void 0),landingPageId:w(Y,"landingPageId")??w(X,"landingPageId")??(H?w(H,"id"):void 0),sequenceId:w(Y,"sequenceId")??w(X,"sequenceId")??(J?w(J,"id"):void 0),emailId:w(X,"templateId")??(A?w(A,"id"):void 0)??(U?w(U,"emailId"):void 0)??w(Y,"templateId"),transactionalId:w(Y,"transactionalId")??(U?w(U,"id"):void 0)??w(Y,"idOrSlug"),emailSendId:w(Y,"emailSendId")??w(X,"emailSendId")??(J0(X.emailSend)?w(X.emailSend,"id"):void 0),status:w(Y,"status")},D=Z1(K),L=W?Z1({companyId:$}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:aV(X.companies)},...Array.isArray(X.campaigns)&&{campaigns:e4(X.campaigns,$,"campaign")},...Array.isArray(X.landingPages)&&{landingPages:e4(X.landingPages,$,"landingPage")},...Array.isArray(X.sequences)&&{sequences:e4(X.sequences,$,"sequence")},...Array.isArray(X.templates)&&{templates:e4(X.templates,$,"template")},...Array.isArray(X.transactional)&&{transactional:e4(X.transactional,$,"transactional")},...W&&L!==void 0&&{company:{...W,url:L.urls.dashboard,settingsUrl:L.urls.settings}},...z&&D.urls.campaign!==void 0&&{campaign:HH(z,D.urls)},...J&&D.urls.sequence!==void 0&&{sequence:Y4(J,D.urls.sequence)},...H&&D.urls.landingPage!==void 0&&{landingPage:Y4(H,D.urls.landingPage)},...A&&D.urls.email!==void 0&&{template:Y4(A,D.urls.email)},...U&&D.urls.transactionalEmail!==void 0&&{transactional:Y4(U,D.urls.transactionalEmail)},...J0(X.emailSend)&&D.urls.emailSend!==void 0&&{emailSend:Y4(X.emailSend,D.urls.emailSend)},appUrls:D.urls}}var eV={type:"boolean",description:"Whether the Sequenzy operation succeeded."},QZ={type:"string",description:"Human-readable status, confirmation, or next-step message."},YZ={type:"string",description:"Additional context about the result."};function W0(Q){return{type:"object",description:Q,additionalProperties:!0}}function XZ(Q){return{type:"array",description:Q,items:W0("One item in the returned collection.")}}function E(Q){return{type:"string",description:Q}}function b0(Q){return{type:"number",description:Q}}function d0(Q){return{type:"boolean",description:Q}}function V(Q){return W0(`The ${Q} record returned by Sequenzy.`)}function p(Q){return XZ(`List of ${Q} records returned by Sequenzy.`)}var WZ={appUrls:W0("Dashboard URLs for relevant Sequenzy resources."),url:E("Primary dashboard URL for this result."),settingsUrl:E("Company settings URL when available.")},GZ={success:eV,message:QZ,note:YZ,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:W0("One returned item.")},value:W0("Fallback object wrapper used only when a tool returns a non-object value.")},$Z={get_account:{account:V("account"),companies:p("company"),apiKeyPermissions:W0("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:E("Company ID selected by the authenticated API key, when available."),selectedCompanyId:E("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:E("Selected company ID."),companyName:E("Selected company name.")},get_app_urls:{dashboard:E("Company dashboard URL."),settings:E("Company settings URL."),campaign:E("Campaign editor URL."),landingPage:E("Landing page editor URL."),sequence:E("Sequence editor URL."),email:E("Email editor URL."),transactionalEmail:E("Transactional email URL."),emailSend:E("Sent email detail URL."),domain:E("Sending domain settings URL."),urls:W0("All generated URLs keyed by resource type.")},create_company:{company:V("company"),autoSelected:d0("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:V("company")},get_company:{company:V("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:W0("One sync rule.")},isDefault:d0("Whether the company still uses the platform default rules.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:W0("One sync rule.")},isDefault:d0("Whether the company now uses the platform default rules.")},get_shopify_automation_settings:{browseAbandonment:W0("Effective browse-abandonment settings (defaults applied)."),priceDrop:W0("Effective price-drop settings (defaults applied)."),shopDomain:E("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:W0("Effective browse-abandonment settings after the update."),priceDrop:W0("Effective price-drop settings after the update."),shopDomain:E("Connected Shopify store domain.")},create_api_key:{apiKey:W0("Created API key metadata: the newly created secret in `key`, plus `scopes` listing the assigned permission scopes (null when the key has full access)."),key:E("Newly created API key if the API response uses the short key field.")},list_websites:{websites:p("sender website")},add_website:{website:V("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},add_sending_domain:{website:V("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},check_website:{website:V("sender website"),ready:d0("Whether the sender website is ready."),status:E("Current processing or verification status.")},verify_sending_domain:{website:V("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:d0("Whether the sending domain passed the fresh verification check."),message:E("Verification result summary.")},get_integration_guide:{guide:V("integration guide"),code:E("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:W0("One setup step.")}},add_subscriber:{subscriber:V("subscriber")},update_subscriber:{subscriber:V("subscriber")},remove_subscriber:{subscriber:V("subscriber"),hardDeleted:d0("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:V("subscriber")},list_subscriber_notes:{notes:p("subscriber note")},add_subscriber_note:{note:V("subscriber note")},delete_subscriber_note:{id:E("Deleted subscriber note ID."),deleted:d0("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:p("subscriber"),pagination:W0("Pagination metadata."),returned:b0("Number of subscribers returned."),truncated:d0("Whether the result was truncated by the requested limit.")},list_products:{products:p("product")},upsert_products:{products:p("product"),created:b0("Number of products created."),updated:b0("Number of products updated.")},delete_product:{productId:E("Deleted product ID.")},attach_product_file:{product:V("product"),delivery:V("digital delivery file")},remove_product_file:{product:V("product")},sync_products:{job:V("product sync job"),jobId:E("Queued product sync job ID.")},list_tags:{tags:p("tag")},create_tag:{tag:V("tag")},update_tag:{tag:V("tag")},delete_tag:{tagId:E("Deleted tag ID.")},list_lists:{lists:p("list")},create_list:{list:V("list")},update_list:{list:V("list")},delete_list:{listId:E("Deleted list ID.")},add_subscribers_to_list:{list:V("list"),added:b0("Number of subscribers added to the list."),skipped:b0("Number of subscribers skipped.")},remove_subscribers_from_list:{list:V("list"),removed:b0("Number of subscribers removed from the list."),skipped:b0("Number of subscribers skipped.")},list_segments:{segments:p("segment")},create_segment:{segment:V("segment")},update_segment:{segment:V("segment")},delete_segment:{segmentId:E("Deleted segment ID.")},get_segment_count:{count:b0("Number of subscribers matching the segment."),segmentId:E("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:p("audience sync")},list_ad_accounts:{adAccounts:p("ad account")},create_audience_sync:{audienceSync:V("audience sync")},update_audience_sync:{audienceSync:V("audience sync")},delete_audience_sync:{audienceSyncId:E("Deleted audience sync ID.")},sync_audience_now:{audienceSync:V("audience sync"),job:V("audience sync job"),jobId:E("Queued audience sync job ID.")},list_templates:{templates:p("email template")},get_template:{template:V("email template")},create_template:{template:V("email template")},update_template:{template:V("email template")},delete_template:{templateId:E("Deleted template ID.")},list_ab_tests:{abTests:p("A/B test")},get_ab_test:{abTest:V("A/B test")},get_ab_test_stats:{abTest:V("A/B test"),stats:V("A/B test statistics")},restart_ab_test:{abTest:V("A/B test")},update_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},create_ab_test:{abTest:V("A/B test")},add_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},delete_ab_test_variant:{abTest:V("A/B test"),variantId:E("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:E("Deleted A/B test ID.")},list_campaigns:{campaigns:p("campaign")},get_campaign:{campaign:V("campaign")},get_email_send:{emailSend:V("email send")},create_campaign:{campaign:V("campaign")},update_campaign:{campaign:V("campaign")},schedule_campaign:{campaign:V("campaign"),scheduledAt:E("Scheduled send timestamp.")},send_test_email:{emailSend:V("test email send"),recipient:E("Test email recipient.")},send_test_sms:{smsSendId:E("Created test SMS send ID."),toPhone:E("Normalized E.164 destination phone.")},cancel_campaign:{campaign:V("campaign")},pause_campaign:{campaign:V("campaign")},resume_campaign:{campaign:V("campaign")},delete_campaign:{campaignId:E("Deleted campaign ID.")},duplicate_campaign:{campaign:V("duplicated campaign")},resend_campaign_to_non_openers:{campaign:V("non-opener resend draft campaign"),estimatedNonOpenerCount:b0("Estimated number of subscribers who haven't opened the original campaign.")},list_landing_pages:{landingPages:p("landing page")},get_landing_page:{landingPage:V("landing page")},create_landing_page:{landingPage:V("landing page")},update_landing_page:{landingPage:V("landing page")},delete_landing_page:{landingPageId:E("Deleted landing page ID.")},publish_landing_page:{landingPage:V("landing page")},unpublish_landing_page:{landingPage:V("landing page")},connect_landing_page_domain:{landingPage:V("landing page"),domain:E("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:V("landing page"),domain:E("Landing page domain.")},list_sequences:{sequences:p("sequence")},get_sequence:{sequence:V("sequence")},create_sequence:{sequence:V("sequence")},update_sequence:{sequence:V("sequence")},insert_sequence_step:{sequence:V("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for the inserted step, including any delay node.",items:E("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:E("Inserted email template ID.")},insertedEmailCount:b0("Number of email steps inserted.")},enable_sequence:{sequence:V("sequence")},disable_sequence:{sequence:V("sequence")},pause_sequence_enrollments:{sequenceId:E("Sequence ID."),enrollmentPaused:d0("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:E("Sequence ID."),enrollmentPaused:d0("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:V("sequence"),enrollments:p("sequence enrollment"),enrolled:b0("Number of subscribers enrolled."),skipped:b0("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:V("sequence"),cancelled:b0("Number of enrollments cancelled."),skipped:b0("Number of enrollments skipped.")},delete_sequence:{sequenceId:E("Deleted sequence ID.")},list_transactional_emails:{transactional:p("transactional email")},get_transactional_email:{transactional:V("transactional email")},create_transactional_email:{transactional:V("transactional email")},update_transactional_email:{transactional:V("transactional email")},send_email:{emailSend:V("transactional email send"),transactional:V("transactional email")},get_stats:{stats:V("account or company statistics")},get_campaign_stats:{campaign:V("campaign"),stats:V("campaign statistics")},get_sequence_stats:{sequence:V("sequence"),stats:V("sequence statistics")},list_campaign_events:{events:p("campaign email event"),pagination:W0("Pagination metadata.")},list_sequence_events:{events:p("sequence email event"),pagination:W0("Pagination metadata.")},get_subscriber_activity:{activity:p("subscriber activity event"),subscribers:p("subscriber"),pagination:W0("Pagination metadata.")},list_team_members:{members:p("team member"),invitations:p("team invitation")},invite_team_member:{invitation:V("team invitation")},cancel_team_invitation:{invitationId:E("Cancelled invitation ID.")},list_conversations:{conversations:p("inbox conversation"),pagination:W0("Pagination metadata.")},get_conversation:{conversation:V("inbox conversation"),messages:p("conversation message")},reply_to_conversation:{conversation:V("inbox conversation"),message:V("conversation message")},update_conversation_status:{conversation:V("inbox conversation")},mark_conversation_read:{conversation:V("inbox conversation")},list_webhooks:{webhooks:p("outbound webhook")},create_webhook:{webhook:V("outbound webhook")},update_webhook:{webhook:V("outbound webhook")},delete_webhook:{webhookId:E("Deleted outbound webhook ID.")},test_webhook:{webhook:V("outbound webhook"),delivery:V("test webhook delivery")},list_webhook_deliveries:{deliveries:p("webhook delivery")},replay_webhook_delivery:{delivery:V("webhook delivery"),job:V("webhook replay job")},generate_email:{email:V("generated email"),html:E("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:W0("One generated email block.")},subject:E("Generated subject line."),previewText:E("Generated inbox preview text.")},generate_sequence:{sequence:V("generated sequence"),steps:p("generated sequence step")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:E("One generated subject line.")},variants:p("generated subject line variant")},generate_sms:{prompt:E("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:W0("One generated SMS message.")}},get_sms_settings:{sms:W0("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{}};function zZ(Q){let Y=$Z[Q];if(Y===void 0)throw Error(`MCP tool "${Q}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${Q}\` MCP tool.`,properties:{...GZ,...Y,...AH.has(Q)?WZ:{}},additionalProperties:!0}}function JZ(Q){return{...Q,outputSchema:zZ(Q.name)}}function HZ(Q){if(J0(Q))return Q;if(Array.isArray(Q))return{items:Q};return{value:Q}}var AZ=[{name:"get_account",description:`Get current account information including available companies, the current API key's permission scopes, and the API Keys management URL. Call this after a missing-scope error to inspect access and find the replacement-key settings. IMPORTANT: If you have access to multiple companies, you MUST either:
|
|
30
30
|
1. Call select_company first to choose which company to work with, OR
|
|
31
31
|
2. Pass companyId explicitly in each tool call
|
|
32
32
|
|
|
33
|
-
The response shows 'companies' (all available) and 'selectedCompanyId' (currently active). All subsequent operations will use the selected company unless you pass a companyId override.`,inputSchema:{type:"object",properties:{}}},{name:"select_company",description:"Select which company to operate on (for user-scoped API keys with access to multiple companies). Use get_account to see available companies. After selecting, all subsequent operations will use this company unless you pass a companyId override.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"The company ID to select (from get_account's companies list)"}},required:["companyId"]}},{name:"get_app_urls",description:"Generate Sequenzy dashboard URLs for known resource IDs. Use this when the user asks where to review or edit a generated sequence, campaign, template, or company settings. If companyId is omitted, the selected/current company is used when available.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If omitted, uses the selected/current company when available."},campaignId:{type:"string",description:"Campaign ID for the campaign editor URL."},landingPageId:{type:"string",description:"Landing page ID for the landing page editor URL."},sequenceId:{type:"string",description:"Sequence ID for the sequence editor URL."},templateId:{type:"string",description:"Template/email ID for the email editor URL."},emailId:{type:"string",description:"Email ID for the email editor URL."},transactionalId:{type:"string",description:"Transactional email ID."},emailSendId:{type:"string",description:"Email send ID for the sent email detail URL."},domainId:{type:"string",description:"Sending domain ID."},status:{type:"string",description:"Status for campaign/sequence list URLs."},settingsTab:{type:"string",description:"Settings tab slug, e.g. integrations, domain, tracking, api-keys, team."}}}},{name:"create_company",description:"Create a new company/brand. This will parse your website to extract brand information. The tool polls every 20 seconds until the company is fully processed (typically 30-60 seconds).",inputSchema:{type:"object",properties:{name:{type:"string",description:"Company name (optional, will be extracted from domain if not provided)"},domain:{type:"string",description:"The company's website domain (e.g., example.com)"}},required:["domain"]}},{name:"get_company",description:"Get company details, processing status, product info, brand colors, AI writing context, and effective email localization settings",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"The company ID to check"}},required:["companyId"]}},{name:"update_company",description:"Edit company product info, brand context, and account-wide sending identity defaults. fromEmail must use a verified sending domain; replyTo may be any valid mailbox. Missing sender/reply profiles are created automatically. Provide at least one editable field.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If omitted, uses the selected/current company when available."},name:{type:"string",description:"Company display name."},description:{type:"string",description:"Short product or company summary for AI writing context."},logoUrl:{type:"string",description:"Public logo URL."},founderName:{type:"string",description:"Founder or sender name for personal email signatures."},primaryColor:{type:"string",description:"Primary brand color as a 6-digit hex value, e.g. #f97316."},brandColors:{type:"object",description:"Stored brand color object. Prefer primaryColor for the main color.",additionalProperties:!0},valueProps:{type:"array",description:"Value propositions, usually objects with title and description.",items:{type:"object",additionalProperties:!0}},testimonials:{type:"array",description:"Testimonials, usually objects with quote/text and author.",items:{type:"object",additionalProperties:!0}},toneVoice:{type:"string",description:"Tone of voice guidance for AI-written content."},companyContext:{type:"string",description:"Basic product/company knowledge AI should use when writing emails."},emailLengthPreference:{type:"string",description:"Email length preference: concise, balanced, or detailed."},socialLinks:{type:"object",description:"Social profile URLs keyed by platform.",additionalProperties:{type:"string"}},privacyPolicyUrl:{type:"string",description:"Privacy policy URL."},termsUrl:{type:"string",description:"Terms of service URL."},address:{type:"string",description:"Physical mailing address for email footers."},language:{type:"string",description:"Primary language code, e.g. en, es, de."},pricing:{type:"object",description:"Pricing information used as product context.",additionalProperties:!0},fontFamily:{type:"string",description:"Default email font family stack."},emailDirection:{type:"string",description:"Default email text direction: ltr or rtl."},fromEmail:{type:"string",description:"Set the account-wide default From address. Its domain must already be configured and verified."},fromName:{type:"string",description:"Display name for a newly created default From profile. Requires fromEmail."},replyTo:{type:"string",description:"Set the account-wide default Reply-To address. Creates a reply profile when needed."},replyToName:{type:"string",description:"Display name for a newly created default Reply-To profile. Requires replyTo."}}}},{name:"get_shopify_automation_settings",description:"Get the connected Shopify store's automation settings: browse abandonment (emails shoppers who viewed a product but didn't buy) and price drop alerts (emails recent viewers when a product's price falls). Returns the effective values with platform defaults applied.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"update_shopify_automation_settings",description:"Update the connected Shopify store's browse-abandonment and/or price-drop automation settings. Partial update: omitted sections are untouched, omitted fields within a section keep their current value, and passing null for a section resets it to the platform defaults (browse abandonment: on, 2h delay, 24h cooldown; price drop: on, 5% minimum drop, 30-day viewer lookback, 7-day cooldown).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},browseAbandonment:{type:["object","null"],description:"Browse abandonment settings, or null to reset to defaults.",properties:{enabled:{type:"boolean"},delayHours:{type:"number",description:"Hours to wait after a product view before checking for abandonment (default 2)."},cooldownHours:{type:"number",description:"Minimum hours between browse-abandoned events per subscriber (default 24)."}},additionalProperties:!1},priceDrop:{type:["object","null"],description:"Price drop settings, or null to reset to defaults.",properties:{enabled:{type:"boolean"},minPercent:{type:"number",description:"Minimum price decrease percent to alert on (default 5)."},lookbackDays:{type:"number",description:"How many days back product viewers qualify as the audience (default 30)."},cooldownDays:{type:"number",description:"Minimum days between price-drop events per subscriber and product (default 7)."}},additionalProperties:!1}},additionalProperties:!1}},{name:"get_sync_rules",description:"Get the company's sync rules: the automatic tag changes applied when events fire (e.g. order placed -> add a tag). Returns the effective rules plus isDefault, which is true while the company still uses the platform defaults.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"update_sync_rules",description:"Replace the company's sync rules. Pass the FULL rule set (fetch with get_sync_rules first and edit it - this is not a partial update), or null to reset to the platform defaults. Each rule: { triggerEvent, actions: { addTags, removeTags }, conditions? }. Conditions support requiresTags, requiresNotTags, and purchasedProduct ({ tags?, collectionIds?, productTypes?, vendors? }) which matches products on commerce events - e.g. tag buyers of products carrying a given product tag.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncRules:{type:["array","null"],description:"Full replacement rule set, or null to reset to the platform defaults.",items:{type:"object",properties:{triggerEvent:{type:"string",description:"Event name that triggers the rule, e.g. ecommerce.order_placed or saas.purchase."},actions:{type:"object",properties:{addTags:{type:"array",items:{type:"string"}},removeTags:{type:"array",items:{type:"string"}}},required:["addTags","removeTags"],additionalProperties:!1},conditions:{type:"object",properties:{requiresTags:{type:"array",items:{type:"string"},description:"Rule only applies if the subscriber has ALL of these tags."},requiresNotTags:{type:"array",items:{type:"string"},description:"Rule only applies if the subscriber has NONE of these tags."},purchasedProduct:{type:"object",description:"For commerce events with product context: rule only applies when a product on the event matches every specified selector.",properties:{tags:{type:"array",items:{type:"string"}},collectionIds:{type:"array",items:{type:"string"}},productTypes:{type:"array",items:{type:"string"}},vendors:{type:"array",items:{type:"string"}}},additionalProperties:!1}},additionalProperties:!1}},required:["triggerEvent","actions"],additionalProperties:!1}}},required:["syncRules"],additionalProperties:!1}},{name:"create_api_key",description:"Create a new API key for a company. Use this when setting up Sequenzy integration in a project. The returned key should be saved to the project's .env file as SEQUENZY_API_KEY. The key can only be retrieved once at creation time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the key for"},name:{type:"string",description:"Optional name for the API key (e.g., 'Production', 'Development')"},preset:{type:"string",description:"Optional permission preset. Supported values: full_access, read_only, agent_safe, ai_drafting, data_ingest_safe, data_ingest_automations, transactional_sender, marketing_sender. Defaults to full_access when both preset and scopes are omitted; prefer agent_safe when creating a key for an AI agent."},scopes:{type:"array",description:"Optional explicit API key permission scopes. If provided, this overrides preset and must include at least one supported scope.",items:{type:"string"}}},required:["companyId"]}},{name:"list_websites",description:"List configured sending domains with stored aggregate, SPF, DKIM, and MAIL FROM verification status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},label:{type:"string",description:"Optional label name filter. Only templates assigned this label are returned."}}}},{name:"add_website",description:"Add a new sender website. Takes ~30 seconds to process.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"The domain to add (e.g., example.com)"}},required:["domain"]}},{name:"check_website",description:"Read a sending domain's stored aggregate status plus SPF, DKIM, MAIL FROM records and diagnostics. Use verify_sending_domain to run a fresh DNS check.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"The domain to check"}},required:["domain"]}},{name:"verify_sending_domain",description:"Run a fresh DNS/provider verification for a configured sending domain and return current aggregate, SPF, DKIM, and MAIL FROM status with diagnostics.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Configured sending domain to verify."}},required:["domain"]}},{name:"get_integration_guide",description:`Get code examples for integrating Sequenzy into your project.
|
|
33
|
+
The response shows 'companies' (all available) and 'selectedCompanyId' (currently active). All subsequent operations will use the selected company unless you pass a companyId override.`,inputSchema:{type:"object",properties:{}}},{name:"select_company",description:"Select which company to operate on (for user-scoped API keys with access to multiple companies). Use get_account to see available companies. After selecting, all subsequent operations will use this company unless you pass a companyId override.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"The company ID to select (from get_account's companies list)"}},required:["companyId"]}},{name:"get_app_urls",description:"Generate Sequenzy dashboard URLs for known resource IDs. Use this when the user asks where to review or edit a generated sequence, campaign, template, or company settings. If companyId is omitted, the selected/current company is used when available.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If omitted, uses the selected/current company when available."},campaignId:{type:"string",description:"Campaign ID for the campaign editor URL."},landingPageId:{type:"string",description:"Landing page ID for the landing page editor URL."},sequenceId:{type:"string",description:"Sequence ID for the sequence editor URL."},templateId:{type:"string",description:"Template/email ID for the email editor URL."},emailId:{type:"string",description:"Email ID for the email editor URL."},transactionalId:{type:"string",description:"Transactional email ID."},emailSendId:{type:"string",description:"Email send ID for the sent email detail URL."},domainId:{type:"string",description:"Sending domain ID."},status:{type:"string",description:"Status for campaign/sequence list URLs."},settingsTab:{type:"string",description:"Settings tab slug, e.g. integrations, domain, tracking, api-keys, team."}}}},{name:"create_company",description:"Create a new company/brand. This will parse your website to extract brand information. The tool polls every 20 seconds until the company is fully processed (typically 30-60 seconds).",inputSchema:{type:"object",properties:{name:{type:"string",description:"Company name (optional, will be extracted from domain if not provided)"},domain:{type:"string",description:"The company's website domain (e.g., example.com)"}},required:["domain"]}},{name:"get_company",description:"Get company details, processing status, product info, brand colors, AI writing context, and effective email localization settings",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"The company ID to check"}},required:["companyId"]}},{name:"update_company",description:"Edit company product info, brand context, and account-wide sending identity defaults. fromEmail must use a verified sending domain; replyTo may be any valid mailbox. Missing sender/reply profiles are created automatically. Provide at least one editable field.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If omitted, uses the selected/current company when available."},name:{type:"string",description:"Company display name."},description:{type:"string",description:"Short product or company summary for AI writing context."},logoUrl:{type:"string",description:"Public logo URL."},founderName:{type:"string",description:"Founder or sender name for personal email signatures."},primaryColor:{type:"string",description:"Primary brand color as a 6-digit hex value, e.g. #f97316."},brandColors:{type:"object",description:"Stored brand color object. Prefer primaryColor for the main color.",additionalProperties:!0},valueProps:{type:"array",description:"Value propositions, usually objects with title and description.",items:{type:"object",additionalProperties:!0}},testimonials:{type:"array",description:"Testimonials, usually objects with quote/text and author.",items:{type:"object",additionalProperties:!0}},toneVoice:{type:"string",description:"Tone of voice guidance for AI-written content."},companyContext:{type:"string",description:"Basic product/company knowledge AI should use when writing emails."},emailLengthPreference:{type:"string",description:"Email length preference: concise, balanced, or detailed."},socialLinks:{type:"object",description:"Social profile URLs keyed by platform.",additionalProperties:{type:"string"}},privacyPolicyUrl:{type:"string",description:"Privacy policy URL."},termsUrl:{type:"string",description:"Terms of service URL."},address:{type:"string",description:"Physical mailing address for email footers."},language:{type:"string",description:"Primary language code, e.g. en, es, de."},pricing:{type:"object",description:"Pricing information used as product context.",additionalProperties:!0},fontFamily:{type:"string",description:"Default email font family stack."},emailDirection:{type:"string",description:"Default email text direction: ltr or rtl."},fromEmail:{type:"string",description:"Set the account-wide default From address. Its domain must already be configured and verified."},fromName:{type:"string",description:"Display name for a newly created default From profile. Requires fromEmail."},replyTo:{type:"string",description:"Set the account-wide default Reply-To address. Creates a reply profile when needed."},replyToName:{type:"string",description:"Display name for a newly created default Reply-To profile. Requires replyTo."}}}},{name:"get_shopify_automation_settings",description:"Get the connected Shopify store's automation settings: browse abandonment (emails shoppers who viewed a product but didn't buy) and price drop alerts (emails recent viewers when a product's price falls). Returns the effective values with platform defaults applied.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"update_shopify_automation_settings",description:"Update the connected Shopify store's browse-abandonment and/or price-drop automation settings. Partial update: omitted sections are untouched, omitted fields within a section keep their current value, and passing null for a section resets it to the platform defaults (browse abandonment: on, 2h delay, 24h cooldown; price drop: on, 5% minimum drop, 30-day viewer lookback, 7-day cooldown).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},browseAbandonment:{type:["object","null"],description:"Browse abandonment settings, or null to reset to defaults.",properties:{enabled:{type:"boolean"},delayHours:{type:"number",description:"Hours to wait after a product view before checking for abandonment (default 2)."},cooldownHours:{type:"number",description:"Minimum hours between browse-abandoned events per subscriber (default 24)."}},additionalProperties:!1},priceDrop:{type:["object","null"],description:"Price drop settings, or null to reset to defaults.",properties:{enabled:{type:"boolean"},minPercent:{type:"number",description:"Minimum price decrease percent to alert on (default 5)."},lookbackDays:{type:"number",description:"How many days back product viewers qualify as the audience (default 30)."},cooldownDays:{type:"number",description:"Minimum days between price-drop events per subscriber and product (default 7)."}},additionalProperties:!1}},additionalProperties:!1}},{name:"get_sync_rules",description:"Get the company's sync rules: the automatic tag changes applied when events fire (e.g. order placed -> add a tag). Returns the effective rules plus isDefault, which is true while the company still uses the platform defaults.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"update_sync_rules",description:"Replace the company's sync rules. Pass the FULL rule set (fetch with get_sync_rules first and edit it - this is not a partial update), or null to reset to the platform defaults. Each rule: { triggerEvent, actions: { addTags, removeTags }, conditions? }. Conditions support requiresTags, requiresNotTags, and purchasedProduct ({ tags?, collectionIds?, productTypes?, vendors? }) which matches products on commerce events - e.g. tag buyers of products carrying a given product tag.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncRules:{type:["array","null"],description:"Full replacement rule set, or null to reset to the platform defaults.",items:{type:"object",properties:{triggerEvent:{type:"string",description:"Event name that triggers the rule, e.g. ecommerce.order_placed or saas.purchase."},actions:{type:"object",properties:{addTags:{type:"array",items:{type:"string"}},removeTags:{type:"array",items:{type:"string"}}},required:["addTags","removeTags"],additionalProperties:!1},conditions:{type:"object",properties:{requiresTags:{type:"array",items:{type:"string"},description:"Rule only applies if the subscriber has ALL of these tags."},requiresNotTags:{type:"array",items:{type:"string"},description:"Rule only applies if the subscriber has NONE of these tags."},purchasedProduct:{type:"object",description:"For commerce events with product context: rule only applies when a product on the event matches every specified selector.",properties:{tags:{type:"array",items:{type:"string"}},collectionIds:{type:"array",items:{type:"string"}},productTypes:{type:"array",items:{type:"string"}},vendors:{type:"array",items:{type:"string"}}},additionalProperties:!1}},additionalProperties:!1}},required:["triggerEvent","actions"],additionalProperties:!1}}},required:["syncRules"],additionalProperties:!1}},{name:"create_api_key",description:"Create a new API key for a company. Use this when setting up Sequenzy integration in a project. The returned key should be saved to the project's .env file as SEQUENZY_API_KEY. The key can only be retrieved once at creation time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the key for"},name:{type:"string",description:"Optional name for the API key (e.g., 'Production', 'Development')"},preset:{type:"string",description:"Optional permission preset. Supported values: full_access, read_only, agent_safe, ai_drafting, data_ingest_safe, data_ingest_automations, transactional_sender, marketing_sender. Defaults to full_access when both preset and scopes are omitted; prefer agent_safe when creating a key for an AI agent."},scopes:{type:"array",description:"Optional explicit API key permission scopes. If provided, this overrides preset and must include at least one supported scope.",items:{type:"string"}}},required:["companyId"]}},{name:"list_websites",description:"List configured sending domains with stored aggregate, SPF, DKIM, and MAIL FROM verification status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},label:{type:"string",description:"Optional label name filter. Only templates assigned this label are returned."}}}},{name:"add_sending_domain",description:"Add and configure a sending domain. Returns the SPF, DKIM, MAIL FROM, and inbound DNS records to publish before calling verify_sending_domain.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Sending domain to add (for example, mail.example.com)."}},required:["domain"]}},{name:"add_website",description:"Compatibility alias for add_sending_domain. Adds a sending domain and returns the DNS records required for setup.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"The domain to add (e.g., example.com)"}},required:["domain"]}},{name:"check_website",description:"Read a sending domain's stored aggregate status plus SPF, DKIM, MAIL FROM records and diagnostics. Use verify_sending_domain to run a fresh DNS check.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"The domain to check"}},required:["domain"]}},{name:"verify_sending_domain",description:"Run a fresh DNS/provider verification for a configured sending domain and return current aggregate, SPF, DKIM, and MAIL FROM status with diagnostics.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Configured sending domain to verify."}},required:["domain"]}},{name:"get_integration_guide",description:`Get code examples for integrating Sequenzy into your project.
|
|
34
34
|
|
|
35
35
|
CRITICAL - FOR SAAS/SUBSCRIPTION APPS:
|
|
36
36
|
If the app uses Stripe, Polar, Paddle, Dodo, or Creem - tell the user to connect it in Sequenzy dashboard (Settings → Integrations).
|
|
@@ -187,7 +187,7 @@ BUILT-IN EVENTS (auto-fired by payment integrations):
|
|
|
187
187
|
|
|
188
188
|
OTHER BUILT-IN EVENTS:
|
|
189
189
|
- email.opened, email.clicked, email.replied, email.bounced, email.unsubscribed
|
|
190
|
-
- 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."},fromEmail:{type:"string",description:"From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Reply-To address for all emails in this sequence. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},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)"},durationDays:{type:"number",description:"Total duration in days used to space AI-generated sequence emails. Only applies when using goal-based AI generation."},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:a5,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, use type: 'sms' for SMS, type: 'create_discount' for a dynamic discount, or type: 'update_subscriber' with nodeType: 'action_update_attributes' and config to copy trigger-event values such as {{event.plan}} into subscriber data.",items:{type:"object",properties:{type:{type:"string",enum:["email","sms","create_discount","discount","update_subscriber"],description:"Step type. Omit or use 'email' for email content. Use 'sms' to send a text message, 'create_discount' to generate a code, or 'update_subscriber' to copy trigger data into the subscriber."},nodeType:{type:"string",enum:["action_email","action_sms","action_create_discount","action_update_attributes"],description:"Internal step type. Use action_update_attributes with config for Update Subscriber steps."},config:XX,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:tY,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:sY,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:aY,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","shopify"],description:"Discount provider. Use 'stripe' to dynamically create a Stripe coupon plus promotion code, or 'shopify' to dynamically create a Shopify Admin discount code. Defaults to 'stripe' when omitted."},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:"Discount 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:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. 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 display name for each dynamically generated provider discount."}}},label:{type:"string",description:"Legacy top-level discount label. Prefer discount.label."},provider:{type:"string",enum:["stripe","shopify"],description:"Legacy top-level discount provider. Prefer discount.provider. Supports 'stripe' and 'shopify'."},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:"Discount 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:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. 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 existing step, use IDs returned by get_sequence. The emails/steps arrays edit email steps, smsSteps edits SMS steps, and subscriberUpdateSteps replaces the config of action_update_attributes steps. To insert new linear steps, use insertSteps with an afterNodeId from get_sequence; omit afterNodeId only to append to an unambiguous linear tail. For active sequences, structural changes such as insertSteps or branch require confirmStructuralChange:true after the user confirms the live-flow impact.",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"},fromEmail:{type:"string",description:"Set the From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Set the Reply-To address for all emails in this sequence."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Set an existing reply profile. Mutually exclusive with replyTo."},enrollmentPaused:{type:"boolean",description:"Set true to stop new enrollments for an active sequence while current recipients continue. Set false to resume new enrollments. The sequence must already be active."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence. Required for insertSteps or branch when the sequence is active; not needed for content-only email edits."},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:a5,clearSendingWindow:{type:"boolean",description:"Set true to remove the sequence sending window. Do not provide this together with sendingWindow."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses that receive a blind copy of every email this sequence sends, such as a customer support inbox (max 10). Omit to leave unchanged. Use clearBccEmails to remove them."},clearBccEmails:{type:"boolean",description:"Set true to remove the sequence BCC addresses. Do not provide this together with bccEmails."},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 tag presence/absence, 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","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"],description:"Condition type for this branch. has_phone (contact has a phone number) and sms_subscribed (contact opted in to SMS marketing) need no extra fields."},tagName:{type:"string",description:"Tag name for has_tag and does_not_have_tag conditions. This can be used instead of tagId."},tagId:{type:"string",description:"Tag ID or tag name for has_tag and does_not_have_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:rY}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:rY},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"]},insertSteps:{type:"object",description:"Insert one or more new linear steps into an existing sequence. Use get_sequence first, then pass afterNodeId to insert after a specific node. If afterNodeId is omitted, the steps are appended only when the sequence has exactly one linear tail. Inserted email steps require subject plus blocks or html.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},steps:{type:"array",description:"New steps to insert. Supports emails, delays, create_discount actions, webhooks, and other supported sequence path node types.",items:rY}},required:["steps"]},emails:{type:"array",description:"Updated existing sequence emails. If you omit emailId/nodeId, items are matched by existing step order. This field does not create new steps; use insertSteps for insertion and include delay on inserted email steps when a timer is needed.",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. Stored as one raw HTML block. Use this to preserve imported provider HTML."},htmlContent:{type:"string",description:"Alias for html. Stored as one raw HTML block. Use this when updating imported provider HTML for a step."},blocks:{type:"array",description:Q4,items:{type:"object"}}}}},steps:{type:"array",description:"Alias for emails. Supports the same fields and matching rules, and only edits existing email steps. Use insertSteps to create new steps.",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. Stored as one raw HTML block. Use this to preserve imported provider HTML."},htmlContent:{type:"string",description:"Alias for html. Stored as one raw HTML block. Use this when updating HTML content for a step."},blocks:{type:"array",description:Q4,items:{type:"object"}}}}},smsSteps:{type:"array",description:"Content updates for existing SMS steps, targeted by nodeId (an action_sms node from get_sequence.sequence.nodes). Content-only edits - use insertSteps to create new SMS steps.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_sms node ID. Required."},text:{type:"string",description:"Replacement plain-text message body. Merge tags like {{FIRST_NAME}} work. Provide text or blocks, not both."},blocks:{type:"array",items:{type:"object"},description:"Replacement SMS content blocks (text + image subset)."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable MMS image URLs. Only valid together with text."},label:{type:"string",description:"Updated display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"Updated behavior when the contact can't receive SMS."}},required:["nodeId"]}},subscriberUpdateSteps:{type:"array",description:"Full config replacements for existing Update Subscriber steps, targeted by action_update_attributes nodeId.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_update_attributes node ID."},config:XX},required:["nodeId","config"]}}},required:["sequenceId"]}},{name:"insert_sequence_step",description:"Insert one new email or SMS step into an existing sequence. Prefer this over update_sequence.steps/emails when adding a step: it creates the step node (plus an email template for email steps) and, when delay or delayMs is provided, a logic_delay node immediately before it. For SMS steps set type:'sms' and provide 'text' (generate copy with generate_sms; check get_sms_settings first and warn the user if SMS is not enabled). Use get_sequence first, then pass afterNodeId from sequence.nodes or sequence.emails to choose the insertion point. If afterNodeId is omitted, the step is appended only when the sequence has exactly one linear tail. For active sequences, set confirmStructuralChange:true only after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},type:{type:"string",enum:["email","sms"],description:"Step type. Defaults to 'email'. Use 'sms' to insert an SMS step (requires 'text')."},afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."},name:{type:"string",description:"Optional email template and step name."},subject:{type:"string",description:"Email subject for the new step. Required for email steps; not used for SMS steps."},previewText:{type:"string",description:"Optional email preview text for the new step."},blocks:{type:"array",description:tY,items:{type:"object"}},html:{type:"string",description:"HTML content for the new step. Stored as one raw HTML block. Use this for imported provider HTML. Provide either html or blocks, not both."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},label:{type:"string",description:"SMS steps only: display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:sY,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:aY},required:["sequenceId"],additionalProperties:!1}},{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/freeze a sequence. This blocks new enrollments and holds current recipients until the sequence is enabled again. To only stop new enrollments while current recipients continue, use pause_sequence_enrollments.",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:"pause_sequence_enrollments",description:"Stop new enrollments for an active sequence while current recipients continue through the sequence. This matches the dashboard 'Stop new enrollments' control and does not freeze current recipients.",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:"resume_sequence_enrollments",description:"Resume new enrollments for an active sequence whose enrollment gate was paused. Use enable_sequence instead for a fully disabled/frozen 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. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup.",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`. Sequenzy stores it as one raw HTML block."},blocks:{type:"array",description:`${s4} Mutually exclusive with \`html\`.`,items:{type:"object"}},prompt:{type:"string",description:"Generate transactional email blocks from a prompt. Generated blocks include the company's branding (logo and a footer without an unsubscribe link). 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. Prompt-created templates default to false; explicit HTML/blocks retain the compatibility default of 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`. Sequenzy stores it as one raw HTML block."},blocks:{type:"array",description:`${Q4} 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)"},includeMachineEngagement:N1}}},{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"},includeMachineEngagement:N1},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"},includeMachineEngagement:N1},required:["sequenceId"]}},{name:"list_campaign_events",description:"List paginated raw email events for a campaign. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},eventType:{type:"string",description:"Optional single event type. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery."},eventTypes:{type:"array",description:"Optional event types to include. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery.",items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:N1},required:["campaignId"]}},{name:"list_sequence_events",description:"List paginated raw email events for every email step in a sequence. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},eventType:{type:"string",description:"Optional single event type. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery."},eventTypes:{type:"array",description:"Optional event types to include. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery.",items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:N1},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."},includeMachineEngagement:N1},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, viewer, or restricted. 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 and is not available for restricted members.",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","restricted"],description:"Team role. Admins can manage the workspace; viewers have read-only access; restricted members can open direct campaign links only."},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:[...PQ]},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:[...PQ]},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. Generated blocks include the company's branding chrome (logo, footer with company name/address/unsubscribe) by default, matching emails created in the dashboard.",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"},applyBranding:{type:"boolean",description:"Wrap the generated content with company branding (logo + footer). Defaults to true; set false to get raw content blocks only."},emailType:{type:"string",enum:["marketing","transactional"],description:"Email type. Transactional emails get a footer without the unsubscribe link. Defaults to marketing."}},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"]}},{name:"generate_sms",description:"Generate SMS marketing message variants from a prompt. Returns plain-text messages with per-message encoding and segment counts. Use the results as the 'text' of an SMS sequence step (insert_sequence_step with type 'sms' or a create_sequence sms step). Messages exclude opt-out footers and brand prefixes - the platform adds those automatically at send time.",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 SMS to generate (e.g., 'cart reminder with a free-shipping hook')"},count:{type:"number",description:"Number of message variants to generate (default: 3, max: 10)"}},required:["prompt"]}},{name:"get_sms_settings",description:"Get the company's SMS add-on status: whether SMS is enabled, plan eligibility, credit balance, brand prefix, phone numbers, and whether SMS steps will actually send. Check this before adding SMS steps to sequences so you can warn the user when SMS is not ready.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"send_test_sms",description:"Send a test SMS to a phone number. IMPORTANT: sends a real text message and charges SMS credits - only call when the user explicitly asks for a test send. Requires the SMS add-on with a verified number (check get_sms_settings). Limited to 5 test sends per hour; bypasses quiet hours; excluded from step stats.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Destination phone number in international E.164 format, e.g. +15550100123."},text:{type:"string",description:"Plain-text message body. Merge tags are not resolved for test sends to arbitrary numbers. Provide text or blocks."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable image URLs sent as MMS media (US/CA only)."},blocks:{type:"array",items:{type:"object"},description:"SMS content blocks (text + image subset). Provide text or blocks, not both."}},required:["to"]}},{name:"submit_feedback",description:"Send product feedback about Sequenzy itself to the Sequenzy team. IMPORTANT: call this tool whenever the user wanted to accomplish something and Sequenzy did not expose functionality for it - a missing tool or argument, an unsupported workflow, a confusing behavior, or a bug. Briefly tell the user you reported the gap. This feedback goes straight to the team and shapes what gets built next. Do not use it for questions about the user's own account or data, and never include secrets or API keys. Submitting feedback never changes account data.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},message:{type:"string",description:"The feedback itself. Be specific: what was needed, what was missing or wrong, and what you did instead (workaround, gave up, used the dashboard)."},category:{type:"string",enum:["missing_capability","bug","docs","ux","praise","other"],description:"Feedback category. Use missing_capability when the user wanted something these tools do not support (default: other)."},context:{type:"string",description:"Optional: what the user was trying to accomplish, in their words, plus any relevant tool names or arguments you tried."}},required:["message"]}}],UH=AZ.map(JZ).map(qV);async function KH(Q,Y){try{let X;switch(Q){case"get_account":{let G=await B("GET","/api/v1/account"),$=b1();X={...G,selectedCompanyId:$??G.currentCompanyId};break}case"select_company":{let G=Y.companyId,$=await B("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"}`);Q6(G),X={success:!0,message:`Switched to company: ${z.name}`,companyId:z.id,companyName:z.name};break}case"get_app_urls":{let G=await JX(Y);X={...Z1({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 B("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((K)=>setTimeout(K,20000)),J++;let U=await B("GET",`/api/v1/companies/${$}`);if(U.success)H=U.company.status}Q6($);let A=await B("GET",`/api/v1/companies/${$}`);X={success:!0,company:A.company,message:H==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${A.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let G=Y.companyId;X=await B("GET",`/api/v1/companies/${G}`);break}case"update_company":{let G=await tV("update_company",Y),$=CV(Y);X=await B("PATCH",`/api/v1/companies/${G}`,$);break}case"get_sync_rules":{let G=Y.companyId;X=await B("GET","/api/v1/sync-rules",void 0,G);break}case"update_sync_rules":{let G=Y.companyId;if(Y.syncRules!==null&&!Array.isArray(Y.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");X=await B("PUT","/api/v1/sync-rules",{syncRules:Y.syncRules},G);break}case"get_shopify_automation_settings":{let G=Y.companyId;X=await B("GET","/api/v1/shopify/automation-settings",void 0,G);break}case"update_shopify_automation_settings":{let G=Y.companyId,$={};if(Y.browseAbandonment!==void 0)$.browseAbandonment=Y.browseAbandonment;if(Y.priceDrop!==void 0)$.priceDrop=Y.priceDrop;if(Object.keys($).length===0)throw Error("Provide `browseAbandonment` and/or `priceDrop` when calling `update_shopify_automation_settings`.");X=await B("PUT","/api/v1/shopify/automation-settings",$,G);break}case"create_api_key":{let G=Y.companyId,$={};if(typeof Y.name==="string")$.name=Y.name;if(typeof Y.preset==="string")$.preset=Y.preset;if(Array.isArray(Y.scopes))$.scopes=Y.scopes;X=await B("POST","/api/v1/api-keys",$,G);break}case"list_websites":{let G=Y.companyId;X=await B("GET","/api/v1/websites",void 0,G);break}case"add_website":{let G=Y.companyId;X=await B("POST","/api/v1/websites",{domain:Y.domain},G);break}case"check_website":{let G=Y.companyId;X=await B("GET",`/api/v1/websites/${encodeURIComponent(String(Y.domain))}`,void 0,G);break}case"verify_sending_domain":{let G=Y.companyId;X=await B("POST",`/api/v1/websites/${encodeURIComponent(String(Y.domain))}/verify`,void 0,G);break}case"get_integration_guide":X=await B("POST","/api/v1/integration-guide",Y);break;case"add_subscriber":{let G=Y.companyId,$=v1("add_subscriber",Y);X=await B("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,$=v1("update_subscriber",Y),z=await dY($,G),J=Array.isArray(z.subscriber.tags)?z.subscriber.tags.filter((D)=>typeof D==="string"):[],H=Array.isArray(Y.addTags)?Y.addTags.filter((D)=>typeof D==="string"&&D.trim()!=="").map(XH):[],A=new Set(Array.isArray(Y.removeTags)?Y.removeTags.filter((D)=>typeof D==="string"&&D.trim()!=="").map(XH):[]),U=J.filter((D)=>!A.has(D));for(let D of H)if(!U.includes(D))U.push(D);let K={};if($.email&&$.externalId)K.externalId=$.externalId;if(J0(Y.attributes))K.customAttributes={...J0(z.subscriber.customAttributes)?z.subscriber.customAttributes:{},...Y.attributes};if(Y.addTags||Y.removeTags)K.tags=U;X=await B("PATCH",WX($),K,G);break}case"remove_subscriber":{let G=Y.companyId,$=v1("remove_subscriber",Y),z=WX($);if(Y.hardDelete===!0)X=await B("DELETE",z,void 0,G);else X=await B("PATCH",z,{status:"unsubscribed"},G);break}case"get_subscriber":{let G=Y.companyId,$=v1("get_subscriber",Y);X=await dY($,G,{includeMachineEngagement:Y.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let G=Y.companyId,$=v1("list_subscriber_notes",Y);X=await B("GET",WH($),void 0,G);break}case"add_subscriber_note":{let G=Y.companyId,$=v1("add_subscriber_note",Y),z=typeof Y.body==="string"?Y.body.trim():void 0;if(!z)throw Error("`body` is required when calling `add_subscriber_note`.");if(z.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");X=await B("POST",WH($),{body:z},G);break}case"delete_subscriber_note":{let G=Y.companyId,$=typeof Y.noteId==="string"?Y.noteId.trim():"";if(!$)throw Error("`noteId` is required when calling `delete_subscriber_note`.");X=await B("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent($)}`,void 0,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 B("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 B("POST","/api/v1/products",{products:Y.products},G);break}case"delete_product":{let G=Y.companyId,$=R("delete_product",Y,"productId");X=await B("DELETE",`/api/v1/products/${encodeURIComponent($)}`,void 0,G);break}case"attach_product_file":{let G=Y.companyId,$=R("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 A=await oV(J,G);H={url:A.url,source:"upload",fileName:w(Y,"fileName")??A.fileName,fileSizeBytes:A.fileSizeBytes,mimeType:A.mimeType}}else{H={url:z};let A=w(Y,"fileName");if(A)H.fileName=A}X=await B("PUT",`/api/v1/products/${encodeURIComponent($)}/delivery`,H,G);break}case"remove_product_file":{let G=Y.companyId,$=R("remove_product_file",Y,"productId");X=await B("DELETE",`/api/v1/products/${encodeURIComponent($)}/delivery`,void 0,G);break}case"sync_products":{let G=Y.companyId;X=await B("POST","/api/v1/products/sync",void 0,G);break}case"list_tags":{let G=Y.companyId;X=await B("GET","/api/v1/tags",void 0,G);break}case"create_tag":{let G=Y.companyId,$=R("create_tag",Y,"name"),z=m0("create_tag",Y,"color",wQ);X=await B("POST","/api/v1/tags",{name:$,...z!==void 0&&{color:z}},G);break}case"update_tag":{let G=Y.companyId,$=R("update_tag",Y,"tagId"),z=oY("update_tag",Y,"color",wQ);X=await B("PATCH",`/api/v1/tags/${encodeURIComponent($)}`,{color:z},G);break}case"delete_tag":{let G=Y.companyId,$=R("delete_tag",Y,"tagId");X=await B("DELETE",`/api/v1/tags/${encodeURIComponent($)}`,void 0,G);break}case"list_lists":{let G=Y.companyId;X=await B("GET","/api/v1/lists",void 0,G);break}case"create_list":{let G=Y.companyId;X=await B("POST","/api/v1/lists",Y,G);break}case"update_list":{let G=Y.companyId,$=R("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 B("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,$=R("delete_list",Y,"listId");X=await B("DELETE",`/api/v1/lists/${encodeURIComponent($)}`,void 0,G);break}case"add_subscribers_to_list":{let G=Y.companyId,$=R("add_subscribers_to_list",Y,"listId"),z=zH("add_subscribers_to_list",Y),J=m0("add_subscribers_to_list",Y,"duplicateStrategy",["skip","merge","overwrite"])??"skip",H=m0("add_subscribers_to_list",Y,"optInMode",["default","confirmed","double_opt_in"])??"default";X=await B("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,$=R("remove_subscribers_from_list",Y,"listId"),z=zH("remove_subscribers_from_list",Y);X=await B("POST",`/api/v1/lists/${encodeURIComponent($)}/subscribers/remove`,{emails:z},G);break}case"list_segments":{let G=Y.companyId;X=await B("GET","/api/v1/segments",void 0,G);break}case"create_segment":{SV(Y);let G=Y.companyId;X=await B("POST","/api/v1/segments",{...Y,...Y.filters!==void 0?{filters:QX(Y.filters)}:{},...Y.root!==void 0?{root:YX(Y.root)}:{}},G);break}case"update_segment":{RV(Y);let G=Y.companyId,$=R("update_segment",Y,"segmentId"),z=w(Y,"name"),J=m0("update_segment",Y,"filterJoinOperator",["and","or"]);X=await B("PATCH",`/api/v1/segments/${encodeURIComponent($)}`,{...z!==void 0&&{name:z},...J!==void 0&&{filterJoinOperator:J},...Y.filters!==void 0?{filters:QX(Y.filters)}:{},...Y.root!==void 0?{root:YX(Y.root)}:{}},G);break}case"delete_segment":{let G=Y.companyId,$=R("delete_segment",Y,"segmentId");X=await B("DELETE",`/api/v1/segments/${encodeURIComponent($)}`,void 0,G);break}case"get_segment_count":{let G=Y.companyId;X=await B("GET",`/api/v1/segments/${Y.segmentId}/count`,void 0,G);break}case"list_audience_syncs":{let G=Y.companyId;X=await B("GET","/api/v1/audience-syncs",void 0,G);break}case"list_ad_accounts":{let G=Y.companyId;X=await B("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 B("POST","/api/v1/audience-syncs",{segmentId:$,predefinedSegmentId:z,adAccountId:R("create_audience_sync",Y,"adAccountId"),audienceName:R("create_audience_sync",Y,"audienceName"),...Y.frequency!==void 0?{frequency:Y.frequency}:{}},G);break}case"update_audience_sync":{let G=Y.companyId,$=R("update_audience_sync",Y,"syncId");X=await B("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,$=R("delete_audience_sync",Y,"syncId");X=await B("DELETE",`/api/v1/audience-syncs/${encodeURIComponent($)}`,void 0,G);break}case"sync_audience_now":{let G=Y.companyId,$=R("sync_audience_now",Y,"syncId");X=await B("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 B("GET",`/api/v1/templates${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_template":{let G=Y.companyId;X=await B("GET",`/api/v1/templates/${Y.templateId}`,void 0,G);break}case"create_template":{let G=Y.companyId;gV(Y);let $=Object.fromEntries(Object.entries(Y).filter(([z])=>z!=="companyId"));X=await B("POST","/api/v1/templates",$,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(w1("update_template",Y),bQ("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 B("PUT",`/api/v1/templates/${Y.templateId}`,Y,G);break}case"delete_template":{let G=Y.companyId;X=await B("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 B("GET",`/api/v1/ab-tests${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_ab_test":{let G=Y.companyId;X=await B("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);if(Y.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");X=await B("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((U)=>!$.has(U));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((U)=>`\`${U}\``).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 A=Y.variantCount===void 0?void 0:Number(Y.variantCount);if(A!==void 0&&(!Number.isInteger(A)||A<2||A>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");X=await B("POST",`/api/v1/ab-tests/${Y.abTestId}/restart`,{sourceVariantId:w(Y,"sourceVariantId"),testType:J,winnerThreshold:H,variantCount:A},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(w1("update_ab_test_variant",Y),Y.subject===void 0&&Y.previewText===void 0&&Y.html===void 0&&Y.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");X=await B("PATCH",`/api/v1/ab-tests/${Y.abTestId}/variants/${Y.variantId}`,Y,G);break}case"create_ab_test":{let G=Y.companyId,$=R("create_ab_test",Y,"campaignId"),z=w(Y,"name"),J=x1("create_ab_test",Y,"testPercentage",5,50),H=x1("create_ab_test",Y,"testDurationMinutes",15,1440),A=m0("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((U,K)=>{if(!J0(U)||typeof U.subject!=="string"||U.subject.trim()==="")throw Error(`\`variants\` item ${K+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(U.blocks!==void 0&&!Array.isArray(U.blocks))throw Error(`\`variants\` item ${K+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}X=await B("POST","/api/v1/ab-tests",{campaignId:$,...z!==void 0&&{name:z},...J!==void 0&&{testPercentage:J},...H!==void 0&&{testDurationMinutes:H},...A!==void 0&&{winnerCriteria:A},...Y.variants!==void 0&&{variants:Y.variants}},G);break}case"add_ab_test_variant":{let G=Y.companyId,$=R("add_ab_test_variant",Y,"abTestId"),z=R("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 B("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,$=R("delete_ab_test_variant",Y,"abTestId"),z=R("delete_ab_test_variant",Y,"variantId");X=await B("DELETE",`/api/v1/ab-tests/${encodeURIComponent($)}/variants/${encodeURIComponent(z)}`,void 0,G);break}case"delete_ab_test":{let G=Y.companyId,$=R("delete_ab_test",Y,"abTestId");X=await B("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 B("GET",`/api/v1/campaigns?${$}`,void 0,G);break}case"get_campaign":{let G=Y.companyId;X=await B("GET",`/api/v1/campaigns/${Y.campaignId}`,void 0,G);break}case"get_email_send":{let G=Y.companyId;X=await B("GET",`/api/v1/email-sends/${encodeURIComponent(String(Y.emailSendId))}`,void 0,G);break}case"create_campaign":{let G=Y.companyId;if(_V(Y),Y.fromEmail!==void 0&&Y.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_campaign`, not both.");if(Y.replyTo!==void 0&&Y.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_campaign`, not both.");if(Y.fromName!==void 0&&Y.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_campaign`.");if(Y.replyToName!==void 0&&Y.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_campaign`.");let $=Object.fromEntries(Object.entries(Y).filter(([z])=>z!=="companyId"));X=await B("POST","/api/v1/campaigns",$,G);break}case"update_campaign":{let G=Y.companyId,$=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","campaignData","computedLists","labels"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, and label update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);if(w1("update_campaign",Y),bQ("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.fromEmail!==void 0&&Y.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_campaign`, not both.");if(Y.fromName!==void 0&&Y.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_campaign`.");if(Y.replyToName!==void 0&&Y.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_campaign`.");if(Y.name===void 0&&Y.subject===void 0&&Y.trackingCode===void 0&&Y.html===void 0&&Y.blocks===void 0&&Y.fromEmail===void 0&&Y.senderProfileId===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 campaign content, sending identity, campaign data, computed list, or label field when calling `update_campaign`.");X=await B("PUT",`/api/v1/campaigns/${Y.campaignId}`,Y,G);break}case"schedule_campaign":{let G=Y.companyId,$=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours","recurringInterval"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);yV(Y),X=await B("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},...Y.recurringInterval!==void 0&&{recurringInterval:Y.recurringInterval}},G);break}case"send_test_email":{let G=Y.companyId;X=await B("POST",`/api/v1/campaigns/${Y.campaignId}/test`,{to:Y.to},G);break}case"cancel_campaign":{let G=Y.companyId,$=R("cancel_campaign",Y,"campaignId");X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/cancel`,void 0,G);break}case"pause_campaign":{let G=Y.companyId,$=R("pause_campaign",Y,"campaignId");X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/pause`,void 0,G);break}case"resume_campaign":{let G=Y.companyId,$=R("resume_campaign",Y,"campaignId"),z=x1("resume_campaign",Y,"spreadOverHours",1,72);X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/resume`,{...z!==void 0&&{spreadOverHours:z}},G);break}case"delete_campaign":{let G=Y.companyId,$=R("delete_campaign",Y,"campaignId");X=await B("DELETE",`/api/v1/campaigns/${encodeURIComponent($)}`,void 0,G);break}case"duplicate_campaign":{let G=Y.companyId,$=R("duplicate_campaign",Y,"campaignId"),z=m0("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 B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/duplicate`,{...z!==void 0&&{mode:z},...J!==void 0&&{variantId:J}},G);break}case"resend_campaign_to_non_openers":{let G=Y.companyId,$=R("resend_campaign_to_non_openers",Y,"campaignId");X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/resend-to-non-openers`,void 0,G);break}case"list_landing_pages":{let G=Y.companyId;X=await B("GET","/api/v1/landing-pages",void 0,G);break}case"get_landing_page":{let G=Y.companyId;X=await B("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 B("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,$=nY("update_landing_page",Y,{requireUpdate:!0});X=await B("PUT",`/api/v1/landing-pages/${Y.landingPageId}`,$,G);break}case"publish_landing_page":{let G=Y.companyId,$=nY("publish_landing_page",Y,{requireUpdate:!1});X=await B("POST",`/api/v1/landing-pages/${Y.landingPageId}/publish`,$,G);break}case"unpublish_landing_page":{let G=Y.companyId,$=nY("unpublish_landing_page",Y,{requireUpdate:!1});X=await B("POST",`/api/v1/landing-pages/${Y.landingPageId}/unpublish`,$,G);break}case"delete_landing_page":{let G=Y.companyId;X=await B("DELETE",`/api/v1/landing-pages/${Y.landingPageId}`,void 0,G);break}case"connect_landing_page_domain":{let G=Y.companyId;X=await B("POST","/api/v1/landing-pages/domain",{domain:Y.domain},G);break}case"update_landing_page_domain_settings":{let G=Y.companyId,$=uV(Y);X=await B("PUT","/api/v1/landing-pages/domain",$,G);break}case"list_sequences":{let G=Y.companyId;X=await B("GET","/api/v1/sequences",void 0,G);break}case"get_sequence":{let G=Y.companyId;X=await B("GET",`/api/v1/sequences/${Y.sequenceId}`,void 0,G);break}case"create_sequence":{let G=Y.companyId;if(Y.fromEmail!==void 0&&Y.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_sequence`, not both.");if(Y.replyTo!==void 0&&Y.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_sequence`, not both.");if(Y.fromName!==void 0&&Y.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_sequence`.");if(Y.replyToName!==void 0&&Y.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_sequence`.");let $=Array.isArray(Y.steps)&&Y.steps.length>0,z=await B("POST","/api/v1/sequences",Y,G);if(!z.success){X=z;break}let J=z.sequence.id;if($){let D=await B("GET",`/api/v1/sequences/${J}`,void 0,G);if(D.success)X={success:!0,sequence:D.sequence,message:`Sequence "${D.sequence.name}" created with explicit steps. Review it before enabling.`};else X=D;break}let H=6,A=0,U="pending";while(U!=="complete"&&A<H){await new Promise((L)=>setTimeout(L,20000)),A++;let D=await B("GET",`/api/v1/sequences/${J}`,void 0,G);if(D.success)U=D.sequence.enrichmentStatus}let K=await B("GET",`/api/v1/sequences/${J}`,void 0,G);if(K.success)X={success:!0,sequence:K.sequence,message:K.sequence.enrichmentStatus==="complete"?`Sequence "${K.sequence.name}" created with ${K.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.`:`Sequence "${K.sequence.name}" created. Email enrichment is still in progress (${K.sequence.enrichedCount}/${K.sequence.emailCount} emails generated). You can check status with get_sequence.`};else X=K;break}case"update_sequence":{let G=Y.companyId,$=kV(Y);X=await B("PUT",`/api/v1/sequences/${Y.sequenceId}`,$,G);break}case"insert_sequence_step":{let G=Y.companyId,$=vV(Y);X=await B("PUT",`/api/v1/sequences/${Y.sequenceId}`,$,G);break}case"enable_sequence":{let G=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/enable`,void 0,G);break}case"disable_sequence":{let G=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/disable`,void 0,G);break}case"pause_sequence_enrollments":{let G=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/pause-enrollments`,void 0,G);break}case"resume_sequence_enrollments":{let G=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/resume-enrollments`,void 0,G);break}case"enroll_subscribers_in_sequence":{let G=Y.companyId,$=R("enroll_subscribers_in_sequence",Y,"sequenceId"),z=iV(Y);X=await B("POST",`/api/v1/sequences/${encodeURIComponent($)}/enroll`,z,G);break}case"cancel_sequence_enrollments":{let G=Y.companyId,$=xV(Y);X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/enrollments/cancel`,$,G);break}case"delete_sequence":{let G=Y.companyId;X=await B("DELETE",`/api/v1/sequences/${Y.sequenceId}`,void 0,G);break}case"list_transactional_emails":{let G=Y.companyId;X=await B("GET","/api/v1/transactional",void 0,G);break}case"get_transactional_email":{let G=Y.companyId;X=await B("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((H)=>!$.has(H));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((H)=>`\`${H}\``).join(", ")}.`);hV(Y);let J=Object.fromEntries(Object.entries(Y).filter(([H])=>H!=="companyId"));X=await B("POST","/api/v1/transactional",J,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(w1("update_transactional_email",Y),Y.name===void 0&&Y.enabled===void 0&&Y.subject===void 0&&Y.previewText===void 0&&Y.html===void 0&&Y.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let J=Object.fromEntries(Object.entries(Y).filter(([H])=>H!=="companyId"&&H!=="idOrSlug"));X=await B("PATCH",`/api/v1/transactional/${Y.idOrSlug}`,J,G);break}case"send_email":{let G=Y.companyId;X=await B("POST","/api/v1/transactional/send",Y,G);break}case"get_stats":{let G=Y.companyId,$=Y.period??"7d",z=new URLSearchParams({period:String($)});if(Y.includeMachineEngagement===!0)z.set("includeMachineEngagement","true");X=await B("GET",`/api/v1/metrics?${z.toString()}`,void 0,G);break}case"get_campaign_stats":{let G=Y.companyId,$=new URLSearchParams;if(Y.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");let z=$.toString();X=await B("GET",`/api/v1/metrics/campaigns/${Y.campaignId}${z?`?${z}`:""}`,void 0,G);break}case"get_sequence_stats":{let G=Y.companyId,$=new URLSearchParams;if(Y.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");let z=$.toString();X=await B("GET",`/api/v1/metrics/sequences/${Y.sequenceId}${z?`?${z}`:""}`,void 0,G);break}case"list_campaign_events":{let G=Y.companyId,$=R("list_campaign_events",Y,"campaignId"),J=GH("list_campaign_events",Y).toString();X=await B("GET",`/api/v1/metrics/campaigns/${encodeURIComponent($)}/events${J?`?${J}`:""}`,void 0,G);break}case"list_sequence_events":{let G=Y.companyId,$=R("list_sequence_events",Y,"sequenceId"),J=GH("list_sequence_events",Y).toString();X=await B("GET",`/api/v1/metrics/sequences/${encodeURIComponent($)}/events${J?`?${J}`:""}`,void 0,G);break}case"get_subscriber_activity":{let G=Y.companyId,$=v1("get_subscriber_activity",Y),z=await dY($,G,{includeMachineEngagement:Y.includeMachineEngagement===!0});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 B("GET","/api/v1/team",void 0,G);break}case"invite_team_member":{let G=Y.companyId,$=R("invite_team_member",Y,"email"),z=oY("invite_team_member",Y,"role",["admin","viewer","restricted"]);if(Y.canManageBilling!==void 0&&typeof Y.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");X=await B("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,$=R("cancel_team_invitation",Y,"invitationId");X=await B("DELETE",`/api/v1/team/invitations/${encodeURIComponent($)}`,void 0,G);break}case"list_conversations":{let G=Y.companyId,$=new URLSearchParams,z=m0("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=x1("list_conversations",Y,"limit",1,100);if(H!==void 0)$.set("limit",String(H));X=await B("GET",`/api/v1/conversations${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_conversation":{let G=Y.companyId,$=R("get_conversation",Y,"conversationId");X=await B("GET",`/api/v1/conversations/${encodeURIComponent($)}`,void 0,G);break}case"reply_to_conversation":{let G=Y.companyId,$=R("reply_to_conversation",Y,"conversationId"),z=m0("reply_to_conversation",Y,"type",["outbound","note"])??"outbound",J=w(Y,"subject"),H=w(Y,"bodyText"),A=w(Y,"bodyHtml");if(z==="outbound"&&H===void 0&&A===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");X=await B("POST",`/api/v1/conversations/${encodeURIComponent($)}/messages`,{type:z,...J!==void 0&&{subject:J},...H!==void 0&&{bodyText:H},...A!==void 0&&{bodyHtml:A}},G);break}case"update_conversation_status":{let G=Y.companyId,$=R("update_conversation_status",Y,"conversationId"),z=oY("update_conversation_status",Y,"status",["open","closed"]);X=await B("POST",`/api/v1/conversations/${encodeURIComponent($)}/status`,{status:z},G);break}case"mark_conversation_read":{let G=Y.companyId,$=R("mark_conversation_read",Y,"conversationId");X=await B("POST",`/api/v1/conversations/${encodeURIComponent($)}/read`,void 0,G);break}case"list_webhooks":{let G=Y.companyId;X=await B("GET","/api/v1/webhooks",void 0,G);break}case"create_webhook":{let G=Y.companyId,$=R("create_webhook",Y,"name"),z=R("create_webhook",Y,"url"),J=$H("create_webhook",Y);X=await B("POST","/api/v1/webhooks",{name:$,url:z,...J!==void 0&&{events:J}},G);break}case"update_webhook":{let G=Y.companyId,$=R("update_webhook",Y,"webhookId"),z=w(Y,"name"),J=w(Y,"url"),H=$H("update_webhook",Y),A=m0("update_webhook",Y,"status",["enabled","disabled"]);if(z===void 0&&J===void 0&&H===void 0&&A===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");X=await B("PATCH",`/api/v1/webhooks/${encodeURIComponent($)}`,{...z!==void 0&&{name:z},...J!==void 0&&{url:J},...H!==void 0&&{events:H},...A!==void 0&&{status:A}},G);break}case"delete_webhook":{let G=Y.companyId,$=R("delete_webhook",Y,"webhookId");X=await B("DELETE",`/api/v1/webhooks/${encodeURIComponent($)}`,void 0,G);break}case"test_webhook":{let G=Y.companyId,$=R("test_webhook",Y,"webhookId");X=await B("POST",`/api/v1/webhooks/${encodeURIComponent($)}/test`,void 0,G);break}case"list_webhook_deliveries":{let G=Y.companyId,$=R("list_webhook_deliveries",Y,"webhookId"),z=x1("list_webhook_deliveries",Y,"limit",1,100),J=new URLSearchParams;if(z!==void 0)J.set("limit",String(z));X=await B("GET",`/api/v1/webhooks/${encodeURIComponent($)}/deliveries${J.size>0?`?${J}`:""}`,void 0,G);break}case"replay_webhook_delivery":{let G=Y.companyId,$=R("replay_webhook_delivery",Y,"webhookId"),z=R("replay_webhook_delivery",Y,"deliveryId");X=await B("POST",`/api/v1/webhooks/${encodeURIComponent($)}/deliveries/${encodeURIComponent(z)}/replay`,void 0,G);break}case"generate_email":{let G=Y.companyId;X=await B("POST","/api/v1/generate/email",Y,G);break}case"generate_sequence":{let G=Y.companyId;X=await B("POST","/api/v1/generate/sequence",Y,G);break}case"generate_subject_lines":{let G=Y.companyId;X=await B("POST","/api/v1/generate/subjects",Y,G);break}case"generate_sms":{let G=Y.companyId;X=await B("POST","/api/v1/generate/sms",Y,G);break}case"get_sms_settings":{let G=Y.companyId;X=await B("GET","/api/v1/sms/settings",void 0,G);break}case"send_test_sms":{let G=Y.companyId,$={to:R("send_test_sms",Y,"to")};for(let z of["text","imageUrls","blocks"])if(Y[z]!==void 0)$[z]=Y[z];X=await B("POST","/api/v1/sms/test",$,G);break}case"submit_feedback":{let G=Y.companyId,$={message:R("submit_feedback",Y,"message"),source:"mcp"};for(let z of["category","context"])if(Y[z]!==void 0)$[z]=Y[z];X=await B("POST","/api/v1/feedback",$,G);break}default:throw Error(`Unknown tool: ${Q}`)}let W=fV(X);if(W)throw W;return X=await sV(Q,Y,X),{structuredContent:HZ(X),content:[{type:"text",text:JSON.stringify(X,null,2)}]}}catch(X){return{isError:!0,content:[{type:"text",text:$1(X)}]}}}async function DH(Q,Y,X){let W=Y.getRequestContext?.(Q)??{};try{return await SQ(W,X)}finally{await Y.onRequestContextUpdated?.(W,Q)}}function HX(Q={}){let Y=new lY({name:"sequenzy",version:p5.version},{capabilities:{tools:{},resources:{}},instructions:["Sequenzy email marketing MCP server: manage subscribers, campaigns, sequences, templates, and delivery stats.","If you have access to multiple companies, call get_account and then select_company (or pass companyId per call) before other tools.","IMPORTANT: whenever the user wanted to accomplish something and these tools did not expose functionality for it (missing tool, missing argument, unsupported workflow, or broken behavior), call submit_feedback describing the gap before finishing the task. The Sequenzy team reads every submission and uses it to decide what to build next."].join(`
|
|
190
|
+
- 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."},fromEmail:{type:"string",description:"From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Reply-To address for all emails in this sequence. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},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)"},durationDays:{type:"number",description:"Total duration in days used to space AI-generated sequence emails. Only applies when using goal-based AI generation."},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:a5,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, use type: 'sms' for SMS, type: 'create_discount' for a dynamic discount, or type: 'update_subscriber' with nodeType: 'action_update_attributes' and config to copy trigger-event values such as {{event.plan}} into subscriber data.",items:{type:"object",properties:{type:{type:"string",enum:["email","sms","create_discount","discount","update_subscriber"],description:"Step type. Omit or use 'email' for email content. Use 'sms' to send a text message, 'create_discount' to generate a code, or 'update_subscriber' to copy trigger data into the subscriber."},nodeType:{type:"string",enum:["action_email","action_sms","action_create_discount","action_update_attributes"],description:"Internal step type. Use action_update_attributes with config for Update Subscriber steps."},config:XX,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:tY,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:sY,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:aY,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","shopify"],description:"Discount provider. Use 'stripe' to dynamically create a Stripe coupon plus promotion code, or 'shopify' to dynamically create a Shopify Admin discount code. Defaults to 'stripe' when omitted."},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:"Discount 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:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. 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 display name for each dynamically generated provider discount."}}},label:{type:"string",description:"Legacy top-level discount label. Prefer discount.label."},provider:{type:"string",enum:["stripe","shopify"],description:"Legacy top-level discount provider. Prefer discount.provider. Supports 'stripe' and 'shopify'."},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:"Discount 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:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. 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 existing step, use IDs returned by get_sequence. The emails/steps arrays edit email steps, smsSteps edits SMS steps, and subscriberUpdateSteps replaces the config of action_update_attributes steps. To insert new linear steps, use insertSteps with an afterNodeId from get_sequence; omit afterNodeId only to append to an unambiguous linear tail. For active sequences, structural changes such as insertSteps or branch require confirmStructuralChange:true after the user confirms the live-flow impact.",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"},fromEmail:{type:"string",description:"Set the From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Set the Reply-To address for all emails in this sequence."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Set an existing reply profile. Mutually exclusive with replyTo."},enrollmentPaused:{type:"boolean",description:"Set true to stop new enrollments for an active sequence while current recipients continue. Set false to resume new enrollments. The sequence must already be active."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence. Required for insertSteps or branch when the sequence is active; not needed for content-only email edits."},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:a5,clearSendingWindow:{type:"boolean",description:"Set true to remove the sequence sending window. Do not provide this together with sendingWindow."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses that receive a blind copy of every email this sequence sends, such as a customer support inbox (max 10). Omit to leave unchanged. Use clearBccEmails to remove them."},clearBccEmails:{type:"boolean",description:"Set true to remove the sequence BCC addresses. Do not provide this together with bccEmails."},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 tag presence/absence, 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","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"],description:"Condition type for this branch. has_phone (contact has a phone number) and sms_subscribed (contact opted in to SMS marketing) need no extra fields."},tagName:{type:"string",description:"Tag name for has_tag and does_not_have_tag conditions. This can be used instead of tagId."},tagId:{type:"string",description:"Tag ID or tag name for has_tag and does_not_have_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:rY}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:rY},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"]},insertSteps:{type:"object",description:"Insert one or more new linear steps into an existing sequence. Use get_sequence first, then pass afterNodeId to insert after a specific node. If afterNodeId is omitted, the steps are appended only when the sequence has exactly one linear tail. Inserted email steps require subject plus blocks or html.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},steps:{type:"array",description:"New steps to insert. Supports emails, delays, create_discount actions, webhooks, and other supported sequence path node types.",items:rY}},required:["steps"]},emails:{type:"array",description:"Updated existing sequence emails. If you omit emailId/nodeId, items are matched by existing step order. This field does not create new steps; use insertSteps for insertion and include delay on inserted email steps when a timer is needed.",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. Stored as one raw HTML block. Use this to preserve imported provider HTML."},htmlContent:{type:"string",description:"Alias for html. Stored as one raw HTML block. Use this when updating imported provider HTML for a step."},blocks:{type:"array",description:Q4,items:{type:"object"}}}}},steps:{type:"array",description:"Alias for emails. Supports the same fields and matching rules, and only edits existing email steps. Use insertSteps to create new steps.",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. Stored as one raw HTML block. Use this to preserve imported provider HTML."},htmlContent:{type:"string",description:"Alias for html. Stored as one raw HTML block. Use this when updating HTML content for a step."},blocks:{type:"array",description:Q4,items:{type:"object"}}}}},smsSteps:{type:"array",description:"Content updates for existing SMS steps, targeted by nodeId (an action_sms node from get_sequence.sequence.nodes). Content-only edits - use insertSteps to create new SMS steps.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_sms node ID. Required."},text:{type:"string",description:"Replacement plain-text message body. Merge tags like {{FIRST_NAME}} work. Provide text or blocks, not both."},blocks:{type:"array",items:{type:"object"},description:"Replacement SMS content blocks (text + image subset)."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable MMS image URLs. Only valid together with text."},label:{type:"string",description:"Updated display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"Updated behavior when the contact can't receive SMS."}},required:["nodeId"]}},subscriberUpdateSteps:{type:"array",description:"Full config replacements for existing Update Subscriber steps, targeted by action_update_attributes nodeId.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_update_attributes node ID."},config:XX},required:["nodeId","config"]}}},required:["sequenceId"]}},{name:"insert_sequence_step",description:"Insert one new email or SMS step into an existing sequence. Prefer this over update_sequence.steps/emails when adding a step: it creates the step node (plus an email template for email steps) and, when delay or delayMs is provided, a logic_delay node immediately before it. For SMS steps set type:'sms' and provide 'text' (generate copy with generate_sms; check get_sms_settings first and warn the user if SMS is not enabled). Use get_sequence first, then pass afterNodeId from sequence.nodes or sequence.emails to choose the insertion point. If afterNodeId is omitted, the step is appended only when the sequence has exactly one linear tail. For active sequences, set confirmStructuralChange:true only after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},type:{type:"string",enum:["email","sms"],description:"Step type. Defaults to 'email'. Use 'sms' to insert an SMS step (requires 'text')."},afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."},name:{type:"string",description:"Optional email template and step name."},subject:{type:"string",description:"Email subject for the new step. Required for email steps; not used for SMS steps."},previewText:{type:"string",description:"Optional email preview text for the new step."},blocks:{type:"array",description:tY,items:{type:"object"}},html:{type:"string",description:"HTML content for the new step. Stored as one raw HTML block. Use this for imported provider HTML. Provide either html or blocks, not both."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},label:{type:"string",description:"SMS steps only: display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:sY,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:aY},required:["sequenceId"],additionalProperties:!1}},{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/freeze a sequence. This blocks new enrollments and holds current recipients until the sequence is enabled again. To only stop new enrollments while current recipients continue, use pause_sequence_enrollments.",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:"pause_sequence_enrollments",description:"Stop new enrollments for an active sequence while current recipients continue through the sequence. This matches the dashboard 'Stop new enrollments' control and does not freeze current recipients.",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:"resume_sequence_enrollments",description:"Resume new enrollments for an active sequence whose enrollment gate was paused. Use enable_sequence instead for a fully disabled/frozen 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. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup.",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`. Sequenzy stores it as one raw HTML block."},blocks:{type:"array",description:`${s4} Mutually exclusive with \`html\`.`,items:{type:"object"}},prompt:{type:"string",description:"Generate transactional email blocks from a prompt. Generated blocks include the company's branding (logo and a footer without an unsubscribe link). 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. Prompt-created templates default to false; explicit HTML/blocks retain the compatibility default of 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`. Sequenzy stores it as one raw HTML block."},blocks:{type:"array",description:`${Q4} 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)"},includeMachineEngagement:N1}}},{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"},includeMachineEngagement:N1},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"},includeMachineEngagement:N1},required:["sequenceId"]}},{name:"list_campaign_events",description:"List paginated raw email events for a campaign. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},eventType:{type:"string",description:"Optional single event type. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery."},eventTypes:{type:"array",description:"Optional event types to include. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery.",items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:N1},required:["campaignId"]}},{name:"list_sequence_events",description:"List paginated raw email events for every email step in a sequence. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},eventType:{type:"string",description:"Optional single event type. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery."},eventTypes:{type:"array",description:"Optional event types to include. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery.",items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:N1},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."},includeMachineEngagement:N1},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, viewer, or restricted. 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 and is not available for restricted members.",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","restricted"],description:"Team role. Admins can manage the workspace; viewers have read-only access; restricted members can open direct campaign links only."},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:[...PQ]},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:[...PQ]},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. Generated blocks include the company's branding chrome (logo, footer with company name/address/unsubscribe) by default, matching emails created in the dashboard.",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"},applyBranding:{type:"boolean",description:"Wrap the generated content with company branding (logo + footer). Defaults to true; set false to get raw content blocks only."},emailType:{type:"string",enum:["marketing","transactional"],description:"Email type. Transactional emails get a footer without the unsubscribe link. Defaults to marketing."}},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"]}},{name:"generate_sms",description:"Generate SMS marketing message variants from a prompt. Returns plain-text messages with per-message encoding and segment counts. Use the results as the 'text' of an SMS sequence step (insert_sequence_step with type 'sms' or a create_sequence sms step). Messages exclude opt-out footers and brand prefixes - the platform adds those automatically at send time.",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 SMS to generate (e.g., 'cart reminder with a free-shipping hook')"},count:{type:"number",description:"Number of message variants to generate (default: 3, max: 10)"}},required:["prompt"]}},{name:"get_sms_settings",description:"Get the company's SMS add-on status: whether SMS is enabled, plan eligibility, credit balance, brand prefix, phone numbers, and whether SMS steps will actually send. Check this before adding SMS steps to sequences so you can warn the user when SMS is not ready.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"send_test_sms",description:"Send a test SMS to a phone number. IMPORTANT: sends a real text message and charges SMS credits - only call when the user explicitly asks for a test send. Requires the SMS add-on with a verified number (check get_sms_settings). Limited to 5 test sends per hour; bypasses quiet hours; excluded from step stats.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Destination phone number in international E.164 format, e.g. +15550100123."},text:{type:"string",description:"Plain-text message body. Merge tags are not resolved for test sends to arbitrary numbers. Provide text or blocks."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable image URLs sent as MMS media (US/CA only)."},blocks:{type:"array",items:{type:"object"},description:"SMS content blocks (text + image subset). Provide text or blocks, not both."}},required:["to"]}},{name:"submit_feedback",description:"Send product feedback about Sequenzy itself to the Sequenzy team. IMPORTANT: call this tool whenever the user wanted to accomplish something and Sequenzy did not expose functionality for it - a missing tool or argument, an unsupported workflow, a confusing behavior, or a bug. Briefly tell the user you reported the gap. This feedback goes straight to the team and shapes what gets built next. Do not use it for questions about the user's own account or data, and never include secrets or API keys. Submitting feedback never changes account data.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},message:{type:"string",description:"The feedback itself. Be specific: what was needed, what was missing or wrong, and what you did instead (workaround, gave up, used the dashboard)."},category:{type:"string",enum:["missing_capability","bug","docs","ux","praise","other"],description:"Feedback category. Use missing_capability when the user wanted something these tools do not support (default: other)."},context:{type:"string",description:"Optional: what the user was trying to accomplish, in their words, plus any relevant tool names or arguments you tried."}},required:["message"]}}],UH=AZ.map(JZ).map(qV);async function KH(Q,Y){try{let X;switch(Q){case"get_account":{let G=await B("GET","/api/v1/account"),$=b1();X={...G,selectedCompanyId:$??G.currentCompanyId};break}case"select_company":{let G=Y.companyId,$=await B("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"}`);Q6(G),X={success:!0,message:`Switched to company: ${z.name}`,companyId:z.id,companyName:z.name};break}case"get_app_urls":{let G=await JX(Y);X={...Z1({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 B("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((K)=>setTimeout(K,20000)),J++;let U=await B("GET",`/api/v1/companies/${$}`);if(U.success)H=U.company.status}Q6($);let A=await B("GET",`/api/v1/companies/${$}`);X={success:!0,company:A.company,message:H==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${A.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let G=Y.companyId;X=await B("GET",`/api/v1/companies/${G}`);break}case"update_company":{let G=await tV("update_company",Y),$=CV(Y);X=await B("PATCH",`/api/v1/companies/${G}`,$);break}case"get_sync_rules":{let G=Y.companyId;X=await B("GET","/api/v1/sync-rules",void 0,G);break}case"update_sync_rules":{let G=Y.companyId;if(Y.syncRules!==null&&!Array.isArray(Y.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");X=await B("PUT","/api/v1/sync-rules",{syncRules:Y.syncRules},G);break}case"get_shopify_automation_settings":{let G=Y.companyId;X=await B("GET","/api/v1/shopify/automation-settings",void 0,G);break}case"update_shopify_automation_settings":{let G=Y.companyId,$={};if(Y.browseAbandonment!==void 0)$.browseAbandonment=Y.browseAbandonment;if(Y.priceDrop!==void 0)$.priceDrop=Y.priceDrop;if(Object.keys($).length===0)throw Error("Provide `browseAbandonment` and/or `priceDrop` when calling `update_shopify_automation_settings`.");X=await B("PUT","/api/v1/shopify/automation-settings",$,G);break}case"create_api_key":{let G=Y.companyId,$={};if(typeof Y.name==="string")$.name=Y.name;if(typeof Y.preset==="string")$.preset=Y.preset;if(Array.isArray(Y.scopes))$.scopes=Y.scopes;X=await B("POST","/api/v1/api-keys",$,G);break}case"list_websites":{let G=Y.companyId;X=await B("GET","/api/v1/websites",void 0,G);break}case"add_sending_domain":case"add_website":{let G=Y.companyId;X=await B("POST","/api/v1/websites",{domain:Y.domain},G);break}case"check_website":{let G=Y.companyId;X=await B("GET",`/api/v1/websites/${encodeURIComponent(String(Y.domain))}`,void 0,G);break}case"verify_sending_domain":{let G=Y.companyId;X=await B("POST",`/api/v1/websites/${encodeURIComponent(String(Y.domain))}/verify`,void 0,G);break}case"get_integration_guide":X=await B("POST","/api/v1/integration-guide",Y);break;case"add_subscriber":{let G=Y.companyId,$=v1("add_subscriber",Y);X=await B("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,$=v1("update_subscriber",Y),z=await dY($,G),J=Array.isArray(z.subscriber.tags)?z.subscriber.tags.filter((D)=>typeof D==="string"):[],H=Array.isArray(Y.addTags)?Y.addTags.filter((D)=>typeof D==="string"&&D.trim()!=="").map(XH):[],A=new Set(Array.isArray(Y.removeTags)?Y.removeTags.filter((D)=>typeof D==="string"&&D.trim()!=="").map(XH):[]),U=J.filter((D)=>!A.has(D));for(let D of H)if(!U.includes(D))U.push(D);let K={};if($.email&&$.externalId)K.externalId=$.externalId;if(J0(Y.attributes))K.customAttributes={...J0(z.subscriber.customAttributes)?z.subscriber.customAttributes:{},...Y.attributes};if(Y.addTags||Y.removeTags)K.tags=U;X=await B("PATCH",WX($),K,G);break}case"remove_subscriber":{let G=Y.companyId,$=v1("remove_subscriber",Y),z=WX($);if(Y.hardDelete===!0)X=await B("DELETE",z,void 0,G);else X=await B("PATCH",z,{status:"unsubscribed"},G);break}case"get_subscriber":{let G=Y.companyId,$=v1("get_subscriber",Y);X=await dY($,G,{includeMachineEngagement:Y.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let G=Y.companyId,$=v1("list_subscriber_notes",Y);X=await B("GET",WH($),void 0,G);break}case"add_subscriber_note":{let G=Y.companyId,$=v1("add_subscriber_note",Y),z=typeof Y.body==="string"?Y.body.trim():void 0;if(!z)throw Error("`body` is required when calling `add_subscriber_note`.");if(z.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");X=await B("POST",WH($),{body:z},G);break}case"delete_subscriber_note":{let G=Y.companyId,$=typeof Y.noteId==="string"?Y.noteId.trim():"";if(!$)throw Error("`noteId` is required when calling `delete_subscriber_note`.");X=await B("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent($)}`,void 0,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 B("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 B("POST","/api/v1/products",{products:Y.products},G);break}case"delete_product":{let G=Y.companyId,$=R("delete_product",Y,"productId");X=await B("DELETE",`/api/v1/products/${encodeURIComponent($)}`,void 0,G);break}case"attach_product_file":{let G=Y.companyId,$=R("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 A=await oV(J,G);H={url:A.url,source:"upload",fileName:w(Y,"fileName")??A.fileName,fileSizeBytes:A.fileSizeBytes,mimeType:A.mimeType}}else{H={url:z};let A=w(Y,"fileName");if(A)H.fileName=A}X=await B("PUT",`/api/v1/products/${encodeURIComponent($)}/delivery`,H,G);break}case"remove_product_file":{let G=Y.companyId,$=R("remove_product_file",Y,"productId");X=await B("DELETE",`/api/v1/products/${encodeURIComponent($)}/delivery`,void 0,G);break}case"sync_products":{let G=Y.companyId;X=await B("POST","/api/v1/products/sync",void 0,G);break}case"list_tags":{let G=Y.companyId;X=await B("GET","/api/v1/tags",void 0,G);break}case"create_tag":{let G=Y.companyId,$=R("create_tag",Y,"name"),z=m0("create_tag",Y,"color",wQ);X=await B("POST","/api/v1/tags",{name:$,...z!==void 0&&{color:z}},G);break}case"update_tag":{let G=Y.companyId,$=R("update_tag",Y,"tagId"),z=oY("update_tag",Y,"color",wQ);X=await B("PATCH",`/api/v1/tags/${encodeURIComponent($)}`,{color:z},G);break}case"delete_tag":{let G=Y.companyId,$=R("delete_tag",Y,"tagId");X=await B("DELETE",`/api/v1/tags/${encodeURIComponent($)}`,void 0,G);break}case"list_lists":{let G=Y.companyId;X=await B("GET","/api/v1/lists",void 0,G);break}case"create_list":{let G=Y.companyId;X=await B("POST","/api/v1/lists",Y,G);break}case"update_list":{let G=Y.companyId,$=R("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 B("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,$=R("delete_list",Y,"listId");X=await B("DELETE",`/api/v1/lists/${encodeURIComponent($)}`,void 0,G);break}case"add_subscribers_to_list":{let G=Y.companyId,$=R("add_subscribers_to_list",Y,"listId"),z=zH("add_subscribers_to_list",Y),J=m0("add_subscribers_to_list",Y,"duplicateStrategy",["skip","merge","overwrite"])??"skip",H=m0("add_subscribers_to_list",Y,"optInMode",["default","confirmed","double_opt_in"])??"default";X=await B("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,$=R("remove_subscribers_from_list",Y,"listId"),z=zH("remove_subscribers_from_list",Y);X=await B("POST",`/api/v1/lists/${encodeURIComponent($)}/subscribers/remove`,{emails:z},G);break}case"list_segments":{let G=Y.companyId;X=await B("GET","/api/v1/segments",void 0,G);break}case"create_segment":{SV(Y);let G=Y.companyId;X=await B("POST","/api/v1/segments",{...Y,...Y.filters!==void 0?{filters:QX(Y.filters)}:{},...Y.root!==void 0?{root:YX(Y.root)}:{}},G);break}case"update_segment":{RV(Y);let G=Y.companyId,$=R("update_segment",Y,"segmentId"),z=w(Y,"name"),J=m0("update_segment",Y,"filterJoinOperator",["and","or"]);X=await B("PATCH",`/api/v1/segments/${encodeURIComponent($)}`,{...z!==void 0&&{name:z},...J!==void 0&&{filterJoinOperator:J},...Y.filters!==void 0?{filters:QX(Y.filters)}:{},...Y.root!==void 0?{root:YX(Y.root)}:{}},G);break}case"delete_segment":{let G=Y.companyId,$=R("delete_segment",Y,"segmentId");X=await B("DELETE",`/api/v1/segments/${encodeURIComponent($)}`,void 0,G);break}case"get_segment_count":{let G=Y.companyId;X=await B("GET",`/api/v1/segments/${Y.segmentId}/count`,void 0,G);break}case"list_audience_syncs":{let G=Y.companyId;X=await B("GET","/api/v1/audience-syncs",void 0,G);break}case"list_ad_accounts":{let G=Y.companyId;X=await B("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 B("POST","/api/v1/audience-syncs",{segmentId:$,predefinedSegmentId:z,adAccountId:R("create_audience_sync",Y,"adAccountId"),audienceName:R("create_audience_sync",Y,"audienceName"),...Y.frequency!==void 0?{frequency:Y.frequency}:{}},G);break}case"update_audience_sync":{let G=Y.companyId,$=R("update_audience_sync",Y,"syncId");X=await B("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,$=R("delete_audience_sync",Y,"syncId");X=await B("DELETE",`/api/v1/audience-syncs/${encodeURIComponent($)}`,void 0,G);break}case"sync_audience_now":{let G=Y.companyId,$=R("sync_audience_now",Y,"syncId");X=await B("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 B("GET",`/api/v1/templates${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_template":{let G=Y.companyId;X=await B("GET",`/api/v1/templates/${Y.templateId}`,void 0,G);break}case"create_template":{let G=Y.companyId;gV(Y);let $=Object.fromEntries(Object.entries(Y).filter(([z])=>z!=="companyId"));X=await B("POST","/api/v1/templates",$,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(w1("update_template",Y),bQ("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 B("PUT",`/api/v1/templates/${Y.templateId}`,Y,G);break}case"delete_template":{let G=Y.companyId;X=await B("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 B("GET",`/api/v1/ab-tests${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_ab_test":{let G=Y.companyId;X=await B("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);if(Y.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");X=await B("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((U)=>!$.has(U));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((U)=>`\`${U}\``).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 A=Y.variantCount===void 0?void 0:Number(Y.variantCount);if(A!==void 0&&(!Number.isInteger(A)||A<2||A>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");X=await B("POST",`/api/v1/ab-tests/${Y.abTestId}/restart`,{sourceVariantId:w(Y,"sourceVariantId"),testType:J,winnerThreshold:H,variantCount:A},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(w1("update_ab_test_variant",Y),Y.subject===void 0&&Y.previewText===void 0&&Y.html===void 0&&Y.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");X=await B("PATCH",`/api/v1/ab-tests/${Y.abTestId}/variants/${Y.variantId}`,Y,G);break}case"create_ab_test":{let G=Y.companyId,$=R("create_ab_test",Y,"campaignId"),z=w(Y,"name"),J=x1("create_ab_test",Y,"testPercentage",5,50),H=x1("create_ab_test",Y,"testDurationMinutes",15,1440),A=m0("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((U,K)=>{if(!J0(U)||typeof U.subject!=="string"||U.subject.trim()==="")throw Error(`\`variants\` item ${K+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(U.blocks!==void 0&&!Array.isArray(U.blocks))throw Error(`\`variants\` item ${K+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}X=await B("POST","/api/v1/ab-tests",{campaignId:$,...z!==void 0&&{name:z},...J!==void 0&&{testPercentage:J},...H!==void 0&&{testDurationMinutes:H},...A!==void 0&&{winnerCriteria:A},...Y.variants!==void 0&&{variants:Y.variants}},G);break}case"add_ab_test_variant":{let G=Y.companyId,$=R("add_ab_test_variant",Y,"abTestId"),z=R("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 B("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,$=R("delete_ab_test_variant",Y,"abTestId"),z=R("delete_ab_test_variant",Y,"variantId");X=await B("DELETE",`/api/v1/ab-tests/${encodeURIComponent($)}/variants/${encodeURIComponent(z)}`,void 0,G);break}case"delete_ab_test":{let G=Y.companyId,$=R("delete_ab_test",Y,"abTestId");X=await B("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 B("GET",`/api/v1/campaigns?${$}`,void 0,G);break}case"get_campaign":{let G=Y.companyId;X=await B("GET",`/api/v1/campaigns/${Y.campaignId}`,void 0,G);break}case"get_email_send":{let G=Y.companyId;X=await B("GET",`/api/v1/email-sends/${encodeURIComponent(String(Y.emailSendId))}`,void 0,G);break}case"create_campaign":{let G=Y.companyId;if(_V(Y),Y.fromEmail!==void 0&&Y.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_campaign`, not both.");if(Y.replyTo!==void 0&&Y.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_campaign`, not both.");if(Y.fromName!==void 0&&Y.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_campaign`.");if(Y.replyToName!==void 0&&Y.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_campaign`.");let $=Object.fromEntries(Object.entries(Y).filter(([z])=>z!=="companyId"));X=await B("POST","/api/v1/campaigns",$,G);break}case"update_campaign":{let G=Y.companyId,$=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","campaignData","computedLists","labels"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, and label update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);if(w1("update_campaign",Y),bQ("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.fromEmail!==void 0&&Y.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_campaign`, not both.");if(Y.fromName!==void 0&&Y.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_campaign`.");if(Y.replyToName!==void 0&&Y.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_campaign`.");if(Y.name===void 0&&Y.subject===void 0&&Y.trackingCode===void 0&&Y.html===void 0&&Y.blocks===void 0&&Y.fromEmail===void 0&&Y.senderProfileId===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 campaign content, sending identity, campaign data, computed list, or label field when calling `update_campaign`.");X=await B("PUT",`/api/v1/campaigns/${Y.campaignId}`,Y,G);break}case"schedule_campaign":{let G=Y.companyId,$=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours","recurringInterval"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);yV(Y),X=await B("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},...Y.recurringInterval!==void 0&&{recurringInterval:Y.recurringInterval}},G);break}case"send_test_email":{let G=Y.companyId;X=await B("POST",`/api/v1/campaigns/${Y.campaignId}/test`,{to:Y.to},G);break}case"cancel_campaign":{let G=Y.companyId,$=R("cancel_campaign",Y,"campaignId");X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/cancel`,void 0,G);break}case"pause_campaign":{let G=Y.companyId,$=R("pause_campaign",Y,"campaignId");X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/pause`,void 0,G);break}case"resume_campaign":{let G=Y.companyId,$=R("resume_campaign",Y,"campaignId"),z=x1("resume_campaign",Y,"spreadOverHours",1,72);X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/resume`,{...z!==void 0&&{spreadOverHours:z}},G);break}case"delete_campaign":{let G=Y.companyId,$=R("delete_campaign",Y,"campaignId");X=await B("DELETE",`/api/v1/campaigns/${encodeURIComponent($)}`,void 0,G);break}case"duplicate_campaign":{let G=Y.companyId,$=R("duplicate_campaign",Y,"campaignId"),z=m0("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 B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/duplicate`,{...z!==void 0&&{mode:z},...J!==void 0&&{variantId:J}},G);break}case"resend_campaign_to_non_openers":{let G=Y.companyId,$=R("resend_campaign_to_non_openers",Y,"campaignId");X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/resend-to-non-openers`,void 0,G);break}case"list_landing_pages":{let G=Y.companyId;X=await B("GET","/api/v1/landing-pages",void 0,G);break}case"get_landing_page":{let G=Y.companyId;X=await B("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 B("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,$=nY("update_landing_page",Y,{requireUpdate:!0});X=await B("PUT",`/api/v1/landing-pages/${Y.landingPageId}`,$,G);break}case"publish_landing_page":{let G=Y.companyId,$=nY("publish_landing_page",Y,{requireUpdate:!1});X=await B("POST",`/api/v1/landing-pages/${Y.landingPageId}/publish`,$,G);break}case"unpublish_landing_page":{let G=Y.companyId,$=nY("unpublish_landing_page",Y,{requireUpdate:!1});X=await B("POST",`/api/v1/landing-pages/${Y.landingPageId}/unpublish`,$,G);break}case"delete_landing_page":{let G=Y.companyId;X=await B("DELETE",`/api/v1/landing-pages/${Y.landingPageId}`,void 0,G);break}case"connect_landing_page_domain":{let G=Y.companyId;X=await B("POST","/api/v1/landing-pages/domain",{domain:Y.domain},G);break}case"update_landing_page_domain_settings":{let G=Y.companyId,$=uV(Y);X=await B("PUT","/api/v1/landing-pages/domain",$,G);break}case"list_sequences":{let G=Y.companyId;X=await B("GET","/api/v1/sequences",void 0,G);break}case"get_sequence":{let G=Y.companyId;X=await B("GET",`/api/v1/sequences/${Y.sequenceId}`,void 0,G);break}case"create_sequence":{let G=Y.companyId;if(Y.fromEmail!==void 0&&Y.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_sequence`, not both.");if(Y.replyTo!==void 0&&Y.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_sequence`, not both.");if(Y.fromName!==void 0&&Y.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_sequence`.");if(Y.replyToName!==void 0&&Y.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_sequence`.");let $=Array.isArray(Y.steps)&&Y.steps.length>0,z=await B("POST","/api/v1/sequences",Y,G);if(!z.success){X=z;break}let J=z.sequence.id;if($){let D=await B("GET",`/api/v1/sequences/${J}`,void 0,G);if(D.success)X={success:!0,sequence:D.sequence,message:`Sequence "${D.sequence.name}" created with explicit steps. Review it before enabling.`};else X=D;break}let H=6,A=0,U="pending";while(U!=="complete"&&A<H){await new Promise((L)=>setTimeout(L,20000)),A++;let D=await B("GET",`/api/v1/sequences/${J}`,void 0,G);if(D.success)U=D.sequence.enrichmentStatus}let K=await B("GET",`/api/v1/sequences/${J}`,void 0,G);if(K.success)X={success:!0,sequence:K.sequence,message:K.sequence.enrichmentStatus==="complete"?`Sequence "${K.sequence.name}" created with ${K.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.`:`Sequence "${K.sequence.name}" created. Email enrichment is still in progress (${K.sequence.enrichedCount}/${K.sequence.emailCount} emails generated). You can check status with get_sequence.`};else X=K;break}case"update_sequence":{let G=Y.companyId,$=kV(Y);X=await B("PUT",`/api/v1/sequences/${Y.sequenceId}`,$,G);break}case"insert_sequence_step":{let G=Y.companyId,$=vV(Y);X=await B("PUT",`/api/v1/sequences/${Y.sequenceId}`,$,G);break}case"enable_sequence":{let G=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/enable`,void 0,G);break}case"disable_sequence":{let G=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/disable`,void 0,G);break}case"pause_sequence_enrollments":{let G=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/pause-enrollments`,void 0,G);break}case"resume_sequence_enrollments":{let G=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/resume-enrollments`,void 0,G);break}case"enroll_subscribers_in_sequence":{let G=Y.companyId,$=R("enroll_subscribers_in_sequence",Y,"sequenceId"),z=iV(Y);X=await B("POST",`/api/v1/sequences/${encodeURIComponent($)}/enroll`,z,G);break}case"cancel_sequence_enrollments":{let G=Y.companyId,$=xV(Y);X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/enrollments/cancel`,$,G);break}case"delete_sequence":{let G=Y.companyId;X=await B("DELETE",`/api/v1/sequences/${Y.sequenceId}`,void 0,G);break}case"list_transactional_emails":{let G=Y.companyId;X=await B("GET","/api/v1/transactional",void 0,G);break}case"get_transactional_email":{let G=Y.companyId;X=await B("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((H)=>!$.has(H));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((H)=>`\`${H}\``).join(", ")}.`);hV(Y);let J=Object.fromEntries(Object.entries(Y).filter(([H])=>H!=="companyId"));X=await B("POST","/api/v1/transactional",J,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(w1("update_transactional_email",Y),Y.name===void 0&&Y.enabled===void 0&&Y.subject===void 0&&Y.previewText===void 0&&Y.html===void 0&&Y.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let J=Object.fromEntries(Object.entries(Y).filter(([H])=>H!=="companyId"&&H!=="idOrSlug"));X=await B("PATCH",`/api/v1/transactional/${Y.idOrSlug}`,J,G);break}case"send_email":{let G=Y.companyId;X=await B("POST","/api/v1/transactional/send",Y,G);break}case"get_stats":{let G=Y.companyId,$=Y.period??"7d",z=new URLSearchParams({period:String($)});if(Y.includeMachineEngagement===!0)z.set("includeMachineEngagement","true");X=await B("GET",`/api/v1/metrics?${z.toString()}`,void 0,G);break}case"get_campaign_stats":{let G=Y.companyId,$=new URLSearchParams;if(Y.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");let z=$.toString();X=await B("GET",`/api/v1/metrics/campaigns/${Y.campaignId}${z?`?${z}`:""}`,void 0,G);break}case"get_sequence_stats":{let G=Y.companyId,$=new URLSearchParams;if(Y.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");let z=$.toString();X=await B("GET",`/api/v1/metrics/sequences/${Y.sequenceId}${z?`?${z}`:""}`,void 0,G);break}case"list_campaign_events":{let G=Y.companyId,$=R("list_campaign_events",Y,"campaignId"),J=GH("list_campaign_events",Y).toString();X=await B("GET",`/api/v1/metrics/campaigns/${encodeURIComponent($)}/events${J?`?${J}`:""}`,void 0,G);break}case"list_sequence_events":{let G=Y.companyId,$=R("list_sequence_events",Y,"sequenceId"),J=GH("list_sequence_events",Y).toString();X=await B("GET",`/api/v1/metrics/sequences/${encodeURIComponent($)}/events${J?`?${J}`:""}`,void 0,G);break}case"get_subscriber_activity":{let G=Y.companyId,$=v1("get_subscriber_activity",Y),z=await dY($,G,{includeMachineEngagement:Y.includeMachineEngagement===!0});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 B("GET","/api/v1/team",void 0,G);break}case"invite_team_member":{let G=Y.companyId,$=R("invite_team_member",Y,"email"),z=oY("invite_team_member",Y,"role",["admin","viewer","restricted"]);if(Y.canManageBilling!==void 0&&typeof Y.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");X=await B("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,$=R("cancel_team_invitation",Y,"invitationId");X=await B("DELETE",`/api/v1/team/invitations/${encodeURIComponent($)}`,void 0,G);break}case"list_conversations":{let G=Y.companyId,$=new URLSearchParams,z=m0("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=x1("list_conversations",Y,"limit",1,100);if(H!==void 0)$.set("limit",String(H));X=await B("GET",`/api/v1/conversations${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_conversation":{let G=Y.companyId,$=R("get_conversation",Y,"conversationId");X=await B("GET",`/api/v1/conversations/${encodeURIComponent($)}`,void 0,G);break}case"reply_to_conversation":{let G=Y.companyId,$=R("reply_to_conversation",Y,"conversationId"),z=m0("reply_to_conversation",Y,"type",["outbound","note"])??"outbound",J=w(Y,"subject"),H=w(Y,"bodyText"),A=w(Y,"bodyHtml");if(z==="outbound"&&H===void 0&&A===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");X=await B("POST",`/api/v1/conversations/${encodeURIComponent($)}/messages`,{type:z,...J!==void 0&&{subject:J},...H!==void 0&&{bodyText:H},...A!==void 0&&{bodyHtml:A}},G);break}case"update_conversation_status":{let G=Y.companyId,$=R("update_conversation_status",Y,"conversationId"),z=oY("update_conversation_status",Y,"status",["open","closed"]);X=await B("POST",`/api/v1/conversations/${encodeURIComponent($)}/status`,{status:z},G);break}case"mark_conversation_read":{let G=Y.companyId,$=R("mark_conversation_read",Y,"conversationId");X=await B("POST",`/api/v1/conversations/${encodeURIComponent($)}/read`,void 0,G);break}case"list_webhooks":{let G=Y.companyId;X=await B("GET","/api/v1/webhooks",void 0,G);break}case"create_webhook":{let G=Y.companyId,$=R("create_webhook",Y,"name"),z=R("create_webhook",Y,"url"),J=$H("create_webhook",Y);X=await B("POST","/api/v1/webhooks",{name:$,url:z,...J!==void 0&&{events:J}},G);break}case"update_webhook":{let G=Y.companyId,$=R("update_webhook",Y,"webhookId"),z=w(Y,"name"),J=w(Y,"url"),H=$H("update_webhook",Y),A=m0("update_webhook",Y,"status",["enabled","disabled"]);if(z===void 0&&J===void 0&&H===void 0&&A===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");X=await B("PATCH",`/api/v1/webhooks/${encodeURIComponent($)}`,{...z!==void 0&&{name:z},...J!==void 0&&{url:J},...H!==void 0&&{events:H},...A!==void 0&&{status:A}},G);break}case"delete_webhook":{let G=Y.companyId,$=R("delete_webhook",Y,"webhookId");X=await B("DELETE",`/api/v1/webhooks/${encodeURIComponent($)}`,void 0,G);break}case"test_webhook":{let G=Y.companyId,$=R("test_webhook",Y,"webhookId");X=await B("POST",`/api/v1/webhooks/${encodeURIComponent($)}/test`,void 0,G);break}case"list_webhook_deliveries":{let G=Y.companyId,$=R("list_webhook_deliveries",Y,"webhookId"),z=x1("list_webhook_deliveries",Y,"limit",1,100),J=new URLSearchParams;if(z!==void 0)J.set("limit",String(z));X=await B("GET",`/api/v1/webhooks/${encodeURIComponent($)}/deliveries${J.size>0?`?${J}`:""}`,void 0,G);break}case"replay_webhook_delivery":{let G=Y.companyId,$=R("replay_webhook_delivery",Y,"webhookId"),z=R("replay_webhook_delivery",Y,"deliveryId");X=await B("POST",`/api/v1/webhooks/${encodeURIComponent($)}/deliveries/${encodeURIComponent(z)}/replay`,void 0,G);break}case"generate_email":{let G=Y.companyId;X=await B("POST","/api/v1/generate/email",Y,G);break}case"generate_sequence":{let G=Y.companyId;X=await B("POST","/api/v1/generate/sequence",Y,G);break}case"generate_subject_lines":{let G=Y.companyId;X=await B("POST","/api/v1/generate/subjects",Y,G);break}case"generate_sms":{let G=Y.companyId;X=await B("POST","/api/v1/generate/sms",Y,G);break}case"get_sms_settings":{let G=Y.companyId;X=await B("GET","/api/v1/sms/settings",void 0,G);break}case"send_test_sms":{let G=Y.companyId,$={to:R("send_test_sms",Y,"to")};for(let z of["text","imageUrls","blocks"])if(Y[z]!==void 0)$[z]=Y[z];X=await B("POST","/api/v1/sms/test",$,G);break}case"submit_feedback":{let G=Y.companyId,$={message:R("submit_feedback",Y,"message"),source:"mcp"};for(let z of["category","context"])if(Y[z]!==void 0)$[z]=Y[z];X=await B("POST","/api/v1/feedback",$,G);break}default:throw Error(`Unknown tool: ${Q}`)}let W=fV(X);if(W)throw W;return X=await sV(Q,Y,X),{structuredContent:HZ(X),content:[{type:"text",text:JSON.stringify(X,null,2)}]}}catch(X){return{isError:!0,content:[{type:"text",text:$1(X)}]}}}async function DH(Q,Y,X){let W=Y.getRequestContext?.(Q)??{};try{return await SQ(W,X)}finally{await Y.onRequestContextUpdated?.(W,Q)}}function HX(Q={}){let Y=new lY({name:"sequenzy",version:p5.version},{capabilities:{tools:{},resources:{}},instructions:["Sequenzy email marketing MCP server: manage subscribers, campaigns, sequences, templates, and delivery stats.","If you have access to multiple companies, call get_account and then select_company (or pass companyId per call) before other tools.","IMPORTANT: whenever the user wanted to accomplish something and these tools did not expose functionality for it (missing tool, missing argument, unsupported workflow, or broken behavior), call submit_feedback describing the gap before finishing the task. The Sequenzy team reads every submission and uses it to decide what to build next."].join(`
|
|
191
191
|
`)});return Y.setRequestHandler(T9,async()=>{return{tools:UH}}),Y.setRequestHandler(I4,async(X,W)=>{let{name:G,arguments:$}=X.params;return DH(W,Q,()=>KH(G,$??{}))}),Y.setRequestHandler(N9,async()=>{return{resources:r5}}),Y.setRequestHandler(P9,async(X,W)=>{let{uri:G}=X.params;return DH(W,Q,()=>d5(G))}),Y}import LH from"node:process";class AX{append(Q){this._buffer=this._buffer?Buffer.concat([this._buffer,Q]):Q}readMessage(){if(!this._buffer)return null;let Q=this._buffer.indexOf(`
|
|
192
192
|
`);if(Q===-1)return null;let Y=this._buffer.toString("utf8",0,Q).replace(/\r$/,"");return this._buffer=this._buffer.subarray(Q+1),UZ(Y)}clear(){this._buffer=void 0}}function UZ(Q){return eG.parse(JSON.parse(Q))}function BH(Q){return JSON.stringify(Q)+`
|
|
193
193
|
`}class UX{constructor(Q=LH.stdin,Y=LH.stdout){this._stdin=Q,this._stdout=Y,this._readBuffer=new AX,this._started=!1,this._ondata=(X)=>{this._readBuffer.append(X),this.processReadBuffer()},this._onerror=(X)=>{this.onerror?.(X)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let Q=this._readBuffer.readMessage();if(Q===null)break;this.onmessage?.(Q)}catch(Q){this.onerror?.(Q)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(Q){return new Promise((Y)=>{let X=BH(Q);if(this._stdout.write(X))Y();else this._stdout.once("drain",Y)})}}async function KZ(){ZX(),qX();let Q=HX(),Y=new UX;await Q.connect(Y),console.error("Sequenzy MCP server running on stdio")}KZ().catch((Q)=>{console.error($1(Q)),process.exit(1)});export{SQ as withMcpRequestContext,Q6 as setSelectedCompanyId,b1 as getSelectedCompanyId,HX as createSequenzyMcpServer,B as apiRequest};
|