@sequenzy/mcp 0.0.27 → 0.0.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -27,7 +27,7 @@ var O5=Object.create;var{getPrototypeOf:M5,defineProperty:AQ,getOwnPropertyNames
27
27
 
28
28
  `)}L.write("payload.value = newResult;"),L.write("return payload;");let T=L.compile();return(I,x)=>T(B,I,x)},J,$=U1,z=!h6.jitless,A=z&&DQ.value,K=X.catchall,U;Q._zod.parse=(B,L)=>{U??(U=W.value);let q=B.value;if(!$(q))return B.issues.push({expected:"object",code:"invalid_type",input:q,inst:Q}),B;if(z&&A&&L?.async===!1&&L.jitless!==!0){if(!J)J=G(X.shape);if(B=J(B,L),!K)return B;return IY([],q,B,L,U,Q)}return Y(B,L)}});function m8(Q,X,Y,W){for(let J of Q)if(J.issues.length===0)return X.value=J.value,X;let G=Q.filter((J)=>!s0(J));if(G.length===1)return X.value=G[0].value,G[0];return X.issues.push({code:"invalid_union",input:X.value,inst:Y,errors:Q.map((J)=>J.issues.map(($)=>I0($,W,Z0())))}),X}var PQ=F("$ZodUnion",(Q,X)=>{i.init(Q,X),m(Q._zod,"optin",()=>X.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),m(Q._zod,"optout",()=>X.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),m(Q._zod,"values",()=>{if(X.options.every((G)=>G._zod.values))return new Set(X.options.flatMap((G)=>Array.from(G._zod.values)));return}),m(Q._zod,"pattern",()=>{if(X.options.every((G)=>G._zod.pattern)){let G=X.options.map((J)=>J._zod.pattern);return new RegExp(`^(${G.map((J)=>r1(J.source)).join("|")})$`)}return});let Y=X.options.length===1,W=X.options[0]._zod.run;Q._zod.parse=(G,J)=>{if(Y)return W(G,J);let $=!1,z=[];for(let H of X.options){let A=H._zod.run({value:G.value,issues:[]},J);if(A instanceof Promise)z.push(A),$=!0;else{if(A.issues.length===0)return A;z.push(A)}}if(!$)return m8(z,G,Q,J);return Promise.all(z).then((H)=>{return m8(H,G,Q,J)})}}),TY=F("$ZodDiscriminatedUnion",(Q,X)=>{PQ.init(Q,X);let Y=Q._zod.parse;m(Q._zod,"propValues",()=>{let G={};for(let J of X.options){let $=J._zod.propValues;if(!$||Object.keys($).length===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(J)}"`);for(let[z,H]of Object.entries($)){if(!G[z])G[z]=new Set;for(let A of H)G[z].add(A)}}return G});let W=N1(()=>{let G=X.options,J=new Map;for(let $ of G){let z=$._zod.propValues?.[X.discriminator];if(!z||z.size===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf($)}"`);for(let H of z){if(J.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);J.set(H,$)}}return J});Q._zod.parse=(G,J)=>{let $=G.value;if(!U1($))return G.issues.push({code:"invalid_type",expected:"object",input:$,inst:Q}),G;let z=W.value.get($?.[X.discriminator]);if(z)return z._zod.run(G,J);if(X.unionFallback)return Y(G,J);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:X.discriminator,input:$,path:[X.discriminator],inst:Q}),G}}),SY=F("$ZodIntersection",(Q,X)=>{i.init(Q,X),Q._zod.parse=(Y,W)=>{let G=Y.value,J=X.left._zod.run({value:G,issues:[]},W),$=X.right._zod.run({value:G,issues:[]},W);if(J instanceof Promise||$ instanceof Promise)return Promise.all([J,$]).then(([H,A])=>{return c8(Y,H,A)});return c8(Y,J,$)}});function bQ(Q,X){if(Q===X)return{valid:!0,data:Q};if(Q instanceof Date&&X instanceof Date&&+Q===+X)return{valid:!0,data:Q};if(a0(Q)&&a0(X)){let Y=Object.keys(X),W=Object.keys(Q).filter((J)=>Y.indexOf(J)!==-1),G={...Q,...X};for(let J of W){let $=bQ(Q[J],X[J]);if(!$.valid)return{valid:!1,mergeErrorPath:[J,...$.mergeErrorPath]};G[J]=$.data}return{valid:!0,data:G}}if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return{valid:!1,mergeErrorPath:[]};let Y=[];for(let W=0;W<Q.length;W++){let G=Q[W],J=X[W],$=bQ(G,J);if(!$.valid)return{valid:!1,mergeErrorPath:[W,...$.mergeErrorPath]};Y.push($.data)}return{valid:!0,data:Y}}return{valid:!1,mergeErrorPath:[]}}function c8(Q,X,Y){if(X.issues.length)Q.issues.push(...X.issues);if(Y.issues.length)Q.issues.push(...Y.issues);if(s0(Q))return Q;let W=bQ(X.value,Y.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return Q.value=W.data,Q}var RY=F("$ZodRecord",(Q,X)=>{i.init(Q,X),Q._zod.parse=(Y,W)=>{let G=Y.value;if(!a0(G))return Y.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),Y;let J=[];if(X.keyType._zod.values){let $=X.keyType._zod.values;Y.value={};for(let H of $)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let A=X.valueType._zod.run({value:G[H],issues:[]},W);if(A instanceof Promise)J.push(A.then((K)=>{if(K.issues.length)Y.issues.push(...l0(H,K.issues));Y.value[H]=K.value}));else{if(A.issues.length)Y.issues.push(...l0(H,A.issues));Y.value[H]=A.value}}let z;for(let H in G)if(!$.has(H))z=z??[],z.push(H);if(z&&z.length>0)Y.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:z})}else{Y.value={};for(let $ of Reflect.ownKeys(G)){if($==="__proto__")continue;let z=X.keyType._zod.run({value:$,issues:[]},W);if(z instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(z.issues.length){Y.issues.push({code:"invalid_key",origin:"record",issues:z.issues.map((A)=>I0(A,W,Z0())),input:$,path:[$],inst:Q}),Y.value[z.value]=z.value;continue}let H=X.valueType._zod.run({value:G[$],issues:[]},W);if(H instanceof Promise)J.push(H.then((A)=>{if(A.issues.length)Y.issues.push(...l0($,A.issues));Y.value[z.value]=A.value}));else{if(H.issues.length)Y.issues.push(...l0($,H.issues));Y.value[z.value]=H.value}}}if(J.length)return Promise.all(J).then(()=>Y);return Y}});var CY=F("$ZodEnum",(Q,X)=>{i.init(Q,X);let Y=UQ(X.entries),W=new Set(Y);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${Y.filter((G)=>LQ.has(typeof G)).map((G)=>typeof G==="string"?f0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,J)=>{let $=G.value;if(W.has($))return G;return G.issues.push({code:"invalid_value",values:Y,input:$,inst:Q}),G}}),kY=F("$ZodLiteral",(Q,X)=>{if(i.init(Q,X),X.values.length===0)throw Error("Cannot create literal schema with no valid values");Q._zod.values=new Set(X.values),Q._zod.pattern=new RegExp(`^(${X.values.map((Y)=>typeof Y==="string"?f0(Y):Y?f0(Y.toString()):String(Y)).join("|")})$`),Q._zod.parse=(Y,W)=>{let G=Y.value;if(Q._zod.values.has(G))return Y;return Y.issues.push({code:"invalid_value",values:X.values,input:G,inst:Q}),Y}});var vY=F("$ZodTransform",(Q,X)=>{i.init(Q,X),Q._zod.parse=(Y,W)=>{if(W.direction==="backward")throw new c1(Q.constructor.name);let G=X.transform(Y.value,Y);if(W.async)return(G instanceof Promise?G:Promise.resolve(G)).then(($)=>{return Y.value=$,Y});if(G instanceof Promise)throw new h0;return Y.value=G,Y}});function p8(Q,X){if(Q.issues.length&&X===void 0)return{issues:[],value:void 0};return Q}var xY=F("$ZodOptional",(Q,X)=>{i.init(Q,X),Q._zod.optin="optional",Q._zod.optout="optional",m(Q._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,void 0]):void 0}),m(Q._zod,"pattern",()=>{let Y=X.innerType._zod.pattern;return Y?new RegExp(`^(${r1(Y.source)})?$`):void 0}),Q._zod.parse=(Y,W)=>{if(X.innerType._zod.optin==="optional"){let G=X.innerType._zod.run(Y,W);if(G instanceof Promise)return G.then((J)=>p8(J,Y.value));return p8(G,Y.value)}if(Y.value===void 0)return Y;return X.innerType._zod.run(Y,W)}}),_Y=F("$ZodNullable",(Q,X)=>{i.init(Q,X),m(Q._zod,"optin",()=>X.innerType._zod.optin),m(Q._zod,"optout",()=>X.innerType._zod.optout),m(Q._zod,"pattern",()=>{let Y=X.innerType._zod.pattern;return Y?new RegExp(`^(${r1(Y.source)}|null)$`):void 0}),m(Q._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,null]):void 0}),Q._zod.parse=(Y,W)=>{if(Y.value===null)return Y;return X.innerType._zod.run(Y,W)}}),yY=F("$ZodDefault",(Q,X)=>{i.init(Q,X),Q._zod.optin="optional",m(Q._zod,"values",()=>X.innerType._zod.values),Q._zod.parse=(Y,W)=>{if(W.direction==="backward")return X.innerType._zod.run(Y,W);if(Y.value===void 0)return Y.value=X.defaultValue,Y;let G=X.innerType._zod.run(Y,W);if(G instanceof Promise)return G.then((J)=>i8(J,X));return i8(G,X)}});function i8(Q,X){if(Q.value===void 0)Q.value=X.defaultValue;return Q}var gY=F("$ZodPrefault",(Q,X)=>{i.init(Q,X),Q._zod.optin="optional",m(Q._zod,"values",()=>X.innerType._zod.values),Q._zod.parse=(Y,W)=>{if(W.direction==="backward")return X.innerType._zod.run(Y,W);if(Y.value===void 0)Y.value=X.defaultValue;return X.innerType._zod.run(Y,W)}}),uY=F("$ZodNonOptional",(Q,X)=>{i.init(Q,X),m(Q._zod,"values",()=>{let Y=X.innerType._zod.values;return Y?new Set([...Y].filter((W)=>W!==void 0)):void 0}),Q._zod.parse=(Y,W)=>{let G=X.innerType._zod.run(Y,W);if(G instanceof Promise)return G.then((J)=>r8(J,Q));return r8(G,Q)}});function r8(Q,X){if(!Q.issues.length&&Q.value===void 0)Q.issues.push({code:"invalid_type",expected:"nonoptional",input:Q.value,inst:X});return Q}var hY=F("$ZodCatch",(Q,X)=>{i.init(Q,X),m(Q._zod,"optin",()=>X.innerType._zod.optin),m(Q._zod,"optout",()=>X.innerType._zod.optout),m(Q._zod,"values",()=>X.innerType._zod.values),Q._zod.parse=(Y,W)=>{if(W.direction==="backward")return X.innerType._zod.run(Y,W);let G=X.innerType._zod.run(Y,W);if(G instanceof Promise)return G.then((J)=>{if(Y.value=J.value,J.issues.length)Y.value=X.catchValue({...Y,error:{issues:J.issues.map(($)=>I0($,W,Z0()))},input:Y.value}),Y.issues=[];return Y});if(Y.value=G.value,G.issues.length)Y.value=X.catchValue({...Y,error:{issues:G.issues.map((J)=>I0(J,W,Z0()))},input:Y.value}),Y.issues=[];return Y}});var fY=F("$ZodPipe",(Q,X)=>{i.init(Q,X),m(Q._zod,"values",()=>X.in._zod.values),m(Q._zod,"optin",()=>X.in._zod.optin),m(Q._zod,"optout",()=>X.out._zod.optout),m(Q._zod,"propValues",()=>X.in._zod.propValues),Q._zod.parse=(Y,W)=>{if(W.direction==="backward"){let J=X.out._zod.run(Y,W);if(J instanceof Promise)return J.then(($)=>o6($,X.in,W));return o6(J,X.in,W)}let G=X.in._zod.run(Y,W);if(G instanceof Promise)return G.then((J)=>o6(J,X.out,W));return o6(G,X.out,W)}});function o6(Q,X,Y){if(Q.issues.length)return Q.aborted=!0,Q;return X._zod.run({value:Q.value,issues:Q.issues},Y)}var lY=F("$ZodReadonly",(Q,X)=>{i.init(Q,X),m(Q._zod,"propValues",()=>X.innerType._zod.propValues),m(Q._zod,"values",()=>X.innerType._zod.values),m(Q._zod,"optin",()=>X.innerType._zod.optin),m(Q._zod,"optout",()=>X.innerType._zod.optout),Q._zod.parse=(Y,W)=>{if(W.direction==="backward")return X.innerType._zod.run(Y,W);let G=X.innerType._zod.run(Y,W);if(G instanceof Promise)return G.then(n8);return n8(G)}});function n8(Q){return Q.value=Object.freeze(Q.value),Q}var mY=F("$ZodCustom",(Q,X)=>{X0.init(Q,X),i.init(Q,X),Q._zod.parse=(Y,W)=>{return Y},Q._zod.check=(Y)=>{let W=Y.value,G=X.fn(W);if(G instanceof Promise)return G.then((J)=>d8(J,Y,W,Q));d8(G,Y,W,Q);return}});function d8(Q,X,Y,W){if(!Q){let G={code:"custom",input:Y,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)G.params=W._zod.def.params;X.issues.push(w1(G))}}var WH=(Q)=>{let X=typeof Q;switch(X){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 X},GH=()=>{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 X(W){return Q[W]??null}let Y={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 ${WH(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${c6(W.values[0])}`;return`Invalid option: expected one of ${f6(W.values,"|")}`;case"too_big":{let G=W.inclusive?"<=":"<",J=X(W.origin);if(J)return`Too big: expected ${W.origin??"value"} to have ${G}${W.maximum.toString()} ${J.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${G}${W.maximum.toString()}`}case"too_small":{let G=W.inclusive?">=":">",J=X(W.origin);if(J)return`Too small: expected ${W.origin} to have ${G}${W.minimum.toString()} ${J.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 ${Y[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":""}: ${f6(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 IQ(){return{localeError:GH()}}var vM=Symbol("ZodOutput"),xM=Symbol("ZodInput");class cY{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Q,...X){let Y=X[0];if(this._map.set(Q,Y),Y&&typeof Y==="object"&&"id"in Y){if(this._idmap.has(Y.id))throw Error(`ID ${Y.id} already exists in the registry`);this._idmap.set(Y.id,Q)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Q){let X=this._map.get(Q);if(X&&typeof X==="object"&&"id"in X)this._idmap.delete(X.id);return this._map.delete(Q),this}get(Q){let X=Q._zod.parent;if(X){let Y={...this.get(X)??{}};delete Y.id;let W={...Y,...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 JH(){return new cY}var s1=JH();function pY(Q,X){return new Q({type:"string",...P(X)})}function iY(Q,X){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...P(X)})}function EQ(Q,X){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...P(X)})}function rY(Q,X){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...P(X)})}function nY(Q,X){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...P(X)})}function dY(Q,X){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...P(X)})}function oY(Q,X){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...P(X)})}function tY(Q,X){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...P(X)})}function aY(Q,X){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...P(X)})}function sY(Q,X){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...P(X)})}function eY(Q,X){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...P(X)})}function QW(Q,X){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...P(X)})}function XW(Q,X){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...P(X)})}function YW(Q,X){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...P(X)})}function WW(Q,X){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...P(X)})}function GW(Q,X){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...P(X)})}function JW(Q,X){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...P(X)})}function $W(Q,X){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...P(X)})}function zW(Q,X){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...P(X)})}function HW(Q,X){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...P(X)})}function AW(Q,X){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...P(X)})}function KW(Q,X){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...P(X)})}function UW(Q,X){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...P(X)})}function BW(Q,X){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...P(X)})}function DW(Q,X){return new Q({type:"string",format:"date",check:"string_format",...P(X)})}function LW(Q,X){return new Q({type:"string",format:"time",check:"string_format",precision:null,...P(X)})}function FW(Q,X){return new Q({type:"string",format:"duration",check:"string_format",...P(X)})}function qW(Q,X){return new Q({type:"number",checks:[],...P(X)})}function OW(Q,X){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...P(X)})}function MW(Q,X){return new Q({type:"boolean",...P(X)})}function VW(Q,X){return new Q({type:"null",...P(X)})}function ZW(Q){return new Q({type:"unknown"})}function NW(Q,X){return new Q({type:"never",...P(X)})}function s6(Q,X){return new ZQ({check:"less_than",...P(X),value:Q,inclusive:!1})}function e1(Q,X){return new ZQ({check:"less_than",...P(X),value:Q,inclusive:!0})}function e6(Q,X){return new NQ({check:"greater_than",...P(X),value:Q,inclusive:!1})}function Q6(Q,X){return new NQ({check:"greater_than",...P(X),value:Q,inclusive:!0})}function Q4(Q,X){return new E8({check:"multiple_of",...P(X),value:Q})}function X4(Q,X){return new S8({check:"max_length",...P(X),maximum:Q})}function b1(Q,X){return new R8({check:"min_length",...P(X),minimum:Q})}function Y4(Q,X){return new C8({check:"length_equals",...P(X),length:Q})}function TQ(Q,X){return new k8({check:"string_format",format:"regex",...P(X),pattern:Q})}function SQ(Q){return new v8({check:"string_format",format:"lowercase",...P(Q)})}function RQ(Q){return new x8({check:"string_format",format:"uppercase",...P(Q)})}function CQ(Q,X){return new _8({check:"string_format",format:"includes",...P(X),includes:Q})}function kQ(Q,X){return new y8({check:"string_format",format:"starts_with",...P(X),prefix:Q})}function vQ(Q,X){return new g8({check:"string_format",format:"ends_with",...P(X),suffix:Q})}function B1(Q){return new u8({check:"overwrite",tx:Q})}function xQ(Q){return B1((X)=>X.normalize(Q))}function _Q(){return B1((Q)=>Q.trim())}function yQ(){return B1((Q)=>Q.toLowerCase())}function gQ(){return B1((Q)=>Q.toUpperCase())}function wW(Q,X,Y){return new Q({type:"array",element:X,...P(Y)})}function bW(Q,X,Y){let W=P(Y);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:X,...W})}function jW(Q,X,Y){return new Q({type:"custom",check:"custom",fn:X,...P(Y)})}function PW(Q){let X=$H((Y)=>{return Y.addIssue=(W)=>{if(typeof W==="string")Y.issues.push(w1(W,Y.value,X._zod.def));else{let G=W;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=Y.value),G.inst??(G.inst=X),G.continue??(G.continue=!X._zod.def.abort),Y.issues.push(w1(G))}},Q(Y.value,Y)});return X}function $H(Q,X){let Y=new X0({check:"custom",...P(X)});return Y._zod.check=Q,Y}function j1(Q){return!!Q._zod}function e0(Q,X){if(j1(Q))return o1(Q,X);return Q.safeParse(X)}function W4(Q){if(!Q)return;let X;if(j1(Q))X=Q._zod?.def?.shape;else X=Q.shape;if(!X)return;if(typeof X==="function")try{return X()}catch{return}return X}function IW(Q){if(j1(Q)){let J=Q._zod?.def;if(J){if(J.value!==void 0)return J.value;if(Array.isArray(J.values)&&J.values.length>0)return J.values[0]}}let Y=Q._def;if(Y){if(Y.value!==void 0)return Y.value;if(Array.isArray(Y.values)&&Y.values.length>0)return Y.values[0]}let W=Q.value;if(W!==void 0)return W;return}var Y6={};CX(Y6,{time:()=>fQ,duration:()=>lQ,datetime:()=>uQ,date:()=>hQ,ZodISOTime:()=>SW,ZodISODuration:()=>RW,ZodISODateTime:()=>EW,ZodISODate:()=>TW});var EW=F("ZodISODateTime",(Q,X)=>{$Y.init(Q,X),d.init(Q,X)});function uQ(Q){return BW(EW,Q)}var TW=F("ZodISODate",(Q,X)=>{zY.init(Q,X),d.init(Q,X)});function hQ(Q){return DW(TW,Q)}var SW=F("ZodISOTime",(Q,X)=>{HY.init(Q,X),d.init(Q,X)});function fQ(Q){return LW(SW,Q)}var RW=F("ZodISODuration",(Q,X)=>{AY.init(Q,X),d.init(Q,X)});function lQ(Q){return FW(RW,Q)}var CW=(Q,X)=>{p6.init(Q,X),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(Y)=>mX(Q,Y)},flatten:{value:(Y)=>lX(Q,Y)},addIssue:{value:(Y)=>{Q.issues.push(Y),Q.message=JSON.stringify(Q.issues,Z1,2)}},addIssues:{value:(Y)=>{Q.issues.push(...Y),Q.message=JSON.stringify(Q.issues,Z1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},VV=F("ZodError",CW),M0=F("ZodError",CW,{Parent:Error});var kW=i6(M0),vW=r6(M0),xW=d1(M0),_W=t1(M0),yW=cX(M0),gW=pX(M0),uW=iX(M0),hW=rX(M0),fW=nX(M0),lW=dX(M0),mW=oX(M0),cW=tX(M0);var s=F("ZodType",(Q,X)=>{return i.init(Q,X),Q.def=X,Q.type=X.type,Object.defineProperty(Q,"_def",{value:X}),Q.check=(...Y)=>{return Q.clone(h.mergeDefs(X,{checks:[...X.checks??[],...Y.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},Q.clone=(Y,W)=>P0(Q,Y,W),Q.brand=()=>Q,Q.register=(Y,W)=>{return Y.add(Q,W),Q},Q.parse=(Y,W)=>kW(Q,Y,W,{callee:Q.parse}),Q.safeParse=(Y,W)=>xW(Q,Y,W),Q.parseAsync=async(Y,W)=>vW(Q,Y,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(Y,W)=>_W(Q,Y,W),Q.spa=Q.safeParseAsync,Q.encode=(Y,W)=>yW(Q,Y,W),Q.decode=(Y,W)=>gW(Q,Y,W),Q.encodeAsync=async(Y,W)=>uW(Q,Y,W),Q.decodeAsync=async(Y,W)=>hW(Q,Y,W),Q.safeEncode=(Y,W)=>fW(Q,Y,W),Q.safeDecode=(Y,W)=>lW(Q,Y,W),Q.safeEncodeAsync=async(Y,W)=>mW(Q,Y,W),Q.safeDecodeAsync=async(Y,W)=>cW(Q,Y,W),Q.refine=(Y,W)=>Q.check(Y3(Y,W)),Q.superRefine=(Y)=>Q.check(W3(Y)),Q.overwrite=(Y)=>Q.check(B1(Y)),Q.optional=()=>a(Q),Q.nullable=()=>rW(Q),Q.nullish=()=>a(rW(Q)),Q.nonoptional=(Y)=>tH(Q,Y),Q.array=()=>_(Q),Q.or=(Y)=>p([Q,Y]),Q.and=(Y)=>J4(Q,Y),Q.transform=(Y)=>cQ(Q,aW(Y)),Q.default=(Y)=>nH(Q,Y),Q.prefault=(Y)=>oH(Q,Y),Q.catch=(Y)=>sH(Q,Y),Q.pipe=(Y)=>cQ(Q,Y),Q.readonly=()=>X3(Q),Q.describe=(Y)=>{let W=Q.clone();return s1.add(W,{description:Y}),W},Object.defineProperty(Q,"description",{get(){return s1.get(Q)?.description},configurable:!0}),Q.meta=(...Y)=>{if(Y.length===0)return s1.get(Q);let W=Q.clone();return s1.add(W,Y[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),nW=F("_ZodString",(Q,X)=>{a6.init(Q,X),s.init(Q,X);let Y=Q._zod.bag;Q.format=Y.format??null,Q.minLength=Y.minimum??null,Q.maxLength=Y.maximum??null,Q.regex=(...W)=>Q.check(TQ(...W)),Q.includes=(...W)=>Q.check(CQ(...W)),Q.startsWith=(...W)=>Q.check(kQ(...W)),Q.endsWith=(...W)=>Q.check(vQ(...W)),Q.min=(...W)=>Q.check(b1(...W)),Q.max=(...W)=>Q.check(X4(...W)),Q.length=(...W)=>Q.check(Y4(...W)),Q.nonempty=(...W)=>Q.check(b1(1,...W)),Q.lowercase=(W)=>Q.check(SQ(W)),Q.uppercase=(W)=>Q.check(RQ(W)),Q.trim=()=>Q.check(_Q()),Q.normalize=(...W)=>Q.check(xQ(...W)),Q.toLowerCase=()=>Q.check(yQ()),Q.toUpperCase=()=>Q.check(gQ())}),FH=F("ZodString",(Q,X)=>{a6.init(Q,X),nW.init(Q,X),Q.email=(Y)=>Q.check(iY(qH,Y)),Q.url=(Y)=>Q.check(tY(OH,Y)),Q.jwt=(Y)=>Q.check(UW(kH,Y)),Q.emoji=(Y)=>Q.check(aY(MH,Y)),Q.guid=(Y)=>Q.check(EQ(pW,Y)),Q.uuid=(Y)=>Q.check(rY(G4,Y)),Q.uuidv4=(Y)=>Q.check(nY(G4,Y)),Q.uuidv6=(Y)=>Q.check(dY(G4,Y)),Q.uuidv7=(Y)=>Q.check(oY(G4,Y)),Q.nanoid=(Y)=>Q.check(sY(VH,Y)),Q.guid=(Y)=>Q.check(EQ(pW,Y)),Q.cuid=(Y)=>Q.check(eY(ZH,Y)),Q.cuid2=(Y)=>Q.check(QW(NH,Y)),Q.ulid=(Y)=>Q.check(XW(wH,Y)),Q.base64=(Y)=>Q.check(HW(SH,Y)),Q.base64url=(Y)=>Q.check(AW(RH,Y)),Q.xid=(Y)=>Q.check(YW(bH,Y)),Q.ksuid=(Y)=>Q.check(WW(jH,Y)),Q.ipv4=(Y)=>Q.check(GW(PH,Y)),Q.ipv6=(Y)=>Q.check(JW(IH,Y)),Q.cidrv4=(Y)=>Q.check($W(EH,Y)),Q.cidrv6=(Y)=>Q.check(zW(TH,Y)),Q.e164=(Y)=>Q.check(KW(CH,Y)),Q.datetime=(Y)=>Q.check(uQ(Y)),Q.date=(Y)=>Q.check(hQ(Y)),Q.time=(Y)=>Q.check(fQ(Y)),Q.duration=(Y)=>Q.check(lQ(Y))});function D(Q){return pY(FH,Q)}var d=F("ZodStringFormat",(Q,X)=>{r.init(Q,X),nW.init(Q,X)}),qH=F("ZodEmail",(Q,X)=>{a8.init(Q,X),d.init(Q,X)});var pW=F("ZodGUID",(Q,X)=>{o8.init(Q,X),d.init(Q,X)});var G4=F("ZodUUID",(Q,X)=>{t8.init(Q,X),d.init(Q,X)});var OH=F("ZodURL",(Q,X)=>{s8.init(Q,X),d.init(Q,X)});var MH=F("ZodEmoji",(Q,X)=>{e8.init(Q,X),d.init(Q,X)});var VH=F("ZodNanoID",(Q,X)=>{QY.init(Q,X),d.init(Q,X)});var ZH=F("ZodCUID",(Q,X)=>{XY.init(Q,X),d.init(Q,X)});var NH=F("ZodCUID2",(Q,X)=>{YY.init(Q,X),d.init(Q,X)});var wH=F("ZodULID",(Q,X)=>{WY.init(Q,X),d.init(Q,X)});var bH=F("ZodXID",(Q,X)=>{GY.init(Q,X),d.init(Q,X)});var jH=F("ZodKSUID",(Q,X)=>{JY.init(Q,X),d.init(Q,X)});var PH=F("ZodIPv4",(Q,X)=>{KY.init(Q,X),d.init(Q,X)});var IH=F("ZodIPv6",(Q,X)=>{UY.init(Q,X),d.init(Q,X)});var EH=F("ZodCIDRv4",(Q,X)=>{BY.init(Q,X),d.init(Q,X)});var TH=F("ZodCIDRv6",(Q,X)=>{DY.init(Q,X),d.init(Q,X)});var SH=F("ZodBase64",(Q,X)=>{FY.init(Q,X),d.init(Q,X)});var RH=F("ZodBase64URL",(Q,X)=>{qY.init(Q,X),d.init(Q,X)});var CH=F("ZodE164",(Q,X)=>{OY.init(Q,X),d.init(Q,X)});var kH=F("ZodJWT",(Q,X)=>{MY.init(Q,X),d.init(Q,X)});var dW=F("ZodNumber",(Q,X)=>{jQ.init(Q,X),s.init(Q,X),Q.gt=(W,G)=>Q.check(e6(W,G)),Q.gte=(W,G)=>Q.check(Q6(W,G)),Q.min=(W,G)=>Q.check(Q6(W,G)),Q.lt=(W,G)=>Q.check(s6(W,G)),Q.lte=(W,G)=>Q.check(e1(W,G)),Q.max=(W,G)=>Q.check(e1(W,G)),Q.int=(W)=>Q.check(iW(W)),Q.safe=(W)=>Q.check(iW(W)),Q.positive=(W)=>Q.check(e6(0,W)),Q.nonnegative=(W)=>Q.check(Q6(0,W)),Q.negative=(W)=>Q.check(s6(0,W)),Q.nonpositive=(W)=>Q.check(e1(0,W)),Q.multipleOf=(W,G)=>Q.check(Q4(W,G)),Q.step=(W,G)=>Q.check(Q4(W,G)),Q.finite=()=>Q;let Y=Q._zod.bag;Q.minValue=Math.max(Y.minimum??Number.NEGATIVE_INFINITY,Y.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Q.maxValue=Math.min(Y.maximum??Number.POSITIVE_INFINITY,Y.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Q.isInt=(Y.format??"").includes("int")||Number.isSafeInteger(Y.multipleOf??0.5),Q.isFinite=!0,Q.format=Y.format??null});function l(Q){return qW(dW,Q)}var vH=F("ZodNumberFormat",(Q,X)=>{VY.init(Q,X),dW.init(Q,X)});function iW(Q){return OW(vH,Q)}var xH=F("ZodBoolean",(Q,X)=>{ZY.init(Q,X),s.init(Q,X)});function Q0(Q){return MW(xH,Q)}var _H=F("ZodNull",(Q,X)=>{NY.init(Q,X),s.init(Q,X)});function pQ(Q){return VW(_H,Q)}var yH=F("ZodUnknown",(Q,X)=>{wY.init(Q,X),s.init(Q,X)});function o(){return ZW(yH)}var gH=F("ZodNever",(Q,X)=>{bY.init(Q,X),s.init(Q,X)});function uH(Q){return NW(gH,Q)}var hH=F("ZodArray",(Q,X)=>{jY.init(Q,X),s.init(Q,X),Q.element=X.element,Q.min=(Y,W)=>Q.check(b1(Y,W)),Q.nonempty=(Y)=>Q.check(b1(1,Y)),Q.max=(Y,W)=>Q.check(X4(Y,W)),Q.length=(Y,W)=>Q.check(Y4(Y,W)),Q.unwrap=()=>Q.element});function _(Q,X){return wW(hH,Q,X)}var oW=F("ZodObject",(Q,X)=>{EY.init(Q,X),s.init(Q,X),h.defineLazy(Q,"shape",()=>{return X.shape}),Q.keyof=()=>D0(Object.keys(Q._zod.def.shape)),Q.catchall=(Y)=>Q.clone({...Q._zod.def,catchall:Y}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:o()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:o()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:uH()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(Y)=>{return h.extend(Q,Y)},Q.safeExtend=(Y)=>{return h.safeExtend(Q,Y)},Q.merge=(Y)=>h.merge(Q,Y),Q.pick=(Y)=>h.pick(Q,Y),Q.omit=(Y)=>h.omit(Q,Y),Q.partial=(...Y)=>h.partial(sW,Q,Y[0]),Q.required=(...Y)=>h.required(eW,Q,Y[0])});function w(Q,X){let Y={type:"object",shape:Q??{},...h.normalizeParams(X)};return new oW(Y)}function K0(Q,X){return new oW({type:"object",shape:Q,catchall:o(),...h.normalizeParams(X)})}var tW=F("ZodUnion",(Q,X)=>{PQ.init(Q,X),s.init(Q,X),Q.options=X.options});function p(Q,X){return new tW({type:"union",options:Q,...h.normalizeParams(X)})}var fH=F("ZodDiscriminatedUnion",(Q,X)=>{tW.init(Q,X),TY.init(Q,X)});function iQ(Q,X,Y){return new fH({type:"union",options:X,discriminator:Q,...h.normalizeParams(Y)})}var lH=F("ZodIntersection",(Q,X)=>{SY.init(Q,X),s.init(Q,X)});function J4(Q,X){return new lH({type:"intersection",left:Q,right:X})}var mH=F("ZodRecord",(Q,X)=>{RY.init(Q,X),s.init(Q,X),Q.keyType=X.keyType,Q.valueType=X.valueType});function t(Q,X,Y){return new mH({type:"record",keyType:Q,valueType:X,...h.normalizeParams(Y)})}var mQ=F("ZodEnum",(Q,X)=>{CY.init(Q,X),s.init(Q,X),Q.enum=X.entries,Q.options=Object.values(X.entries);let Y=new Set(Object.keys(X.entries));Q.extract=(W,G)=>{let J={};for(let $ of W)if(Y.has($))J[$]=X.entries[$];else throw Error(`Key ${$} not found in enum`);return new mQ({...X,checks:[],...h.normalizeParams(G),entries:J})},Q.exclude=(W,G)=>{let J={...X.entries};for(let $ of W)if(Y.has($))delete J[$];else throw Error(`Key ${$} not found in enum`);return new mQ({...X,checks:[],...h.normalizeParams(G),entries:J})}});function D0(Q,X){let Y=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new mQ({type:"enum",entries:Y,...h.normalizeParams(X)})}var cH=F("ZodLiteral",(Q,X)=>{kY.init(Q,X),s.init(Q,X),Q.values=new Set(X.values),Object.defineProperty(Q,"value",{get(){if(X.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return X.values[0]}})});function b(Q,X){return new cH({type:"literal",values:Array.isArray(Q)?Q:[Q],...h.normalizeParams(X)})}var pH=F("ZodTransform",(Q,X)=>{vY.init(Q,X),s.init(Q,X),Q._zod.parse=(Y,W)=>{if(W.direction==="backward")throw new c1(Q.constructor.name);Y.addIssue=(J)=>{if(typeof J==="string")Y.issues.push(h.issue(J,Y.value,X));else{let $=J;if($.fatal)$.continue=!1;$.code??($.code="custom"),$.input??($.input=Y.value),$.inst??($.inst=Q),Y.issues.push(h.issue($))}};let G=X.transform(Y.value,Y);if(G instanceof Promise)return G.then((J)=>{return Y.value=J,Y});return Y.value=G,Y}});function aW(Q){return new pH({type:"transform",transform:Q})}var sW=F("ZodOptional",(Q,X)=>{xY.init(Q,X),s.init(Q,X),Q.unwrap=()=>Q._zod.def.innerType});function a(Q){return new sW({type:"optional",innerType:Q})}var iH=F("ZodNullable",(Q,X)=>{_Y.init(Q,X),s.init(Q,X),Q.unwrap=()=>Q._zod.def.innerType});function rW(Q){return new iH({type:"nullable",innerType:Q})}var rH=F("ZodDefault",(Q,X)=>{yY.init(Q,X),s.init(Q,X),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function nH(Q,X){return new rH({type:"default",innerType:Q,get defaultValue(){return typeof X==="function"?X():h.shallowClone(X)}})}var dH=F("ZodPrefault",(Q,X)=>{gY.init(Q,X),s.init(Q,X),Q.unwrap=()=>Q._zod.def.innerType});function oH(Q,X){return new dH({type:"prefault",innerType:Q,get defaultValue(){return typeof X==="function"?X():h.shallowClone(X)}})}var eW=F("ZodNonOptional",(Q,X)=>{uY.init(Q,X),s.init(Q,X),Q.unwrap=()=>Q._zod.def.innerType});function tH(Q,X){return new eW({type:"nonoptional",innerType:Q,...h.normalizeParams(X)})}var aH=F("ZodCatch",(Q,X)=>{hY.init(Q,X),s.init(Q,X),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function sH(Q,X){return new aH({type:"catch",innerType:Q,catchValue:typeof X==="function"?X:()=>X})}var eH=F("ZodPipe",(Q,X)=>{fY.init(Q,X),s.init(Q,X),Q.in=X.in,Q.out=X.out});function cQ(Q,X){return new eH({type:"pipe",in:Q,out:X})}var Q3=F("ZodReadonly",(Q,X)=>{lY.init(Q,X),s.init(Q,X),Q.unwrap=()=>Q._zod.def.innerType});function X3(Q){return new Q3({type:"readonly",innerType:Q})}var QG=F("ZodCustom",(Q,X)=>{mY.init(Q,X),s.init(Q,X)});function XG(Q,X){return bW(QG,Q??(()=>!0),X)}function Y3(Q,X={}){return jW(QG,Q,X)}function W3(Q){return PW(Q)}function rQ(Q,X){return cQ(aW(Q),X)}Z0(IQ());var nQ="2025-11-25";var YG=[nQ,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Q1="io.modelcontextprotocol/related-task",z4="2.0",Y0=XG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),WG=p([D(),l().int()]),GG=D(),LZ=K0({ttl:p([l(),pQ()]).optional(),pollInterval:l().optional()}),G3=w({ttl:l().optional()}),J3=w({taskId:D()}),dQ=K0({progressToken:WG.optional(),[Q1]:J3.optional()}),V0=w({_meta:dQ.optional()}),W6=V0.extend({task:G3.optional()}),JG=(Q)=>W6.safeParse(Q).success,W0=w({method:D(),params:V0.loose().optional()}),N0=w({_meta:dQ.optional()}),w0=w({method:D(),params:N0.loose().optional()}),G0=K0({_meta:dQ.optional()}),H4=p([D(),l().int()]),$G=w({jsonrpc:b(z4),id:H4,...W0.shape}).strict(),oQ=(Q)=>$G.safeParse(Q).success,zG=w({jsonrpc:b(z4),...w0.shape}).strict(),HG=(Q)=>zG.safeParse(Q).success,tQ=w({jsonrpc:b(z4),id:H4,result:G0}).strict(),G6=(Q)=>tQ.safeParse(Q).success;var y;(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"})(y||(y={}));var aQ=w({jsonrpc:b(z4),id:H4.optional(),error:w({code:l().int(),message:D(),data:o().optional()})}).strict();var AG=(Q)=>aQ.safeParse(Q).success;var KG=p([$G,zG,tQ,aQ]),FZ=p([tQ,aQ]),A4=G0.strict(),$3=N0.extend({requestId:H4.optional(),reason:D().optional()}),K4=w0.extend({method:b("notifications/cancelled"),params:$3}),z3=w({src:D(),mimeType:D().optional(),sizes:_(D()).optional(),theme:D0(["light","dark"]).optional()}),J6=w({icons:_(z3).optional()}),P1=w({name:D(),title:D().optional()}),UG=P1.extend({...P1.shape,...J6.shape,version:D(),websiteUrl:D().optional(),description:D().optional()}),H3=J4(w({applyDefaults:Q0().optional()}),t(D(),o())),A3=rQ((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},J4(w({form:H3.optional(),url:Y0.optional()}),t(D(),o()).optional())),K3=K0({list:Y0.optional(),cancel:Y0.optional(),requests:K0({sampling:K0({createMessage:Y0.optional()}).optional(),elicitation:K0({create:Y0.optional()}).optional()}).optional()}),U3=K0({list:Y0.optional(),cancel:Y0.optional(),requests:K0({tools:K0({call:Y0.optional()}).optional()}).optional()}),B3=w({experimental:t(D(),Y0).optional(),sampling:w({context:Y0.optional(),tools:Y0.optional()}).optional(),elicitation:A3.optional(),roots:w({listChanged:Q0().optional()}).optional(),tasks:K3.optional()}),D3=V0.extend({protocolVersion:D(),capabilities:B3,clientInfo:UG}),sQ=W0.extend({method:b("initialize"),params:D3});var L3=w({experimental:t(D(),Y0).optional(),logging:Y0.optional(),completions:Y0.optional(),prompts:w({listChanged:Q0().optional()}).optional(),resources:w({subscribe:Q0().optional(),listChanged:Q0().optional()}).optional(),tools:w({listChanged:Q0().optional()}).optional(),tasks:U3.optional()}),F3=G0.extend({protocolVersion:D(),capabilities:L3,serverInfo:UG,instructions:D().optional()}),eQ=w0.extend({method:b("notifications/initialized"),params:N0.optional()});var U4=W0.extend({method:b("ping"),params:V0.optional()}),q3=w({progress:l(),total:a(l()),message:a(D())}),O3=w({...N0.shape,...q3.shape,progressToken:WG}),B4=w0.extend({method:b("notifications/progress"),params:O3}),M3=V0.extend({cursor:GG.optional()}),$6=W0.extend({params:M3.optional()}),z6=G0.extend({nextCursor:GG.optional()}),V3=D0(["working","input_required","completed","failed","cancelled"]),H6=w({taskId:D(),status:V3,ttl:p([l(),pQ()]),createdAt:D(),lastUpdatedAt:D(),pollInterval:a(l()),statusMessage:a(D())}),I1=G0.extend({task:H6}),Z3=N0.merge(H6),A6=w0.extend({method:b("notifications/tasks/status"),params:Z3}),D4=W0.extend({method:b("tasks/get"),params:V0.extend({taskId:D()})}),L4=G0.merge(H6),F4=W0.extend({method:b("tasks/result"),params:V0.extend({taskId:D()})}),qZ=G0.loose(),q4=$6.extend({method:b("tasks/list")}),O4=z6.extend({tasks:_(H6)}),M4=W0.extend({method:b("tasks/cancel"),params:V0.extend({taskId:D()})}),BG=G0.merge(H6),DG=w({uri:D(),mimeType:a(D()),_meta:t(D(),o()).optional()}),LG=DG.extend({text:D()}),Q9=D().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),FG=DG.extend({blob:Q9}),K6=D0(["user","assistant"]),E1=w({audience:_(K6).optional(),priority:l().min(0).max(1).optional(),lastModified:Y6.datetime({offset:!0}).optional()}),qG=w({...P1.shape,...J6.shape,uri:D(),description:a(D()),mimeType:a(D()),annotations:E1.optional(),_meta:a(K0({}))}),N3=w({...P1.shape,...J6.shape,uriTemplate:D(),description:a(D()),mimeType:a(D()),annotations:E1.optional(),_meta:a(K0({}))}),X9=$6.extend({method:b("resources/list")}),w3=z6.extend({resources:_(qG)}),b3=$6.extend({method:b("resources/templates/list")}),j3=z6.extend({resourceTemplates:_(N3)}),Y9=V0.extend({uri:D()}),P3=Y9,W9=W0.extend({method:b("resources/read"),params:P3}),I3=G0.extend({contents:_(p([LG,FG]))}),E3=w0.extend({method:b("notifications/resources/list_changed"),params:N0.optional()}),T3=Y9,S3=W0.extend({method:b("resources/subscribe"),params:T3}),R3=Y9,C3=W0.extend({method:b("resources/unsubscribe"),params:R3}),k3=N0.extend({uri:D()}),v3=w0.extend({method:b("notifications/resources/updated"),params:k3}),x3=w({name:D(),description:a(D()),required:a(Q0())}),_3=w({...P1.shape,...J6.shape,description:a(D()),arguments:a(_(x3)),_meta:a(K0({}))}),y3=$6.extend({method:b("prompts/list")}),g3=z6.extend({prompts:_(_3)}),u3=V0.extend({name:D(),arguments:t(D(),D()).optional()}),h3=W0.extend({method:b("prompts/get"),params:u3}),G9=w({type:b("text"),text:D(),annotations:E1.optional(),_meta:t(D(),o()).optional()}),J9=w({type:b("image"),data:Q9,mimeType:D(),annotations:E1.optional(),_meta:t(D(),o()).optional()}),$9=w({type:b("audio"),data:Q9,mimeType:D(),annotations:E1.optional(),_meta:t(D(),o()).optional()}),f3=w({type:b("tool_use"),name:D(),id:D(),input:t(D(),o()),_meta:t(D(),o()).optional()}),l3=w({type:b("resource"),resource:p([LG,FG]),annotations:E1.optional(),_meta:t(D(),o()).optional()}),m3=qG.extend({type:b("resource_link")}),z9=p([G9,J9,$9,m3,l3]),c3=w({role:K6,content:z9}),p3=G0.extend({description:D().optional(),messages:_(c3)}),i3=w0.extend({method:b("notifications/prompts/list_changed"),params:N0.optional()}),r3=w({title:D().optional(),readOnlyHint:Q0().optional(),destructiveHint:Q0().optional(),idempotentHint:Q0().optional(),openWorldHint:Q0().optional()}),n3=w({taskSupport:D0(["required","optional","forbidden"]).optional()}),OG=w({...P1.shape,...J6.shape,description:D().optional(),inputSchema:w({type:b("object"),properties:t(D(),Y0).optional(),required:_(D()).optional()}).catchall(o()),outputSchema:w({type:b("object"),properties:t(D(),Y0).optional(),required:_(D()).optional()}).catchall(o()).optional(),annotations:r3.optional(),execution:n3.optional(),_meta:t(D(),o()).optional()}),H9=$6.extend({method:b("tools/list")}),d3=z6.extend({tools:_(OG)}),V4=G0.extend({content:_(z9).default([]),structuredContent:t(D(),o()).optional(),isError:Q0().optional()}),OZ=V4.or(G0.extend({toolResult:o()})),o3=W6.extend({name:D(),arguments:t(D(),o()).optional()}),U6=W0.extend({method:b("tools/call"),params:o3}),t3=w0.extend({method:b("notifications/tools/list_changed"),params:N0.optional()}),MZ=w({autoRefresh:Q0().default(!0),debounceMs:l().int().nonnegative().default(300)}),B6=D0(["debug","info","notice","warning","error","critical","alert","emergency"]),a3=V0.extend({level:B6}),A9=W0.extend({method:b("logging/setLevel"),params:a3}),s3=N0.extend({level:B6,logger:D().optional(),data:o()}),e3=w0.extend({method:b("notifications/message"),params:s3}),QA=w({name:D().optional()}),XA=w({hints:_(QA).optional(),costPriority:l().min(0).max(1).optional(),speedPriority:l().min(0).max(1).optional(),intelligencePriority:l().min(0).max(1).optional()}),YA=w({mode:D0(["auto","required","none"]).optional()}),WA=w({type:b("tool_result"),toolUseId:D().describe("The unique identifier for the corresponding tool call."),content:_(z9).default([]),structuredContent:w({}).loose().optional(),isError:Q0().optional(),_meta:t(D(),o()).optional()}),GA=iQ("type",[G9,J9,$9]),$4=iQ("type",[G9,J9,$9,f3,WA]),JA=w({role:K6,content:p([$4,_($4)]),_meta:t(D(),o()).optional()}),$A=W6.extend({messages:_(JA),modelPreferences:XA.optional(),systemPrompt:D().optional(),includeContext:D0(["none","thisServer","allServers"]).optional(),temperature:l().optional(),maxTokens:l().int(),stopSequences:_(D()).optional(),metadata:Y0.optional(),tools:_(OG).optional(),toolChoice:YA.optional()}),zA=W0.extend({method:b("sampling/createMessage"),params:$A}),K9=G0.extend({model:D(),stopReason:a(D0(["endTurn","stopSequence","maxTokens"]).or(D())),role:K6,content:GA}),U9=G0.extend({model:D(),stopReason:a(D0(["endTurn","stopSequence","maxTokens","toolUse"]).or(D())),role:K6,content:p([$4,_($4)])}),HA=w({type:b("boolean"),title:D().optional(),description:D().optional(),default:Q0().optional()}),AA=w({type:b("string"),title:D().optional(),description:D().optional(),minLength:l().optional(),maxLength:l().optional(),format:D0(["email","uri","date","date-time"]).optional(),default:D().optional()}),KA=w({type:D0(["number","integer"]),title:D().optional(),description:D().optional(),minimum:l().optional(),maximum:l().optional(),default:l().optional()}),UA=w({type:b("string"),title:D().optional(),description:D().optional(),enum:_(D()),default:D().optional()}),BA=w({type:b("string"),title:D().optional(),description:D().optional(),oneOf:_(w({const:D(),title:D()})),default:D().optional()}),DA=w({type:b("string"),title:D().optional(),description:D().optional(),enum:_(D()),enumNames:_(D()).optional(),default:D().optional()}),LA=p([UA,BA]),FA=w({type:b("array"),title:D().optional(),description:D().optional(),minItems:l().optional(),maxItems:l().optional(),items:w({type:b("string"),enum:_(D())}),default:_(D()).optional()}),qA=w({type:b("array"),title:D().optional(),description:D().optional(),minItems:l().optional(),maxItems:l().optional(),items:w({anyOf:_(w({const:D(),title:D()}))}),default:_(D()).optional()}),OA=p([FA,qA]),MA=p([DA,LA,OA]),VA=p([MA,HA,AA,KA]),ZA=W6.extend({mode:b("form").optional(),message:D(),requestedSchema:w({type:b("object"),properties:t(D(),VA),required:_(D()).optional()})}),NA=W6.extend({mode:b("url"),message:D(),elicitationId:D(),url:D().url()}),wA=p([ZA,NA]),bA=W0.extend({method:b("elicitation/create"),params:wA}),jA=N0.extend({elicitationId:D()}),PA=w0.extend({method:b("notifications/elicitation/complete"),params:jA}),Z4=G0.extend({action:D0(["accept","decline","cancel"]),content:rQ((Q)=>Q===null?void 0:Q,t(D(),p([D(),l(),Q0(),_(D())])).optional())}),IA=w({type:b("ref/resource"),uri:D()});var EA=w({type:b("ref/prompt"),name:D()}),TA=V0.extend({ref:p([EA,IA]),argument:w({name:D(),value:D()}),context:w({arguments:t(D(),D()).optional()}).optional()}),SA=W0.extend({method:b("completion/complete"),params:TA});var RA=G0.extend({completion:K0({values:_(D()).max(100),total:a(l().int()),hasMore:a(Q0())})}),CA=w({uri:D().startsWith("file://"),name:D().optional(),_meta:t(D(),o()).optional()}),kA=W0.extend({method:b("roots/list"),params:V0.optional()}),B9=G0.extend({roots:_(CA)}),vA=w0.extend({method:b("notifications/roots/list_changed"),params:N0.optional()}),VZ=p([U4,sQ,SA,A9,h3,y3,X9,b3,W9,S3,C3,U6,H9,D4,F4,q4,M4]),ZZ=p([K4,B4,eQ,vA,A6]),NZ=p([A4,K9,U9,Z4,B9,L4,O4,I1]),wZ=p([U4,zA,bA,kA,D4,F4,q4,M4]),bZ=p([K4,B4,e3,v3,E3,t3,i3,A6,PA]),jZ=p([A4,F3,RA,p3,g3,w3,j3,I3,V4,d3,L4,O4,I1]);class C extends Error{constructor(Q,X,Y){super(`MCP error ${Q}: ${X}`);this.code=Q,this.data=Y,this.name="McpError"}static fromError(Q,X,Y){if(Q===y.UrlElicitationRequired&&Y){let W=Y;if(W.elicitations)return new MG(W.elicitations,X)}return new C(Q,X,Y)}}class MG extends C{constructor(Q,X=`URL elicitation${Q.length>1?"s":""} required`){super(y.UrlElicitationRequired,X,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function X1(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var xA=Symbol("Let zodToJsonSchema decide on which parser to use");var WN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function D9(Q){let Y=W4(Q)?.method;if(!Y)throw Error("Schema is missing a method literal");let W=IW(Y);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function L9(Q,X){let Y=e0(Q,X);if(!Y.success)throw Y.error;return Y.data}var fA=60000;class F9{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(K4,(X)=>{this._oncancel(X)}),this.setNotificationHandler(B4,(X)=>{this._onprogress(X)}),this.setRequestHandler(U4,(X)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(D4,async(X,Y)=>{let W=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!W)throw new C(y.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(F4,async(X,Y)=>{let W=async()=>{let G=X.params.taskId;if(this._taskMessageQueue){let $;while($=await this._taskMessageQueue.dequeue(G,Y.sessionId)){if($.type==="response"||$.type==="error"){let z=$.message,H=z.id,A=this._requestResolvers.get(H);if(A)if(this._requestResolvers.delete(H),$.type==="response")A(z);else{let K=z,U=new C(K.error.code,K.error.message,K.error.data);A(U)}else{let K=$.type==="response"?"Response":"Error";this._onerror(Error(`${K} handler missing for request ${H}`))}continue}await this._transport?.send($.message,{relatedRequestId:Y.requestId})}}let J=await this._taskStore.getTask(G,Y.sessionId);if(!J)throw new C(y.InvalidParams,`Task not found: ${G}`);if(!X1(J.status))return await this._waitForTaskUpdate(G,Y.signal),await W();if(X1(J.status)){let $=await this._taskStore.getTaskResult(G,Y.sessionId);return this._clearTaskQueue(G),{...$,_meta:{...$._meta,[Q1]:{taskId:G}}}}return await W()};return await W()}),this.setRequestHandler(q4,async(X,Y)=>{try{let{tasks:W,nextCursor:G}=await this._taskStore.listTasks(X.params?.cursor,Y.sessionId);return{tasks:W,nextCursor:G,_meta:{}}}catch(W){throw new C(y.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(M4,async(X,Y)=>{try{let W=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!W)throw new C(y.InvalidParams,`Task not found: ${X.params.taskId}`);if(X1(W.status))throw new C(y.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(X.params.taskId,"cancelled","Client cancelled task execution.",Y.sessionId),this._clearTaskQueue(X.params.taskId);let G=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!G)throw new C(y.InvalidParams,`Task not found after cancellation: ${X.params.taskId}`);return{_meta:{},...G}}catch(W){if(W instanceof C)throw W;throw new C(y.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,X,Y,W,G=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,X),startTime:Date.now(),timeout:X,maxTotalTimeout:Y,resetTimeoutOnProgress:G,onTimeout:W})}_resetTimeout(Q){let X=this._timeoutInfo.get(Q);if(!X)return!1;let Y=Date.now()-X.startTime;if(X.maxTotalTimeout&&Y>=X.maxTotalTimeout)throw this._timeoutInfo.delete(Q),C.fromError(y.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:X.maxTotalTimeout,totalElapsed:Y});return clearTimeout(X.timeoutId),X.timeoutId=setTimeout(X.onTimeout,X.timeout),!0}_cleanupTimeout(Q){let X=this._timeoutInfo.get(Q);if(X)clearTimeout(X.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let X=this.transport?.onclose;this._transport.onclose=()=>{X?.(),this._onclose()};let Y=this.transport?.onerror;this._transport.onerror=(G)=>{Y?.(G),this._onerror(G)};let W=this._transport?.onmessage;this._transport.onmessage=(G,J)=>{if(W?.(G,J),G6(G)||AG(G))this._onresponse(G);else if(oQ(G))this._onrequest(G,J);else if(HG(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 X=C.fromError(y.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let Y of Q.values())Y(X)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let X=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(X===void 0)return;Promise.resolve().then(()=>X(Q)).catch((Y)=>this._onerror(Error(`Uncaught error in notification handler: ${Y}`)))}_onrequest(Q,X){let Y=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,G=Q.params?._meta?.[Q1]?.taskId;if(Y===void 0){let A={jsonrpc:"2.0",id:Q.id,error:{code:y.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId).catch((K)=>this._onerror(Error(`Failed to enqueue error response: ${K}`)));else W?.send(A).catch((K)=>this._onerror(Error(`Failed to send an error response: ${K}`)));return}let J=new AbortController;this._requestHandlerAbortControllers.set(Q.id,J);let $=JG(Q.params)?Q.params.task:void 0,z=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:J.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(A)=>{let K={relatedRequestId:Q.id};if(G)K.relatedTask={taskId:G};await this.notification(A,K)},sendRequest:async(A,K,U)=>{let B={...U,relatedRequestId:Q.id};if(G&&!B.relatedTask)B.relatedTask={taskId:G};let L=B.relatedTask?.taskId??G;if(L&&z)await z.updateTaskStatus(L,"input_required");return await this.request(A,K,B)},authInfo:X?.authInfo,requestId:Q.id,requestInfo:X?.requestInfo,taskId:G,taskStore:z,taskRequestedTtl:$?.ttl,closeSSEStream:X?.closeSSEStream,closeStandaloneSSEStream:X?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if($)this.assertTaskHandlerCapability(Q.method)}).then(()=>Y(Q,H)).then(async(A)=>{if(J.signal.aborted)return;let K={result:A,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:K,timestamp:Date.now()},W?.sessionId);else await W?.send(K)},async(A)=>{if(J.signal.aborted)return;let K={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(A.code)?A.code:y.InternalError,message:A.message??"Internal error",...A.data!==void 0&&{data:A.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:K,timestamp:Date.now()},W?.sessionId);else await W?.send(K)}).catch((A)=>this._onerror(Error(`Failed to send response: ${A}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:X,...Y}=Q.params,W=Number(X),G=this._progressHandlers.get(W);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let J=this._responseHandlers.get(W),$=this._timeoutInfo.get(W);if($&&J&&$.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(z){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),J(z);return}G(Y)}_onresponse(Q){let X=Number(Q.id),Y=this._requestResolvers.get(X);if(Y){if(this._requestResolvers.delete(X),G6(Q))Y(Q);else{let J=new C(Q.error.code,Q.error.message,Q.error.data);Y(J)}return}let W=this._responseHandlers.get(X);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(X),this._cleanupTimeout(X);let G=!1;if(G6(Q)&&Q.result&&typeof Q.result==="object"){let J=Q.result;if(J.task&&typeof J.task==="object"){let $=J.task;if(typeof $.taskId==="string")G=!0,this._taskProgressTokens.set($.taskId,X)}}if(!G)this._progressHandlers.delete(X);if(G6(Q))W(Q);else{let J=C.fromError(Q.error.code,Q.error.message,Q.error.data);W(J)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,X,Y){let{task:W}=Y??{};if(!W){try{yield{type:"result",result:await this.request(Q,X,Y)}}catch(J){yield{type:"error",error:J instanceof C?J:new C(y.InternalError,String(J))}}return}let G;try{let J=await this.request(Q,I1,Y);if(J.task)G=J.task.taskId,yield{type:"taskCreated",task:J.task};else throw new C(y.InternalError,"Task creation did not return a task");while(!0){let $=await this.getTask({taskId:G},Y);if(yield{type:"taskStatus",task:$},X1($.status)){if($.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},X,Y)};else if($.status==="failed")yield{type:"error",error:new C(y.InternalError,`Task ${G} failed`)};else if($.status==="cancelled")yield{type:"error",error:new C(y.InternalError,`Task ${G} was cancelled`)};return}if($.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},X,Y)};return}let z=$.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,z)),Y?.signal?.throwIfAborted()}}catch(J){yield{type:"error",error:J instanceof C?J:new C(y.InternalError,String(J))}}}request(Q,X,Y){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:J,task:$,relatedTask:z}=Y??{};return new Promise((H,A)=>{let K=(M)=>{A(M)};if(!this._transport){K(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),$)this.assertTaskCapability(Q.method)}catch(M){K(M);return}Y?.signal?.throwIfAborted();let U=this._requestMessageId++,B={...Q,jsonrpc:"2.0",id:U};if(Y?.onprogress)this._progressHandlers.set(U,Y.onprogress),B.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:U}};if($)B.params={...B.params,task:$};if(z)B.params={...B.params,_meta:{...B.params?._meta||{},[Q1]:z}};let L=(M)=>{this._responseHandlers.delete(U),this._progressHandlers.delete(U),this._cleanupTimeout(U),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:U,reason:String(M)}},{relatedRequestId:W,resumptionToken:G,onresumptiontoken:J}).catch((I)=>this._onerror(Error(`Failed to send cancellation: ${I}`)));let T=M instanceof C?M:new C(y.RequestTimeout,String(M));A(T)};this._responseHandlers.set(U,(M)=>{if(Y?.signal?.aborted)return;if(M instanceof Error)return A(M);try{let T=e0(X,M.result);if(!T.success)A(T.error);else H(T.data)}catch(T){A(T)}}),Y?.signal?.addEventListener("abort",()=>{L(Y?.signal?.reason)});let q=Y?.timeout??fA,O=()=>L(C.fromError(y.RequestTimeout,"Request timed out",{timeout:q}));this._setupTimeout(U,q,Y?.maxTotalTimeout,O,Y?.resetTimeoutOnProgress??!1);let V=z?.taskId;if(V){let M=(T)=>{let I=this._responseHandlers.get(U);if(I)I(T);else this._onerror(Error(`Response handler missing for side-channeled request ${U}`))};this._requestResolvers.set(U,M),this._enqueueTaskMessage(V,{type:"request",message:B,timestamp:Date.now()}).catch((T)=>{this._cleanupTimeout(U),A(T)})}else this._transport.send(B,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:J}).catch((M)=>{this._cleanupTimeout(U),A(M)})})}async getTask(Q,X){return this.request({method:"tasks/get",params:Q},L4,X)}async getTaskResult(Q,X,Y){return this.request({method:"tasks/result",params:Q},X,Y)}async listTasks(Q,X){return this.request({method:"tasks/list",params:Q},O4,X)}async cancelTask(Q,X){return this.request({method:"tasks/cancel",params:Q},BG,X)}async notification(Q,X){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let Y=X?.relatedTask?.taskId;if(Y){let $={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[Q1]:X.relatedTask}}};await this._enqueueTaskMessage(Y,{type:"notification",message:$,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!X?.relatedRequestId&&!X?.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 $={...Q,jsonrpc:"2.0"};if(X?.relatedTask)$={...$,params:{...$.params,_meta:{...$.params?._meta||{},[Q1]:X.relatedTask}}};this._transport?.send($,X).catch((z)=>this._onerror(z))});return}let J={...Q,jsonrpc:"2.0"};if(X?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[Q1]:X.relatedTask}}};await this._transport.send(J,X)}setRequestHandler(Q,X){let Y=D9(Q);this.assertRequestHandlerCapability(Y),this._requestHandlers.set(Y,(W,G)=>{let J=L9(Q,W);return Promise.resolve(X(J,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,X){let Y=D9(Q);this._notificationHandlers.set(Y,(W)=>{let G=L9(Q,W);return Promise.resolve(X(G))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let X=this._taskProgressTokens.get(Q);if(X!==void 0)this._progressHandlers.delete(X),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,X,Y){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,X,Y,W)}async _clearTaskQueue(Q,X){if(this._taskMessageQueue){let Y=await this._taskMessageQueue.dequeueAll(Q,X);for(let W of Y)if(W.type==="request"&&oQ(W.message)){let G=W.message.id,J=this._requestResolvers.get(G);if(J)J(new C(y.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,X){let Y=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)Y=W.pollInterval}catch{}return new Promise((W,G)=>{if(X.aborted){G(new C(y.InvalidRequest,"Request cancelled"));return}let J=setTimeout(W,Y);X.addEventListener("abort",()=>{clearTimeout(J),G(new C(y.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,X){let Y=this._taskStore;if(!Y)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await Y.createTask(W,Q.id,{method:Q.method,params:Q.params},X)},getTask:async(W)=>{let G=await Y.getTask(W,X);if(!G)throw new C(y.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(W,G,J)=>{await Y.storeTaskResult(W,G,J,X);let $=await Y.getTask(W,X);if($){let z=A6.parse({method:"notifications/tasks/status",params:$});if(await this.notification(z),X1($.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return Y.getTaskResult(W,X)},updateTaskStatus:async(W,G,J)=>{let $=await Y.getTask(W,X);if(!$)throw new C(y.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(X1($.status))throw new C(y.InvalidParams,`Cannot update task "${W}" from terminal status "${$.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await Y.updateTaskStatus(W,G,J,X);let z=await Y.getTask(W,X);if(z){let H=A6.parse({method:"notifications/tasks/status",params:z});if(await this.notification(H),X1(z.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return Y.listTasks(W,X)}}}}function VG(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function ZG(Q,X){let Y={...Q};for(let W in X){let G=W,J=X[G];if(J===void 0)continue;let $=Y[G];if(VG($)&&VG(J))Y[G]={...$,...J};else Y[G]=J}return Y}var a7=RX(AX(),1),s7=RX(t7(),1);function oO(){let Q=new a7.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return s7.default(Q),Q}class VX{constructor(Q){this._ajv=Q??oO()}getValidator(Q){let X="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(Y)=>{if(X(Y))return{valid:!0,data:Y,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(X.errors)}}}}class ZX{constructor(Q){this._server=Q}requestStream(Q,X,Y){return this._server.requestStream(Q,X,Y)}async getTask(Q,X){return this._server.getTask({taskId:Q},X)}async getTaskResult(Q,X,Y){return this._server.getTaskResult({taskId:Q},X,Y)}async listTasks(Q,X){return this._server.listTasks(Q?{cursor:Q}:void 0,X)}async cancelTask(Q,X){return this._server.cancelTask({taskId:Q},X)}}function e7(Q,X,Y){if(!Q)throw Error(`${Y} does not support task creation (required for ${X})`);switch(X){case"tools/call":if(!Q.tools?.call)throw Error(`${Y} does not support task creation for tools/call (required for ${X})`);break;default:break}}function Q5(Q,X,Y){if(!Q)throw Error(`${Y} does not support task creation (required for ${X})`);switch(X){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${Y} does not support task creation for sampling/createMessage (required for ${X})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${Y} does not support task creation for elicitation/create (required for ${X})`);break;default:break}}class NX extends F9{constructor(Q,X){super(X);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(B6.options.map((Y,W)=>[Y,W])),this.isMessageIgnored=(Y,W)=>{let G=this._loggingLevels.get(W);return G?this.LOG_LEVEL_SEVERITY.get(Y)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=X?.capabilities??{},this._instructions=X?.instructions,this._jsonSchemaValidator=X?.jsonSchemaValidator??new VX,this.setRequestHandler(sQ,(Y)=>this._oninitialize(Y)),this.setNotificationHandler(eQ,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(A9,async(Y,W)=>{let G=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:J}=Y.params,$=B6.safeParse(J);if($.success)this._loggingLevels.set(G,$.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new ZX(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=ZG(this._capabilities,Q)}setRequestHandler(Q,X){let W=W4(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let G;if(j1(W)){let $=W;G=$._zod?.def?.value??$.value}else{let $=W;G=$._def?.value??$.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let $=async(z,H)=>{let A=e0(U6,z);if(!A.success){let L=A.error instanceof Error?A.error.message:String(A.error);throw new C(y.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:K}=A.data,U=await Promise.resolve(X(z,H));if(K.task){let L=e0(I1,U);if(!L.success){let q=L.error instanceof Error?L.error.message:String(L.error);throw new C(y.InvalidParams,`Invalid task creation result: ${q}`)}return L.data}let B=e0(V4,U);if(!B.success){let L=B.error instanceof Error?B.error.message:String(B.error);throw new C(y.InvalidParams,`Invalid tools/call result: ${L}`)}return B.data};return super.setRequestHandler(Q,$)}return super.setRequestHandler(Q,X)}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){Q5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;e7(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let X=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:YG.includes(X)?X:nQ,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"},A4)}async createMessage(Q,X){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 Y=Q.messages[Q.messages.length-1],W=Array.isArray(Y.content)?Y.content:[Y.content],G=W.some((H)=>H.type==="tool_result"),J=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,$=J?Array.isArray(J.content)?J.content:[J.content]:[],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(!z)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(z){let H=new Set($.filter((K)=>K.type==="tool_use").map((K)=>K.id)),A=new Set(W.filter((K)=>K.type==="tool_result").map((K)=>K.toolUseId));if(H.size!==A.size||![...H].every((K)=>A.has(K)))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},U9,X);return this.request({method:"sampling/createMessage",params:Q},K9,X)}async elicitInput(Q,X){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},Z4,X)}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},Z4,X);if(G.action==="accept"&&G.content&&W.requestedSchema)try{let $=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!$.valid)throw new C(y.InvalidParams,`Elicitation response content does not match requested schema: ${$.errorMessage}`)}catch(J){if(J instanceof C)throw J;throw new C(y.InternalError,`Error validating elicitation response: ${J instanceof Error?J.message:String(J)}`)}return G}}}createElicitationCompletionNotifier(Q,X){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}},X)}async listRoots(Q,X){return this.request({method:"roots/list",params:Q},B9,X)}async sendLoggingMessage(Q,X){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,X))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"})}}import Y5 from"node:process";class wX{append(Q){this._buffer=this._buffer?Buffer.concat([this._buffer,Q]):Q}readMessage(){if(!this._buffer)return null;let Q=this._buffer.indexOf(`
29
29
  `);if(Q===-1)return null;let X=this._buffer.toString("utf8",0,Q).replace(/\r$/,"");return this._buffer=this._buffer.subarray(Q+1),tO(X)}clear(){this._buffer=void 0}}function tO(Q){return KG.parse(JSON.parse(Q))}function X5(Q){return JSON.stringify(Q)+`
30
- `}class bX{constructor(Q=Y5.stdin,X=Y5.stdout){this._stdin=Q,this._stdout=X,this._readBuffer=new wX,this._started=!1,this._ondata=(Y)=>{this._readBuffer.append(Y),this.processReadBuffer()},this._onerror=(Y)=>{this.onerror?.(Y)}}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((X)=>{let Y=X5(Q);if(this._stdout.write(Y))X();else this._stdout.once("drain",X)})}}var W5={name:"@sequenzy/mcp",version:"0.0.27",mcpName:"io.github.polnikale/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.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^5.8.0"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/sequenzy/sequenzy.git"}};class h1 extends Error{statusCode;rawDetails;code;constructor(Q,X,Y,W){super(Q);this.statusCode=X;this.rawDetails=Y;this.code=W;this.name="McpApiError"}}function sO(Q){if(Q instanceof h1)return{message:Q.message,statusCode:Q.statusCode,code:Q.code,rawDetails:Q.rawDetails};if(Q instanceof Error)return{message:Q.message};return{message:String(Q)}}function eO(Q){let X=sO(Q),Y=X.message.trim()||"Unknown error",W=Y.toLowerCase(),G=X.rawDetails?.trim()||Y;if(X.code==="MCP_AUTH_REQUIRED"||W.includes("sequenzy_api_key environment variable is required"))return{title:"Missing MCP API key",description:"The MCP server started without a Sequenzy API key, so it cannot authenticate any tool or resource request.",howToFix:"Add `SEQUENZY_API_KEY` to the MCP server environment, or run `npx @sequenzy/setup` to configure the integration automatically.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(X.statusCode===401||X.code==="UNAUTHORIZED")return{title:"Authentication failed",description:"The MCP server reached Sequenzy, but the current API key was rejected.",howToFix:"Replace `SEQUENZY_API_KEY` with a valid personal API key, then restart the MCP client so it reconnects with fresh credentials.",docsUrl:"https://docs.sequenzy.com/authentication",details:G};if(X.statusCode===403||W.includes("access denied"))return{title:"Access denied",description:"The current API key is valid, but it does not have permission to access the requested company or action.",howToFix:"Use an API key that belongs to the right account, or select a company the key can access before retrying the tool call.",docsUrl:"https://docs.sequenzy.com/authentication",details:G};if(W.includes("no company available")||W.includes("company not found"))return{title:"Company selection required",description:"The MCP server could not resolve a company for this request.",howToFix:"Call `get_account` to inspect available companies, then call `select_company`, or pass `companyId` explicitly in the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(X.statusCode===404||W.includes("not found"))return{title:"Requested resource not found",description:"Sequenzy could not find the requested campaign, template, sequence, company, or subscriber.",howToFix:"List or fetch the resource collection first, then retry the tool with a confirmed ID or email value.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(X.statusCode===429||W.includes("rate limit"))return{title:"Rate limited",description:"Sequenzy temporarily slowed this MCP request because too many requests were sent too quickly.",howToFix:"Wait briefly before retrying. If the client is looping, reduce retries or add backoff before the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(X.code==="NETWORK_ERROR"||W.includes("fetch failed"))return{title:"Network or configuration error",description:"The MCP server could not reach the Sequenzy API from this environment.",howToFix:"Check connectivity and verify `SEQUENZY_API_URL` if you override it in the MCP environment.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(W.includes("unknown tool")||W.includes("unknown resource"))return{title:"Unsupported MCP request",description:"The client asked for a tool or resource name that this Sequenzy MCP server does not expose.",howToFix:"Refresh the client's tool list and call only the names returned by `list_tools` or `list_resources`.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(W.includes("is required")||W.includes("invalid"))return{title:"Invalid MCP input",description:"The tool call was missing a required field or included an invalid value.",howToFix:"Review the tool schema, supply the missing argument, and retry the request with corrected input.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(X.statusCode&&X.statusCode>=500)return{title:"Sequenzy server error",description:"The request reached Sequenzy, but the server could not complete it successfully.",howToFix:"Retry once. If it still fails, keep the details below and consult the docs before escalating.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};return{title:"Tool execution failed",description:"The MCP server could not complete the requested operation.",howToFix:"Review the details below, adjust the tool input or credentials, and retry.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G}}function V1(Q){let X=eO(Q);return[`Sequenzy MCP error: ${X.title}`,`Description: ${X.description}`,`How to fix: ${X.howToFix}`,`Docs: ${X.docsUrl}`,`Details: ${X.details}`].join(`
30
+ `}class bX{constructor(Q=Y5.stdin,X=Y5.stdout){this._stdin=Q,this._stdout=X,this._readBuffer=new wX,this._started=!1,this._ondata=(Y)=>{this._readBuffer.append(Y),this.processReadBuffer()},this._onerror=(Y)=>{this.onerror?.(Y)}}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((X)=>{let Y=X5(Q);if(this._stdout.write(Y))X();else this._stdout.once("drain",X)})}}var W5={name:"@sequenzy/mcp",version:"0.0.29",mcpName:"io.github.polnikale/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.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^5.8.0"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/sequenzy/sequenzy.git"}};class h1 extends Error{statusCode;rawDetails;code;constructor(Q,X,Y,W){super(Q);this.statusCode=X;this.rawDetails=Y;this.code=W;this.name="McpApiError"}}function sO(Q){if(Q instanceof h1)return{message:Q.message,statusCode:Q.statusCode,code:Q.code,rawDetails:Q.rawDetails};if(Q instanceof Error)return{message:Q.message};return{message:String(Q)}}function eO(Q){let X=sO(Q),Y=X.message.trim()||"Unknown error",W=Y.toLowerCase(),G=X.rawDetails?.trim()||Y;if(X.code==="MCP_AUTH_REQUIRED"||W.includes("sequenzy_api_key environment variable is required"))return{title:"Missing MCP API key",description:"The MCP server started without a Sequenzy API key, so it cannot authenticate any tool or resource request.",howToFix:"Add `SEQUENZY_API_KEY` to the MCP server environment, or run `npx @sequenzy/setup` to configure the integration automatically.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(X.statusCode===401||X.code==="UNAUTHORIZED")return{title:"Authentication failed",description:"The MCP server reached Sequenzy, but the current API key was rejected.",howToFix:"Replace `SEQUENZY_API_KEY` with a valid personal API key, then restart the MCP client so it reconnects with fresh credentials.",docsUrl:"https://docs.sequenzy.com/authentication",details:G};if(X.statusCode===403||W.includes("access denied"))return{title:"Access denied",description:"The current API key is valid, but it does not have permission to access the requested company or action.",howToFix:"Use an API key that belongs to the right account, or select a company the key can access before retrying the tool call.",docsUrl:"https://docs.sequenzy.com/authentication",details:G};if(W.includes("no company available")||W.includes("company not found"))return{title:"Company selection required",description:"The MCP server could not resolve a company for this request.",howToFix:"Call `get_account` to inspect available companies, then call `select_company`, or pass `companyId` explicitly in the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(X.statusCode===404||W.includes("not found"))return{title:"Requested resource not found",description:"Sequenzy could not find the requested campaign, template, sequence, company, or subscriber.",howToFix:"List or fetch the resource collection first, then retry the tool with a confirmed ID or email value.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(X.statusCode===429||W.includes("rate limit"))return{title:"Rate limited",description:"Sequenzy temporarily slowed this MCP request because too many requests were sent too quickly.",howToFix:"Wait briefly before retrying. If the client is looping, reduce retries or add backoff before the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(X.code==="NETWORK_ERROR"||W.includes("fetch failed"))return{title:"Network or configuration error",description:"The MCP server could not reach the Sequenzy API from this environment.",howToFix:"Check connectivity and verify `SEQUENZY_API_URL` if you override it in the MCP environment.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(W.includes("unknown tool")||W.includes("unknown resource"))return{title:"Unsupported MCP request",description:"The client asked for a tool or resource name that this Sequenzy MCP server does not expose.",howToFix:"Refresh the client's tool list and call only the names returned by `list_tools` or `list_resources`.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(W.includes("is required")||W.includes("invalid"))return{title:"Invalid MCP input",description:"The tool call was missing a required field or included an invalid value.",howToFix:"Review the tool schema, supply the missing argument, and retry the request with corrected input.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(X.statusCode&&X.statusCode>=500)return{title:"Sequenzy server error",description:"The request reached Sequenzy, but the server could not complete it successfully.",howToFix:"Retry once. If it still fails, keep the details below and consult the docs before escalating.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};return{title:"Tool execution failed",description:"The MCP server could not complete the requested operation.",howToFix:"Review the details below, adjust the tool input or credentials, and retry.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G}}function V1(Q){let X=eO(Q);return[`Sequenzy MCP error: ${X.title}`,`Description: ${X.description}`,`How to fix: ${X.howToFix}`,`Docs: ${X.docsUrl}`,`Details: ${X.details}`].join(`
31
31
  `)}var jX=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],G5={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",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 QM(Q){let Y=(Q??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return Y.length>0?Y:"https://sequenzy.com"}function d0(Q){let X=Q?.trim();return X?X:void 0}function A1(Q){return encodeURIComponent(Q)}function z0(Q,X){return`${Q}${X}`}function H0(Q,X=""){return`/dashboard/company/${A1(Q)}${X}`}function J5(Q,X,Y){return z0(Q,`${H0(X,"/settings")}?tab=${encodeURIComponent(Y)}`)}function XM(Q,X){let Y=jX.map((W)=>[W,X?J5(Q,X,W):""]);return Object.fromEntries(Y)}function K1(Q={},X){let Y=QM(X),W=d0(Q.companyId),G={},J=XM(Y,W);if(!W)return{appUrl:Y,routeTemplates:G5,settingsTabValues:jX,urls:G,settingsUrls:J};G.dashboard=z0(Y,H0(W)),G.campaigns=z0(Y,H0(W,"/campaign")),G.sequences=z0(Y,H0(W,"/sequences")),G.settings=z0(Y,H0(W,"/settings")),G.emails=z0(Y,H0(W,"/emails")),G.subscribers=z0(Y,H0(W,"/subscribers")),G.segments=z0(Y,H0(W,"/segments")),G.metrics=z0(Y,H0(W,"/metrics")),G.transactional=z0(Y,H0(W,"/transactional"));let $=d0(Q.campaignId);if($)G.campaign=z0(Y,H0(W,`/campaign/${A1($)}`));let z=d0(Q.sequenceId);if(z)G.sequence=z0(Y,H0(W,`/sequences/${A1(z)}`));let H=d0(Q.emailId)??d0(Q.templateId);if(H)G.email=z0(Y,H0(W,`/emails/${A1(H)}`)),G.template=G.email;let A=d0(Q.transactionalId);if(A)G.transactionalEmail=z0(Y,H0(W,`/transactional/${A1(A)}`));let K=d0(Q.domainId);if(K)G.domain=z0(Y,H0(W,`/settings/domain/${A1(K)}`)),G.domainVerify=`${G.domain}/verify`;let U=d0(Q.status);if(U)G.campaignList=z0(Y,H0(W,`/campaign/list/${A1(U)}`)),G.sequenceList=z0(Y,H0(W,`/sequences/list/${A1(U)}`));let B=d0(Q.settingsTab);if(B)G.settingsTab=J5(Y,W,B);return{appUrl:Y,routeTemplates:G5,settingsTabValues:jX,urls:G,settingsUrls:J}}var $5=[{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 z5(Q){try{let X;switch(Q){case"sequenzy://dashboard":X=await Z("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let Y=await Z("GET","/api/v1/account"),W=f1()??Y.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");X=await Z("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":X=await Z("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":X=await Z("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":X=await Z("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":X=await Z("GET","/api/v1/sequences");break;case"sequenzy://templates":X=await Z("GET","/api/v1/templates");break;case"sequenzy://segments":X=await Z("GET","/api/v1/segments");break;case"sequenzy://tags":X=await Z("GET","/api/v1/tags");break;case"sequenzy://health":X=await Z("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":X=K1();break;default:throw Error(`Unknown resource: ${Q}`)}return{contents:[{uri:Q,mimeType:"application/json",text:JSON.stringify(X,null,2)}]}}catch(X){return{contents:[{uri:Q,mimeType:"text/plain",text:V1(X)}]}}}var YM={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct"],description:"Filter field. Use `event` for custom subscriber events, `segment` for saved segment membership, and `stripeProduct`/`stripeCurrentProduct`/`stripeTrialProduct` for Stripe product-based segments. Engagement fields (`emailSent`, `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","at_least","less_than_count","gte","lte","gt","lt"],description:"Filter operator. Use `is_empty` or `is_not_empty` for fields that can be blank, including custom attributes. For `stripeProduct`, use `is` or `is_not` with a raw product ID, and `at_least` or `less_than_count` with `productId:count`. For `event`, use `is`, `is_not`, `at_least`, or `less_than_count`. For engagement fields, use `is` (event happened) or `is_not` (event did not happen)."},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, `prod_123:3` for payment thresholds. 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},WM={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 K5(Q){if(!Array.isArray(Q))return Q;return Q.map((X)=>{if(typeof X!=="object"||X===null)return X;let Y=X;if(typeof Y.id==="string"&&Y.id.trim()!=="")return Y;return{...Y,id:crypto.randomUUID()}})}function U5(Q){if(typeof Q!=="object"||Q===null)return Q;let X=Q;if(X.kind==="filter"){let Y=K5([X]);return Array.isArray(Y)?Y[0]:X}if(X.kind!=="group")return Q;return{...X,id:typeof X.id==="string"&&X.id.trim()!==""?X.id:crypto.randomUUID(),children:Array.isArray(X.children)?X.children.map(U5):[]}}function l1(Q,X,Y){if(X.html!==void 0&&X.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`, not both.`);if(X.blocks!==void 0&&!Array.isArray(X.blocks))throw Error(`\`blocks\` must be an array when calling \`${Q}\`.`);if(Y?.requireContent&&X.html===void 0&&X.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`.`)}function GM(Q){let X=Q.filters!==void 0,Y=Q.root!==void 0;if(X&&Y)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!X&&!Y)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(X){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(Y&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `create_segment`.")}function JM(Q){if(Q.clearEnrollmentFieldPath===!0&&Q.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");let X={...Q};if(delete X.clearEnrollmentFieldPath,Q.clearEnrollmentFieldPath===!0)X.enrollmentFieldPath=null;return X}function $M(Q){l1("create_campaign",Q);let X=v(Q,"prompt")!==void 0,Y=Q.html!==void 0,W=Q.blocks!==void 0,G=Q.templateId!==void 0;if(Q.prompt!==void 0&&!X)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(X&&(Y||W||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!X&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!X&&v(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function zM(Q){l1("create_transactional_email",Q);let X=v(Q,"prompt")!==void 0,Y=Q.html!==void 0,W=Q.blocks!==void 0;if(Q.prompt!==void 0&&!X)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(X&&(Y||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!X&&(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(!X&&!Y&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!X&&v(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var H5={type:"object",description:"A step to create inside a branch path. Use type:'delay' for a standalone delay, type:'email' for an email, or type:'create_discount' for a discount action.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","webhook"],description:"Branch path step type. Omit for email steps; use delay for standalone waits."},nodeType:{type:"string",enum:["logic_delay","action_email","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","action_webhook"],description:"Advanced branch path node type. Prefer type unless creating a non-email action."},config:{type:"object",description:"Config for advanced nodeType steps such as tag/list/webhook/wait-for-event actions.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:"Sequenzy email blocks for email steps.",items:{type:"object"}},html:{type:"string",description:"HTML content for email steps."},delay:{type:"object",description:"Delay before this step, or the delay duration when type is delay.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}}},delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"]},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"}},additionalProperties:!1};function HM(Q){if(!Q||typeof Q!=="object")return null;let X=Q;if(X.success!==!1)return null;if(typeof X.error==="string")return Error(X.error);if(X.error&&typeof X.error==="object"&&typeof X.error.message==="string")return Error(X.error.message);if(typeof X.message==="string")return Error(X.message);return Error("The tool returned an unsuccessful response.")}function v0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function A5(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function AM(Q){let X=new URLSearchParams;if(typeof Q.query==="string"&&Q.query.trim()!=="")X.set("query",Q.query.trim());if(Array.isArray(Q.tags)&&Q.tags.length>0)X.set("tags",Q.tags.filter((Y)=>typeof Y==="string"&&Y.trim()!=="").join(","));if(typeof Q.segmentId==="string"&&Q.segmentId.trim()!=="")X.set("segmentId",Q.segmentId);return X.set("page",String(Q.page)),X.set("limit",String(Q.pageSize)),X}async function KM(Q,X){let Y=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,W=Math.min(100,Math.max(1,Y??100)),G=[],J=1,$=0,z=0,H=0;while(!0){let K=AM({query:Q.query,tags:Q.tags,segmentId:Q.segmentId,page:J,pageSize:W}),U=await Z("GET",`/api/v1/subscribers?${K.toString()}`,void 0,X);$=U.pagination?.total??U.subscribers.length,z=U.pagination?.totalPages??1,H+=1,G.push(...U.subscribers??[]);let B=Y!==void 0&&G.length>=Y,L=U.pagination?J>=U.pagination.totalPages:(U.subscribers??[]).length<W;if(B||L)break;J+=1}let A=Y!==void 0?G.slice(0,Y):G;return{success:!0,subscribers:A,pagination:{page:1,limit:W,total:$,totalPages:z,fetchedPages:H},returned:A.length,truncated:Y!==void 0&&$>0&&A.length<$}}async function PX(Q,X){return Z("GET",`/api/v1/subscribers/${encodeURIComponent(Q)}`,void 0,X)}function v(Q,X){let Y=Q[X];if(typeof Y!=="string")return;let W=Y.trim();return W.length>0?W:void 0}async function B5(Q){let X=v(Q,"companyId");if(X)return X;let Y=f1();if(Y)return Y;try{return(await Z("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}function g6(Q,X){if(!v0(Q)||!X)return Q;return{...Q,url:X}}function JQ(Q,X,Y){if(!Array.isArray(Q)||!X)return Q;return Q.map((W)=>{if(!v0(W))return W;let G=v(W,"id");if(!G)return W;let J=K1({companyId:X,...Y==="campaign"&&{campaignId:G},...Y==="sequence"&&{sequenceId:G},...Y==="template"&&{emailId:G},...Y==="transactional"&&{transactionalId:G}}),$=Y==="campaign"?J.urls.campaign:Y==="sequence"?J.urls.sequence:Y==="template"?J.urls.email:J.urls.transactionalEmail;return g6(W,$)})}function UM(Q){if(!Array.isArray(Q))return Q;return Q.map((X)=>{if(!v0(X))return X;let Y=v(X,"id");if(!Y)return X;let W=K1({companyId:Y});return{...X,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var BM=new Set(["get_account","select_company","create_company","get_company","list_campaigns","get_campaign","create_campaign","update_campaign","send_test_email","list_sequences","get_sequence","create_sequence","update_sequence","enable_sequence","disable_sequence","list_templates","get_template","create_template","update_template","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function DM(Q,X,Y){if(!v0(Y)||!BM.has(Q))return Y;let W=v0(Y.company)?Y.company:void 0,J=v(Y,"selectedCompanyId")??v(Y,"currentCompanyId")??v(Y,"companyId")??(W?v(W,"id"):void 0)??(W?v(W,"companyId"):void 0)??await B5(X);if(!J)return Y;let $=v0(Y.campaign)?Y.campaign:void 0,z=v0(Y.sequence)?Y.sequence:void 0,H=v0(Y.template)?Y.template:void 0,A=v0(Y.transactional)&&!Array.isArray(Y.transactional)?Y.transactional:void 0,K={companyId:J,campaignId:v(X,"campaignId")??v(Y,"campaignId")??($?v($,"id"):void 0),sequenceId:v(X,"sequenceId")??v(Y,"sequenceId")??(z?v(z,"id"):void 0),emailId:v(Y,"templateId")??(H?v(H,"id"):void 0)??(A?v(A,"emailId"):void 0)??v(X,"templateId"),transactionalId:v(X,"transactionalId")??(A?v(A,"id"):void 0)??v(X,"idOrSlug"),status:v(X,"status")},U=K1(K),B=W?K1({companyId:J}):void 0;return{...Y,...Array.isArray(Y.companies)&&{companies:UM(Y.companies)},...Array.isArray(Y.campaigns)&&{campaigns:JQ(Y.campaigns,J,"campaign")},...Array.isArray(Y.sequences)&&{sequences:JQ(Y.sequences,J,"sequence")},...Array.isArray(Y.templates)&&{templates:JQ(Y.templates,J,"template")},...Array.isArray(Y.transactional)&&{transactional:JQ(Y.transactional,J,"transactional")},...W&&B!==void 0&&{company:{...W,url:B.urls.dashboard,settingsUrl:B.urls.settings}},...$&&U.urls.campaign!==void 0&&{campaign:g6($,U.urls.campaign)},...z&&U.urls.sequence!==void 0&&{sequence:g6(z,U.urls.sequence)},...H&&U.urls.email!==void 0&&{template:g6(H,U.urls.email)},...A&&U.urls.transactionalEmail!==void 0&&{transactional:g6(A,U.urls.transactionalEmail)},appUrls:U.urls}}var D5=[{name:"get_account",description:`Get current account information including available companies. IMPORTANT: If you have access to multiple companies, you MUST either:
32
32
  1. Call select_company first to choose which company to work with, OR
33
33
  2. Pass companyId explicitly in each tool call
@@ -45,7 +45,7 @@ Use cases:
45
45
  - 'subscribe_form': Adding subscribers from signup forms
46
46
  - 'event_tracking': Tracking CUSTOM events only (not payment events - those come from the integration)
47
47
 
48
- Before implementing, use create_api_key to generate an API key and save it to .env as SEQUENZY_API_KEY.`,inputSchema:{type:"object",properties:{framework:{type:"string",description:"Framework/language (nextjs, express, python, etc.)"},use_case:{type:"string",description:"Use case: 'transactional' (sending emails), 'subscribe_form' (adding subscribers), 'event_tracking' (tracking CUSTOM events only - payment events should come from Stripe/Polar/etc integration)"}}}},{name:"add_subscriber",description:"Add a new subscriber to your list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to add subscriber to. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"},attributes:{type:"object",description:"Custom attributes (name, plan, etc.)"},tags:{type:"array",items:{type:"string"},description:"Tags to apply to the subscriber"},listIds:{type:"array",items:{type:"string"},description:"List IDs to add subscriber to"}},required:["email"]}},{name:"update_subscriber",description:"Update an existing subscriber's attributes or tags",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"},attributes:{type:"object",description:"Attributes to update"},addTags:{type:"array",items:{type:"string"},description:"Tags to add"},removeTags:{type:"array",items:{type:"string"},description:"Tags to remove"}},required:["email"]}},{name:"remove_subscriber",description:"Unsubscribe or delete a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"},hardDelete:{type:"boolean",description:"If true, permanently deletes. If false, just unsubscribes."}},required:["email"]}},{name:"get_subscriber",description:"Get the full subscriber profile, including tags, list memberships, sequence enrollments, email stats, and recent activity",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"}},required:["email"]}},{name:"search_subscribers",description:"Search subscribers by free-text query, tags, or segment. If you omit limit, the tool fetches all pages and returns every match.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},query:{type:"string",description:"Search query (email or name)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"},segmentId:{type:"string",description:"Filter by segment ID"},limit:{type:"number",description:"Maximum results to return. If omitted, the tool returns all matches across pages."}}}},{name:"list_tags",description:"List all tags in the account",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list tags for. If not provided, uses the currently selected company."}}}},{name:"list_lists",description:"List all subscriber lists",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list lists for. If not provided, uses the currently selected company."}}}},{name:"create_list",description:"Create a new subscriber list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the list in. If not provided, uses the currently selected company."},name:{type:"string",description:"List name"},description:{type:"string",description:"List description"}},required:["name"]}},{name:"list_segments",description:"List all segments",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list segments for. If not provided, uses the currently selected company."}}}},{name:"create_segment",description:'Create a new segment from explicit filter rules. Use `filters` plus `filterJoinOperator` for flat legacy rules, or `root` for nested AND/OR groups such as `{ "kind": "group", "joinOperator": "and", "children": [{ "kind": "filter", "field": "attribute", "operator": "gte", "value": "mrr:50" }, { "kind": "group", "joinOperator": "or", "children": [{ "kind": "filter", "field": "tag", "operator": "contains", "value": "vip" }, { "kind": "filter", "field": "event", "operator": "is_not", "value": "saas.purchase:30d" }] }] }`. Supports `event` and `segment` fields, Stripe product purchase filters, and campaign-specific engagement filters.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the segment in. If not provided, uses the currently selected company."},name:{type:"string",description:"Segment name"},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:YM,minItems:1,description:'Array of segment filters. Example custom attribute empty check: [{"id":"filter-1","field":"attribute","operator":"is_empty","value":"last_logged_in:"}]. Example Stripe purchase filter: [{"id":"filter-1","field":"stripeProduct","operator":"is","value":"prod_123"}]. Example threshold filter: [{"id":"filter-1","field":"stripeProduct","operator":"at_least","value":"prod_123:3"}]. Example campaign-specific engagement combo: [{"id":"filter-1","field":"emailBounced","operator":"is","value":"campaign:cmp_abc"},{"id":"filter-2","field":"emailBounced","operator":"is_not","value":"campaign:cmp_xyz"}]. Combine them with `filterJoinOperator: "or"` to match any filter.'},root:{...WM,description:"Nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["name"]}},{name:"get_segment_count",description:"Get the number of subscribers in a segment",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID"}},required:["segmentId"]}},{name:"list_templates",description:"List all email templates, including per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_template",description:"Get a template's details, content, and all localized variants with sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"create_template",description:"Create a new email template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line"},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:"Sequenzy email blocks. Use this for editor-compatible content, including conditional blocks.",items:{type:"object"}}},required:["name","subject"]}},{name:"update_template",description:"Update an existing template. At least one of `name`, `subject`, `html`, or `blocks` is required, and only those update fields are accepted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line"},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:"Sequenzy email blocks. Use this for editor-compatible content, including conditional blocks.",items:{type:"object"}}},required:["templateId"],additionalProperties:!1}},{name:"delete_template",description:"Delete a template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"list_campaigns",description:"List all campaigns",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list campaigns for. If not provided, uses the currently selected company."},status:{type:"string",description:"Filter by status (draft, scheduled, sent)"}}}},{name:"get_campaign",description:"Get campaign details and stats",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"create_campaign",description:"Create a new campaign (as draft)",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:"Sequenzy email blocks. Use this for editor-compatible content, including conditional blocks.",items:{type:"object"}},prompt:{type:"string",description:"Generate campaign blocks from a prompt. Mutually exclusive with `html`, `blocks`, and `templateId`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},templateId:{type:"string",description:"Use a template instead of html"},segmentId:{type:"string",description:"Target segment ID"}},required:["name"]}},{name:"update_campaign",description:"Update a draft campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line"},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:"Sequenzy email blocks. Use this for editor-compatible content, including conditional blocks.",items:{type:"object"}},replyTo:{type:"string",description:"Set reply-to using an existing reply profile email address for this company."},replyProfileId:{type:"string",description:"Set reply-to using a reply profile ID for this company."}},required:["campaignId"],additionalProperties:!1}},{name:"send_test_email",description:"Send a test email to a single address",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"list_sequences",description:"List all email sequences (automations)",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list sequences for. If not provided, uses the currently selected company."}}}},{name:"get_sequence",description:"Get sequence details plus editable step content. The response includes sequence.emails with each step's nodeId, linked emailId, subject, previewText, and blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"create_sequence",description:`Create a new email sequence. Provide either a goal for AI generation or explicit steps. Explicit steps can include email content and create_discount actions; emails after a discount action can use merge tags such as {{discount.code}} and {{discount.percentOff}}. For AI-generated sequences, the tool polls until emails are generated (typically 30-60 seconds).
48
+ Before implementing, use create_api_key to generate an API key and save it to .env as SEQUENZY_API_KEY.`,inputSchema:{type:"object",properties:{framework:{type:"string",description:"Framework/language (nextjs, express, python, etc.)"},use_case:{type:"string",description:"Use case: 'transactional' (sending emails), 'subscribe_form' (adding subscribers), 'event_tracking' (tracking CUSTOM events only - payment events should come from Stripe/Polar/etc integration)"}}}},{name:"add_subscriber",description:"Add a new subscriber to your list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to add subscriber to. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"},attributes:{type:"object",description:"Custom attributes (name, plan, etc.)"},tags:{type:"array",items:{type:"string"},description:"Tags to apply to the subscriber"},listIds:{type:"array",items:{type:"string"},description:"List IDs to add subscriber to"}},required:["email"]}},{name:"update_subscriber",description:"Update an existing subscriber's attributes or tags",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"},attributes:{type:"object",description:"Attributes to update"},addTags:{type:"array",items:{type:"string"},description:"Tags to add"},removeTags:{type:"array",items:{type:"string"},description:"Tags to remove"}},required:["email"]}},{name:"remove_subscriber",description:"Unsubscribe or delete a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"},hardDelete:{type:"boolean",description:"If true, permanently deletes. If false, just unsubscribes."}},required:["email"]}},{name:"get_subscriber",description:"Get the full subscriber profile, including tags, list memberships, sequence enrollments, email stats, and recent activity",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"}},required:["email"]}},{name:"search_subscribers",description:"Search subscribers by free-text query, tags, or segment. If you omit limit, the tool fetches all pages and returns every match.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},query:{type:"string",description:"Search query (email or name)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"},segmentId:{type:"string",description:"Filter by segment ID"},limit:{type:"number",description:"Maximum results to return. If omitted, the tool returns all matches across pages."}}}},{name:"list_tags",description:"List all tags in the account",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list tags for. If not provided, uses the currently selected company."}}}},{name:"list_lists",description:"List all subscriber lists",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list lists for. If not provided, uses the currently selected company."}}}},{name:"create_list",description:"Create a new subscriber list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the list in. If not provided, uses the currently selected company."},name:{type:"string",description:"List name"},description:{type:"string",description:"List description"}},required:["name"]}},{name:"list_segments",description:"List all segments",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list segments for. If not provided, uses the currently selected company."}}}},{name:"create_segment",description:'Create a new segment from explicit filter rules. Use `filters` plus `filterJoinOperator` for flat legacy rules, or `root` for nested AND/OR groups such as `{ "kind": "group", "joinOperator": "and", "children": [{ "kind": "filter", "field": "attribute", "operator": "gte", "value": "mrr:50" }, { "kind": "group", "joinOperator": "or", "children": [{ "kind": "filter", "field": "tag", "operator": "contains", "value": "vip" }, { "kind": "filter", "field": "event", "operator": "is_not", "value": "saas.purchase:30d" }] }] }`. Supports `event` and `segment` fields, Stripe product purchase filters, and campaign-specific engagement filters.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the segment in. If not provided, uses the currently selected company."},name:{type:"string",description:"Segment name"},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:YM,minItems:1,description:'Array of segment filters. Example custom attribute empty check: [{"id":"filter-1","field":"attribute","operator":"is_empty","value":"last_logged_in:"}]. Example Stripe purchase filter: [{"id":"filter-1","field":"stripeProduct","operator":"is","value":"prod_123"}]. Example threshold filter: [{"id":"filter-1","field":"stripeProduct","operator":"at_least","value":"prod_123:3"}]. Example campaign-specific engagement combo: [{"id":"filter-1","field":"emailBounced","operator":"is","value":"campaign:cmp_abc"},{"id":"filter-2","field":"emailBounced","operator":"is_not","value":"campaign:cmp_xyz"}]. Combine them with `filterJoinOperator: "or"` to match any filter.'},root:{...WM,description:"Nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["name"]}},{name:"get_segment_count",description:"Get the number of subscribers in a segment",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID"}},required:["segmentId"]}},{name:"list_templates",description:"List all email templates, including per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_template",description:"Get a template's details, content, and all localized variants with sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"create_template",description:"Create a new email template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line"},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:"Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.",items:{type:"object"}}},required:["name","subject"]}},{name:"update_template",description:"Update an existing template. At least one of `name`, `subject`, `html`, or `blocks` is required, and only those update fields are accepted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line"},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:"Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.",items:{type:"object"}}},required:["templateId"],additionalProperties:!1}},{name:"delete_template",description:"Delete a template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"list_campaigns",description:"List all campaigns",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list campaigns for. If not provided, uses the currently selected company."},status:{type:"string",description:"Filter by status (draft, scheduled, sent)"}}}},{name:"get_campaign",description:"Get campaign details and stats",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"create_campaign",description:"Create a new campaign (as draft)",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:"Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.",items:{type:"object"}},prompt:{type:"string",description:"Generate campaign blocks from a prompt. Mutually exclusive with `html`, `blocks`, and `templateId`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},templateId:{type:"string",description:"Use a template instead of html"},segmentId:{type:"string",description:"Target segment ID"}},required:["name"]}},{name:"update_campaign",description:"Update a draft campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line"},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:"Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.",items:{type:"object"}},replyTo:{type:"string",description:"Set reply-to using an existing reply profile email address for this company."},replyProfileId:{type:"string",description:"Set reply-to using a reply profile ID for this company."}},required:["campaignId"],additionalProperties:!1}},{name:"send_test_email",description:"Send a test email to a single address",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"list_sequences",description:"List all email sequences (automations)",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list sequences for. If not provided, uses the currently selected company."}}}},{name:"get_sequence",description:"Get sequence details plus editable step content. The response includes sequence.emails with each step's nodeId, linked emailId, subject, previewText, and blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"create_sequence",description:`Create a new email sequence. Provide either a goal for AI generation or explicit steps. Explicit steps can include email content and create_discount actions; emails after a discount action can use merge tags such as {{discount.code}} and {{discount.percentOff}}. For AI-generated sequences, the tool polls until emails are generated (typically 30-60 seconds).
49
49
 
50
50
  IMPORTANT GUIDELINES:
51
51
 
@@ -174,4 +174,4 @@ BUILT-IN EVENTS (auto-fired by payment integrations):
174
174
 
175
175
  OTHER BUILT-IN EVENTS:
176
176
  - email.opened, email.clicked, email.replied, email.bounced, email.unsubscribed
177
- - contact.subscribed, contact.unsubscribed`,inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inactivity","frequency"],description:"Trigger type: 'contact_added' (when added to a list), 'tag_added' (when tag is applied), 'segment_entered' (when a contact newly enters a saved segment), 'event_received' (when custom event fires), 'inactivity' (when subscriber hasn't performed an event for X days), 'frequency' (when subscriber performs event X times in Y days)"},listId:{type:"string",description:"List ID to trigger on (for contact_added trigger). If not provided, triggers on any list."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger)"},segmentId:{type:"string",description:"Segment ID to trigger on (required for segment_entered trigger). Use list_segments first to choose a saved segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inactivity, and frequency triggers)"},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value."},enrollmentFieldPath:{type:"string",description:"Dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},stopCondition:{type:"object",description:"Optional explicit auto-stop condition. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'does_not_have_tag', value: 'trial' } when a tag is removed, { type: 'removed_from_list', value: 'list_123' } when they leave a list, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","event_received"],description:"Stop condition type."},value:{type:["string","null"],description:"Tag name, list ID, or event name for the stop condition. Use null or omit for type 'none'."}},required:["type"]},steps:{type:"array",description:"Explicit sequence steps. Omit type for email steps, or use type: 'create_discount' for a Stripe discount action. Later email steps can reference the most recent discount with {{discount.code}}, {{discount.percentOff}}, {{discount.amountOff}}, and {{discount.expiresAt}}.",items:{type:"object",properties:{type:{type:"string",enum:["email","create_discount","discount"],description:"Step type. Omit or use 'email' for email content. Use 'create_discount' to generate a discount code before later emails."},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:"Sequenzy email blocks. Provide blocks or html for email steps.",items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Will be converted to Sequenzy blocks."},delay:{type:"object",description:"Delay before this step.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}}},name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Prefer this nested shape for new integrations; legacy top-level discount fields are still accepted.",properties:{label:{type:"string",description:"Builder label for the discount step."},provider:{type:"string",enum:["stripe"],description:"Discount provider. Currently only 'stripe'."},discountType:{type:"string",enum:["percent","amount"],description:"Discount type."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Stripe coupon duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Stripe product IDs, such as prod_abc123, when appliesToAllPlans is false.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated promotion codes."},maxRedemptions:{type:"number",description:"Maximum promotion code redemptions. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Stripe-only. Restrict each generated promotion code to the matched subscriber's Stripe customer."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."},name:{type:"string",description:"Optional provider coupon name."}}},label:{type:"string",description:"Legacy top-level discount label. Prefer discount.label."},provider:{type:"string",enum:["stripe"],description:"Legacy top-level discount provider. Prefer discount.provider."},discountType:{type:"string",enum:["percent","amount"],description:"Legacy top-level discount type. Prefer discount.discountType."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Stripe coupon duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Stripe product IDs, such as prod_abc123, when appliesToAllPlans is false.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated promotion codes."},maxRedemptions:{type:"number",description:"Maximum promotion code redemptions. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Legacy top-level Stripe-only flag. Prefer discount.lockToSubscriber."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."}}}}},required:["name","trigger"]}},{name:"update_sequence",description:"Update an existing sequence. To target a specific step, use the emailId or nodeId returned in get_sequence.sequence.emails. You can also update enrollmentMode and enrollmentFieldPath for event-triggered matching-field enrollment. When inserting an if/else branch, include steps for every branch arm and elseSteps so the branch is usable immediately.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},name:{type:"string",description:"Sequence name"},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Updated sequence re-entry mode. 'matching_field' is only valid for event-based sequence triggers."},enrollmentFieldPath:{type:"string",description:"Dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Omit to leave unchanged. Use clearEnrollmentFieldPath to clear it."},clearEnrollmentFieldPath:{type:"boolean",description:"Set true to clear enrollmentFieldPath without sending a nullable schema value."},stopCondition:{type:"object",description:"Update the sequence auto-stop condition. Example: { type: 'has_tag', value: 'customer' } ends the sequence when the subscriber has that tag. Use { type: 'removed_from_list', value: 'list_123' } to stop when they leave a list, or { type: 'none', value: null } to clear it.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","event_received"]},value:{type:["string","null"],description:"Tag name, list ID, or event name for the stop condition."}},required:["type"]},branch:{type:"object",description:"Insert an if/else branch into an existing sequence. The branch is inserted after afterNodeId and creates an if path plus an else fallback path. Use get_sequence first to choose afterNodeId. Each branch condition should include steps, and elseSteps is required unless allowEmptyPaths is true.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert the branch after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails."},label:{type:"string",description:"Optional branch node label."},branches:{type:"array",description:"Conditional branches evaluated in order. An else fallback is created automatically.",items:{type:"object",properties:{id:{type:"string",description:"Optional stable branch ID. Defaults to branch-0, branch-1, etc."},label:{type:"string",description:"Display label, e.g. 'If has customer tag'."},conditionType:{type:"string",enum:["has_tag","in_list","field_equals","field_contains","field_greater_than","field_less_than"],description:"Condition type for this branch."},tagName:{type:"string",description:"Tag name for has_tag conditions. This can be used instead of tagId."},tagId:{type:"string",description:"Tag ID or tag name for has_tag conditions."},listId:{type:"string",description:"List ID for in_list conditions."},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:H5}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:H5},allowEmptyPaths:{type:"boolean",description:"Set true only when intentionally creating empty UI placeholders. Normal API/MCP use should omit this and provide branch steps plus elseSteps."}},required:["afterNodeId","branches"]},emails:{type:"array",description:"Updated sequence emails. If you omit emailId/nodeId, items are matched by existing step order.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Will be converted to Sequenzy blocks."},htmlContent:{type:"string",description:"Alias for html. Use this when updating HTML content for a step."},blocks:{type:"array",description:"Updated Sequenzy block JSON for the step"}}}},steps:{type:"array",description:"Alias for emails. Supports the same fields and matching rules.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Will be converted to Sequenzy blocks."},htmlContent:{type:"string",description:"Alias for html. Use this when updating HTML content for a step."},blocks:{type:"array",description:"Updated Sequenzy block JSON for the step"}}}}},required:["sequenceId"]}},{name:"enable_sequence",description:"Enable/activate a sequence. IMPORTANT: Only call this when the user EXPLICITLY asks to enable or activate a sequence. Never enable sequences automatically after creation - the user must review the content first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"disable_sequence",description:"Disable/pause a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"delete_sequence",description:"Delete a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"list_transactional_emails",description:"List transactional email templates, including their API slugs and linked email IDs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_transactional_email",description:"Get a transactional email by ID or slug, including subject, preview text, blocks, variables, and linked dashboard URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"]}},{name:"create_transactional_email",description:"Create a saved transactional email template with an API slug. Provide `prompt` to generate the email with AI, or provide either `html` or Sequenzy `blocks` for the email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Transactional email name."},slug:{type:"string",description:"Optional API slug used when sending by slug, for example `password-reset`. If omitted, Sequenzy generates one from the name."},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:"Sequenzy email blocks. Use this for editor-compatible content, including conditional blocks. Mutually exclusive with `html`.",items:{type:"object"}},prompt:{type:"string",description:"Generate transactional email blocks from a prompt. Mutually exclusive with `html` and `blocks`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},enabled:{type:"boolean",description:"Whether this transactional email can be sent immediately. Defaults to true."}},required:["name"],additionalProperties:!1}},{name:"update_transactional_email",description:"Update a transactional email by ID or slug. At least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` is required. Use `html` or `blocks` to replace the linked email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."},name:{type:"string",description:"Transactional email name."},enabled:{type:"boolean",description:"Whether this transactional email can be sent."},subject:{type:"string",description:"Email subject line."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:"Sequenzy email blocks. 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"}},required:["to"]}},{name:"get_stats",description:"Get overview statistics for a time period",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},period:{type:"string",description:"Time period: 7d, 30d, or 90d (default: 7d)"}}}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_sequence_stats",description:"Get statistics for a sequence, including per-step failed subscribers and failure reasons",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"get_subscriber_activity",description:"Get recent activity, email stats, and current sequence enrollments for a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"}},required:["email"]}},{name:"generate_email",description:"Generate email blocks from a prompt",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the email to generate"},style:{type:"string",description:"Style: minimal, branded, promotional"},tone:{type:"string",description:"Tone: professional, casual, friendly"}},required:["prompt"]}},{name:"generate_sequence",description:"[DEPRECATED - Use create_sequence instead] Generate a multi-email sequence from a goal. Note: create_sequence now handles AI generation automatically.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},goal:{type:"string",description:"Goal of the sequence (e.g., 'onboard new SaaS trial users')"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days (default: 14)"}},required:["goal"]}},{name:"generate_subject_lines",description:"Generate A/B test subject line variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},topic:{type:"string",description:"Topic or context for the subject lines"},count:{type:"number",description:"Number of variants to generate (default: 5)"}},required:["topic"]}}];async function L5(Q,X){try{let Y;switch(Q){case"get_account":{let G=await Z("GET","/api/v1/account"),J=f1();Y={...G,selectedCompanyId:J??G.currentCompanyId};break}case"select_company":{let G=X.companyId,J=await Z("GET","/api/v1/account"),$=J.companies?.find((z)=>z.id===G);if(!$)throw Error(`Company not found. Available companies: ${J.companies?.map((z)=>`${z.name} (${z.id})`).join(", ")??"none"}`);IX(G),Y={success:!0,message:`Switched to company: ${$.name}`,companyId:$.id,companyName:$.name};break}case"get_app_urls":{let G=await B5(X);Y={...K1({companyId:G,campaignId:v(X,"campaignId"),sequenceId:v(X,"sequenceId"),emailId:v(X,"emailId")??v(X,"templateId"),transactionalId:v(X,"transactionalId"),domainId:v(X,"domainId"),status:v(X,"status"),settingsTab:v(X,"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 Z("POST","/api/v1/companies",{name:X.name,domain:X.domain});if(!G.success)throw Error("Failed to create company");let J=G.company.id,$=6,z=0,H=G.company.status;while(H==="processing"&&z<$){await new Promise((U)=>setTimeout(U,20000)),z++;let K=await Z("GET",`/api/v1/companies/${J}`);if(K.success)H=K.company.status}IX(J);let A=await Z("GET",`/api/v1/companies/${J}`);Y={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=X.companyId;Y=await Z("GET",`/api/v1/companies/${G}`);break}case"create_api_key":{let G=X.companyId;Y=await Z("POST","/api/v1/api-keys",{name:X.name},G);break}case"list_websites":{let G=X.companyId;Y=await Z("GET","/api/v1/websites",void 0,G);break}case"add_website":{let G=X.companyId;Y=await Z("POST","/api/v1/websites",{domain:X.domain},G);break}case"check_website":{let G=X.companyId;Y=await Z("GET",`/api/v1/websites/${X.domain}`,void 0,G);break}case"get_integration_guide":Y=await Z("POST","/api/v1/integration-guide",X);break;case"add_subscriber":{let G=X.companyId;Y=await Z("POST","/api/v1/subscribers",{email:X.email,customAttributes:X.attributes,tags:X.tags,lists:X.listIds},G);break}case"update_subscriber":{let G=X.companyId,J=await PX(String(X.email),G),$=Array.isArray(J.subscriber.tags)?J.subscriber.tags.filter((U)=>typeof U==="string"):[],z=Array.isArray(X.addTags)?X.addTags.filter((U)=>typeof U==="string"&&U.trim()!=="").map(A5):[],H=new Set(Array.isArray(X.removeTags)?X.removeTags.filter((U)=>typeof U==="string"&&U.trim()!=="").map(A5):[]),A=$.filter((U)=>!H.has(U));for(let U of z)if(!A.includes(U))A.push(U);let K={};if(v0(X.attributes))K.customAttributes={...v0(J.subscriber.customAttributes)?J.subscriber.customAttributes:{},...X.attributes};if(X.addTags||X.removeTags)K.tags=A;Y=await Z("PATCH",`/api/v1/subscribers/${encodeURIComponent(String(X.email))}`,K,G);break}case"remove_subscriber":{let G=X.companyId;if(X.hardDelete===!0)Y=await Z("DELETE",`/api/v1/subscribers/${encodeURIComponent(String(X.email))}`,void 0,G);else Y=await Z("PATCH",`/api/v1/subscribers/${encodeURIComponent(String(X.email))}`,{status:"unsubscribed"},G);break}case"get_subscriber":{let G=X.companyId;Y=await PX(String(X.email),G);break}case"search_subscribers":{let G=X.companyId;Y=await KM(X,G);break}case"list_tags":{let G=X.companyId;Y=await Z("GET","/api/v1/tags",void 0,G);break}case"list_lists":{let G=X.companyId;Y=await Z("GET","/api/v1/lists",void 0,G);break}case"create_list":{let G=X.companyId;Y=await Z("POST","/api/v1/lists",X,G);break}case"list_segments":{let G=X.companyId;Y=await Z("GET","/api/v1/segments",void 0,G);break}case"create_segment":{GM(X);let G=X.companyId;Y=await Z("POST","/api/v1/segments",{...X,...X.filters!==void 0?{filters:K5(X.filters)}:{},...X.root!==void 0?{root:U5(X.root)}:{}},G);break}case"get_segment_count":{let G=X.companyId;Y=await Z("GET",`/api/v1/segments/${X.segmentId}/count`,void 0,G);break}case"list_templates":{let G=X.companyId;Y=await Z("GET","/api/v1/templates",void 0,G);break}case"get_template":{let G=X.companyId;Y=await Z("GET",`/api/v1/templates/${X.templateId}`,void 0,G);break}case"create_template":{let G=X.companyId;l1("create_template",X,{requireContent:!0}),Y=await Z("POST","/api/v1/templates",X,G);break}case"update_template":{let G=X.companyId,J=new Set(["companyId","templateId","name","subject","html","blocks"]),$=Object.keys(X).filter((z)=>!J.has(z));if($.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`html\`, and \`blocks\` update fields. Unsupported field${$.length===1?"":"s"}: ${$.map((z)=>`\`${z}\``).join(", ")}.`);if(l1("update_template",X),X.name===void 0&&X.subject===void 0&&X.html===void 0&&X.blocks===void 0)throw Error("Provide at least one of `name`, `subject`, `html`, or `blocks` when calling `update_template`.");Y=await Z("PUT",`/api/v1/templates/${X.templateId}`,X,G);break}case"delete_template":{let G=X.companyId;Y=await Z("DELETE",`/api/v1/templates/${X.templateId}`,void 0,G);break}case"list_campaigns":{let G=X.companyId,J=new URLSearchParams;if(X.status)J.set("status",String(X.status));Y=await Z("GET",`/api/v1/campaigns?${J}`,void 0,G);break}case"get_campaign":{let G=X.companyId;Y=await Z("GET",`/api/v1/campaigns/${X.campaignId}`,void 0,G);break}case"create_campaign":{let G=X.companyId;$M(X);let J=v(X,"prompt");if(J!==void 0){let $=await Z("POST","/api/v1/generate/email",{prompt:J,...X.style!==void 0&&{style:X.style},...X.tone!==void 0&&{tone:X.tone}},G),z=v(X,"subject")??(typeof $.subject==="string"&&$.subject.trim()!==""?$.subject.trim():void 0);if(!z)throw Error("`create_campaign` prompt generation did not return a subject. Provide `subject` explicitly.");let H=Array.isArray($.blocks)&&$.blocks.length>0?$.blocks:void 0,A=typeof $.html==="string"&&$.html.trim()!==""?$.html:void 0;if(H===void 0&&A===void 0)throw Error("`create_campaign` prompt generation did not return email blocks. Try again or provide `html` or `blocks` explicitly.");Y=await Z("POST","/api/v1/campaigns",{name:X.name,subject:z,...H!==void 0?{blocks:H}:{html:A},...X.segmentId!==void 0&&{segmentId:X.segmentId}},G);break}Y=await Z("POST","/api/v1/campaigns",X,G);break}case"update_campaign":{let G=X.companyId,J=new Set(["companyId","campaignId","name","subject","html","blocks","replyTo","replyProfileId"]),$=Object.keys(X).filter((z)=>!J.has(z));if($.length>0)throw Error(`\`update_campaign\` accepts only \`name\`, \`subject\`, \`html\`, \`blocks\`, \`replyTo\`, and \`replyProfileId\` update fields. Unsupported field${$.length===1?"":"s"}: ${$.map((z)=>`\`${z}\``).join(", ")}.`);if(l1("update_campaign",X),X.replyTo!==void 0&&X.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_campaign`, not both.");if(X.name===void 0&&X.subject===void 0&&X.html===void 0&&X.blocks===void 0&&X.replyTo===void 0&&X.replyProfileId===void 0)throw Error("Provide at least one of `name`, `subject`, `html`, `blocks`, `replyTo`, or `replyProfileId` when calling `update_campaign`.");Y=await Z("PUT",`/api/v1/campaigns/${X.campaignId}`,X,G);break}case"send_test_email":{let G=X.companyId;Y=await Z("POST",`/api/v1/campaigns/${X.campaignId}/test`,{to:X.to},G);break}case"list_sequences":{let G=X.companyId;Y=await Z("GET","/api/v1/sequences",void 0,G);break}case"get_sequence":{let G=X.companyId;Y=await Z("GET",`/api/v1/sequences/${X.sequenceId}`,void 0,G);break}case"create_sequence":{let G=X.companyId,J=Array.isArray(X.steps)&&X.steps.length>0,$=await Z("POST","/api/v1/sequences",X,G);if(!$.success){Y=$;break}let z=$.sequence.id;if(J){let B=await Z("GET",`/api/v1/sequences/${z}`,void 0,G);if(B.success)Y={success:!0,sequence:B.sequence,message:`Sequence "${B.sequence.name}" created with explicit steps. Review it before enabling.`};else Y=B;break}let H=6,A=0,K="pending";while(K!=="complete"&&A<H){await new Promise((L)=>setTimeout(L,20000)),A++;let B=await Z("GET",`/api/v1/sequences/${z}`,void 0,G);if(B.success)K=B.sequence.enrichmentStatus}let U=await Z("GET",`/api/v1/sequences/${z}`,void 0,G);if(U.success)Y={success:!0,sequence:U.sequence,message:U.sequence.enrichmentStatus==="complete"?`Sequence "${U.sequence.name}" created with ${U.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.`:`Sequence "${U.sequence.name}" created. Email enrichment is still in progress (${U.sequence.enrichedCount}/${U.sequence.emailCount} emails generated). You can check status with get_sequence.`};else Y=U;break}case"update_sequence":{let G=X.companyId,J=JM(X);Y=await Z("PUT",`/api/v1/sequences/${X.sequenceId}`,J,G);break}case"enable_sequence":{let G=X.companyId;Y=await Z("POST",`/api/v1/sequences/${X.sequenceId}/enable`,void 0,G);break}case"disable_sequence":{let G=X.companyId;Y=await Z("POST",`/api/v1/sequences/${X.sequenceId}/disable`,void 0,G);break}case"delete_sequence":{let G=X.companyId;Y=await Z("DELETE",`/api/v1/sequences/${X.sequenceId}`,void 0,G);break}case"list_transactional_emails":{let G=X.companyId;Y=await Z("GET","/api/v1/transactional",void 0,G);break}case"get_transactional_email":{let G=X.companyId;Y=await Z("GET",`/api/v1/transactional/${X.idOrSlug}`,void 0,G);break}case"create_transactional_email":{let G=X.companyId,J=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),$=Object.keys(X).filter((A)=>!J.has(A));if($.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${$.length===1?"":"s"}: ${$.map((A)=>`\`${A}\``).join(", ")}.`);zM(X);let z=v(X,"prompt");if(z!==void 0){let A={companyId:G??f1()??"",name:typeof X.name==="string"&&X.name.trim()!==""?X.name.trim():"",slug:typeof X.slug==="string"&&X.slug.trim()!==""?X.slug.trim():"",promptLength:z.length,style:typeof X.style==="string"?X.style:"",tone:typeof X.tone==="string"?X.tone:""};try{console.error("[mcp:create_transactional_email] generating from prompt",A);let K=await Z("POST","/api/v1/generate/email",{prompt:z,...X.style!==void 0&&{style:X.style},...X.tone!==void 0&&{tone:X.tone}},G);console.error("[mcp:create_transactional_email] prompt generation complete",{...A,subject:K.subject??"",previewTextLength:typeof K.previewText==="string"?K.previewText.length:0,blockCount:Array.isArray(K.blocks)?K.blocks.length:0,htmlLength:typeof K.html==="string"?K.html.length:0});let U=v(X,"subject")??(typeof K.subject==="string"&&K.subject.trim()!==""?K.subject.trim():void 0);if(!U)throw Error("`create_transactional_email` prompt generation did not return a subject. Provide `subject` explicitly.");let B=Array.isArray(K.blocks)&&K.blocks.length>0?K.blocks:void 0,L=typeof K.html==="string"&&K.html.trim()!==""?K.html:void 0,q=v(X,"previewText")??(typeof K.previewText==="string"?K.previewText.trim():void 0);if(B===void 0&&L===void 0)throw Error("`create_transactional_email` prompt generation did not return email blocks. Try again or provide `html` or `blocks` explicitly.");console.error("[mcp:create_transactional_email] creating generated transactional",{...A,subject:U,contentSource:B!==void 0?"blocks":"html",blockCount:B?.length??0,htmlLength:L?.length??0}),Y=await Z("POST","/api/v1/transactional",{name:X.name,...X.slug!==void 0&&{slug:X.slug},subject:U,...q!==void 0&&{previewText:q},...B!==void 0?{blocks:B}:{html:L},...X.enabled!==void 0&&{enabled:X.enabled}},G),console.error("[mcp:create_transactional_email] generated transactional created",A)}catch(K){throw console.error("[mcp:create_transactional_email] prompt-based create failed",{...A,error:K instanceof Error?K.message:String(K)}),K}break}let H=Object.fromEntries(Object.entries(X).filter(([A])=>A!=="companyId"));Y=await Z("POST","/api/v1/transactional",H,G);break}case"update_transactional_email":{let G=X.companyId,J=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),$=Object.keys(X).filter((H)=>!J.has(H));if($.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${$.length===1?"":"s"}: ${$.map((H)=>`\`${H}\``).join(", ")}.`);if(l1("update_transactional_email",X),X.name===void 0&&X.enabled===void 0&&X.subject===void 0&&X.previewText===void 0&&X.html===void 0&&X.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let z=Object.fromEntries(Object.entries(X).filter(([H])=>H!=="companyId"&&H!=="idOrSlug"));Y=await Z("PATCH",`/api/v1/transactional/${X.idOrSlug}`,z,G);break}case"send_email":{let G=X.companyId;Y=await Z("POST","/api/v1/transactional/send",X,G);break}case"get_stats":{let G=X.companyId,J=X.period??"7d";Y=await Z("GET",`/api/v1/metrics?period=${J}`,void 0,G);break}case"get_campaign_stats":{let G=X.companyId;Y=await Z("GET",`/api/v1/metrics/campaigns/${X.campaignId}`,void 0,G);break}case"get_sequence_stats":{let G=X.companyId;Y=await Z("GET",`/api/v1/metrics/sequences/${X.sequenceId}`,void 0,G);break}case"get_subscriber_activity":{let G=X.companyId,J=await PX(String(X.email),G);Y={success:J.success,email:J.subscriber.email,emailStats:J.subscriber.emailStats??null,activity:J.subscriber.activity??[],sequenceEnrollments:J.subscriber.sequenceEnrollments??[]};break}case"generate_email":{let G=X.companyId;Y=await Z("POST","/api/v1/generate/email",X,G);break}case"generate_sequence":{let G=X.companyId;Y=await Z("POST","/api/v1/generate/sequence",X,G);break}case"generate_subject_lines":{let G=X.companyId;Y=await Z("POST","/api/v1/generate/subjects",X,G);break}default:throw Error(`Unknown tool: ${Q}`)}let W=HM(Y);if(W)throw W;return Y=await DM(Q,X,Y),{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}catch(Y){return{isError:!0,content:[{type:"text",text:V1(Y)}]}}}var LM=process.env.SEQUENZY_API_URL??"https://api.sequenzy.com",F5=process.env.SEQUENZY_API_KEY,EX=null;if(!F5)console.error(V1(new h1("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1);function f1(){return EX}function IX(Q){EX=Q}var u6=new NX({name:"sequenzy",version:W5.version},{capabilities:{tools:{},resources:{}}});function FM(Q){if(!Q.trim())return{message:"Request failed"};try{let X=JSON.parse(Q);if(typeof X==="string")return{message:X};if(typeof X.error==="string")return{message:X.error,code:X.code};if(X.error&&typeof X.error==="object")return{message:X.error.message??X.message??Q,code:X.error.code??X.code};return{message:X.message??Q,code:X.code}}catch{return{message:Q}}}async function Z(Q,X,Y,W){let G={"Content-Type":"application/json",Authorization:`Bearer ${F5}`},J=W??EX;if(J)G["x-company-id"]=J;let $;try{$=await fetch(`${LM}${X}`,{method:Q,headers:G,body:Y?JSON.stringify(Y):void 0})}catch(z){throw new h1(z instanceof Error?z.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!$.ok){let z=await $.text(),H=FM(z);throw new h1(H.message,$.status,z,H.code)}return $.json()}u6.setRequestHandler(H9,async()=>{return{tools:D5}});u6.setRequestHandler(U6,async(Q)=>{let{name:X,arguments:Y}=Q.params;return L5(X,Y??{})});u6.setRequestHandler(X9,async()=>{return{resources:$5}});u6.setRequestHandler(W9,async(Q)=>{let{uri:X}=Q.params;return z5(X)});async function qM(){let Q=new bX;await u6.connect(Q),console.error("Sequenzy MCP server running on stdio")}qM().catch((Q)=>{console.error(V1(Q)),process.exit(1)});export{IX as setSelectedCompanyId,f1 as getSelectedCompanyId,Z as apiRequest};
177
+ - contact.subscribed, contact.unsubscribed`,inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inactivity","frequency"],description:"Trigger type: 'contact_added' (when added to a list), 'tag_added' (when tag is applied), 'segment_entered' (when a contact newly enters a saved segment), 'event_received' (when custom event fires), 'inactivity' (when subscriber hasn't performed an event for X days), 'frequency' (when subscriber performs event X times in Y days)"},listId:{type:"string",description:"List ID to trigger on (for contact_added trigger). If not provided, triggers on any list."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger)"},segmentId:{type:"string",description:"Segment ID to trigger on (required for segment_entered trigger). Use list_segments first to choose a saved segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inactivity, and frequency triggers)"},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value."},enrollmentFieldPath:{type:"string",description:"Dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},stopCondition:{type:"object",description:"Optional explicit auto-stop condition. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'does_not_have_tag', value: 'trial' } when a tag is removed, { type: 'removed_from_list', value: 'list_123' } when they leave a list, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","event_received"],description:"Stop condition type."},value:{type:["string","null"],description:"Tag name, list ID, or event name for the stop condition. Use null or omit for type 'none'."}},required:["type"]},steps:{type:"array",description:"Explicit sequence steps. Omit type for email steps, or use type: 'create_discount' for a Stripe discount action. Later email steps can reference the most recent discount with {{discount.code}}, {{discount.percentOff}}, {{discount.amountOff}}, and {{discount.expiresAt}}.",items:{type:"object",properties:{type:{type:"string",enum:["email","create_discount","discount"],description:"Step type. Omit or use 'email' for email content. Use 'create_discount' to generate a discount code before later emails."},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:"Sequenzy email blocks. Provide blocks or html for email steps. Blocks can include repeat blocks over array variables such as items.",items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Will be converted to Sequenzy blocks."},delay:{type:"object",description:"Delay before this step.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}}},name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Prefer this nested shape for new integrations; legacy top-level discount fields are still accepted.",properties:{label:{type:"string",description:"Builder label for the discount step."},provider:{type:"string",enum:["stripe"],description:"Discount provider. Currently only 'stripe'."},discountType:{type:"string",enum:["percent","amount"],description:"Discount type."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Stripe coupon duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Stripe product IDs, such as prod_abc123, when appliesToAllPlans is false.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated promotion codes."},maxRedemptions:{type:"number",description:"Maximum promotion code redemptions. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Stripe-only. Restrict each generated promotion code to the matched subscriber's Stripe customer."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."},name:{type:"string",description:"Optional provider coupon name."}}},label:{type:"string",description:"Legacy top-level discount label. Prefer discount.label."},provider:{type:"string",enum:["stripe"],description:"Legacy top-level discount provider. Prefer discount.provider."},discountType:{type:"string",enum:["percent","amount"],description:"Legacy top-level discount type. Prefer discount.discountType."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Stripe coupon duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Stripe product IDs, such as prod_abc123, when appliesToAllPlans is false.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated promotion codes."},maxRedemptions:{type:"number",description:"Maximum promotion code redemptions. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Legacy top-level Stripe-only flag. Prefer discount.lockToSubscriber."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."}}}}},required:["name","trigger"]}},{name:"update_sequence",description:"Update an existing sequence. To target a specific step, use the emailId or nodeId returned in get_sequence.sequence.emails. You can also update enrollmentMode and enrollmentFieldPath for event-triggered matching-field enrollment. When inserting an if/else branch, include steps for every branch arm and elseSteps so the branch is usable immediately. Branch conditions support tags, lists, saved segments, custom events, clicked links, and subscriber field comparisons.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},name:{type:"string",description:"Sequence name"},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Updated sequence re-entry mode. 'matching_field' is only valid for event-based sequence triggers."},enrollmentFieldPath:{type:"string",description:"Dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Omit to leave unchanged. Use clearEnrollmentFieldPath to clear it."},clearEnrollmentFieldPath:{type:"boolean",description:"Set true to clear enrollmentFieldPath without sending a nullable schema value."},stopCondition:{type:"object",description:"Update the sequence auto-stop condition. Example: { type: 'has_tag', value: 'customer' } ends the sequence when the subscriber has that tag. Use { type: 'removed_from_list', value: 'list_123' } to stop when they leave a list, or { type: 'none', value: null } to clear it.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","event_received"]},value:{type:["string","null"],description:"Tag name, list ID, or event name for the stop condition."}},required:["type"]},branch:{type:"object",description:"Insert an if/else branch into an existing sequence. The branch is inserted after afterNodeId and creates an if path plus an else fallback path. Use get_sequence first to choose afterNodeId. Each branch condition should include steps, and elseSteps is required unless allowEmptyPaths is true. Conditions support tags, lists, saved segments, events, clicked links, and field comparisons. Use activityScope for event_received and link_clicked checks.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert the branch after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails."},label:{type:"string",description:"Optional branch node label."},branches:{type:"array",description:"Conditional branches evaluated in order. An else fallback is created automatically.",items:{type:"object",properties:{id:{type:"string",description:"Optional stable branch ID. Defaults to branch-0, branch-1, etc."},label:{type:"string",description:"Display label, e.g. 'If has customer tag'."},conditionType:{type:"string",enum:["has_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than"],description:"Condition type for this branch."},tagName:{type:"string",description:"Tag name for has_tag conditions. This can be used instead of tagId."},tagId:{type:"string",description:"Tag ID or tag name for has_tag conditions."},listId:{type:"string",description:"List ID for in_list conditions."},segmentId:{type:"string",description:"Segment ID for in_segment conditions."},segmentName:{type:"string",description:"Optional display name for in_segment conditions."},eventName:{type:"string",description:"Event name for event_received conditions, such as project.invite.accepted."},linkUrl:{type:"string",description:"Optional URL substring for link_clicked conditions. Omit to match any clicked link."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"Scope for event_received and link_clicked conditions. Omit to check ever."},fieldName:{type:"string",description:"Subscriber attribute name for field conditions."},fieldValue:{type:"string",description:"Comparison value for field conditions."},steps:{type:"array",description:"Steps to create inside this branch path. Required by default so the branch is not an empty placeholder.",items:H5}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:H5},allowEmptyPaths:{type:"boolean",description:"Set true only when intentionally creating empty UI placeholders. Normal API/MCP use should omit this and provide branch steps plus elseSteps."}},required:["afterNodeId","branches"]},emails:{type:"array",description:"Updated sequence emails. If you omit emailId/nodeId, items are matched by existing step order.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Will be converted to Sequenzy blocks."},htmlContent:{type:"string",description:"Alias for html. Use this when updating HTML content for a step."},blocks:{type:"array",description:"Updated Sequenzy block JSON for the step"}}}},steps:{type:"array",description:"Alias for emails. Supports the same fields and matching rules.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Will be converted to Sequenzy blocks."},htmlContent:{type:"string",description:"Alias for html. Use this when updating HTML content for a step."},blocks:{type:"array",description:"Updated Sequenzy block JSON for the step"}}}}},required:["sequenceId"]}},{name:"enable_sequence",description:"Enable/activate a sequence. IMPORTANT: Only call this when the user EXPLICITLY asks to enable or activate a sequence. Never enable sequences automatically after creation - the user must review the content first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"disable_sequence",description:"Disable/pause a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"delete_sequence",description:"Delete a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"list_transactional_emails",description:"List transactional email templates, including their API slugs and linked email IDs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_transactional_email",description:"Get a transactional email by ID or slug, including subject, preview text, blocks, variables, and linked dashboard URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"]}},{name:"create_transactional_email",description:"Create a saved transactional email template with an API slug. Provide `prompt` to generate the email with AI, or provide either `html` or Sequenzy `blocks` for the email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Transactional email name."},slug:{type:"string",description:"Optional API slug used when sending by slug, for example `password-reset`. If omitted, Sequenzy generates one from the name."},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:"Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }. Mutually exclusive with `html`.",items:{type:"object"}},prompt:{type:"string",description:"Generate transactional email blocks from a prompt. Mutually exclusive with `html` and `blocks`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},enabled:{type:"boolean",description:"Whether this transactional email can be sent immediately. Defaults to true."}},required:["name"],additionalProperties:!1}},{name:"update_transactional_email",description:"Update a transactional email by ID or slug. At least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` is required. Use `html` or `blocks` to replace the linked email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."},name:{type:"string",description:"Transactional email name."},enabled:{type:"boolean",description:"Whether this transactional email can be sent."},subject:{type:"string",description:"Email subject line."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`."},blocks:{type:"array",description:"Sequenzy email blocks, including conditional and repeat blocks. 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: [...] }."}},required:["to"]}},{name:"get_stats",description:"Get overview statistics for a time period",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},period:{type:"string",description:"Time period: 7d, 30d, or 90d (default: 7d)"}}}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_sequence_stats",description:"Get statistics for a sequence, including per-step failed subscribers and failure reasons",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"get_subscriber_activity",description:"Get recent activity, email stats, and current sequence enrollments for a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"}},required:["email"]}},{name:"generate_email",description:"Generate email blocks from a prompt",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the email to generate"},style:{type:"string",description:"Style: minimal, branded, promotional"},tone:{type:"string",description:"Tone: professional, casual, friendly"}},required:["prompt"]}},{name:"generate_sequence",description:"[DEPRECATED - Use create_sequence instead] Generate a multi-email sequence from a goal. Note: create_sequence now handles AI generation automatically.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},goal:{type:"string",description:"Goal of the sequence (e.g., 'onboard new SaaS trial users')"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days (default: 14)"}},required:["goal"]}},{name:"generate_subject_lines",description:"Generate A/B test subject line variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},topic:{type:"string",description:"Topic or context for the subject lines"},count:{type:"number",description:"Number of variants to generate (default: 5)"}},required:["topic"]}}];async function L5(Q,X){try{let Y;switch(Q){case"get_account":{let G=await Z("GET","/api/v1/account"),J=f1();Y={...G,selectedCompanyId:J??G.currentCompanyId};break}case"select_company":{let G=X.companyId,J=await Z("GET","/api/v1/account"),$=J.companies?.find((z)=>z.id===G);if(!$)throw Error(`Company not found. Available companies: ${J.companies?.map((z)=>`${z.name} (${z.id})`).join(", ")??"none"}`);IX(G),Y={success:!0,message:`Switched to company: ${$.name}`,companyId:$.id,companyName:$.name};break}case"get_app_urls":{let G=await B5(X);Y={...K1({companyId:G,campaignId:v(X,"campaignId"),sequenceId:v(X,"sequenceId"),emailId:v(X,"emailId")??v(X,"templateId"),transactionalId:v(X,"transactionalId"),domainId:v(X,"domainId"),status:v(X,"status"),settingsTab:v(X,"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 Z("POST","/api/v1/companies",{name:X.name,domain:X.domain});if(!G.success)throw Error("Failed to create company");let J=G.company.id,$=6,z=0,H=G.company.status;while(H==="processing"&&z<$){await new Promise((U)=>setTimeout(U,20000)),z++;let K=await Z("GET",`/api/v1/companies/${J}`);if(K.success)H=K.company.status}IX(J);let A=await Z("GET",`/api/v1/companies/${J}`);Y={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=X.companyId;Y=await Z("GET",`/api/v1/companies/${G}`);break}case"create_api_key":{let G=X.companyId;Y=await Z("POST","/api/v1/api-keys",{name:X.name},G);break}case"list_websites":{let G=X.companyId;Y=await Z("GET","/api/v1/websites",void 0,G);break}case"add_website":{let G=X.companyId;Y=await Z("POST","/api/v1/websites",{domain:X.domain},G);break}case"check_website":{let G=X.companyId;Y=await Z("GET",`/api/v1/websites/${X.domain}`,void 0,G);break}case"get_integration_guide":Y=await Z("POST","/api/v1/integration-guide",X);break;case"add_subscriber":{let G=X.companyId;Y=await Z("POST","/api/v1/subscribers",{email:X.email,customAttributes:X.attributes,tags:X.tags,lists:X.listIds},G);break}case"update_subscriber":{let G=X.companyId,J=await PX(String(X.email),G),$=Array.isArray(J.subscriber.tags)?J.subscriber.tags.filter((U)=>typeof U==="string"):[],z=Array.isArray(X.addTags)?X.addTags.filter((U)=>typeof U==="string"&&U.trim()!=="").map(A5):[],H=new Set(Array.isArray(X.removeTags)?X.removeTags.filter((U)=>typeof U==="string"&&U.trim()!=="").map(A5):[]),A=$.filter((U)=>!H.has(U));for(let U of z)if(!A.includes(U))A.push(U);let K={};if(v0(X.attributes))K.customAttributes={...v0(J.subscriber.customAttributes)?J.subscriber.customAttributes:{},...X.attributes};if(X.addTags||X.removeTags)K.tags=A;Y=await Z("PATCH",`/api/v1/subscribers/${encodeURIComponent(String(X.email))}`,K,G);break}case"remove_subscriber":{let G=X.companyId;if(X.hardDelete===!0)Y=await Z("DELETE",`/api/v1/subscribers/${encodeURIComponent(String(X.email))}`,void 0,G);else Y=await Z("PATCH",`/api/v1/subscribers/${encodeURIComponent(String(X.email))}`,{status:"unsubscribed"},G);break}case"get_subscriber":{let G=X.companyId;Y=await PX(String(X.email),G);break}case"search_subscribers":{let G=X.companyId;Y=await KM(X,G);break}case"list_tags":{let G=X.companyId;Y=await Z("GET","/api/v1/tags",void 0,G);break}case"list_lists":{let G=X.companyId;Y=await Z("GET","/api/v1/lists",void 0,G);break}case"create_list":{let G=X.companyId;Y=await Z("POST","/api/v1/lists",X,G);break}case"list_segments":{let G=X.companyId;Y=await Z("GET","/api/v1/segments",void 0,G);break}case"create_segment":{GM(X);let G=X.companyId;Y=await Z("POST","/api/v1/segments",{...X,...X.filters!==void 0?{filters:K5(X.filters)}:{},...X.root!==void 0?{root:U5(X.root)}:{}},G);break}case"get_segment_count":{let G=X.companyId;Y=await Z("GET",`/api/v1/segments/${X.segmentId}/count`,void 0,G);break}case"list_templates":{let G=X.companyId;Y=await Z("GET","/api/v1/templates",void 0,G);break}case"get_template":{let G=X.companyId;Y=await Z("GET",`/api/v1/templates/${X.templateId}`,void 0,G);break}case"create_template":{let G=X.companyId;l1("create_template",X,{requireContent:!0}),Y=await Z("POST","/api/v1/templates",X,G);break}case"update_template":{let G=X.companyId,J=new Set(["companyId","templateId","name","subject","html","blocks"]),$=Object.keys(X).filter((z)=>!J.has(z));if($.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`html\`, and \`blocks\` update fields. Unsupported field${$.length===1?"":"s"}: ${$.map((z)=>`\`${z}\``).join(", ")}.`);if(l1("update_template",X),X.name===void 0&&X.subject===void 0&&X.html===void 0&&X.blocks===void 0)throw Error("Provide at least one of `name`, `subject`, `html`, or `blocks` when calling `update_template`.");Y=await Z("PUT",`/api/v1/templates/${X.templateId}`,X,G);break}case"delete_template":{let G=X.companyId;Y=await Z("DELETE",`/api/v1/templates/${X.templateId}`,void 0,G);break}case"list_campaigns":{let G=X.companyId,J=new URLSearchParams;if(X.status)J.set("status",String(X.status));Y=await Z("GET",`/api/v1/campaigns?${J}`,void 0,G);break}case"get_campaign":{let G=X.companyId;Y=await Z("GET",`/api/v1/campaigns/${X.campaignId}`,void 0,G);break}case"create_campaign":{let G=X.companyId;$M(X);let J=v(X,"prompt");if(J!==void 0){let $=await Z("POST","/api/v1/generate/email",{prompt:J,...X.style!==void 0&&{style:X.style},...X.tone!==void 0&&{tone:X.tone}},G),z=v(X,"subject")??(typeof $.subject==="string"&&$.subject.trim()!==""?$.subject.trim():void 0);if(!z)throw Error("`create_campaign` prompt generation did not return a subject. Provide `subject` explicitly.");let H=Array.isArray($.blocks)&&$.blocks.length>0?$.blocks:void 0,A=typeof $.html==="string"&&$.html.trim()!==""?$.html:void 0;if(H===void 0&&A===void 0)throw Error("`create_campaign` prompt generation did not return email blocks. Try again or provide `html` or `blocks` explicitly.");Y=await Z("POST","/api/v1/campaigns",{name:X.name,subject:z,...H!==void 0?{blocks:H}:{html:A},...X.segmentId!==void 0&&{segmentId:X.segmentId}},G);break}Y=await Z("POST","/api/v1/campaigns",X,G);break}case"update_campaign":{let G=X.companyId,J=new Set(["companyId","campaignId","name","subject","html","blocks","replyTo","replyProfileId"]),$=Object.keys(X).filter((z)=>!J.has(z));if($.length>0)throw Error(`\`update_campaign\` accepts only \`name\`, \`subject\`, \`html\`, \`blocks\`, \`replyTo\`, and \`replyProfileId\` update fields. Unsupported field${$.length===1?"":"s"}: ${$.map((z)=>`\`${z}\``).join(", ")}.`);if(l1("update_campaign",X),X.replyTo!==void 0&&X.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_campaign`, not both.");if(X.name===void 0&&X.subject===void 0&&X.html===void 0&&X.blocks===void 0&&X.replyTo===void 0&&X.replyProfileId===void 0)throw Error("Provide at least one of `name`, `subject`, `html`, `blocks`, `replyTo`, or `replyProfileId` when calling `update_campaign`.");Y=await Z("PUT",`/api/v1/campaigns/${X.campaignId}`,X,G);break}case"send_test_email":{let G=X.companyId;Y=await Z("POST",`/api/v1/campaigns/${X.campaignId}/test`,{to:X.to},G);break}case"list_sequences":{let G=X.companyId;Y=await Z("GET","/api/v1/sequences",void 0,G);break}case"get_sequence":{let G=X.companyId;Y=await Z("GET",`/api/v1/sequences/${X.sequenceId}`,void 0,G);break}case"create_sequence":{let G=X.companyId,J=Array.isArray(X.steps)&&X.steps.length>0,$=await Z("POST","/api/v1/sequences",X,G);if(!$.success){Y=$;break}let z=$.sequence.id;if(J){let B=await Z("GET",`/api/v1/sequences/${z}`,void 0,G);if(B.success)Y={success:!0,sequence:B.sequence,message:`Sequence "${B.sequence.name}" created with explicit steps. Review it before enabling.`};else Y=B;break}let H=6,A=0,K="pending";while(K!=="complete"&&A<H){await new Promise((L)=>setTimeout(L,20000)),A++;let B=await Z("GET",`/api/v1/sequences/${z}`,void 0,G);if(B.success)K=B.sequence.enrichmentStatus}let U=await Z("GET",`/api/v1/sequences/${z}`,void 0,G);if(U.success)Y={success:!0,sequence:U.sequence,message:U.sequence.enrichmentStatus==="complete"?`Sequence "${U.sequence.name}" created with ${U.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.`:`Sequence "${U.sequence.name}" created. Email enrichment is still in progress (${U.sequence.enrichedCount}/${U.sequence.emailCount} emails generated). You can check status with get_sequence.`};else Y=U;break}case"update_sequence":{let G=X.companyId,J=JM(X);Y=await Z("PUT",`/api/v1/sequences/${X.sequenceId}`,J,G);break}case"enable_sequence":{let G=X.companyId;Y=await Z("POST",`/api/v1/sequences/${X.sequenceId}/enable`,void 0,G);break}case"disable_sequence":{let G=X.companyId;Y=await Z("POST",`/api/v1/sequences/${X.sequenceId}/disable`,void 0,G);break}case"delete_sequence":{let G=X.companyId;Y=await Z("DELETE",`/api/v1/sequences/${X.sequenceId}`,void 0,G);break}case"list_transactional_emails":{let G=X.companyId;Y=await Z("GET","/api/v1/transactional",void 0,G);break}case"get_transactional_email":{let G=X.companyId;Y=await Z("GET",`/api/v1/transactional/${X.idOrSlug}`,void 0,G);break}case"create_transactional_email":{let G=X.companyId,J=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),$=Object.keys(X).filter((A)=>!J.has(A));if($.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${$.length===1?"":"s"}: ${$.map((A)=>`\`${A}\``).join(", ")}.`);zM(X);let z=v(X,"prompt");if(z!==void 0){let A={companyId:G??f1()??"",name:typeof X.name==="string"&&X.name.trim()!==""?X.name.trim():"",slug:typeof X.slug==="string"&&X.slug.trim()!==""?X.slug.trim():"",promptLength:z.length,style:typeof X.style==="string"?X.style:"",tone:typeof X.tone==="string"?X.tone:""};try{console.error("[mcp:create_transactional_email] generating from prompt",A);let K=await Z("POST","/api/v1/generate/email",{prompt:z,...X.style!==void 0&&{style:X.style},...X.tone!==void 0&&{tone:X.tone}},G);console.error("[mcp:create_transactional_email] prompt generation complete",{...A,subject:K.subject??"",previewTextLength:typeof K.previewText==="string"?K.previewText.length:0,blockCount:Array.isArray(K.blocks)?K.blocks.length:0,htmlLength:typeof K.html==="string"?K.html.length:0});let U=v(X,"subject")??(typeof K.subject==="string"&&K.subject.trim()!==""?K.subject.trim():void 0);if(!U)throw Error("`create_transactional_email` prompt generation did not return a subject. Provide `subject` explicitly.");let B=Array.isArray(K.blocks)&&K.blocks.length>0?K.blocks:void 0,L=typeof K.html==="string"&&K.html.trim()!==""?K.html:void 0,q=v(X,"previewText")??(typeof K.previewText==="string"?K.previewText.trim():void 0);if(B===void 0&&L===void 0)throw Error("`create_transactional_email` prompt generation did not return email blocks. Try again or provide `html` or `blocks` explicitly.");console.error("[mcp:create_transactional_email] creating generated transactional",{...A,subject:U,contentSource:B!==void 0?"blocks":"html",blockCount:B?.length??0,htmlLength:L?.length??0}),Y=await Z("POST","/api/v1/transactional",{name:X.name,...X.slug!==void 0&&{slug:X.slug},subject:U,...q!==void 0&&{previewText:q},...B!==void 0?{blocks:B}:{html:L},...X.enabled!==void 0&&{enabled:X.enabled}},G),console.error("[mcp:create_transactional_email] generated transactional created",A)}catch(K){throw console.error("[mcp:create_transactional_email] prompt-based create failed",{...A,error:K instanceof Error?K.message:String(K)}),K}break}let H=Object.fromEntries(Object.entries(X).filter(([A])=>A!=="companyId"));Y=await Z("POST","/api/v1/transactional",H,G);break}case"update_transactional_email":{let G=X.companyId,J=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),$=Object.keys(X).filter((H)=>!J.has(H));if($.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${$.length===1?"":"s"}: ${$.map((H)=>`\`${H}\``).join(", ")}.`);if(l1("update_transactional_email",X),X.name===void 0&&X.enabled===void 0&&X.subject===void 0&&X.previewText===void 0&&X.html===void 0&&X.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let z=Object.fromEntries(Object.entries(X).filter(([H])=>H!=="companyId"&&H!=="idOrSlug"));Y=await Z("PATCH",`/api/v1/transactional/${X.idOrSlug}`,z,G);break}case"send_email":{let G=X.companyId;Y=await Z("POST","/api/v1/transactional/send",X,G);break}case"get_stats":{let G=X.companyId,J=X.period??"7d";Y=await Z("GET",`/api/v1/metrics?period=${J}`,void 0,G);break}case"get_campaign_stats":{let G=X.companyId;Y=await Z("GET",`/api/v1/metrics/campaigns/${X.campaignId}`,void 0,G);break}case"get_sequence_stats":{let G=X.companyId;Y=await Z("GET",`/api/v1/metrics/sequences/${X.sequenceId}`,void 0,G);break}case"get_subscriber_activity":{let G=X.companyId,J=await PX(String(X.email),G);Y={success:J.success,email:J.subscriber.email,emailStats:J.subscriber.emailStats??null,activity:J.subscriber.activity??[],sequenceEnrollments:J.subscriber.sequenceEnrollments??[]};break}case"generate_email":{let G=X.companyId;Y=await Z("POST","/api/v1/generate/email",X,G);break}case"generate_sequence":{let G=X.companyId;Y=await Z("POST","/api/v1/generate/sequence",X,G);break}case"generate_subject_lines":{let G=X.companyId;Y=await Z("POST","/api/v1/generate/subjects",X,G);break}default:throw Error(`Unknown tool: ${Q}`)}let W=HM(Y);if(W)throw W;return Y=await DM(Q,X,Y),{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}catch(Y){return{isError:!0,content:[{type:"text",text:V1(Y)}]}}}var LM=process.env.SEQUENZY_API_URL??"https://api.sequenzy.com",F5=process.env.SEQUENZY_API_KEY,EX=null;if(!F5)console.error(V1(new h1("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1);function f1(){return EX}function IX(Q){EX=Q}var u6=new NX({name:"sequenzy",version:W5.version},{capabilities:{tools:{},resources:{}}});function FM(Q){if(!Q.trim())return{message:"Request failed"};try{let X=JSON.parse(Q);if(typeof X==="string")return{message:X};if(typeof X.error==="string")return{message:X.error,code:X.code};if(X.error&&typeof X.error==="object")return{message:X.error.message??X.message??Q,code:X.error.code??X.code};return{message:X.message??Q,code:X.code}}catch{return{message:Q}}}async function Z(Q,X,Y,W){let G={"Content-Type":"application/json",Authorization:`Bearer ${F5}`},J=W??EX;if(J)G["x-company-id"]=J;let $;try{$=await fetch(`${LM}${X}`,{method:Q,headers:G,body:Y?JSON.stringify(Y):void 0})}catch(z){throw new h1(z instanceof Error?z.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!$.ok){let z=await $.text(),H=FM(z);throw new h1(H.message,$.status,z,H.code)}return $.json()}u6.setRequestHandler(H9,async()=>{return{tools:D5}});u6.setRequestHandler(U6,async(Q)=>{let{name:X,arguments:Y}=Q.params;return L5(X,Y??{})});u6.setRequestHandler(X9,async()=>{return{resources:$5}});u6.setRequestHandler(W9,async(Q)=>{let{uri:X}=Q.params;return z5(X)});async function qM(){let Q=new bX;await u6.connect(Q),console.error("Sequenzy MCP server running on stdio")}qM().catch((Q)=>{console.error(V1(Q)),process.exit(1)});export{IX as setSelectedCompanyId,f1 as getSelectedCompanyId,Z as apiRequest};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sequenzy/mcp",
3
- "version": "0.0.27",
3
+ "version": "0.0.29",
4
4
  "mcpName": "io.github.polnikale/sequenzy-mcp",
5
5
  "description": "Sequenzy MCP server for AI-powered email marketing automation",
6
6
  "type": "module",
package/server.json CHANGED
@@ -7,12 +7,12 @@
7
7
  "source": "github",
8
8
  "subfolder": "packages/mcp"
9
9
  },
10
- "version": "0.0.27",
10
+ "version": "0.0.29",
11
11
  "packages": [
12
12
  {
13
13
  "registryType": "npm",
14
14
  "identifier": "@sequenzy/mcp",
15
- "version": "0.0.27",
15
+ "version": "0.0.29",
16
16
  "runtime": "node",
17
17
  "transport": {
18
18
  "type": "stdio"