@sequenzy/mcp 0.0.81 → 0.0.82
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +3 -3
- package/dist/server.js +3 -3
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/server.js
CHANGED
|
@@ -25,7 +25,7 @@ var JH=Object.create;var{getPrototypeOf:HH,defineProperty:EQ,getOwnPropertyNames
|
|
|
25
25
|
newResult[${S}] = ${y}.value;
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
-
`)}L.write("payload.value = newResult;"),L.write("return payload;");let R=L.compile();return(T,y)=>R(K,T,y)},$,z=j1,J=!Q6.jitless,U=J&&kQ.value,A=Y.catchall,B;Q._zod.parse=(K,L)=>{B??(B=W.value);let O=K.value;if(!z(O))return K.issues.push({expected:"object",code:"invalid_type",input:O,inst:Q}),K;if(J&&U&&L?.async===!1&&L.jitless!==!0){if(!$)$=G(Y.shape);if(K=$(K,L),!A)return K;return UW([],O,K,L,B,Q)}return X(K,L)}});function bX(Q,Y,X,W){for(let $ of Q)if($.issues.length===0)return Y.value=$.value,Y;let G=Q.filter(($)=>!J1($));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map(($)=>$.issues.map((z)=>x0(z,W,T0())))}),Y}var pQ=q("$ZodUnion",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),n(Q._zod,"optout",()=>Y.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),n(Q._zod,"values",()=>{if(Y.options.every((G)=>G._zod.values))return new Set(Y.options.flatMap((G)=>Array.from(G._zod.values)));return}),n(Q._zod,"pattern",()=>{if(Y.options.every((G)=>G._zod.pattern)){let G=Y.options.map(($)=>$._zod.pattern);return new RegExp(`^(${G.map(($)=>J4($.source)).join("|")})$`)}return});let X=Y.options.length===1,W=Y.options[0]._zod.run;Q._zod.parse=(G,$)=>{if(X)return W(G,$);let z=!1,J=[];for(let H of Y.options){let U=H._zod.run({value:G.value,issues:[]},$);if(U instanceof Promise)J.push(U),z=!0;else{if(U.issues.length===0)return U;J.push(U)}}if(!z)return bX(J,G,Q,$);return Promise.all(J).then((H)=>{return bX(H,G,Q,$)})}}),BW=q("$ZodDiscriminatedUnion",(Q,Y)=>{pQ.init(Q,Y);let X=Q._zod.parse;n(Q._zod,"propValues",()=>{let G={};for(let $ of Y.options){let z=$._zod.propValues;if(!z||Object.keys(z).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf($)}"`);for(let[J,H]of Object.entries(z)){if(!G[J])G[J]=new Set;for(let U of H)G[J].add(U)}}return G});let W=g1(()=>{let G=Y.options,$=new Map;for(let z of G){let J=z._zod.propValues?.[Y.discriminator];if(!J||J.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(z)}"`);for(let H of J){if($.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);$.set(H,z)}}return $});Q._zod.parse=(G,$)=>{let z=G.value;if(!j1(z))return G.issues.push({code:"invalid_type",expected:"object",input:z,inst:Q}),G;let J=W.value.get(z?.[Y.discriminator]);if(J)return J._zod.run(G,$);if(Y.unionFallback)return X(G,$);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,input:z,path:[Y.discriminator],inst:Q}),G}}),KW=q("$ZodIntersection",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value,$=Y.left._zod.run({value:G,issues:[]},W),z=Y.right._zod.run({value:G,issues:[]},W);if($ instanceof Promise||z instanceof Promise)return Promise.all([$,z]).then(([H,U])=>{return IX(X,H,U)});return IX(X,$,z)}});function mQ(Q,Y){if(Q===Y)return{valid:!0,data:Q};if(Q instanceof Date&&Y instanceof Date&&+Q===+Y)return{valid:!0,data:Q};if(z1(Q)&&z1(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter(($)=>X.indexOf($)!==-1),G={...Q,...Y};for(let $ of W){let z=mQ(Q[$],Y[$]);if(!z.valid)return{valid:!1,mergeErrorPath:[$,...z.mergeErrorPath]};G[$]=z.data}return{valid:!0,data:G}}if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let W=0;W<Q.length;W++){let G=Q[W],$=Y[W],z=mQ(G,$);if(!z.valid)return{valid:!1,mergeErrorPath:[W,...z.mergeErrorPath]};X.push(z.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function IX(Q,Y,X){if(Y.issues.length)Q.issues.push(...Y.issues);if(X.issues.length)Q.issues.push(...X.issues);if(J1(Q))return Q;let W=mQ(Y.value,X.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return Q.value=W.data,Q}var DW=q("$ZodRecord",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!z1(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let $=[];if(Y.keyType._zod.values){let z=Y.keyType._zod.values;X.value={};for(let H of z)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let U=Y.valueType._zod.run({value:G[H],issues:[]},W);if(U instanceof Promise)$.push(U.then((A)=>{if(A.issues.length)X.issues.push(...a0(H,A.issues));X.value[H]=A.value}));else{if(U.issues.length)X.issues.push(...a0(H,U.issues));X.value[H]=U.value}}let J;for(let H in G)if(!z.has(H))J=J??[],J.push(H);if(J&&J.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:J})}else{X.value={};for(let z of Reflect.ownKeys(G)){if(z==="__proto__")continue;let J=Y.keyType._zod.run({value:z,issues:[]},W);if(J instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(J.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:J.issues.map((U)=>x0(U,W,T0())),input:z,path:[z],inst:Q}),X.value[J.value]=J.value;continue}let H=Y.valueType._zod.run({value:G[z],issues:[]},W);if(H instanceof Promise)$.push(H.then((U)=>{if(U.issues.length)X.issues.push(...a0(z,U.issues));X.value[J.value]=U.value}));else{if(H.issues.length)X.issues.push(...a0(z,H.issues));X.value[J.value]=H.value}}}if($.length)return Promise.all($).then(()=>X);return X}});var LW=q("$ZodEnum",(Q,Y)=>{o.init(Q,Y);let X=RQ(Y.entries),W=new Set(X);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${X.filter((G)=>vQ.has(typeof G)).map((G)=>typeof G==="string"?t0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,$)=>{let z=G.value;if(W.has(z))return G;return G.issues.push({code:"invalid_value",values:X,input:z,inst:Q}),G}}),FW=q("$ZodLiteral",(Q,Y)=>{if(o.init(Q,Y),Y.values.length===0)throw Error("Cannot create literal schema with no valid values");Q._zod.values=new Set(Y.values),Q._zod.pattern=new RegExp(`^(${Y.values.map((X)=>typeof X==="string"?t0(X):X?t0(X.toString()):String(X)).join("|")})$`),Q._zod.parse=(X,W)=>{let G=X.value;if(Q._zod.values.has(G))return X;return X.issues.push({code:"invalid_value",values:Y.values,input:G,inst:Q}),X}});var qW=q("$ZodTransform",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new G4(Q.constructor.name);let G=Y.transform(X.value,X);if(W.async)return(G instanceof Promise?G:Promise.resolve(G)).then((z)=>{return X.value=z,X});if(G instanceof Promise)throw new o0;return X.value=G,X}});function EX(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var OW=q("$ZodOptional",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",n(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),n(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${J4(X.source)})?$`):void 0}),Q._zod.parse=(X,W)=>{if(Y.innerType._zod.optin==="optional"){let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>EX($,X.value));return EX(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),MW=q("$ZodNullable",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),n(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${J4(X.source)}|null)$`):void 0}),n(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,null]):void 0}),Q._zod.parse=(X,W)=>{if(X.value===null)return X;return Y.innerType._zod.run(X,W)}}),VW=q("$ZodDefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)return X.value=Y.defaultValue,X;let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>TX($,Y));return TX(G,Y)}});function TX(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var NW=q("$ZodPrefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)X.value=Y.defaultValue;return Y.innerType._zod.run(X,W)}}),ZW=q("$ZodNonOptional",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"values",()=>{let X=Y.innerType._zod.values;return X?new Set([...X].filter((W)=>W!==void 0)):void 0}),Q._zod.parse=(X,W)=>{let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>SX($,Q));return SX(G,Q)}});function SX(Q,Y){if(!Q.issues.length&&Q.value===void 0)Q.issues.push({code:"invalid_type",expected:"nonoptional",input:Q.value,inst:Y});return Q}var wW=q("$ZodCatch",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>{if(X.value=$.value,$.issues.length)X.value=Y.catchValue({...X,error:{issues:$.issues.map((z)=>x0(z,W,T0()))},input:X.value}),X.issues=[];return X});if(X.value=G.value,G.issues.length)X.value=Y.catchValue({...X,error:{issues:G.issues.map(($)=>x0($,W,T0()))},input:X.value}),X.issues=[];return X}});var jW=q("$ZodPipe",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"values",()=>Y.in._zod.values),n(Q._zod,"optin",()=>Y.in._zod.optin),n(Q._zod,"optout",()=>Y.out._zod.optout),n(Q._zod,"propValues",()=>Y.in._zod.propValues),Q._zod.parse=(X,W)=>{if(W.direction==="backward"){let $=Y.out._zod.run(X,W);if($ instanceof Promise)return $.then((z)=>A6(z,Y.in,W));return A6($,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>A6($,Y.out,W));return A6(G,Y.out,W)}});function A6(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var PW=q("$ZodReadonly",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"propValues",()=>Y.innerType._zod.propValues),n(Q._zod,"values",()=>Y.innerType._zod.values),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(RX);return RX(G)}});function RX(Q){return Q.value=Object.freeze(Q.value),Q}var bW=q("$ZodCustom",(Q,Y)=>{H0.init(Q,Y),o.init(Q,Y),Q._zod.parse=(X,W)=>{return X},Q._zod.check=(X)=>{let W=X.value,G=Y.fn(W);if(G instanceof Promise)return G.then(($)=>CX($,X,W,Q));CX(G,X,W,Q);return}});function CX(Q,Y,X,W){if(!Q){let G={code:"custom",input:X,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)G.params=W._zod.def.params;Y.issues.push(y1(G))}}var Q3=(Q)=>{let Y=typeof Q;switch(Y){case"number":return Number.isNaN(Q)?"NaN":"number";case"object":{if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Object.getPrototypeOf(Q)!==Object.prototype&&Q.constructor)return Q.constructor.name}}return Y},Y3=()=>{let Q={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function Y(W){return Q[W]??null}let X={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${Q3(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${G6(W.values[0])}`;return`Invalid option: expected one of ${Y6(W.values,"|")}`;case"too_big":{let G=W.inclusive?"<=":"<",$=Y(W.origin);if($)return`Too big: expected ${W.origin??"value"} to have ${G}${W.maximum.toString()} ${$.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${G}${W.maximum.toString()}`}case"too_small":{let G=W.inclusive?">=":">",$=Y(W.origin);if($)return`Too small: expected ${W.origin} to have ${G}${W.minimum.toString()} ${$.unit}`;return`Too small: expected ${W.origin} to be ${G}${W.minimum.toString()}`}case"invalid_format":{let G=W;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${X[G.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${Y6(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:Y3()}}var ZN=Symbol("ZodOutput"),wN=Symbol("ZodInput");class IW{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Q,...Y){let X=Y[0];if(this._map.set(Q,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.id,Q)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Q){let Y=this._map.get(Q);if(Y&&typeof Y==="object"&&"id"in Y)this._idmap.delete(Y.id);return this._map.delete(Q),this}get(Q){let Y=Q._zod.parent;if(Y){let X={...this.get(Y)??{}};delete X.id;let W={...X,...this._map.get(Q)};return Object.keys(W).length?W:void 0}return this._map.get(Q)}has(Q){return this._map.has(Q)}}function X3(){return new IW}var D4=X3();function EW(Q,Y){return new Q({type:"string",...E(Y)})}function TW(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...E(Y)})}function nQ(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...E(Y)})}function SW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...E(Y)})}function RW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...E(Y)})}function CW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...E(Y)})}function kW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...E(Y)})}function vW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...E(Y)})}function xW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...E(Y)})}function _W(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...E(Y)})}function gW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...E(Y)})}function yW(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...E(Y)})}function uW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...E(Y)})}function hW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...E(Y)})}function fW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...E(Y)})}function lW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...E(Y)})}function mW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...E(Y)})}function cW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...E(Y)})}function pW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...E(Y)})}function iW(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...E(Y)})}function nW(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...E(Y)})}function rW(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...E(Y)})}function dW(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...E(Y)})}function oW(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...E(Y)})}function tW(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...E(Y)})}function aW(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...E(Y)})}function sW(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...E(Y)})}function eW(Q,Y){return new Q({type:"number",checks:[],...E(Y)})}function QG(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...E(Y)})}function YG(Q,Y){return new Q({type:"boolean",...E(Y)})}function XG(Q,Y){return new Q({type:"null",...E(Y)})}function WG(Q){return new Q({type:"unknown"})}function GG(Q,Y){return new Q({type:"never",...E(Y)})}function D6(Q,Y){return new hQ({check:"less_than",...E(Y),value:Q,inclusive:!1})}function L4(Q,Y){return new hQ({check:"less_than",...E(Y),value:Q,inclusive:!0})}function L6(Q,Y){return new fQ({check:"greater_than",...E(Y),value:Q,inclusive:!1})}function F4(Q,Y){return new fQ({check:"greater_than",...E(Y),value:Q,inclusive:!0})}function F6(Q,Y){return new AX({check:"multiple_of",...E(Y),value:Q})}function q6(Q,Y){return new KX({check:"max_length",...E(Y),maximum:Q})}function u1(Q,Y){return new DX({check:"min_length",...E(Y),minimum:Q})}function O6(Q,Y){return new LX({check:"length_equals",...E(Y),length:Q})}function rQ(Q,Y){return new FX({check:"string_format",format:"regex",...E(Y),pattern:Q})}function dQ(Q){return new qX({check:"string_format",format:"lowercase",...E(Q)})}function oQ(Q){return new OX({check:"string_format",format:"uppercase",...E(Q)})}function tQ(Q,Y){return new MX({check:"string_format",format:"includes",...E(Y),includes:Q})}function aQ(Q,Y){return new VX({check:"string_format",format:"starts_with",...E(Y),prefix:Q})}function sQ(Q,Y){return new NX({check:"string_format",format:"ends_with",...E(Y),suffix:Q})}function P1(Q){return new ZX({check:"overwrite",tx:Q})}function eQ(Q){return P1((Y)=>Y.normalize(Q))}function Q9(){return P1((Q)=>Q.trim())}function Y9(){return P1((Q)=>Q.toLowerCase())}function X9(){return P1((Q)=>Q.toUpperCase())}function $G(Q,Y,X){return new Q({type:"array",element:Y,...E(X)})}function zG(Q,Y,X){let W=E(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function JG(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...E(X)})}function HG(Q){let Y=W3((X)=>{return X.addIssue=(W)=>{if(typeof W==="string")X.issues.push(y1(W,X.value,Y._zod.def));else{let G=W;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=X.value),G.inst??(G.inst=Y),G.continue??(G.continue=!Y._zod.def.abort),X.issues.push(y1(G))}},Q(X.value,X)});return Y}function W3(Q,Y){let X=new H0({check:"custom",...E(Y)});return X._zod.check=Q,X}function h1(Q){return!!Q._zod}function H1(Q,Y){if(h1(Q))return A4(Q,Y);return Q.safeParse(Y)}function M6(Q){if(!Q)return;let Y;if(h1(Q))Y=Q._zod?.def?.shape;else Y=Q.shape;if(!Y)return;if(typeof Y==="function")try{return Y()}catch{return}return Y}function UG(Q){if(h1(Q)){let $=Q._zod?.def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}}let X=Q._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let W=Q.value;if(W!==void 0)return W;return}var O4={};U8(O4,{time:()=>$9,duration:()=>z9,datetime:()=>W9,date:()=>G9,ZodISOTime:()=>KG,ZodISODuration:()=>DG,ZodISODateTime:()=>AG,ZodISODate:()=>BG});var AG=q("ZodISODateTime",(Q,Y)=>{cX.init(Q,Y),s.init(Q,Y)});function W9(Q){return oW(AG,Q)}var BG=q("ZodISODate",(Q,Y)=>{pX.init(Q,Y),s.init(Q,Y)});function G9(Q){return tW(BG,Q)}var KG=q("ZodISOTime",(Q,Y)=>{iX.init(Q,Y),s.init(Q,Y)});function $9(Q){return aW(KG,Q)}var DG=q("ZodISODuration",(Q,Y)=>{nX.init(Q,Y),s.init(Q,Y)});function z9(Q){return sW(DG,Q)}var LG=(Q,Y)=>{$6.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>b8(Q,X)},flatten:{value:(X)=>P8(Q,X)},addIssue:{value:(X)=>{Q.issues.push(X),Q.message=JSON.stringify(Q.issues,_1,2)}},addIssues:{value:(X)=>{Q.issues.push(...X),Q.message=JSON.stringify(Q.issues,_1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},JZ=q("ZodError",LG),b0=q("ZodError",LG,{Parent:Error});var FG=z6(b0),qG=J6(b0),OG=U4(b0),MG=B4(b0),VG=I8(b0),NG=E8(b0),ZG=T8(b0),wG=S8(b0),jG=R8(b0),PG=C8(b0),bG=k8(b0),IG=v8(b0);var X0=q("ZodType",(Q,Y)=>{return o.init(Q,Y),Q.def=Y,Q.type=Y.type,Object.defineProperty(Q,"_def",{value:Y}),Q.check=(...X)=>{return Q.clone(m.mergeDefs(Y,{checks:[...Y.checks??[],...X.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},Q.clone=(X,W)=>v0(Q,X,W),Q.brand=()=>Q,Q.register=(X,W)=>{return X.add(Q,W),Q},Q.parse=(X,W)=>FG(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>OG(Q,X,W),Q.parseAsync=async(X,W)=>qG(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>MG(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>VG(Q,X,W),Q.decode=(X,W)=>NG(Q,X,W),Q.encodeAsync=async(X,W)=>ZG(Q,X,W),Q.decodeAsync=async(X,W)=>wG(Q,X,W),Q.safeEncode=(X,W)=>jG(Q,X,W),Q.safeDecode=(X,W)=>PG(Q,X,W),Q.safeEncodeAsync=async(X,W)=>bG(Q,X,W),Q.safeDecodeAsync=async(X,W)=>IG(Q,X,W),Q.refine=(X,W)=>Q.check(e3(X,W)),Q.superRefine=(X)=>Q.check(QU(X)),Q.overwrite=(X)=>Q.check(P1(X)),Q.optional=()=>Y0(Q),Q.nullable=()=>SG(Q),Q.nullish=()=>Y0(SG(Q)),Q.nonoptional=(X)=>r3(Q,X),Q.array=()=>u(Q),Q.or=(X)=>d([Q,X]),Q.and=(X)=>N6(Q,X),Q.transform=(X)=>H9(Q,xG(X)),Q.default=(X)=>p3(Q,X),Q.prefault=(X)=>n3(Q,X),Q.catch=(X)=>o3(Q,X),Q.pipe=(X)=>H9(Q,X),Q.readonly=()=>s3(Q),Q.describe=(X)=>{let W=Q.clone();return D4.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return D4.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return D4.get(Q);let W=Q.clone();return D4.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),RG=q("_ZodString",(Q,Y)=>{K6.init(Q,Y),X0.init(Q,Y);let X=Q._zod.bag;Q.format=X.format??null,Q.minLength=X.minimum??null,Q.maxLength=X.maximum??null,Q.regex=(...W)=>Q.check(rQ(...W)),Q.includes=(...W)=>Q.check(tQ(...W)),Q.startsWith=(...W)=>Q.check(aQ(...W)),Q.endsWith=(...W)=>Q.check(sQ(...W)),Q.min=(...W)=>Q.check(u1(...W)),Q.max=(...W)=>Q.check(q6(...W)),Q.length=(...W)=>Q.check(O6(...W)),Q.nonempty=(...W)=>Q.check(u1(1,...W)),Q.lowercase=(W)=>Q.check(dQ(W)),Q.uppercase=(W)=>Q.check(oQ(W)),Q.trim=()=>Q.check(Q9()),Q.normalize=(...W)=>Q.check(eQ(...W)),Q.toLowerCase=()=>Q.check(Y9()),Q.toUpperCase=()=>Q.check(X9())}),K3=q("ZodString",(Q,Y)=>{K6.init(Q,Y),RG.init(Q,Y),Q.email=(X)=>Q.check(TW(D3,X)),Q.url=(X)=>Q.check(vW(L3,X)),Q.jwt=(X)=>Q.check(dW(S3,X)),Q.emoji=(X)=>Q.check(xW(F3,X)),Q.guid=(X)=>Q.check(nQ(EG,X)),Q.uuid=(X)=>Q.check(SW(V6,X)),Q.uuidv4=(X)=>Q.check(RW(V6,X)),Q.uuidv6=(X)=>Q.check(CW(V6,X)),Q.uuidv7=(X)=>Q.check(kW(V6,X)),Q.nanoid=(X)=>Q.check(_W(q3,X)),Q.guid=(X)=>Q.check(nQ(EG,X)),Q.cuid=(X)=>Q.check(gW(O3,X)),Q.cuid2=(X)=>Q.check(yW(M3,X)),Q.ulid=(X)=>Q.check(uW(V3,X)),Q.base64=(X)=>Q.check(iW(I3,X)),Q.base64url=(X)=>Q.check(nW(E3,X)),Q.xid=(X)=>Q.check(hW(N3,X)),Q.ksuid=(X)=>Q.check(fW(Z3,X)),Q.ipv4=(X)=>Q.check(lW(w3,X)),Q.ipv6=(X)=>Q.check(mW(j3,X)),Q.cidrv4=(X)=>Q.check(cW(P3,X)),Q.cidrv6=(X)=>Q.check(pW(b3,X)),Q.e164=(X)=>Q.check(rW(T3,X)),Q.datetime=(X)=>Q.check(W9(X)),Q.date=(X)=>Q.check(G9(X)),Q.time=(X)=>Q.check($9(X)),Q.duration=(X)=>Q.check(z9(X))});function F(Q){return EW(K3,Q)}var s=q("ZodStringFormat",(Q,Y)=>{t.init(Q,Y),RG.init(Q,Y)}),D3=q("ZodEmail",(Q,Y)=>{xX.init(Q,Y),s.init(Q,Y)});var EG=q("ZodGUID",(Q,Y)=>{kX.init(Q,Y),s.init(Q,Y)});var V6=q("ZodUUID",(Q,Y)=>{vX.init(Q,Y),s.init(Q,Y)});var L3=q("ZodURL",(Q,Y)=>{_X.init(Q,Y),s.init(Q,Y)});var F3=q("ZodEmoji",(Q,Y)=>{gX.init(Q,Y),s.init(Q,Y)});var q3=q("ZodNanoID",(Q,Y)=>{yX.init(Q,Y),s.init(Q,Y)});var O3=q("ZodCUID",(Q,Y)=>{uX.init(Q,Y),s.init(Q,Y)});var M3=q("ZodCUID2",(Q,Y)=>{hX.init(Q,Y),s.init(Q,Y)});var V3=q("ZodULID",(Q,Y)=>{fX.init(Q,Y),s.init(Q,Y)});var N3=q("ZodXID",(Q,Y)=>{lX.init(Q,Y),s.init(Q,Y)});var Z3=q("ZodKSUID",(Q,Y)=>{mX.init(Q,Y),s.init(Q,Y)});var w3=q("ZodIPv4",(Q,Y)=>{rX.init(Q,Y),s.init(Q,Y)});var j3=q("ZodIPv6",(Q,Y)=>{dX.init(Q,Y),s.init(Q,Y)});var P3=q("ZodCIDRv4",(Q,Y)=>{oX.init(Q,Y),s.init(Q,Y)});var b3=q("ZodCIDRv6",(Q,Y)=>{tX.init(Q,Y),s.init(Q,Y)});var I3=q("ZodBase64",(Q,Y)=>{sX.init(Q,Y),s.init(Q,Y)});var E3=q("ZodBase64URL",(Q,Y)=>{eX.init(Q,Y),s.init(Q,Y)});var T3=q("ZodE164",(Q,Y)=>{QW.init(Q,Y),s.init(Q,Y)});var S3=q("ZodJWT",(Q,Y)=>{YW.init(Q,Y),s.init(Q,Y)});var CG=q("ZodNumber",(Q,Y)=>{cQ.init(Q,Y),X0.init(Q,Y),Q.gt=(W,G)=>Q.check(L6(W,G)),Q.gte=(W,G)=>Q.check(F4(W,G)),Q.min=(W,G)=>Q.check(F4(W,G)),Q.lt=(W,G)=>Q.check(D6(W,G)),Q.lte=(W,G)=>Q.check(L4(W,G)),Q.max=(W,G)=>Q.check(L4(W,G)),Q.int=(W)=>Q.check(TG(W)),Q.safe=(W)=>Q.check(TG(W)),Q.positive=(W)=>Q.check(L6(0,W)),Q.nonnegative=(W)=>Q.check(F4(0,W)),Q.negative=(W)=>Q.check(D6(0,W)),Q.nonpositive=(W)=>Q.check(L4(0,W)),Q.multipleOf=(W,G)=>Q.check(F6(W,G)),Q.step=(W,G)=>Q.check(F6(W,G)),Q.finite=()=>Q;let X=Q._zod.bag;Q.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Q.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Q.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Q.isFinite=!0,Q.format=X.format??null});function i(Q){return eW(CG,Q)}var R3=q("ZodNumberFormat",(Q,Y)=>{XW.init(Q,Y),CG.init(Q,Y)});function TG(Q){return QG(R3,Q)}var C3=q("ZodBoolean",(Q,Y)=>{WW.init(Q,Y),X0.init(Q,Y)});function J0(Q){return YG(C3,Q)}var k3=q("ZodNull",(Q,Y)=>{GW.init(Q,Y),X0.init(Q,Y)});function U9(Q){return XG(k3,Q)}var v3=q("ZodUnknown",(Q,Y)=>{$W.init(Q,Y),X0.init(Q,Y)});function e(){return WG(v3)}var x3=q("ZodNever",(Q,Y)=>{zW.init(Q,Y),X0.init(Q,Y)});function _3(Q){return GG(x3,Q)}var g3=q("ZodArray",(Q,Y)=>{JW.init(Q,Y),X0.init(Q,Y),Q.element=Y.element,Q.min=(X,W)=>Q.check(u1(X,W)),Q.nonempty=(X)=>Q.check(u1(1,X)),Q.max=(X,W)=>Q.check(q6(X,W)),Q.length=(X,W)=>Q.check(O6(X,W)),Q.unwrap=()=>Q.element});function u(Q,Y){return $G(g3,Q,Y)}var kG=q("ZodObject",(Q,Y)=>{AW.init(Q,Y),X0.init(Q,Y),m.defineLazy(Q,"shape",()=>{return Y.shape}),Q.keyof=()=>M0(Object.keys(Q._zod.def.shape)),Q.catchall=(X)=>Q.clone({...Q._zod.def,catchall:X}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:_3()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(X)=>{return m.extend(Q,X)},Q.safeExtend=(X)=>{return m.safeExtend(Q,X)},Q.merge=(X)=>m.merge(Q,X),Q.pick=(X)=>m.pick(Q,X),Q.omit=(X)=>m.omit(Q,X),Q.partial=(...X)=>m.partial(_G,Q,X[0]),Q.required=(...X)=>m.required(gG,Q,X[0])});function P(Q,Y){let X={type:"object",shape:Q??{},...m.normalizeParams(Y)};return new kG(X)}function F0(Q,Y){return new kG({type:"object",shape:Q,catchall:e(),...m.normalizeParams(Y)})}var vG=q("ZodUnion",(Q,Y)=>{pQ.init(Q,Y),X0.init(Q,Y),Q.options=Y.options});function d(Q,Y){return new vG({type:"union",options:Q,...m.normalizeParams(Y)})}var y3=q("ZodDiscriminatedUnion",(Q,Y)=>{vG.init(Q,Y),BW.init(Q,Y)});function A9(Q,Y,X){return new y3({type:"union",options:Y,discriminator:Q,...m.normalizeParams(X)})}var u3=q("ZodIntersection",(Q,Y)=>{KW.init(Q,Y),X0.init(Q,Y)});function N6(Q,Y){return new u3({type:"intersection",left:Q,right:Y})}var h3=q("ZodRecord",(Q,Y)=>{DW.init(Q,Y),X0.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function Q0(Q,Y,X){return new h3({type:"record",keyType:Q,valueType:Y,...m.normalizeParams(X)})}var J9=q("ZodEnum",(Q,Y)=>{LW.init(Q,Y),X0.init(Q,Y),Q.enum=Y.entries,Q.options=Object.values(Y.entries);let X=new Set(Object.keys(Y.entries));Q.extract=(W,G)=>{let $={};for(let z of W)if(X.has(z))$[z]=Y.entries[z];else throw Error(`Key ${z} not found in enum`);return new J9({...Y,checks:[],...m.normalizeParams(G),entries:$})},Q.exclude=(W,G)=>{let $={...Y.entries};for(let z of W)if(X.has(z))delete $[z];else throw Error(`Key ${z} not found in enum`);return new J9({...Y,checks:[],...m.normalizeParams(G),entries:$})}});function M0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new J9({type:"enum",entries:X,...m.normalizeParams(Y)})}var f3=q("ZodLiteral",(Q,Y)=>{FW.init(Q,Y),X0.init(Q,Y),Q.values=new Set(Y.values),Object.defineProperty(Q,"value",{get(){if(Y.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return Y.values[0]}})});function b(Q,Y){return new f3({type:"literal",values:Array.isArray(Q)?Q:[Q],...m.normalizeParams(Y)})}var l3=q("ZodTransform",(Q,Y)=>{qW.init(Q,Y),X0.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new G4(Q.constructor.name);X.addIssue=($)=>{if(typeof $==="string")X.issues.push(m.issue($,X.value,Y));else{let z=$;if(z.fatal)z.continue=!1;z.code??(z.code="custom"),z.input??(z.input=X.value),z.inst??(z.inst=Q),X.issues.push(m.issue(z))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then(($)=>{return X.value=$,X});return X.value=G,X}});function xG(Q){return new l3({type:"transform",transform:Q})}var _G=q("ZodOptional",(Q,Y)=>{OW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function Y0(Q){return new _G({type:"optional",innerType:Q})}var m3=q("ZodNullable",(Q,Y)=>{MW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function SG(Q){return new m3({type:"nullable",innerType:Q})}var c3=q("ZodDefault",(Q,Y)=>{VW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function p3(Q,Y){return new c3({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var i3=q("ZodPrefault",(Q,Y)=>{NW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function n3(Q,Y){return new i3({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var gG=q("ZodNonOptional",(Q,Y)=>{ZW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function r3(Q,Y){return new gG({type:"nonoptional",innerType:Q,...m.normalizeParams(Y)})}var d3=q("ZodCatch",(Q,Y)=>{wW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function o3(Q,Y){return new d3({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var t3=q("ZodPipe",(Q,Y)=>{jW.init(Q,Y),X0.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function H9(Q,Y){return new t3({type:"pipe",in:Q,out:Y})}var a3=q("ZodReadonly",(Q,Y)=>{PW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function s3(Q){return new a3({type:"readonly",innerType:Q})}var yG=q("ZodCustom",(Q,Y)=>{bW.init(Q,Y),X0.init(Q,Y)});function uG(Q,Y){return zG(yG,Q??(()=>!0),Y)}function e3(Q,Y={}){return JG(yG,Q,Y)}function QU(Q){return HG(Q)}function B9(Q,Y){return H9(xG(Q),Y)}T0(iQ());var K9="2025-11-25";var hG=[K9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],U1="io.modelcontextprotocol/related-task",w6="2.0",U0=uG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),fG=d([F(),i().int()]),lG=F(),Xw=F0({ttl:d([i(),U9()]).optional(),pollInterval:i().optional()}),YU=P({ttl:i().optional()}),XU=P({taskId:F()}),D9=F0({progressToken:fG.optional(),[U1]:XU.optional()}),I0=P({_meta:D9.optional()}),M4=I0.extend({task:YU.optional()}),mG=(Q)=>M4.safeParse(Q).success,A0=P({method:F(),params:I0.loose().optional()}),S0=P({_meta:D9.optional()}),R0=P({method:F(),params:S0.loose().optional()}),B0=F0({_meta:D9.optional()}),j6=d([F(),i().int()]),cG=P({jsonrpc:b(w6),id:j6,...A0.shape}).strict(),L9=(Q)=>cG.safeParse(Q).success,pG=P({jsonrpc:b(w6),...R0.shape}).strict(),iG=(Q)=>pG.safeParse(Q).success,F9=P({jsonrpc:b(w6),id:j6,result:B0}).strict(),V4=(Q)=>F9.safeParse(Q).success;var h;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(h||(h={}));var q9=P({jsonrpc:b(w6),id:j6.optional(),error:P({code:i().int(),message:F(),data:e().optional()})}).strict();var nG=(Q)=>q9.safeParse(Q).success;var Ww=d([cG,pG,F9,q9]),Gw=d([F9,q9]),P6=B0.strict(),WU=S0.extend({requestId:j6.optional(),reason:F().optional()}),b6=R0.extend({method:b("notifications/cancelled"),params:WU}),GU=P({src:F(),mimeType:F().optional(),sizes:u(F()).optional(),theme:M0(["light","dark"]).optional()}),N4=P({icons:u(GU).optional()}),f1=P({name:F(),title:F().optional()}),rG=f1.extend({...f1.shape,...N4.shape,version:F(),websiteUrl:F().optional(),description:F().optional()}),$U=N6(P({applyDefaults:J0().optional()}),Q0(F(),e())),zU=B9((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},N6(P({form:$U.optional(),url:U0.optional()}),Q0(F(),e()).optional())),JU=F0({list:U0.optional(),cancel:U0.optional(),requests:F0({sampling:F0({createMessage:U0.optional()}).optional(),elicitation:F0({create:U0.optional()}).optional()}).optional()}),HU=F0({list:U0.optional(),cancel:U0.optional(),requests:F0({tools:F0({call:U0.optional()}).optional()}).optional()}),UU=P({experimental:Q0(F(),U0).optional(),sampling:P({context:U0.optional(),tools:U0.optional()}).optional(),elicitation:zU.optional(),roots:P({listChanged:J0().optional()}).optional(),tasks:JU.optional()}),AU=I0.extend({protocolVersion:F(),capabilities:UU,clientInfo:rG}),O9=A0.extend({method:b("initialize"),params:AU});var BU=P({experimental:Q0(F(),U0).optional(),logging:U0.optional(),completions:U0.optional(),prompts:P({listChanged:J0().optional()}).optional(),resources:P({subscribe:J0().optional(),listChanged:J0().optional()}).optional(),tools:P({listChanged:J0().optional()}).optional(),tasks:HU.optional()}),KU=B0.extend({protocolVersion:F(),capabilities:BU,serverInfo:rG,instructions:F().optional()}),M9=R0.extend({method:b("notifications/initialized"),params:S0.optional()});var I6=A0.extend({method:b("ping"),params:I0.optional()}),DU=P({progress:i(),total:Y0(i()),message:Y0(F())}),LU=P({...S0.shape,...DU.shape,progressToken:fG}),E6=R0.extend({method:b("notifications/progress"),params:LU}),FU=I0.extend({cursor:lG.optional()}),Z4=A0.extend({params:FU.optional()}),w4=B0.extend({nextCursor:lG.optional()}),qU=M0(["working","input_required","completed","failed","cancelled"]),j4=P({taskId:F(),status:qU,ttl:d([i(),U9()]),createdAt:F(),lastUpdatedAt:F(),pollInterval:Y0(i()),statusMessage:Y0(F())}),l1=B0.extend({task:j4}),OU=S0.merge(j4),P4=R0.extend({method:b("notifications/tasks/status"),params:OU}),T6=A0.extend({method:b("tasks/get"),params:I0.extend({taskId:F()})}),S6=B0.merge(j4),R6=A0.extend({method:b("tasks/result"),params:I0.extend({taskId:F()})}),$w=B0.loose(),C6=Z4.extend({method:b("tasks/list")}),k6=w4.extend({tasks:u(j4)}),v6=A0.extend({method:b("tasks/cancel"),params:I0.extend({taskId:F()})}),dG=B0.merge(j4),oG=P({uri:F(),mimeType:Y0(F()),_meta:Q0(F(),e()).optional()}),tG=oG.extend({text:F()}),V9=F().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),aG=oG.extend({blob:V9}),b4=M0(["user","assistant"]),m1=P({audience:u(b4).optional(),priority:i().min(0).max(1).optional(),lastModified:O4.datetime({offset:!0}).optional()}),sG=P({...f1.shape,...N4.shape,uri:F(),description:Y0(F()),mimeType:Y0(F()),annotations:m1.optional(),_meta:Y0(F0({}))}),MU=P({...f1.shape,...N4.shape,uriTemplate:F(),description:Y0(F()),mimeType:Y0(F()),annotations:m1.optional(),_meta:Y0(F0({}))}),N9=Z4.extend({method:b("resources/list")}),VU=w4.extend({resources:u(sG)}),NU=Z4.extend({method:b("resources/templates/list")}),ZU=w4.extend({resourceTemplates:u(MU)}),Z9=I0.extend({uri:F()}),wU=Z9,w9=A0.extend({method:b("resources/read"),params:wU}),jU=B0.extend({contents:u(d([tG,aG]))}),PU=R0.extend({method:b("notifications/resources/list_changed"),params:S0.optional()}),bU=Z9,IU=A0.extend({method:b("resources/subscribe"),params:bU}),EU=Z9,TU=A0.extend({method:b("resources/unsubscribe"),params:EU}),SU=S0.extend({uri:F()}),RU=R0.extend({method:b("notifications/resources/updated"),params:SU}),CU=P({name:F(),description:Y0(F()),required:Y0(J0())}),kU=P({...f1.shape,...N4.shape,description:Y0(F()),arguments:Y0(u(CU)),_meta:Y0(F0({}))}),vU=Z4.extend({method:b("prompts/list")}),xU=w4.extend({prompts:u(kU)}),_U=I0.extend({name:F(),arguments:Q0(F(),F()).optional()}),gU=A0.extend({method:b("prompts/get"),params:_U}),j9=P({type:b("text"),text:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),P9=P({type:b("image"),data:V9,mimeType:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),b9=P({type:b("audio"),data:V9,mimeType:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),yU=P({type:b("tool_use"),name:F(),id:F(),input:Q0(F(),e()),_meta:Q0(F(),e()).optional()}),uU=P({type:b("resource"),resource:d([tG,aG]),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),hU=sG.extend({type:b("resource_link")}),I9=d([j9,P9,b9,hU,uU]),fU=P({role:b4,content:I9}),lU=B0.extend({description:F().optional(),messages:u(fU)}),mU=R0.extend({method:b("notifications/prompts/list_changed"),params:S0.optional()}),cU=P({title:F().optional(),readOnlyHint:J0().optional(),destructiveHint:J0().optional(),idempotentHint:J0().optional(),openWorldHint:J0().optional()}),pU=P({taskSupport:M0(["required","optional","forbidden"]).optional()}),eG=P({...f1.shape,...N4.shape,description:F().optional(),inputSchema:P({type:b("object"),properties:Q0(F(),U0).optional(),required:u(F()).optional()}).catchall(e()),outputSchema:P({type:b("object"),properties:Q0(F(),U0).optional(),required:u(F()).optional()}).catchall(e()).optional(),annotations:cU.optional(),execution:pU.optional(),_meta:Q0(F(),e()).optional()}),E9=Z4.extend({method:b("tools/list")}),iU=w4.extend({tools:u(eG)}),x6=B0.extend({content:u(I9).default([]),structuredContent:Q0(F(),e()).optional(),isError:J0().optional()}),zw=x6.or(B0.extend({toolResult:e()})),nU=M4.extend({name:F(),arguments:Q0(F(),e()).optional()}),I4=A0.extend({method:b("tools/call"),params:nU}),rU=R0.extend({method:b("notifications/tools/list_changed"),params:S0.optional()}),Jw=P({autoRefresh:J0().default(!0),debounceMs:i().int().nonnegative().default(300)}),E4=M0(["debug","info","notice","warning","error","critical","alert","emergency"]),dU=I0.extend({level:E4}),T9=A0.extend({method:b("logging/setLevel"),params:dU}),oU=S0.extend({level:E4,logger:F().optional(),data:e()}),tU=R0.extend({method:b("notifications/message"),params:oU}),aU=P({name:F().optional()}),sU=P({hints:u(aU).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),eU=P({mode:M0(["auto","required","none"]).optional()}),QA=P({type:b("tool_result"),toolUseId:F().describe("The unique identifier for the corresponding tool call."),content:u(I9).default([]),structuredContent:P({}).loose().optional(),isError:J0().optional(),_meta:Q0(F(),e()).optional()}),YA=A9("type",[j9,P9,b9]),Z6=A9("type",[j9,P9,b9,yU,QA]),XA=P({role:b4,content:d([Z6,u(Z6)]),_meta:Q0(F(),e()).optional()}),WA=M4.extend({messages:u(XA),modelPreferences:sU.optional(),systemPrompt:F().optional(),includeContext:M0(["none","thisServer","allServers"]).optional(),temperature:i().optional(),maxTokens:i().int(),stopSequences:u(F()).optional(),metadata:U0.optional(),tools:u(eG).optional(),toolChoice:eU.optional()}),GA=A0.extend({method:b("sampling/createMessage"),params:WA}),S9=B0.extend({model:F(),stopReason:Y0(M0(["endTurn","stopSequence","maxTokens"]).or(F())),role:b4,content:YA}),R9=B0.extend({model:F(),stopReason:Y0(M0(["endTurn","stopSequence","maxTokens","toolUse"]).or(F())),role:b4,content:d([Z6,u(Z6)])}),$A=P({type:b("boolean"),title:F().optional(),description:F().optional(),default:J0().optional()}),zA=P({type:b("string"),title:F().optional(),description:F().optional(),minLength:i().optional(),maxLength:i().optional(),format:M0(["email","uri","date","date-time"]).optional(),default:F().optional()}),JA=P({type:M0(["number","integer"]),title:F().optional(),description:F().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),HA=P({type:b("string"),title:F().optional(),description:F().optional(),enum:u(F()),default:F().optional()}),UA=P({type:b("string"),title:F().optional(),description:F().optional(),oneOf:u(P({const:F(),title:F()})),default:F().optional()}),AA=P({type:b("string"),title:F().optional(),description:F().optional(),enum:u(F()),enumNames:u(F()).optional(),default:F().optional()}),BA=d([HA,UA]),KA=P({type:b("array"),title:F().optional(),description:F().optional(),minItems:i().optional(),maxItems:i().optional(),items:P({type:b("string"),enum:u(F())}),default:u(F()).optional()}),DA=P({type:b("array"),title:F().optional(),description:F().optional(),minItems:i().optional(),maxItems:i().optional(),items:P({anyOf:u(P({const:F(),title:F()}))}),default:u(F()).optional()}),LA=d([KA,DA]),FA=d([AA,BA,LA]),qA=d([FA,$A,zA,JA]),OA=M4.extend({mode:b("form").optional(),message:F(),requestedSchema:P({type:b("object"),properties:Q0(F(),qA),required:u(F()).optional()})}),MA=M4.extend({mode:b("url"),message:F(),elicitationId:F(),url:F().url()}),VA=d([OA,MA]),NA=A0.extend({method:b("elicitation/create"),params:VA}),ZA=S0.extend({elicitationId:F()}),wA=R0.extend({method:b("notifications/elicitation/complete"),params:ZA}),_6=B0.extend({action:M0(["accept","decline","cancel"]),content:B9((Q)=>Q===null?void 0:Q,Q0(F(),d([F(),i(),J0(),u(F())])).optional())}),jA=P({type:b("ref/resource"),uri:F()});var PA=P({type:b("ref/prompt"),name:F()}),bA=I0.extend({ref:d([PA,jA]),argument:P({name:F(),value:F()}),context:P({arguments:Q0(F(),F()).optional()}).optional()}),IA=A0.extend({method:b("completion/complete"),params:bA});var EA=B0.extend({completion:F0({values:u(F()).max(100),total:Y0(i().int()),hasMore:Y0(J0())})}),TA=P({uri:F().startsWith("file://"),name:F().optional(),_meta:Q0(F(),e()).optional()}),SA=A0.extend({method:b("roots/list"),params:I0.optional()}),C9=B0.extend({roots:u(TA)}),RA=R0.extend({method:b("notifications/roots/list_changed"),params:S0.optional()}),Hw=d([I6,O9,IA,T9,gU,vU,N9,NU,w9,IU,TU,I4,E9,T6,R6,C6,v6]),Uw=d([b6,E6,M9,RA,P4]),Aw=d([P6,S9,R9,_6,C9,S6,k6,l1]),Bw=d([I6,GA,NA,SA,T6,R6,C6,v6]),Kw=d([b6,E6,tU,RU,PU,rU,mU,P4,wA]),Dw=d([P6,KU,EA,lU,xU,VU,ZU,jU,x6,iU,S6,k6,l1]);class _ extends Error{constructor(Q,Y,X){super(`MCP error ${Q}: ${Y}`);this.code=Q,this.data=X,this.name="McpError"}static fromError(Q,Y,X){if(Q===h.UrlElicitationRequired&&X){let W=X;if(W.elicitations)return new Q$(W.elicitations,Y)}return new _(Q,Y,X)}}class Q$ extends _{constructor(Q,Y=`URL elicitation${Q.length>1?"s":""} required`){super(h.UrlElicitationRequired,Y,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function A1(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var CA=Symbol("Let zodToJsonSchema decide on which parser to use");var nw=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function k9(Q){let X=M6(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=UG(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function v9(Q,Y){let X=H1(Q,Y);if(!X.success)throw X.error;return X.data}var yA=60000;class x9{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(b6,(Y)=>{this._oncancel(Y)}),this.setNotificationHandler(E6,(Y)=>{this._onprogress(Y)}),this.setRequestHandler(I6,(Y)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(T6,async(Y,X)=>{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(R6,async(Y,X)=>{let W=async()=>{let G=Y.params.taskId;if(this._taskMessageQueue){let z;while(z=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(z.type==="response"||z.type==="error"){let J=z.message,H=J.id,U=this._requestResolvers.get(H);if(U)if(this._requestResolvers.delete(H),z.type==="response")U(J);else{let A=J,B=new _(A.error.code,A.error.message,A.error.data);U(B)}else{let A=z.type==="response"?"Response":"Error";this._onerror(Error(`${A} handler missing for request ${H}`))}continue}await this._transport?.send(z.message,{relatedRequestId:X.requestId})}}let $=await this._taskStore.getTask(G,X.sessionId);if(!$)throw new _(h.InvalidParams,`Task not found: ${G}`);if(!A1($.status))return await this._waitForTaskUpdate(G,X.signal),await W();if(A1($.status)){let z=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...z,_meta:{...z._meta,[U1]:{taskId:G}}}}return await W()};return await W()}),this.setRequestHandler(C6,async(Y,X)=>{try{let{tasks:W,nextCursor:G}=await this._taskStore.listTasks(Y.params?.cursor,X.sessionId);return{tasks:W,nextCursor:G,_meta:{}}}catch(W){throw new _(h.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(v6,async(Y,X)=>{try{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,`Task not found: ${Y.params.taskId}`);if(A1(W.status))throw new _(h.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(Y.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Y.params.taskId);let G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new _(h.InvalidParams,`Task not found after cancellation: ${Y.params.taskId}`);return{_meta:{},...G}}catch(W){if(W instanceof _)throw W;throw new _(h.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,Y,X,W,G=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,Y),startTime:Date.now(),timeout:Y,maxTotalTimeout:X,resetTimeoutOnProgress:G,onTimeout:W})}_resetTimeout(Q){let Y=this._timeoutInfo.get(Q);if(!Y)return!1;let X=Date.now()-Y.startTime;if(Y.maxTotalTimeout&&X>=Y.maxTotalTimeout)throw this._timeoutInfo.delete(Q),_.fromError(h.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Y.maxTotalTimeout,totalElapsed:X});return clearTimeout(Y.timeoutId),Y.timeoutId=setTimeout(Y.onTimeout,Y.timeout),!0}_cleanupTimeout(Q){let Y=this._timeoutInfo.get(Q);if(Y)clearTimeout(Y.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let Y=this.transport?.onclose;this._transport.onclose=()=>{Y?.(),this._onclose()};let X=this.transport?.onerror;this._transport.onerror=(G)=>{X?.(G),this._onerror(G)};let W=this._transport?.onmessage;this._transport.onmessage=(G,$)=>{if(W?.(G,$),V4(G)||nG(G))this._onresponse(G);else if(L9(G))this._onrequest(G,$);else if(iG(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let Y=_.fromError(h.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of Q.values())X(Y)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let Y=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(Y===void 0)return;Promise.resolve().then(()=>Y(Q)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(Q,Y){let X=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,G=Q.params?._meta?.[U1]?.taskId;if(X===void 0){let U={jsonrpc:"2.0",id:Q.id,error:{code:h.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId).catch((A)=>this._onerror(Error(`Failed to enqueue error response: ${A}`)));else W?.send(U).catch((A)=>this._onerror(Error(`Failed to send an error response: ${A}`)));return}let $=new AbortController;this._requestHandlerAbortControllers.set(Q.id,$);let z=mG(Q.params)?Q.params.task:void 0,J=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:$.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(U)=>{let A={relatedRequestId:Q.id};if(G)A.relatedTask={taskId:G};await this.notification(U,A)},sendRequest:async(U,A,B)=>{let K={...B,relatedRequestId:Q.id};if(G&&!K.relatedTask)K.relatedTask={taskId:G};let L=K.relatedTask?.taskId??G;if(L&&J)await J.updateTaskStatus(L,"input_required");return await this.request(U,A,K)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:J,taskRequestedTtl:z?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(z)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(U)=>{if($.signal.aborted)return;let A={result:U,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)},async(U)=>{if($.signal.aborted)return;let A={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(U.code)?U.code:h.InternalError,message:U.message??"Internal error",...U.data!==void 0&&{data:U.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)}).catch((U)=>this._onerror(Error(`Failed to send response: ${U}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:Y,...X}=Q.params,W=Number(Y),G=this._progressHandlers.get(W);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let $=this._responseHandlers.get(W),z=this._timeoutInfo.get(W);if(z&&$&&z.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(J){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),$(J);return}G(X)}_onresponse(Q){let Y=Number(Q.id),X=this._requestResolvers.get(Y);if(X){if(this._requestResolvers.delete(Y),V4(Q))X(Q);else{let $=new _(Q.error.code,Q.error.message,Q.error.data);X($)}return}let W=this._responseHandlers.get(Y);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(Y),this._cleanupTimeout(Y);let G=!1;if(V4(Q)&&Q.result&&typeof Q.result==="object"){let $=Q.result;if($.task&&typeof $.task==="object"){let z=$.task;if(typeof z.taskId==="string")G=!0,this._taskProgressTokens.set(z.taskId,Y)}}if(!G)this._progressHandlers.delete(Y);if(V4(Q))W(Q);else{let $=_.fromError(Q.error.code,Q.error.message,Q.error.data);W($)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,Y,X){let{task:W}=X??{};if(!W){try{yield{type:"result",result:await this.request(Q,Y,X)}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}return}let G;try{let $=await this.request(Q,l1,X);if($.task)G=$.task.taskId,yield{type:"taskCreated",task:$.task};else throw new _(h.InternalError,"Task creation did not return a task");while(!0){let z=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:z},A1(z.status)){if(z.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(z.status==="failed")yield{type:"error",error:new _(h.InternalError,`Task ${G} failed`)};else if(z.status==="cancelled")yield{type:"error",error:new _(h.InternalError,`Task ${G} was cancelled`)};return}if(z.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let J=z.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,J)),X?.signal?.throwIfAborted()}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$,task:z,relatedTask:J}=X??{};return new Promise((H,U)=>{let A=(N)=>{U(N)};if(!this._transport){A(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),z)this.assertTaskCapability(Q.method)}catch(N){A(N);return}X?.signal?.throwIfAborted();let B=this._requestMessageId++,K={...Q,jsonrpc:"2.0",id:B};if(X?.onprogress)this._progressHandlers.set(B,X.onprogress),K.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:B}};if(z)K.params={...K.params,task:z};if(J)K.params={...K.params,_meta:{...K.params?._meta||{},[U1]:J}};let L=(N)=>{this._responseHandlers.delete(B),this._progressHandlers.delete(B),this._cleanupTimeout(B),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:B,reason:String(N)}},{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((T)=>this._onerror(Error(`Failed to send cancellation: ${T}`)));let R=N instanceof _?N:new _(h.RequestTimeout,String(N));U(R)};this._responseHandlers.set(B,(N)=>{if(X?.signal?.aborted)return;if(N instanceof Error)return U(N);try{let R=H1(Y,N.result);if(!R.success)U(R.error);else H(R.data)}catch(R){U(R)}}),X?.signal?.addEventListener("abort",()=>{L(X?.signal?.reason)});let O=X?.timeout??yA,M=()=>L(_.fromError(h.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(B,O,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let Z=J?.taskId;if(Z){let N=(R)=>{let T=this._responseHandlers.get(B);if(T)T(R);else this._onerror(Error(`Response handler missing for side-channeled request ${B}`))};this._requestResolvers.set(B,N),this._enqueueTaskMessage(Z,{type:"request",message:K,timestamp:Date.now()}).catch((R)=>{this._cleanupTimeout(B),U(R)})}else this._transport.send(K,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((N)=>{this._cleanupTimeout(B),U(N)})})}async getTask(Q,Y){return this.request({method:"tasks/get",params:Q},S6,Y)}async getTaskResult(Q,Y,X){return this.request({method:"tasks/result",params:Q},Y,X)}async listTasks(Q,Y){return this.request({method:"tasks/list",params:Q},k6,Y)}async cancelTask(Q,Y){return this.request({method:"tasks/cancel",params:Q},dG,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let z={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[U1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:z,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!Y?.relatedRequestId&&!Y?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let z={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)z={...z,params:{...z.params,_meta:{...z.params?._meta||{},[U1]:Y.relatedTask}}};this._transport?.send(z,Y).catch((J)=>this._onerror(J))});return}let $={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)$={...$,params:{...$.params,_meta:{...$.params?._meta||{},[U1]:Y.relatedTask}}};await this._transport.send($,Y)}setRequestHandler(Q,Y){let X=k9(Q);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(W,G)=>{let $=v9(Q,W);return Promise.resolve(Y($,G))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,Y){let X=k9(Q);this._notificationHandlers.set(X,(W)=>{let G=v9(Q,W);return Promise.resolve(Y(G))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let Y=this._taskProgressTokens.get(Q);if(Y!==void 0)this._progressHandlers.delete(Y),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,Y,X){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,Y,X,W)}async _clearTaskQueue(Q,Y){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll(Q,Y);for(let W of X)if(W.type==="request"&&L9(W.message)){let G=W.message.id,$=this._requestResolvers.get(G);if($)$(new _(h.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,Y){let X=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)X=W.pollInterval}catch{}return new Promise((W,G)=>{if(Y.aborted){G(new _(h.InvalidRequest,"Request cancelled"));return}let $=setTimeout(W,X);Y.addEventListener("abort",()=>{clearTimeout($),G(new _(h.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,Y){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await X.createTask(W,Q.id,{method:Q.method,params:Q.params},Y)},getTask:async(W)=>{let G=await X.getTask(W,Y);if(!G)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(W,G,$)=>{await X.storeTaskResult(W,G,$,Y);let z=await X.getTask(W,Y);if(z){let J=P4.parse({method:"notifications/tasks/status",params:z});if(await this.notification(J),A1(z.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,$)=>{let z=await X.getTask(W,Y);if(!z)throw new _(h.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(A1(z.status))throw new _(h.InvalidParams,`Cannot update task "${W}" from terminal status "${z.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,$,Y);let J=await X.getTask(W,Y);if(J){let H=P4.parse({method:"notifications/tasks/status",params:J});if(await this.notification(H),A1(J.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function Y$(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function X$(Q,Y){let X={...Q};for(let W in Y){let G=W,$=Y[G];if($===void 0)continue;let z=X[G];if(Y$(z)&&Y$($))X[G]={...z,...$};else X[G]=$}return X}var v5=H8(TY(),1),x5=H8(k5(),1);function nM(){let Q=new v5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return x5.default(Q),Q}class uY{constructor(Q){this._ajv=Q??nM()}getValidator(Q){let Y="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(X)=>{if(Y(X))return{valid:!0,data:X,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(Y.errors)}}}}class hY{constructor(Q){this._server=Q}requestStream(Q,Y,X){return this._server.requestStream(Q,Y,X)}async getTask(Q,Y){return this._server.getTask({taskId:Q},Y)}async getTaskResult(Q,Y,X){return this._server.getTaskResult({taskId:Q},Y,X)}async listTasks(Q,Y){return this._server.listTasks(Q?{cursor:Q}:void 0,Y)}async cancelTask(Q,Y){return this._server.cancelTask({taskId:Q},Y)}}function _5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"tools/call":if(!Q.tools?.call)throw Error(`${X} does not support task creation for tools/call (required for ${Y})`);break;default:break}}function g5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${X} does not support task creation for sampling/createMessage (required for ${Y})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${X} does not support task creation for elicitation/create (required for ${Y})`);break;default:break}}class fY extends x9{constructor(Q,Y){super(Y);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(E4.options.map((X,W)=>[X,W])),this.isMessageIgnored=(X,W)=>{let G=this._loggingLevels.get(W);return G?this.LOG_LEVEL_SEVERITY.get(X)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=Y?.capabilities??{},this._instructions=Y?.instructions,this._jsonSchemaValidator=Y?.jsonSchemaValidator??new uY,this.setRequestHandler(O9,(X)=>this._oninitialize(X)),this.setNotificationHandler(M9,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(T9,async(X,W)=>{let G=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:$}=X.params,z=E4.safeParse($);if(z.success)this._loggingLevels.set(G,z.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new hY(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=X$(this._capabilities,Q)}setRequestHandler(Q,Y){let W=M6(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let G;if(h1(W)){let z=W;G=z._zod?.def?.value??z.value}else{let z=W;G=z._def?.value??z.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let z=async(J,H)=>{let U=H1(I4,J);if(!U.success){let L=U.error instanceof Error?U.error.message:String(U.error);throw new _(h.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:A}=U.data,B=await Promise.resolve(Y(J,H));if(A.task){let L=H1(l1,B);if(!L.success){let O=L.error instanceof Error?L.error.message:String(L.error);throw new _(h.InvalidParams,`Invalid task creation result: ${O}`)}return L.data}let K=H1(x6,B);if(!K.success){let L=K.error instanceof Error?K.error.message:String(K.error);throw new _(h.InvalidParams,`Invalid tools/call result: ${L}`)}return K.data};return super.setRequestHandler(Q,z)}return super.setRequestHandler(Q,Y)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){g5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;_5(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let Y=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:hG.includes(Y)?Y:K9,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"},P6)}async createMessage(Q,Y){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let X=Q.messages[Q.messages.length-1],W=Array.isArray(X.content)?X.content:[X.content],G=W.some((H)=>H.type==="tool_result"),$=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,z=$?Array.isArray($.content)?$.content:[$.content]:[],J=z.some((H)=>H.type==="tool_use");if(G){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!J)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(J){let H=new Set(z.filter((A)=>A.type==="tool_use").map((A)=>A.id)),U=new Set(W.filter((A)=>A.type==="tool_result").map((A)=>A.toolUseId));if(H.size!==U.size||![...H].every((A)=>U.has(A)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},R9,Y);return this.request({method:"sampling/createMessage",params:Q},S9,Y)}async elicitInput(Q,Y){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},_6,Y)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},G=await this.request({method:"elicitation/create",params:W},_6,Y);if(G.action==="accept"&&G.content&&W.requestedSchema)try{let z=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!z.valid)throw new _(h.InvalidParams,`Elicitation response content does not match requested schema: ${z.errorMessage}`)}catch($){if($ instanceof _)throw $;throw new _(h.InternalError,`Error validating elicitation response: ${$ instanceof Error?$.message:String($)}`)}return G}}}createElicitationCompletionNotifier(Q,Y){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},Y)}async listRoots(Q,Y){return this.request({method:"roots/list",params:Q},C9,Y)}async sendLoggingMessage(Q,Y){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,Y))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var y5={name:"@sequenzy/mcp",version:"0.0.81",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^5.8.0"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var lY=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],u5={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",landingPages:"/dashboard/company/{companyId}/landing-pages",landingPage:"/dashboard/company/{companyId}/landing-pages/{landingPageId}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function dM(Q){let X=(Q??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return X.length>0?X:"https://sequenzy.com"}function l0(Q){let Y=Q?.trim();return Y?Y:void 0}function r0(Q){return encodeURIComponent(Q)}function G0(Q,Y){return`${Q}${Y}`}function $0(Q,Y=""){return`/dashboard/company/${r0(Q)}${Y}`}function h5(Q,Y,X){return G0(Q,`${$0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function oM(Q,Y){let X=lY.map((W)=>[W,Y?h5(Q,Y,W):""]);return Object.fromEntries(X)}function M1(Q={},Y){let X=dM(Y),W=l0(Q.companyId),G={},$=oM(X,W);if(!W)return{appUrl:X,routeTemplates:u5,settingsTabValues:lY,urls:G,settingsUrls:$};G.dashboard=G0(X,$0(W)),G.campaigns=G0(X,$0(W,"/campaign")),G.landingPages=G0(X,$0(W,"/landing-pages")),G.sequences=G0(X,$0(W,"/sequences")),G.settings=G0(X,$0(W,"/settings")),G.emails=G0(X,$0(W,"/emails")),G.subscribers=G0(X,$0(W,"/subscribers")),G.sentEmails=G0(X,$0(W,"/sent-emails")),G.segments=G0(X,$0(W,"/segments")),G.metrics=G0(X,$0(W,"/metrics")),G.transactional=G0(X,$0(W,"/transactional"));let z=l0(Q.campaignId);if(z)G.campaign=G0(X,$0(W,`/campaign/${r0(z)}`)),G.campaignPreview=`${G.campaign}?step=review`;let J=l0(Q.landingPageId);if(J)G.landingPage=G0(X,$0(W,`/landing-pages/${r0(J)}`));let H=l0(Q.sequenceId);if(H)G.sequence=G0(X,$0(W,`/sequences/${r0(H)}`));let U=l0(Q.emailId)??l0(Q.templateId);if(U)G.email=G0(X,$0(W,`/emails/${r0(U)}`)),G.template=G.email;let A=l0(Q.transactionalId);if(A)G.transactionalEmail=G0(X,$0(W,`/transactional/${r0(A)}`));let B=l0(Q.emailSendId);if(B)G.emailSend=G0(X,$0(W,`/sent-emails/${r0(B)}`));let K=l0(Q.domainId);if(K)G.domain=G0(X,$0(W,`/settings/domain/${r0(K)}`)),G.domainVerify=`${G.domain}/verify`;let L=l0(Q.status);if(L)G.campaignList=G0(X,$0(W,`/campaign/list/${r0(L)}`)),G.sequenceList=G0(X,$0(W,`/sequences/list/${r0(L)}`));let O=l0(Q.settingsTab);if(O)G.settingsTab=h5(X,W,O);return{appUrl:X,routeTemplates:u5,settingsTabValues:lY,urls:G,settingsUrls:$}}var f5=[{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 l5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await D("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await D("GET","/api/v1/account"),W=w1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await D("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await D("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await D("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await D("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await D("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await D("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await D("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await D("GET","/api/v1/tags");break;case"sequenzy://health":Y=await D("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=M1();break;default:throw Error(`Unknown resource: ${Q}`)}return{contents:[{uri:Q,mimeType:"application/json",text:JSON.stringify(Y,null,2)}]}}catch(Y){return{contents:[{uri:Q,mimeType:"text/plain",text:x1(Y)}]}}}import{readFileSync as tM,statSync as aM}from"node:fs";import{basename as sM}from"node:path";var X8=' Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in the transactional send `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" } where the text before the colon is a {{merge tag}} path (nested paths like "order.total" or "event.plan" work) and the text after it is the comparison value. `field` may also be "attribute" (same "name:value" form) or "email"/"firstName"/"lastName" (the value is the plain comparison string). Operators: is, is_not, contains, not_contains, gt, gte, lt, lte, is_empty, is_not_empty. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block.',s4=`Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. For provider-migrated HTML from another email platform, prefer the \`html\` field instead; Sequenzy stores it as one raw HTML block to preserve the original design. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.${X8}`,Q4=`Replacement Sequenzy email blocks. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`.${X8}`,oY=`Sequenzy email blocks. Provide blocks or html for email steps. For migrated provider HTML, prefer \`html\`; Sequenzy stores it as one raw HTML block and does not recreate it as native blocks. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Blocks can include repeat blocks over array variables such as items.${X8}`,NQ="Complete Sequenzy landing page content JSON. Use this when replacing the page structure. The content must be the editor-compatible landing page schema with version, template, seo, theme, and blocks. Landing pages must include exactly one footer block and at most one form block.",eM="Optional template key for default content, such as from-scratch, waitlist, lead-magnet, launch, demo-request, webinar, newsletter, product-hunt, pricing-offer, agency-lead-gen, or feature-announcement.",m5=500,c5=500,V1={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},mY=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay"],p5={type:"object",description:"Optional send window for every email step in the sequence. When set, email actions that become due outside the window wait until the next allowed local time. Omit days to allow every day.",properties:{enabled:{type:"boolean",description:"Set false to disable the sending window when creating a sequence. For updates, prefer clearSendingWindow."},timezone:{type:"string",description:"IANA timezone for the window, e.g. Europe/Kiev or America/New_York."},startTime:{type:"string",description:"Earliest local send time in 24-hour HH:mm format, e.g. 08:00."},endTime:{type:"string",description:"Latest local send cutoff in 24-hour HH:mm format, e.g. 20:00. Must be later than startTime."},days:{type:"array",description:"Allowed local days. Use full names or short names such as monday, tuesday, mon, tue. Omit for every day.",items:{type:"string"}}},additionalProperties:!1},QV={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},tY={type:"object",description:"Wait until a date from the trigger event before this step. Use this for renewal reminders, appointment follow-ups, trial-expiry nudges, and other subscriber-specific dates. The field value must be an ISO date string or Unix timestamp.",properties:{field:{type:"string",description:"Dot-path into the trigger event properties, e.g. renews_at or booking.startsAt."},untilDateField:{type:"string",description:"Alias for field."},offset:QV,days:{type:"number",description:"Offset days shorthand. Ignored when offset is provided."},hours:{type:"number",description:"Offset hours shorthand. Ignored when offset is provided."},minutes:{type:"number",description:"Offset minutes shorthand. Ignored when offset is provided."},direction:{type:"string",enum:["before","after"],description:"Whether the offset applies before or after the resolved date. Defaults to after."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"Alias for direction."},missingAction:{type:"string",enum:["continue","exit"],description:"What to do if the event field is missing or invalid. Defaults to continue."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"Alias for missingAction."}},additionalProperties:!1},aY={type:"object",description:"Fixed delay before this step. For a dynamic wait-until-date delay, either set mode:'until_date' plus untilDateField here, or use waitUntil.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"},mode:{type:"string",enum:["duration","until_date"],description:"Use duration for a fixed wait, or until_date to resolve a date from the trigger event."},untilDateField:{type:"string",description:"For mode:'until_date', dot-path into the trigger event properties."},field:{type:"string",description:"Alias for untilDateField."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"For mode:'until_date', whether days/hours/minutes are before or after the event date. Defaults to after."},direction:{type:"string",enum:["before","after"],description:"Alias for untilOffsetDirection."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"For mode:'until_date', what to do when the field is missing or invalid. Defaults to continue."},missingAction:{type:"string",enum:["continue","exit"],description:"Alias for untilMissingAction."}},additionalProperties:!1},wQ=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],jQ=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","sequence.finished","sequence.failed"],YV=new Set(["get_account","get_app_urls","get_company","list_websites","check_website","get_integration_guide","get_subscriber","list_subscriber_notes","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_email_send","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_transactional_emails","get_transactional_email","get_stats","get_campaign_stats","get_sequence_stats","list_campaign_events","list_sequence_events","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_sequence","generate_subject_lines"]),XV=new Set(["select_company","create_company","update_company","create_api_key","add_website","add_subscriber","update_subscriber","add_subscriber_note","remove_subscriber","delete_subscriber_note","upsert_products","delete_product","attach_product_file","remove_product_file","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","delete_template","restart_ab_test","update_ab_test_variant","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_landing_page","update_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","update_sequence","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery"]),WV=new Set(["send_test_email","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","enable_sequence","resume_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery"]),GV=new Set(["remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","disable_sequence","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook"]);function $V(Q){let Y=YV.has(Q),X=XV.has(Q);if(Y===X)throw Error(`MCP tool "${Q}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:Y,destructiveHint:Y?!1:GV.has(Q),openWorldHint:WV.has(Q)}}function zV(Q){return{...Q,annotations:{...Q.annotations,...$V(Q.name)}}}var sY={status:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"],commerceProduct:["is","is_not","at_least","less_than_count"]},JV=Object.entries(sY).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),i5={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct","commerceProduct"],description:"Filter field. Use `event` for custom subscriber events, `segment` for saved segment membership, `stripeProduct`/`stripeCurrentProduct`/`stripeTrialProduct` for Stripe product-based segments, and `commerceProduct` for products purchased through commerce orders - the value is `provider:productId` (provider one of `shopify`, `woocommerce`, `api`; product ids are provider-scoped), optionally with an order-count threshold (`provider:productId:count`) for at_least/less_than_count; a bare product id matches the id on any provider. Engagement fields (`emailSent`, `emailDelivered`, `emailOpened`, `emailClicked`, `emailBounced`, `emailComplained`) accept a time range as the value or a specific campaign via `campaign:<campaign_id>`."},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${JV}.`},value:{type:"string",description:"Filter value. For custom attribute empty checks, use `attributeName:` such as `last_logged_in:`. Event examples: `saas.purchase:30d`, `saas.purchase:all`, or `saas.purchase:5:30d` for thresholds. Segment values are segment IDs. Stripe product examples: `prod_123` for bought/didn't buy/current/trialing, `prod_123:3` for payment thresholds, `prod_123:is_canceled` for products set to cancel, `prod_123:cancels_at:2026-05-26`, `prod_123:end_at:2026-05-26`, or `prod_123:start_at:7 days ago` for product-scoped dates. Engagement examples: `7d`, `30d`, `90d`, `180d`, `all` for rolling time windows, or `campaign:<campaign_id>` to scope to a specific sent campaign (use `list_campaigns` to find IDs)."}},required:["field","operator","value"],additionalProperties:!1},n5={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 eY(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(typeof Y!=="object"||Y===null)return Y;let X=Y;if(typeof X.id==="string"&&X.id.trim()!=="")return X;return{...X,id:crypto.randomUUID()}})}function Q8(Q){if(typeof Q!=="object"||Q===null)return Q;let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=eY([Y]);return Array.isArray(X)?X[0]:Y}if(Y.kind!=="group")return Q;return{...Y,id:typeof Y.id==="string"&&Y.id.trim()!==""?Y.id:crypto.randomUUID(),children:Array.isArray(Y.children)?Y.children.map(Q8):[]}}function HV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function UV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function r5(Q){if(Q==="all")return!0;let Y=Q.match(/^(\d+)d$/);if(!Y?.[1])return!1;let X=Number.parseInt(Y[1],10);return Number.isInteger(X)&&X>0}function AV(Q,Y){let X=Y.split(":");if(Q==="at_least"||Q==="less_than_count"){if(X.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let $=X.slice(0,-2).join(":").trim(),z=X.at(-2),J=X.at(-1),H=z===void 0?Number.NaN:Number.parseInt(z,10);return $&&Number.isInteger(H)&&H>0&&J!==void 0&&r5(J)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(X.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=X.slice(0,-1).join(":").trim(),G=X.at(-1);return W&&G!==void 0&&r5(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function BV(Q){let Y=Q.indexOf(":");if(Y===-1)return{productId:Q,subfilter:null,rawValue:null};let X=Q.substring(0,Y),W=Q.substring(Y+1),G=W.indexOf(":");if(G===-1)return{productId:X,subfilter:W,rawValue:null};return{productId:X,subfilter:W.substring(0,G),rawValue:W.substring(G+1)}}function KV(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function DV(Q){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(Q)}function LV(Q,Y){if(Y==="cancels_at"||Y==="cancel_at"||Y==="cancellation_at")return!0;if(Q==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(Y);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(Y)}function FV(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function qV(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let J=X.indexOf(":");if(J===-1)return null;let H=X.substring(0,J).trim(),U=Number.parseInt(X.substring(J+1).trim(),10);return H&&Number.isInteger(U)&&U>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(Q!=="stripeCurrentProduct"&&Q!=="stripeTrialProduct")return null;let{productId:W,subfilter:G,rawValue:$}=BV(X);if(!W.trim())return"Stripe product filters must include a product ID.";if(!G)return Y==="is"||Y==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let z=KV(G);if(DV(z))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!LV(Q,z))return`Unsupported Stripe product subfilter "${G}".`;if(!FV(Y))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return $?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var OV=new Set(["shopify","woocommerce","api"]);function MV(Q,Y){let X=Y.trim(),W=X.indexOf(":");if(W!==-1&&OV.has(X.substring(0,W).trim()))X=X.substring(W+1).trim();if(!X)return'Purchased Product filters must include a product ID, like "shopify:42".';if(Q!=="at_least"&&Q!=="less_than_count")return null;let G=X.lastIndexOf(":");if(G===-1)return null;let $=X.substring(0,G).trim(),z=Number.parseInt(X.substring(G+1).trim(),10);return $&&Number.isInteger(z)&&z>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function W8(Q){if(typeof Q!=="object"||Q===null)return"Segment filters must be objects.";let Y=Q,X=Y.field,W=Y.operator,G=Y.value;if(typeof X!=="string"||!(X in sY))return`Unsupported segment filter field "${String(X)}".`;if(typeof W!=="string")return`Segment filter "${X}" must include an operator.`;let $=sY[X];if(!$.includes(W))return`Operator "${W}" is not supported for ${X} filters. Use one of: ${$.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${X}" must include a value.`;if(X==="attribute"&&typeof G==="string"){if(!HV(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!UV(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let z=AV(W,G);if(z)return z}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let z=qV(X,W,G);if(z)return z}if(X==="commerceProduct"&&typeof G==="string"){let z=MV(W,G);if(z)return z}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map((J)=>J.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function G8(Q){if(typeof Q!=="object"||Q===null)return[];let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=W8(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap(G8);return[]}function N1(Q,Y,X){if(Y.html!==void 0&&Y.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`, not both.`);if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error(`\`blocks\` must be an array when calling \`${Q}\`.`);if(X?.requireContent&&Y.html===void 0&&Y.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`.`)}function ZQ(Q,Y){if(Y.labels===void 0)return;if(!Array.isArray(Y.labels))throw Error(`\`labels\` must be an array when calling \`${Q}\`.`);if(Y.labels.some((X)=>typeof X!=="string"||X.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${Q}\`.`)}function VV(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!Y&&!X)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=W8(G);return $?[$]:[]}):G8(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function NV(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(Q.name===void 0&&Q.filterJoinOperator===void 0&&!Y&&!X)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=W8(G);return $?[$]:[]}):X?G8(Q.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var cY=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection"];function pY(Q,Y,X){if(Y[X]!==void 0&&!z0(Y[X]))throw Error(`\`${X}\` must be an object when calling \`${Q}\`.`)}function d5(Q,Y,X){if(Y[X]!==void 0&&!Array.isArray(Y[X]))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`)}function ZV(Q){let Y=new Set(["companyId",...cY]),X=Object.keys(Q).filter((G)=>!Y.has(G));if(X.length>0)throw Error(`\`update_company\` accepts only company product-info fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);let W={};for(let G of cY)if(Q[G]!==void 0)W[G]=Q[G];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${cY.map((G)=>`\`${G}\``).join(", ")} when calling \`update_company\`.`);for(let G of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection"])if(Q[G]!==void 0&&typeof Q[G]!=="string")throw Error(`\`${G}\` must be a string when calling \`update_company\`.`);if(pY("update_company",Q,"brandColors"),pY("update_company",Q,"socialLinks"),pY("update_company",Q,"pricing"),d5("update_company",Q,"valueProps"),d5("update_company",Q,"testimonials"),typeof Q.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(Q.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");return W}function wV(Q){if(Q.clearEnrollmentFieldPath===!0&&Q.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(Q.clearSendingWindow===!0&&Q.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(Q.branch!==void 0&&Q.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");let Y={...Q};if(delete Y.clearEnrollmentFieldPath,delete Y.clearSendingWindow,Q.clearEnrollmentFieldPath===!0)Y.enrollmentFieldPath=null;if(Q.clearSendingWindow===!0)Y.sendingWindow=null;return Y}function jV(Q){N1("insert_sequence_step",Q,{requireContent:!0});let Y={subject:C("insert_sequence_step",Q,"subject")};for(let W of["name","previewText","html","blocks","delay","delayMs","waitUntil"])if(Q[W]!==void 0)Y[W]=Q[W];let X={steps:[Y]};if(Q.afterNodeId!==void 0)X.afterNodeId=Q.afterNodeId;return{...Q.confirmStructuralChange!==void 0&&{confirmStructuralChange:Q.confirmStructuralChange},insertSteps:X}}function PV(Q){let Y=w(Q,"subscriberId"),X=Q.fieldValues,W=X===void 0?void 0:Array.isArray(X)?X:void 0;if(X!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let G=W?.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0)??[];if(W?.some((J)=>typeof J!=="string")||W!==void 0&&G.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(Y!==void 0===G.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let $=w(Q,"fieldPath"),z=w(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...$!==void 0&&{fieldPath:$},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...z!==void 0&&{reason:z}}}function bV(Q){N1("create_campaign",Q),ZQ("create_campaign",Q);let Y=w(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0,G=Q.templateId!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(Y&&(X||W||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function IV(Q){if(w(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!z0(Q.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(Q.sendTimeOptimization!==void 0){if(typeof Q.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(Q.spreadOverHours!==void 0){if(typeof Q.spreadOverHours!=="number"||!Number.isInteger(Q.spreadOverHours)||Q.spreadOverHours<1||Q.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}}function iY(Q,Y,X){let W=new Set(["companyId","landingPageId","name","slug","content"]),G=Object.keys(Y).filter(($)=>!W.has($));if(G.length>0)throw Error(`\`${Q}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map(($)=>`\`${$}\``).join(", ")}.`);if(X.requireUpdate&&Y.name===void 0&&Y.slug===void 0&&Y.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${Q}\`.`);return{...Y.name!==void 0&&{name:Y.name},...Y.slug!==void 0&&{slug:Y.slug},...Y.content!==void 0&&{content:Y.content}}}function EV(Q){let Y=new Set(["companyId","domain","verify"]),X=Object.keys(Q).filter((W)=>!Y.has(W));if(X.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${X.length===1?"":"s"}: ${X.map((W)=>`\`${W}\``).join(", ")}.`);if(Q.domain===void 0&&Q.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...Q.domain!==void 0&&{domain:Q.domain},...typeof Q.verify==="boolean"&&{verify:Q.verify}}}function TV(Q){N1("create_transactional_email",Q);let Y=w(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(Y&&(X||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!Y&&!X&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var nY={type:"object",description:"A step to create inside a sequence path. Use type:'delay' for a standalone delay, type:'email' for an email, type:'create_discount' for a discount action, or type:'condition' for a condition gate.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","condition","webhook"],description:"Sequence 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","logic_condition","action_webhook"],description:"Advanced sequence 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/condition actions.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:oY,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},delay:aY,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:tY,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 SV(Q){if(!Q||typeof Q!=="object")return null;let Y=Q;if(Y.success!==!1)return null;if(typeof Y.error==="string")return Error(Y.error);if(Y.error&&typeof Y.error==="object"&&typeof Y.error.message==="string")return Error(Y.error.message);if(typeof Y.message==="string")return Error(Y.message);return Error("The tool returned an unsuccessful response.")}function z0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function o5(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function RV(Q){let Y=new URLSearchParams;if(typeof Q.query==="string"&&Q.query.trim()!=="")Y.set("query",Q.query.trim());if(Array.isArray(Q.tags)&&Q.tags.length>0)Y.set("tags",Q.tags.filter((X)=>typeof X==="string"&&X.trim()!=="").join(","));if(typeof Q.list==="string"&&Q.list.trim()!=="")Y.set("list",Q.list.trim());if(typeof Q.listId==="string"&&Q.listId.trim()!=="")Y.set("listId",Q.listId.trim());if(typeof Q.listName==="string"&&Q.listName.trim()!=="")Y.set("listName",Q.listName.trim());if(typeof Q.segmentId==="string"&&Q.segmentId.trim()!=="")Y.set("segmentId",Q.segmentId);if(typeof Q.status==="string"&&Q.status.trim()!=="")Y.set("status",Q.status.trim());return Y.set("page",String(Q.page)),Y.set("limit",String(Q.pageSize)),Y}async function CV(Q,Y){let X=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,W=Math.min(100,Math.max(1,X??100)),G=[],$=1,z=0,J=0,H=0;while(!0){let A=RV({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:$,pageSize:W}),B=await D("GET",`/api/v1/subscribers?${A.toString()}`,void 0,Y);z=B.pagination?.total??B.subscribers.length,J=B.pagination?.totalPages??1,H+=1,G.push(...B.subscribers??[]);let K=X!==void 0&&G.length>=X,L=B.pagination?$>=B.pagination.totalPages:(B.subscribers??[]).length<W;if(K||L)break;$+=1}let U=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:U,pagination:{page:1,limit:W,total:z,totalPages:J,fetchedPages:H},returned:U.length,truncated:X!==void 0&&z>0&&U.length<z}}function kV(Q){let Y=typeof Q.email==="string"&&Q.email.trim()!==""?Q.email.trim():void 0,X=typeof Q.externalId==="string"&&Q.externalId.trim()!==""?Q.externalId.trim():void 0;return{...Y?{email:Y}:{},...X?{externalId:X}:{}}}function C1(Q,Y){let X=kV(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function Y8(Q,Y){let X=new URLSearchParams;if(Y?.includeMachineEngagement)X.set("includeMachineEngagement","true");let W=X.toString(),G=W?`?${W}`:"";if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}${G}`;return X.set("externalId",String(Q.externalId)),`/api/v1/subscribers/external?${X.toString()}`}function t5(Q){if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}/notes`;let Y=new URLSearchParams;return Y.set("externalId",String(Q.externalId)),`/api/v1/subscribers/external/notes?${Y.toString()}`}async function rY(Q,Y,X){return D("GET",Y8(Q,X),void 0,Y)}function w(Q,Y){let X=Q[Y];if(typeof X!=="string")return;let W=X.trim();return W.length>0?W:void 0}function C(Q,Y,X){let W=w(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function m0(Q,Y,X,W){let G=w(Y,X);if(G===void 0)return;if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function dY(Q,Y,X,W){let G=C(Q,Y,X);if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function v1(Q,Y,X,W,G){let $=Y[X];if($===void 0)return;if(typeof $!=="number"||!Number.isInteger($)||$<W||$>G)throw Error(`\`${X}\` must be an integer between ${W} and ${G} when calling \`${Q}\`.`);return $}function vV(Q,Y){let X=[],W=m0(Q,Y,"eventType",mY);if(W)X.push(W);if(Y.eventTypes!==void 0){if(!Array.isArray(Y.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${Q}\`.`);Y.eventTypes.forEach((G,$)=>{if(typeof G!=="string")throw Error(`\`eventTypes\` item ${$+1} must be a string when calling \`${Q}\`.`);let z=G.trim();if(!mY.includes(z))throw Error(`\`eventTypes\` item ${$+1} must be one of ${mY.join(", ")} when calling \`${Q}\`.`);X.push(z)})}return[...new Set(X)]}function a5(Q,Y){let X=new URLSearchParams,W=vV(Q,Y);if(W.length>0)X.set("eventTypes",W.join(","));let G=m0(Q,Y,"period",["1h","24h","7d","30d","90d"]);if(G)X.set("period",G);let $=w(Y,"start");if($)X.set("start",$);let z=w(Y,"end");if(z)X.set("end",z);let J=v1(Q,Y,"page",1,1e6);if(J!==void 0)X.set("page",String(J));let H=v1(Q,Y,"limit",1,500);if(H!==void 0)X.set("limit",String(H));if(Y.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");return X}function s5(Q,Y){if(Y.events===void 0)return;if(!Array.isArray(Y.events))throw Error(`\`events\` must be an array when calling \`${Q}\`.`);let X=Y.events.map((W,G)=>{if(typeof W!=="string"||!jQ.includes(W))throw Error(`\`events\` item ${G+1} must be one of ${jQ.join(", ")} when calling \`${Q}\`.`);return W});if(X.length===0)throw Error(`\`events\` must include at least one event type when calling \`${Q}\`.`);return X}function e5(Q,Y){if(!Array.isArray(Y.emails))throw Error(`\`emails\` must be an array when calling \`${Q}\`.`);let X=[];if(Y.emails.forEach((W,G)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${Q}\`.`);let $=W.trim();if($.length>0)X.push($)}),X.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${Q}\`.`);if(X.length>m5)throw Error(`\`emails\` must include no more than ${m5} email addresses when calling \`${Q}\`. Split larger batches into multiple calls.`);return X}function QH(Q,Y,X,W){let G=Y[X];if(G===void 0)return;if(!Array.isArray(G))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`);let $=[];if(G.forEach((z,J)=>{if(typeof z!=="string")throw Error(`\`${X}\` item ${J+1} must be a string when calling \`${Q}\`.`);let H=z.trim();if(H.length>0)$.push(H)}),$.length===0)throw Error(`\`${X}\` must include at least one ${W} when calling \`${Q}\`.`);return $}function xV(Q){let X=QH("enroll_subscribers_in_sequence",Q,"emails","email address"),W=QH("enroll_subscribers_in_sequence",Q,"subscriberIds","subscriber ID"),G=(X?.length??0)+(W?.length??0);if(G===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(G>c5)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${c5} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let $=w(Q,"targetNodeId");return{...X!==void 0&&{emails:X},...W!==void 0&&{subscriberIds:W},...$!==void 0&&{targetNodeId:$}}}var _V={pdf:"application/pdf",epub:"application/epub+zip",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",txt:"text/plain",csv:"text/csv"};function gV(Q){let Y=Q.split(".").pop()?.toLowerCase()??"";return _V[Y]??null}var yV=104857600;async function uV(Q,Y){if(!B8())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let X=gV(Q);if(!X)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=aM(Q).size;if(W>yV)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=tM(Q),$=await D("POST","/api/v1/products/delivery/upload-url",{filename:sM(Q),contentType:X,fileSizeBytes:W},Y),z=await fetch($.uploadUrl,{method:"PUT",headers:{"Content-Type":X},body:G});if(!z.ok)throw Error(`File upload failed (${z.status})`);return{url:$.publicUrl,fileName:$.fileName,fileSizeBytes:W,mimeType:X}}async function $8(Q){let Y=w(Q,"companyId");if(Y)return Y;let X=w1();if(X)return X;try{return(await D("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function hV(Q,Y){let X=await $8(Y);if(!X)throw Error(`A company is required when calling \`${Q}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return X}function Y4(Q,Y){if(!z0(Q)||!Y)return Q;return{...Q,url:Y}}function YH(Q,Y){if(!z0(Q))return Q;return{...Q,...Y.campaign!==void 0&&{url:Y.campaign},...Y.campaignPreview!==void 0&&{previewUrl:Y.campaignPreview}}}function e4(Q,Y,X){if(!Array.isArray(Q)||!Y)return Q;return Q.map((W)=>{if(!z0(W))return W;let G=w(W,"id");if(!G)return W;let $=M1({companyId:Y,...X==="campaign"&&{campaignId:G},...X==="landingPage"&&{landingPageId:G},...X==="sequence"&&{sequenceId:G},...X==="template"&&{emailId:G},...X==="transactional"&&{transactionalId:G}});if(X==="campaign")return YH(W,$.urls);let z=X==="sequence"?$.urls.sequence:X==="landingPage"?$.urls.landingPage:X==="template"?$.urls.email:$.urls.transactionalEmail;return Y4(W,z)})}function fV(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!z0(Y))return Y;let X=w(Y,"id");if(!X)return Y;let W=M1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var XH=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","update_sequence","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function lV(Q,Y,X){if(!z0(X)||!XH.has(Q))return X;let W=z0(X.company)?X.company:void 0,$=w(X,"selectedCompanyId")??w(X,"currentCompanyId")??w(X,"companyId")??(W?w(W,"id"):void 0)??(W?w(W,"companyId"):void 0)??await $8(Y);if(!$)return X;let z=z0(X.campaign)?X.campaign:void 0,J=z0(X.sequence)?X.sequence:void 0,H=z0(X.landingPage)?X.landingPage:void 0,U=z0(X.template)?X.template:void 0,A=z0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,B={companyId:$,campaignId:w(Y,"campaignId")??w(X,"campaignId")??(z?w(z,"id"):void 0),landingPageId:w(Y,"landingPageId")??w(X,"landingPageId")??(H?w(H,"id"):void 0),sequenceId:w(Y,"sequenceId")??w(X,"sequenceId")??(J?w(J,"id"):void 0),emailId:w(X,"templateId")??(U?w(U,"id"):void 0)??(A?w(A,"emailId"):void 0)??w(Y,"templateId"),transactionalId:w(Y,"transactionalId")??(A?w(A,"id"):void 0)??w(Y,"idOrSlug"),emailSendId:w(Y,"emailSendId")??w(X,"emailSendId")??(z0(X.emailSend)?w(X.emailSend,"id"):void 0),status:w(Y,"status")},K=M1(B),L=W?M1({companyId:$}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:fV(X.companies)},...Array.isArray(X.campaigns)&&{campaigns:e4(X.campaigns,$,"campaign")},...Array.isArray(X.landingPages)&&{landingPages:e4(X.landingPages,$,"landingPage")},...Array.isArray(X.sequences)&&{sequences:e4(X.sequences,$,"sequence")},...Array.isArray(X.templates)&&{templates:e4(X.templates,$,"template")},...Array.isArray(X.transactional)&&{transactional:e4(X.transactional,$,"transactional")},...W&&L!==void 0&&{company:{...W,url:L.urls.dashboard,settingsUrl:L.urls.settings}},...z&&K.urls.campaign!==void 0&&{campaign:YH(z,K.urls)},...J&&K.urls.sequence!==void 0&&{sequence:Y4(J,K.urls.sequence)},...H&&K.urls.landingPage!==void 0&&{landingPage:Y4(H,K.urls.landingPage)},...U&&K.urls.email!==void 0&&{template:Y4(U,K.urls.email)},...A&&K.urls.transactionalEmail!==void 0&&{transactional:Y4(A,K.urls.transactionalEmail)},...z0(X.emailSend)&&K.urls.emailSend!==void 0&&{emailSend:Y4(X.emailSend,K.urls.emailSend)},appUrls:K.urls}}var mV={type:"boolean",description:"Whether the Sequenzy operation succeeded."},cV={type:"string",description:"Human-readable status, confirmation, or next-step message."},pV={type:"string",description:"Additional context about the result."};function E0(Q){return{type:"object",description:Q,additionalProperties:!0}}function iV(Q){return{type:"array",description:Q,items:E0("One item in the returned collection.")}}function k(Q){return{type:"string",description:Q}}function j0(Q){return{type:"number",description:Q}}function k1(Q){return{type:"boolean",description:Q}}function V(Q){return E0(`The ${Q} record returned by Sequenzy.`)}function p(Q){return iV(`List of ${Q} records returned by Sequenzy.`)}var nV={appUrls:E0("Dashboard URLs for relevant Sequenzy resources."),url:k("Primary dashboard URL for this result."),settingsUrl:k("Company settings URL when available.")},rV={success:mV,message:cV,note:pV,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:E0("One returned item.")},value:E0("Fallback object wrapper used only when a tool returns a non-object value.")},dV={get_account:{account:V("account"),companies:p("company"),currentCompanyId:k("Company ID selected by the authenticated API key, when available."),selectedCompanyId:k("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:k("Selected company ID."),companyName:k("Selected company name.")},get_app_urls:{dashboard:k("Company dashboard URL."),settings:k("Company settings URL."),campaign:k("Campaign editor URL."),landingPage:k("Landing page editor URL."),sequence:k("Sequence editor URL."),email:k("Email editor URL."),transactionalEmail:k("Transactional email URL."),emailSend:k("Sent email detail URL."),domain:k("Sending domain settings URL."),urls:E0("All generated URLs keyed by resource type.")},create_company:{company:V("company"),autoSelected:k1("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:V("company")},get_company:{company:V("company")},create_api_key:{apiKey:k("Newly created API key. This secret is returned only once."),key:k("Newly created API key if the API response uses the short key field.")},list_websites:{websites:p("sender website")},add_website:{website:V("sender website")},check_website:{website:V("sender website"),ready:k1("Whether the sender website is ready."),status:k("Current processing or verification status.")},get_integration_guide:{guide:V("integration guide"),code:k("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:E0("One setup step.")}},add_subscriber:{subscriber:V("subscriber")},update_subscriber:{subscriber:V("subscriber")},remove_subscriber:{subscriber:V("subscriber"),hardDeleted:k1("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:V("subscriber")},list_subscriber_notes:{notes:p("subscriber note")},add_subscriber_note:{note:V("subscriber note")},delete_subscriber_note:{id:k("Deleted subscriber note ID."),deleted:k1("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:p("subscriber"),pagination:E0("Pagination metadata."),returned:j0("Number of subscribers returned."),truncated:k1("Whether the result was truncated by the requested limit.")},list_products:{products:p("product")},upsert_products:{products:p("product"),created:j0("Number of products created."),updated:j0("Number of products updated.")},delete_product:{productId:k("Deleted product ID.")},attach_product_file:{product:V("product"),delivery:V("digital delivery file")},remove_product_file:{product:V("product")},sync_products:{job:V("product sync job"),jobId:k("Queued product sync job ID.")},list_tags:{tags:p("tag")},create_tag:{tag:V("tag")},update_tag:{tag:V("tag")},delete_tag:{tagId:k("Deleted tag ID.")},list_lists:{lists:p("list")},create_list:{list:V("list")},update_list:{list:V("list")},delete_list:{listId:k("Deleted list ID.")},add_subscribers_to_list:{list:V("list"),added:j0("Number of subscribers added to the list."),skipped:j0("Number of subscribers skipped.")},remove_subscribers_from_list:{list:V("list"),removed:j0("Number of subscribers removed from the list."),skipped:j0("Number of subscribers skipped.")},list_segments:{segments:p("segment")},create_segment:{segment:V("segment")},update_segment:{segment:V("segment")},delete_segment:{segmentId:k("Deleted segment ID.")},get_segment_count:{count:j0("Number of subscribers matching the segment."),segmentId:k("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:p("audience sync")},list_ad_accounts:{adAccounts:p("ad account")},create_audience_sync:{audienceSync:V("audience sync")},update_audience_sync:{audienceSync:V("audience sync")},delete_audience_sync:{audienceSyncId:k("Deleted audience sync ID.")},sync_audience_now:{audienceSync:V("audience sync"),job:V("audience sync job"),jobId:k("Queued audience sync job ID.")},list_templates:{templates:p("email template")},get_template:{template:V("email template")},create_template:{template:V("email template")},update_template:{template:V("email template")},delete_template:{templateId:k("Deleted template ID.")},list_ab_tests:{abTests:p("A/B test")},get_ab_test:{abTest:V("A/B test")},get_ab_test_stats:{abTest:V("A/B test"),stats:V("A/B test statistics")},restart_ab_test:{abTest:V("A/B test")},update_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},create_ab_test:{abTest:V("A/B test")},add_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},delete_ab_test_variant:{abTest:V("A/B test"),variantId:k("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:k("Deleted A/B test ID.")},list_campaigns:{campaigns:p("campaign")},get_campaign:{campaign:V("campaign")},get_email_send:{emailSend:V("email send")},create_campaign:{campaign:V("campaign")},update_campaign:{campaign:V("campaign")},schedule_campaign:{campaign:V("campaign"),scheduledAt:k("Scheduled send timestamp.")},send_test_email:{emailSend:V("test email send"),recipient:k("Test email recipient.")},cancel_campaign:{campaign:V("campaign")},pause_campaign:{campaign:V("campaign")},resume_campaign:{campaign:V("campaign")},delete_campaign:{campaignId:k("Deleted campaign ID.")},duplicate_campaign:{campaign:V("duplicated campaign")},resend_campaign_to_non_openers:{campaign:V("non-opener resend draft campaign"),estimatedNonOpenerCount:j0("Estimated number of subscribers who haven't opened the original campaign.")},list_landing_pages:{landingPages:p("landing page")},get_landing_page:{landingPage:V("landing page")},create_landing_page:{landingPage:V("landing page")},update_landing_page:{landingPage:V("landing page")},delete_landing_page:{landingPageId:k("Deleted landing page ID.")},publish_landing_page:{landingPage:V("landing page")},unpublish_landing_page:{landingPage:V("landing page")},connect_landing_page_domain:{landingPage:V("landing page"),domain:k("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:V("landing page"),domain:k("Landing page domain.")},list_sequences:{sequences:p("sequence")},get_sequence:{sequence:V("sequence")},create_sequence:{sequence:V("sequence")},update_sequence:{sequence:V("sequence")},insert_sequence_step:{sequence:V("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for the inserted step, including any delay node.",items:k("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:k("Inserted email template ID.")},insertedEmailCount:j0("Number of email steps inserted.")},enable_sequence:{sequence:V("sequence")},disable_sequence:{sequence:V("sequence")},pause_sequence_enrollments:{sequenceId:k("Sequence ID."),enrollmentPaused:k1("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:k("Sequence ID."),enrollmentPaused:k1("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:V("sequence"),enrollments:p("sequence enrollment"),enrolled:j0("Number of subscribers enrolled."),skipped:j0("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:V("sequence"),cancelled:j0("Number of enrollments cancelled."),skipped:j0("Number of enrollments skipped.")},delete_sequence:{sequenceId:k("Deleted sequence ID.")},list_transactional_emails:{transactional:p("transactional email")},get_transactional_email:{transactional:V("transactional email")},create_transactional_email:{transactional:V("transactional email")},update_transactional_email:{transactional:V("transactional email")},send_email:{emailSend:V("transactional email send"),transactional:V("transactional email")},get_stats:{stats:V("account or company statistics")},get_campaign_stats:{campaign:V("campaign"),stats:V("campaign statistics")},get_sequence_stats:{sequence:V("sequence"),stats:V("sequence statistics")},list_campaign_events:{events:p("campaign email event"),pagination:E0("Pagination metadata.")},list_sequence_events:{events:p("sequence email event"),pagination:E0("Pagination metadata.")},get_subscriber_activity:{activity:p("subscriber activity event"),subscribers:p("subscriber"),pagination:E0("Pagination metadata.")},list_team_members:{members:p("team member"),invitations:p("team invitation")},invite_team_member:{invitation:V("team invitation")},cancel_team_invitation:{invitationId:k("Cancelled invitation ID.")},list_conversations:{conversations:p("inbox conversation"),pagination:E0("Pagination metadata.")},get_conversation:{conversation:V("inbox conversation"),messages:p("conversation message")},reply_to_conversation:{conversation:V("inbox conversation"),message:V("conversation message")},update_conversation_status:{conversation:V("inbox conversation")},mark_conversation_read:{conversation:V("inbox conversation")},list_webhooks:{webhooks:p("outbound webhook")},create_webhook:{webhook:V("outbound webhook")},update_webhook:{webhook:V("outbound webhook")},delete_webhook:{webhookId:k("Deleted outbound webhook ID.")},test_webhook:{webhook:V("outbound webhook"),delivery:V("test webhook delivery")},list_webhook_deliveries:{deliveries:p("webhook delivery")},replay_webhook_delivery:{delivery:V("webhook delivery"),job:V("webhook replay job")},generate_email:{email:V("generated email"),html:k("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks.",items:E0("One generated email block.")},subject:k("Generated subject line."),previewText:k("Generated inbox preview text.")},generate_sequence:{sequence:V("generated sequence"),steps:p("generated sequence step")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:k("One generated subject line.")},variants:p("generated subject line variant")}};function oV(Q){let Y=dV[Q];if(Y===void 0)throw Error(`MCP tool "${Q}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${Q}\` MCP tool.`,properties:{...rV,...Y,...XH.has(Q)?nV:{}},additionalProperties:!0}}function tV(Q){return{...Q,outputSchema:oV(Q.name)}}function aV(Q){if(z0(Q))return Q;if(Array.isArray(Q))return{items:Q};return{value:Q}}var sV=[{name:"get_account",description:`Get current account information including available companies. IMPORTANT: If you have access to multiple companies, you MUST either:
|
|
28
|
+
`)}L.write("payload.value = newResult;"),L.write("return payload;");let R=L.compile();return(T,y)=>R(K,T,y)},$,z=j1,J=!Q6.jitless,U=J&&kQ.value,A=Y.catchall,B;Q._zod.parse=(K,L)=>{B??(B=W.value);let O=K.value;if(!z(O))return K.issues.push({expected:"object",code:"invalid_type",input:O,inst:Q}),K;if(J&&U&&L?.async===!1&&L.jitless!==!0){if(!$)$=G(Y.shape);if(K=$(K,L),!A)return K;return UW([],O,K,L,B,Q)}return X(K,L)}});function bX(Q,Y,X,W){for(let $ of Q)if($.issues.length===0)return Y.value=$.value,Y;let G=Q.filter(($)=>!J1($));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map(($)=>$.issues.map((z)=>x0(z,W,T0())))}),Y}var pQ=q("$ZodUnion",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),n(Q._zod,"optout",()=>Y.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),n(Q._zod,"values",()=>{if(Y.options.every((G)=>G._zod.values))return new Set(Y.options.flatMap((G)=>Array.from(G._zod.values)));return}),n(Q._zod,"pattern",()=>{if(Y.options.every((G)=>G._zod.pattern)){let G=Y.options.map(($)=>$._zod.pattern);return new RegExp(`^(${G.map(($)=>J4($.source)).join("|")})$`)}return});let X=Y.options.length===1,W=Y.options[0]._zod.run;Q._zod.parse=(G,$)=>{if(X)return W(G,$);let z=!1,J=[];for(let H of Y.options){let U=H._zod.run({value:G.value,issues:[]},$);if(U instanceof Promise)J.push(U),z=!0;else{if(U.issues.length===0)return U;J.push(U)}}if(!z)return bX(J,G,Q,$);return Promise.all(J).then((H)=>{return bX(H,G,Q,$)})}}),BW=q("$ZodDiscriminatedUnion",(Q,Y)=>{pQ.init(Q,Y);let X=Q._zod.parse;n(Q._zod,"propValues",()=>{let G={};for(let $ of Y.options){let z=$._zod.propValues;if(!z||Object.keys(z).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf($)}"`);for(let[J,H]of Object.entries(z)){if(!G[J])G[J]=new Set;for(let U of H)G[J].add(U)}}return G});let W=g1(()=>{let G=Y.options,$=new Map;for(let z of G){let J=z._zod.propValues?.[Y.discriminator];if(!J||J.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(z)}"`);for(let H of J){if($.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);$.set(H,z)}}return $});Q._zod.parse=(G,$)=>{let z=G.value;if(!j1(z))return G.issues.push({code:"invalid_type",expected:"object",input:z,inst:Q}),G;let J=W.value.get(z?.[Y.discriminator]);if(J)return J._zod.run(G,$);if(Y.unionFallback)return X(G,$);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,input:z,path:[Y.discriminator],inst:Q}),G}}),KW=q("$ZodIntersection",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value,$=Y.left._zod.run({value:G,issues:[]},W),z=Y.right._zod.run({value:G,issues:[]},W);if($ instanceof Promise||z instanceof Promise)return Promise.all([$,z]).then(([H,U])=>{return IX(X,H,U)});return IX(X,$,z)}});function mQ(Q,Y){if(Q===Y)return{valid:!0,data:Q};if(Q instanceof Date&&Y instanceof Date&&+Q===+Y)return{valid:!0,data:Q};if(z1(Q)&&z1(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter(($)=>X.indexOf($)!==-1),G={...Q,...Y};for(let $ of W){let z=mQ(Q[$],Y[$]);if(!z.valid)return{valid:!1,mergeErrorPath:[$,...z.mergeErrorPath]};G[$]=z.data}return{valid:!0,data:G}}if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let W=0;W<Q.length;W++){let G=Q[W],$=Y[W],z=mQ(G,$);if(!z.valid)return{valid:!1,mergeErrorPath:[W,...z.mergeErrorPath]};X.push(z.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function IX(Q,Y,X){if(Y.issues.length)Q.issues.push(...Y.issues);if(X.issues.length)Q.issues.push(...X.issues);if(J1(Q))return Q;let W=mQ(Y.value,X.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return Q.value=W.data,Q}var DW=q("$ZodRecord",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!z1(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let $=[];if(Y.keyType._zod.values){let z=Y.keyType._zod.values;X.value={};for(let H of z)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let U=Y.valueType._zod.run({value:G[H],issues:[]},W);if(U instanceof Promise)$.push(U.then((A)=>{if(A.issues.length)X.issues.push(...a0(H,A.issues));X.value[H]=A.value}));else{if(U.issues.length)X.issues.push(...a0(H,U.issues));X.value[H]=U.value}}let J;for(let H in G)if(!z.has(H))J=J??[],J.push(H);if(J&&J.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:J})}else{X.value={};for(let z of Reflect.ownKeys(G)){if(z==="__proto__")continue;let J=Y.keyType._zod.run({value:z,issues:[]},W);if(J instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(J.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:J.issues.map((U)=>x0(U,W,T0())),input:z,path:[z],inst:Q}),X.value[J.value]=J.value;continue}let H=Y.valueType._zod.run({value:G[z],issues:[]},W);if(H instanceof Promise)$.push(H.then((U)=>{if(U.issues.length)X.issues.push(...a0(z,U.issues));X.value[J.value]=U.value}));else{if(H.issues.length)X.issues.push(...a0(z,H.issues));X.value[J.value]=H.value}}}if($.length)return Promise.all($).then(()=>X);return X}});var LW=q("$ZodEnum",(Q,Y)=>{o.init(Q,Y);let X=RQ(Y.entries),W=new Set(X);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${X.filter((G)=>vQ.has(typeof G)).map((G)=>typeof G==="string"?t0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,$)=>{let z=G.value;if(W.has(z))return G;return G.issues.push({code:"invalid_value",values:X,input:z,inst:Q}),G}}),FW=q("$ZodLiteral",(Q,Y)=>{if(o.init(Q,Y),Y.values.length===0)throw Error("Cannot create literal schema with no valid values");Q._zod.values=new Set(Y.values),Q._zod.pattern=new RegExp(`^(${Y.values.map((X)=>typeof X==="string"?t0(X):X?t0(X.toString()):String(X)).join("|")})$`),Q._zod.parse=(X,W)=>{let G=X.value;if(Q._zod.values.has(G))return X;return X.issues.push({code:"invalid_value",values:Y.values,input:G,inst:Q}),X}});var qW=q("$ZodTransform",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new G4(Q.constructor.name);let G=Y.transform(X.value,X);if(W.async)return(G instanceof Promise?G:Promise.resolve(G)).then((z)=>{return X.value=z,X});if(G instanceof Promise)throw new o0;return X.value=G,X}});function EX(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var OW=q("$ZodOptional",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",n(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),n(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${J4(X.source)})?$`):void 0}),Q._zod.parse=(X,W)=>{if(Y.innerType._zod.optin==="optional"){let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>EX($,X.value));return EX(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),MW=q("$ZodNullable",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),n(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${J4(X.source)}|null)$`):void 0}),n(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,null]):void 0}),Q._zod.parse=(X,W)=>{if(X.value===null)return X;return Y.innerType._zod.run(X,W)}}),VW=q("$ZodDefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)return X.value=Y.defaultValue,X;let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>TX($,Y));return TX(G,Y)}});function TX(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var NW=q("$ZodPrefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)X.value=Y.defaultValue;return Y.innerType._zod.run(X,W)}}),ZW=q("$ZodNonOptional",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"values",()=>{let X=Y.innerType._zod.values;return X?new Set([...X].filter((W)=>W!==void 0)):void 0}),Q._zod.parse=(X,W)=>{let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>SX($,Q));return SX(G,Q)}});function SX(Q,Y){if(!Q.issues.length&&Q.value===void 0)Q.issues.push({code:"invalid_type",expected:"nonoptional",input:Q.value,inst:Y});return Q}var wW=q("$ZodCatch",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>{if(X.value=$.value,$.issues.length)X.value=Y.catchValue({...X,error:{issues:$.issues.map((z)=>x0(z,W,T0()))},input:X.value}),X.issues=[];return X});if(X.value=G.value,G.issues.length)X.value=Y.catchValue({...X,error:{issues:G.issues.map(($)=>x0($,W,T0()))},input:X.value}),X.issues=[];return X}});var jW=q("$ZodPipe",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"values",()=>Y.in._zod.values),n(Q._zod,"optin",()=>Y.in._zod.optin),n(Q._zod,"optout",()=>Y.out._zod.optout),n(Q._zod,"propValues",()=>Y.in._zod.propValues),Q._zod.parse=(X,W)=>{if(W.direction==="backward"){let $=Y.out._zod.run(X,W);if($ instanceof Promise)return $.then((z)=>A6(z,Y.in,W));return A6($,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>A6($,Y.out,W));return A6(G,Y.out,W)}});function A6(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var PW=q("$ZodReadonly",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"propValues",()=>Y.innerType._zod.propValues),n(Q._zod,"values",()=>Y.innerType._zod.values),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(RX);return RX(G)}});function RX(Q){return Q.value=Object.freeze(Q.value),Q}var bW=q("$ZodCustom",(Q,Y)=>{H0.init(Q,Y),o.init(Q,Y),Q._zod.parse=(X,W)=>{return X},Q._zod.check=(X)=>{let W=X.value,G=Y.fn(W);if(G instanceof Promise)return G.then(($)=>CX($,X,W,Q));CX(G,X,W,Q);return}});function CX(Q,Y,X,W){if(!Q){let G={code:"custom",input:X,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)G.params=W._zod.def.params;Y.issues.push(y1(G))}}var Q3=(Q)=>{let Y=typeof Q;switch(Y){case"number":return Number.isNaN(Q)?"NaN":"number";case"object":{if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Object.getPrototypeOf(Q)!==Object.prototype&&Q.constructor)return Q.constructor.name}}return Y},Y3=()=>{let Q={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function Y(W){return Q[W]??null}let X={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${Q3(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${G6(W.values[0])}`;return`Invalid option: expected one of ${Y6(W.values,"|")}`;case"too_big":{let G=W.inclusive?"<=":"<",$=Y(W.origin);if($)return`Too big: expected ${W.origin??"value"} to have ${G}${W.maximum.toString()} ${$.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${G}${W.maximum.toString()}`}case"too_small":{let G=W.inclusive?">=":">",$=Y(W.origin);if($)return`Too small: expected ${W.origin} to have ${G}${W.minimum.toString()} ${$.unit}`;return`Too small: expected ${W.origin} to be ${G}${W.minimum.toString()}`}case"invalid_format":{let G=W;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${X[G.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${Y6(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:Y3()}}var ZN=Symbol("ZodOutput"),wN=Symbol("ZodInput");class IW{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Q,...Y){let X=Y[0];if(this._map.set(Q,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.id,Q)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Q){let Y=this._map.get(Q);if(Y&&typeof Y==="object"&&"id"in Y)this._idmap.delete(Y.id);return this._map.delete(Q),this}get(Q){let Y=Q._zod.parent;if(Y){let X={...this.get(Y)??{}};delete X.id;let W={...X,...this._map.get(Q)};return Object.keys(W).length?W:void 0}return this._map.get(Q)}has(Q){return this._map.has(Q)}}function X3(){return new IW}var D4=X3();function EW(Q,Y){return new Q({type:"string",...E(Y)})}function TW(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...E(Y)})}function nQ(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...E(Y)})}function SW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...E(Y)})}function RW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...E(Y)})}function CW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...E(Y)})}function kW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...E(Y)})}function vW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...E(Y)})}function xW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...E(Y)})}function _W(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...E(Y)})}function gW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...E(Y)})}function yW(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...E(Y)})}function uW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...E(Y)})}function hW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...E(Y)})}function fW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...E(Y)})}function lW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...E(Y)})}function mW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...E(Y)})}function cW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...E(Y)})}function pW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...E(Y)})}function iW(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...E(Y)})}function nW(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...E(Y)})}function rW(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...E(Y)})}function dW(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...E(Y)})}function oW(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...E(Y)})}function tW(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...E(Y)})}function aW(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...E(Y)})}function sW(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...E(Y)})}function eW(Q,Y){return new Q({type:"number",checks:[],...E(Y)})}function QG(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...E(Y)})}function YG(Q,Y){return new Q({type:"boolean",...E(Y)})}function XG(Q,Y){return new Q({type:"null",...E(Y)})}function WG(Q){return new Q({type:"unknown"})}function GG(Q,Y){return new Q({type:"never",...E(Y)})}function D6(Q,Y){return new hQ({check:"less_than",...E(Y),value:Q,inclusive:!1})}function L4(Q,Y){return new hQ({check:"less_than",...E(Y),value:Q,inclusive:!0})}function L6(Q,Y){return new fQ({check:"greater_than",...E(Y),value:Q,inclusive:!1})}function F4(Q,Y){return new fQ({check:"greater_than",...E(Y),value:Q,inclusive:!0})}function F6(Q,Y){return new AX({check:"multiple_of",...E(Y),value:Q})}function q6(Q,Y){return new KX({check:"max_length",...E(Y),maximum:Q})}function u1(Q,Y){return new DX({check:"min_length",...E(Y),minimum:Q})}function O6(Q,Y){return new LX({check:"length_equals",...E(Y),length:Q})}function rQ(Q,Y){return new FX({check:"string_format",format:"regex",...E(Y),pattern:Q})}function dQ(Q){return new qX({check:"string_format",format:"lowercase",...E(Q)})}function oQ(Q){return new OX({check:"string_format",format:"uppercase",...E(Q)})}function tQ(Q,Y){return new MX({check:"string_format",format:"includes",...E(Y),includes:Q})}function aQ(Q,Y){return new VX({check:"string_format",format:"starts_with",...E(Y),prefix:Q})}function sQ(Q,Y){return new NX({check:"string_format",format:"ends_with",...E(Y),suffix:Q})}function P1(Q){return new ZX({check:"overwrite",tx:Q})}function eQ(Q){return P1((Y)=>Y.normalize(Q))}function Q9(){return P1((Q)=>Q.trim())}function Y9(){return P1((Q)=>Q.toLowerCase())}function X9(){return P1((Q)=>Q.toUpperCase())}function $G(Q,Y,X){return new Q({type:"array",element:Y,...E(X)})}function zG(Q,Y,X){let W=E(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function JG(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...E(X)})}function HG(Q){let Y=W3((X)=>{return X.addIssue=(W)=>{if(typeof W==="string")X.issues.push(y1(W,X.value,Y._zod.def));else{let G=W;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=X.value),G.inst??(G.inst=Y),G.continue??(G.continue=!Y._zod.def.abort),X.issues.push(y1(G))}},Q(X.value,X)});return Y}function W3(Q,Y){let X=new H0({check:"custom",...E(Y)});return X._zod.check=Q,X}function h1(Q){return!!Q._zod}function H1(Q,Y){if(h1(Q))return A4(Q,Y);return Q.safeParse(Y)}function M6(Q){if(!Q)return;let Y;if(h1(Q))Y=Q._zod?.def?.shape;else Y=Q.shape;if(!Y)return;if(typeof Y==="function")try{return Y()}catch{return}return Y}function UG(Q){if(h1(Q)){let $=Q._zod?.def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}}let X=Q._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let W=Q.value;if(W!==void 0)return W;return}var O4={};U8(O4,{time:()=>$9,duration:()=>z9,datetime:()=>W9,date:()=>G9,ZodISOTime:()=>KG,ZodISODuration:()=>DG,ZodISODateTime:()=>AG,ZodISODate:()=>BG});var AG=q("ZodISODateTime",(Q,Y)=>{cX.init(Q,Y),s.init(Q,Y)});function W9(Q){return oW(AG,Q)}var BG=q("ZodISODate",(Q,Y)=>{pX.init(Q,Y),s.init(Q,Y)});function G9(Q){return tW(BG,Q)}var KG=q("ZodISOTime",(Q,Y)=>{iX.init(Q,Y),s.init(Q,Y)});function $9(Q){return aW(KG,Q)}var DG=q("ZodISODuration",(Q,Y)=>{nX.init(Q,Y),s.init(Q,Y)});function z9(Q){return sW(DG,Q)}var LG=(Q,Y)=>{$6.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>b8(Q,X)},flatten:{value:(X)=>P8(Q,X)},addIssue:{value:(X)=>{Q.issues.push(X),Q.message=JSON.stringify(Q.issues,_1,2)}},addIssues:{value:(X)=>{Q.issues.push(...X),Q.message=JSON.stringify(Q.issues,_1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},JZ=q("ZodError",LG),b0=q("ZodError",LG,{Parent:Error});var FG=z6(b0),qG=J6(b0),OG=U4(b0),MG=B4(b0),VG=I8(b0),NG=E8(b0),ZG=T8(b0),wG=S8(b0),jG=R8(b0),PG=C8(b0),bG=k8(b0),IG=v8(b0);var X0=q("ZodType",(Q,Y)=>{return o.init(Q,Y),Q.def=Y,Q.type=Y.type,Object.defineProperty(Q,"_def",{value:Y}),Q.check=(...X)=>{return Q.clone(m.mergeDefs(Y,{checks:[...Y.checks??[],...X.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},Q.clone=(X,W)=>v0(Q,X,W),Q.brand=()=>Q,Q.register=(X,W)=>{return X.add(Q,W),Q},Q.parse=(X,W)=>FG(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>OG(Q,X,W),Q.parseAsync=async(X,W)=>qG(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>MG(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>VG(Q,X,W),Q.decode=(X,W)=>NG(Q,X,W),Q.encodeAsync=async(X,W)=>ZG(Q,X,W),Q.decodeAsync=async(X,W)=>wG(Q,X,W),Q.safeEncode=(X,W)=>jG(Q,X,W),Q.safeDecode=(X,W)=>PG(Q,X,W),Q.safeEncodeAsync=async(X,W)=>bG(Q,X,W),Q.safeDecodeAsync=async(X,W)=>IG(Q,X,W),Q.refine=(X,W)=>Q.check(e3(X,W)),Q.superRefine=(X)=>Q.check(QU(X)),Q.overwrite=(X)=>Q.check(P1(X)),Q.optional=()=>Y0(Q),Q.nullable=()=>SG(Q),Q.nullish=()=>Y0(SG(Q)),Q.nonoptional=(X)=>r3(Q,X),Q.array=()=>u(Q),Q.or=(X)=>d([Q,X]),Q.and=(X)=>N6(Q,X),Q.transform=(X)=>H9(Q,xG(X)),Q.default=(X)=>p3(Q,X),Q.prefault=(X)=>n3(Q,X),Q.catch=(X)=>o3(Q,X),Q.pipe=(X)=>H9(Q,X),Q.readonly=()=>s3(Q),Q.describe=(X)=>{let W=Q.clone();return D4.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return D4.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return D4.get(Q);let W=Q.clone();return D4.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),RG=q("_ZodString",(Q,Y)=>{K6.init(Q,Y),X0.init(Q,Y);let X=Q._zod.bag;Q.format=X.format??null,Q.minLength=X.minimum??null,Q.maxLength=X.maximum??null,Q.regex=(...W)=>Q.check(rQ(...W)),Q.includes=(...W)=>Q.check(tQ(...W)),Q.startsWith=(...W)=>Q.check(aQ(...W)),Q.endsWith=(...W)=>Q.check(sQ(...W)),Q.min=(...W)=>Q.check(u1(...W)),Q.max=(...W)=>Q.check(q6(...W)),Q.length=(...W)=>Q.check(O6(...W)),Q.nonempty=(...W)=>Q.check(u1(1,...W)),Q.lowercase=(W)=>Q.check(dQ(W)),Q.uppercase=(W)=>Q.check(oQ(W)),Q.trim=()=>Q.check(Q9()),Q.normalize=(...W)=>Q.check(eQ(...W)),Q.toLowerCase=()=>Q.check(Y9()),Q.toUpperCase=()=>Q.check(X9())}),K3=q("ZodString",(Q,Y)=>{K6.init(Q,Y),RG.init(Q,Y),Q.email=(X)=>Q.check(TW(D3,X)),Q.url=(X)=>Q.check(vW(L3,X)),Q.jwt=(X)=>Q.check(dW(S3,X)),Q.emoji=(X)=>Q.check(xW(F3,X)),Q.guid=(X)=>Q.check(nQ(EG,X)),Q.uuid=(X)=>Q.check(SW(V6,X)),Q.uuidv4=(X)=>Q.check(RW(V6,X)),Q.uuidv6=(X)=>Q.check(CW(V6,X)),Q.uuidv7=(X)=>Q.check(kW(V6,X)),Q.nanoid=(X)=>Q.check(_W(q3,X)),Q.guid=(X)=>Q.check(nQ(EG,X)),Q.cuid=(X)=>Q.check(gW(O3,X)),Q.cuid2=(X)=>Q.check(yW(M3,X)),Q.ulid=(X)=>Q.check(uW(V3,X)),Q.base64=(X)=>Q.check(iW(I3,X)),Q.base64url=(X)=>Q.check(nW(E3,X)),Q.xid=(X)=>Q.check(hW(N3,X)),Q.ksuid=(X)=>Q.check(fW(Z3,X)),Q.ipv4=(X)=>Q.check(lW(w3,X)),Q.ipv6=(X)=>Q.check(mW(j3,X)),Q.cidrv4=(X)=>Q.check(cW(P3,X)),Q.cidrv6=(X)=>Q.check(pW(b3,X)),Q.e164=(X)=>Q.check(rW(T3,X)),Q.datetime=(X)=>Q.check(W9(X)),Q.date=(X)=>Q.check(G9(X)),Q.time=(X)=>Q.check($9(X)),Q.duration=(X)=>Q.check(z9(X))});function F(Q){return EW(K3,Q)}var s=q("ZodStringFormat",(Q,Y)=>{t.init(Q,Y),RG.init(Q,Y)}),D3=q("ZodEmail",(Q,Y)=>{xX.init(Q,Y),s.init(Q,Y)});var EG=q("ZodGUID",(Q,Y)=>{kX.init(Q,Y),s.init(Q,Y)});var V6=q("ZodUUID",(Q,Y)=>{vX.init(Q,Y),s.init(Q,Y)});var L3=q("ZodURL",(Q,Y)=>{_X.init(Q,Y),s.init(Q,Y)});var F3=q("ZodEmoji",(Q,Y)=>{gX.init(Q,Y),s.init(Q,Y)});var q3=q("ZodNanoID",(Q,Y)=>{yX.init(Q,Y),s.init(Q,Y)});var O3=q("ZodCUID",(Q,Y)=>{uX.init(Q,Y),s.init(Q,Y)});var M3=q("ZodCUID2",(Q,Y)=>{hX.init(Q,Y),s.init(Q,Y)});var V3=q("ZodULID",(Q,Y)=>{fX.init(Q,Y),s.init(Q,Y)});var N3=q("ZodXID",(Q,Y)=>{lX.init(Q,Y),s.init(Q,Y)});var Z3=q("ZodKSUID",(Q,Y)=>{mX.init(Q,Y),s.init(Q,Y)});var w3=q("ZodIPv4",(Q,Y)=>{rX.init(Q,Y),s.init(Q,Y)});var j3=q("ZodIPv6",(Q,Y)=>{dX.init(Q,Y),s.init(Q,Y)});var P3=q("ZodCIDRv4",(Q,Y)=>{oX.init(Q,Y),s.init(Q,Y)});var b3=q("ZodCIDRv6",(Q,Y)=>{tX.init(Q,Y),s.init(Q,Y)});var I3=q("ZodBase64",(Q,Y)=>{sX.init(Q,Y),s.init(Q,Y)});var E3=q("ZodBase64URL",(Q,Y)=>{eX.init(Q,Y),s.init(Q,Y)});var T3=q("ZodE164",(Q,Y)=>{QW.init(Q,Y),s.init(Q,Y)});var S3=q("ZodJWT",(Q,Y)=>{YW.init(Q,Y),s.init(Q,Y)});var CG=q("ZodNumber",(Q,Y)=>{cQ.init(Q,Y),X0.init(Q,Y),Q.gt=(W,G)=>Q.check(L6(W,G)),Q.gte=(W,G)=>Q.check(F4(W,G)),Q.min=(W,G)=>Q.check(F4(W,G)),Q.lt=(W,G)=>Q.check(D6(W,G)),Q.lte=(W,G)=>Q.check(L4(W,G)),Q.max=(W,G)=>Q.check(L4(W,G)),Q.int=(W)=>Q.check(TG(W)),Q.safe=(W)=>Q.check(TG(W)),Q.positive=(W)=>Q.check(L6(0,W)),Q.nonnegative=(W)=>Q.check(F4(0,W)),Q.negative=(W)=>Q.check(D6(0,W)),Q.nonpositive=(W)=>Q.check(L4(0,W)),Q.multipleOf=(W,G)=>Q.check(F6(W,G)),Q.step=(W,G)=>Q.check(F6(W,G)),Q.finite=()=>Q;let X=Q._zod.bag;Q.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Q.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Q.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Q.isFinite=!0,Q.format=X.format??null});function i(Q){return eW(CG,Q)}var R3=q("ZodNumberFormat",(Q,Y)=>{XW.init(Q,Y),CG.init(Q,Y)});function TG(Q){return QG(R3,Q)}var C3=q("ZodBoolean",(Q,Y)=>{WW.init(Q,Y),X0.init(Q,Y)});function J0(Q){return YG(C3,Q)}var k3=q("ZodNull",(Q,Y)=>{GW.init(Q,Y),X0.init(Q,Y)});function U9(Q){return XG(k3,Q)}var v3=q("ZodUnknown",(Q,Y)=>{$W.init(Q,Y),X0.init(Q,Y)});function e(){return WG(v3)}var x3=q("ZodNever",(Q,Y)=>{zW.init(Q,Y),X0.init(Q,Y)});function _3(Q){return GG(x3,Q)}var g3=q("ZodArray",(Q,Y)=>{JW.init(Q,Y),X0.init(Q,Y),Q.element=Y.element,Q.min=(X,W)=>Q.check(u1(X,W)),Q.nonempty=(X)=>Q.check(u1(1,X)),Q.max=(X,W)=>Q.check(q6(X,W)),Q.length=(X,W)=>Q.check(O6(X,W)),Q.unwrap=()=>Q.element});function u(Q,Y){return $G(g3,Q,Y)}var kG=q("ZodObject",(Q,Y)=>{AW.init(Q,Y),X0.init(Q,Y),m.defineLazy(Q,"shape",()=>{return Y.shape}),Q.keyof=()=>M0(Object.keys(Q._zod.def.shape)),Q.catchall=(X)=>Q.clone({...Q._zod.def,catchall:X}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:_3()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(X)=>{return m.extend(Q,X)},Q.safeExtend=(X)=>{return m.safeExtend(Q,X)},Q.merge=(X)=>m.merge(Q,X),Q.pick=(X)=>m.pick(Q,X),Q.omit=(X)=>m.omit(Q,X),Q.partial=(...X)=>m.partial(_G,Q,X[0]),Q.required=(...X)=>m.required(gG,Q,X[0])});function P(Q,Y){let X={type:"object",shape:Q??{},...m.normalizeParams(Y)};return new kG(X)}function F0(Q,Y){return new kG({type:"object",shape:Q,catchall:e(),...m.normalizeParams(Y)})}var vG=q("ZodUnion",(Q,Y)=>{pQ.init(Q,Y),X0.init(Q,Y),Q.options=Y.options});function d(Q,Y){return new vG({type:"union",options:Q,...m.normalizeParams(Y)})}var y3=q("ZodDiscriminatedUnion",(Q,Y)=>{vG.init(Q,Y),BW.init(Q,Y)});function A9(Q,Y,X){return new y3({type:"union",options:Y,discriminator:Q,...m.normalizeParams(X)})}var u3=q("ZodIntersection",(Q,Y)=>{KW.init(Q,Y),X0.init(Q,Y)});function N6(Q,Y){return new u3({type:"intersection",left:Q,right:Y})}var h3=q("ZodRecord",(Q,Y)=>{DW.init(Q,Y),X0.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function Q0(Q,Y,X){return new h3({type:"record",keyType:Q,valueType:Y,...m.normalizeParams(X)})}var J9=q("ZodEnum",(Q,Y)=>{LW.init(Q,Y),X0.init(Q,Y),Q.enum=Y.entries,Q.options=Object.values(Y.entries);let X=new Set(Object.keys(Y.entries));Q.extract=(W,G)=>{let $={};for(let z of W)if(X.has(z))$[z]=Y.entries[z];else throw Error(`Key ${z} not found in enum`);return new J9({...Y,checks:[],...m.normalizeParams(G),entries:$})},Q.exclude=(W,G)=>{let $={...Y.entries};for(let z of W)if(X.has(z))delete $[z];else throw Error(`Key ${z} not found in enum`);return new J9({...Y,checks:[],...m.normalizeParams(G),entries:$})}});function M0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new J9({type:"enum",entries:X,...m.normalizeParams(Y)})}var f3=q("ZodLiteral",(Q,Y)=>{FW.init(Q,Y),X0.init(Q,Y),Q.values=new Set(Y.values),Object.defineProperty(Q,"value",{get(){if(Y.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return Y.values[0]}})});function b(Q,Y){return new f3({type:"literal",values:Array.isArray(Q)?Q:[Q],...m.normalizeParams(Y)})}var l3=q("ZodTransform",(Q,Y)=>{qW.init(Q,Y),X0.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new G4(Q.constructor.name);X.addIssue=($)=>{if(typeof $==="string")X.issues.push(m.issue($,X.value,Y));else{let z=$;if(z.fatal)z.continue=!1;z.code??(z.code="custom"),z.input??(z.input=X.value),z.inst??(z.inst=Q),X.issues.push(m.issue(z))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then(($)=>{return X.value=$,X});return X.value=G,X}});function xG(Q){return new l3({type:"transform",transform:Q})}var _G=q("ZodOptional",(Q,Y)=>{OW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function Y0(Q){return new _G({type:"optional",innerType:Q})}var m3=q("ZodNullable",(Q,Y)=>{MW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function SG(Q){return new m3({type:"nullable",innerType:Q})}var c3=q("ZodDefault",(Q,Y)=>{VW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function p3(Q,Y){return new c3({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var i3=q("ZodPrefault",(Q,Y)=>{NW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function n3(Q,Y){return new i3({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var gG=q("ZodNonOptional",(Q,Y)=>{ZW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function r3(Q,Y){return new gG({type:"nonoptional",innerType:Q,...m.normalizeParams(Y)})}var d3=q("ZodCatch",(Q,Y)=>{wW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function o3(Q,Y){return new d3({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var t3=q("ZodPipe",(Q,Y)=>{jW.init(Q,Y),X0.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function H9(Q,Y){return new t3({type:"pipe",in:Q,out:Y})}var a3=q("ZodReadonly",(Q,Y)=>{PW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function s3(Q){return new a3({type:"readonly",innerType:Q})}var yG=q("ZodCustom",(Q,Y)=>{bW.init(Q,Y),X0.init(Q,Y)});function uG(Q,Y){return zG(yG,Q??(()=>!0),Y)}function e3(Q,Y={}){return JG(yG,Q,Y)}function QU(Q){return HG(Q)}function B9(Q,Y){return H9(xG(Q),Y)}T0(iQ());var K9="2025-11-25";var hG=[K9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],U1="io.modelcontextprotocol/related-task",w6="2.0",U0=uG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),fG=d([F(),i().int()]),lG=F(),Xw=F0({ttl:d([i(),U9()]).optional(),pollInterval:i().optional()}),YU=P({ttl:i().optional()}),XU=P({taskId:F()}),D9=F0({progressToken:fG.optional(),[U1]:XU.optional()}),I0=P({_meta:D9.optional()}),M4=I0.extend({task:YU.optional()}),mG=(Q)=>M4.safeParse(Q).success,A0=P({method:F(),params:I0.loose().optional()}),S0=P({_meta:D9.optional()}),R0=P({method:F(),params:S0.loose().optional()}),B0=F0({_meta:D9.optional()}),j6=d([F(),i().int()]),cG=P({jsonrpc:b(w6),id:j6,...A0.shape}).strict(),L9=(Q)=>cG.safeParse(Q).success,pG=P({jsonrpc:b(w6),...R0.shape}).strict(),iG=(Q)=>pG.safeParse(Q).success,F9=P({jsonrpc:b(w6),id:j6,result:B0}).strict(),V4=(Q)=>F9.safeParse(Q).success;var h;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(h||(h={}));var q9=P({jsonrpc:b(w6),id:j6.optional(),error:P({code:i().int(),message:F(),data:e().optional()})}).strict();var nG=(Q)=>q9.safeParse(Q).success;var Ww=d([cG,pG,F9,q9]),Gw=d([F9,q9]),P6=B0.strict(),WU=S0.extend({requestId:j6.optional(),reason:F().optional()}),b6=R0.extend({method:b("notifications/cancelled"),params:WU}),GU=P({src:F(),mimeType:F().optional(),sizes:u(F()).optional(),theme:M0(["light","dark"]).optional()}),N4=P({icons:u(GU).optional()}),f1=P({name:F(),title:F().optional()}),rG=f1.extend({...f1.shape,...N4.shape,version:F(),websiteUrl:F().optional(),description:F().optional()}),$U=N6(P({applyDefaults:J0().optional()}),Q0(F(),e())),zU=B9((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},N6(P({form:$U.optional(),url:U0.optional()}),Q0(F(),e()).optional())),JU=F0({list:U0.optional(),cancel:U0.optional(),requests:F0({sampling:F0({createMessage:U0.optional()}).optional(),elicitation:F0({create:U0.optional()}).optional()}).optional()}),HU=F0({list:U0.optional(),cancel:U0.optional(),requests:F0({tools:F0({call:U0.optional()}).optional()}).optional()}),UU=P({experimental:Q0(F(),U0).optional(),sampling:P({context:U0.optional(),tools:U0.optional()}).optional(),elicitation:zU.optional(),roots:P({listChanged:J0().optional()}).optional(),tasks:JU.optional()}),AU=I0.extend({protocolVersion:F(),capabilities:UU,clientInfo:rG}),O9=A0.extend({method:b("initialize"),params:AU});var BU=P({experimental:Q0(F(),U0).optional(),logging:U0.optional(),completions:U0.optional(),prompts:P({listChanged:J0().optional()}).optional(),resources:P({subscribe:J0().optional(),listChanged:J0().optional()}).optional(),tools:P({listChanged:J0().optional()}).optional(),tasks:HU.optional()}),KU=B0.extend({protocolVersion:F(),capabilities:BU,serverInfo:rG,instructions:F().optional()}),M9=R0.extend({method:b("notifications/initialized"),params:S0.optional()});var I6=A0.extend({method:b("ping"),params:I0.optional()}),DU=P({progress:i(),total:Y0(i()),message:Y0(F())}),LU=P({...S0.shape,...DU.shape,progressToken:fG}),E6=R0.extend({method:b("notifications/progress"),params:LU}),FU=I0.extend({cursor:lG.optional()}),Z4=A0.extend({params:FU.optional()}),w4=B0.extend({nextCursor:lG.optional()}),qU=M0(["working","input_required","completed","failed","cancelled"]),j4=P({taskId:F(),status:qU,ttl:d([i(),U9()]),createdAt:F(),lastUpdatedAt:F(),pollInterval:Y0(i()),statusMessage:Y0(F())}),l1=B0.extend({task:j4}),OU=S0.merge(j4),P4=R0.extend({method:b("notifications/tasks/status"),params:OU}),T6=A0.extend({method:b("tasks/get"),params:I0.extend({taskId:F()})}),S6=B0.merge(j4),R6=A0.extend({method:b("tasks/result"),params:I0.extend({taskId:F()})}),$w=B0.loose(),C6=Z4.extend({method:b("tasks/list")}),k6=w4.extend({tasks:u(j4)}),v6=A0.extend({method:b("tasks/cancel"),params:I0.extend({taskId:F()})}),dG=B0.merge(j4),oG=P({uri:F(),mimeType:Y0(F()),_meta:Q0(F(),e()).optional()}),tG=oG.extend({text:F()}),V9=F().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),aG=oG.extend({blob:V9}),b4=M0(["user","assistant"]),m1=P({audience:u(b4).optional(),priority:i().min(0).max(1).optional(),lastModified:O4.datetime({offset:!0}).optional()}),sG=P({...f1.shape,...N4.shape,uri:F(),description:Y0(F()),mimeType:Y0(F()),annotations:m1.optional(),_meta:Y0(F0({}))}),MU=P({...f1.shape,...N4.shape,uriTemplate:F(),description:Y0(F()),mimeType:Y0(F()),annotations:m1.optional(),_meta:Y0(F0({}))}),N9=Z4.extend({method:b("resources/list")}),VU=w4.extend({resources:u(sG)}),NU=Z4.extend({method:b("resources/templates/list")}),ZU=w4.extend({resourceTemplates:u(MU)}),Z9=I0.extend({uri:F()}),wU=Z9,w9=A0.extend({method:b("resources/read"),params:wU}),jU=B0.extend({contents:u(d([tG,aG]))}),PU=R0.extend({method:b("notifications/resources/list_changed"),params:S0.optional()}),bU=Z9,IU=A0.extend({method:b("resources/subscribe"),params:bU}),EU=Z9,TU=A0.extend({method:b("resources/unsubscribe"),params:EU}),SU=S0.extend({uri:F()}),RU=R0.extend({method:b("notifications/resources/updated"),params:SU}),CU=P({name:F(),description:Y0(F()),required:Y0(J0())}),kU=P({...f1.shape,...N4.shape,description:Y0(F()),arguments:Y0(u(CU)),_meta:Y0(F0({}))}),vU=Z4.extend({method:b("prompts/list")}),xU=w4.extend({prompts:u(kU)}),_U=I0.extend({name:F(),arguments:Q0(F(),F()).optional()}),gU=A0.extend({method:b("prompts/get"),params:_U}),j9=P({type:b("text"),text:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),P9=P({type:b("image"),data:V9,mimeType:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),b9=P({type:b("audio"),data:V9,mimeType:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),yU=P({type:b("tool_use"),name:F(),id:F(),input:Q0(F(),e()),_meta:Q0(F(),e()).optional()}),uU=P({type:b("resource"),resource:d([tG,aG]),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),hU=sG.extend({type:b("resource_link")}),I9=d([j9,P9,b9,hU,uU]),fU=P({role:b4,content:I9}),lU=B0.extend({description:F().optional(),messages:u(fU)}),mU=R0.extend({method:b("notifications/prompts/list_changed"),params:S0.optional()}),cU=P({title:F().optional(),readOnlyHint:J0().optional(),destructiveHint:J0().optional(),idempotentHint:J0().optional(),openWorldHint:J0().optional()}),pU=P({taskSupport:M0(["required","optional","forbidden"]).optional()}),eG=P({...f1.shape,...N4.shape,description:F().optional(),inputSchema:P({type:b("object"),properties:Q0(F(),U0).optional(),required:u(F()).optional()}).catchall(e()),outputSchema:P({type:b("object"),properties:Q0(F(),U0).optional(),required:u(F()).optional()}).catchall(e()).optional(),annotations:cU.optional(),execution:pU.optional(),_meta:Q0(F(),e()).optional()}),E9=Z4.extend({method:b("tools/list")}),iU=w4.extend({tools:u(eG)}),x6=B0.extend({content:u(I9).default([]),structuredContent:Q0(F(),e()).optional(),isError:J0().optional()}),zw=x6.or(B0.extend({toolResult:e()})),nU=M4.extend({name:F(),arguments:Q0(F(),e()).optional()}),I4=A0.extend({method:b("tools/call"),params:nU}),rU=R0.extend({method:b("notifications/tools/list_changed"),params:S0.optional()}),Jw=P({autoRefresh:J0().default(!0),debounceMs:i().int().nonnegative().default(300)}),E4=M0(["debug","info","notice","warning","error","critical","alert","emergency"]),dU=I0.extend({level:E4}),T9=A0.extend({method:b("logging/setLevel"),params:dU}),oU=S0.extend({level:E4,logger:F().optional(),data:e()}),tU=R0.extend({method:b("notifications/message"),params:oU}),aU=P({name:F().optional()}),sU=P({hints:u(aU).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),eU=P({mode:M0(["auto","required","none"]).optional()}),QA=P({type:b("tool_result"),toolUseId:F().describe("The unique identifier for the corresponding tool call."),content:u(I9).default([]),structuredContent:P({}).loose().optional(),isError:J0().optional(),_meta:Q0(F(),e()).optional()}),YA=A9("type",[j9,P9,b9]),Z6=A9("type",[j9,P9,b9,yU,QA]),XA=P({role:b4,content:d([Z6,u(Z6)]),_meta:Q0(F(),e()).optional()}),WA=M4.extend({messages:u(XA),modelPreferences:sU.optional(),systemPrompt:F().optional(),includeContext:M0(["none","thisServer","allServers"]).optional(),temperature:i().optional(),maxTokens:i().int(),stopSequences:u(F()).optional(),metadata:U0.optional(),tools:u(eG).optional(),toolChoice:eU.optional()}),GA=A0.extend({method:b("sampling/createMessage"),params:WA}),S9=B0.extend({model:F(),stopReason:Y0(M0(["endTurn","stopSequence","maxTokens"]).or(F())),role:b4,content:YA}),R9=B0.extend({model:F(),stopReason:Y0(M0(["endTurn","stopSequence","maxTokens","toolUse"]).or(F())),role:b4,content:d([Z6,u(Z6)])}),$A=P({type:b("boolean"),title:F().optional(),description:F().optional(),default:J0().optional()}),zA=P({type:b("string"),title:F().optional(),description:F().optional(),minLength:i().optional(),maxLength:i().optional(),format:M0(["email","uri","date","date-time"]).optional(),default:F().optional()}),JA=P({type:M0(["number","integer"]),title:F().optional(),description:F().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),HA=P({type:b("string"),title:F().optional(),description:F().optional(),enum:u(F()),default:F().optional()}),UA=P({type:b("string"),title:F().optional(),description:F().optional(),oneOf:u(P({const:F(),title:F()})),default:F().optional()}),AA=P({type:b("string"),title:F().optional(),description:F().optional(),enum:u(F()),enumNames:u(F()).optional(),default:F().optional()}),BA=d([HA,UA]),KA=P({type:b("array"),title:F().optional(),description:F().optional(),minItems:i().optional(),maxItems:i().optional(),items:P({type:b("string"),enum:u(F())}),default:u(F()).optional()}),DA=P({type:b("array"),title:F().optional(),description:F().optional(),minItems:i().optional(),maxItems:i().optional(),items:P({anyOf:u(P({const:F(),title:F()}))}),default:u(F()).optional()}),LA=d([KA,DA]),FA=d([AA,BA,LA]),qA=d([FA,$A,zA,JA]),OA=M4.extend({mode:b("form").optional(),message:F(),requestedSchema:P({type:b("object"),properties:Q0(F(),qA),required:u(F()).optional()})}),MA=M4.extend({mode:b("url"),message:F(),elicitationId:F(),url:F().url()}),VA=d([OA,MA]),NA=A0.extend({method:b("elicitation/create"),params:VA}),ZA=S0.extend({elicitationId:F()}),wA=R0.extend({method:b("notifications/elicitation/complete"),params:ZA}),_6=B0.extend({action:M0(["accept","decline","cancel"]),content:B9((Q)=>Q===null?void 0:Q,Q0(F(),d([F(),i(),J0(),u(F())])).optional())}),jA=P({type:b("ref/resource"),uri:F()});var PA=P({type:b("ref/prompt"),name:F()}),bA=I0.extend({ref:d([PA,jA]),argument:P({name:F(),value:F()}),context:P({arguments:Q0(F(),F()).optional()}).optional()}),IA=A0.extend({method:b("completion/complete"),params:bA});var EA=B0.extend({completion:F0({values:u(F()).max(100),total:Y0(i().int()),hasMore:Y0(J0())})}),TA=P({uri:F().startsWith("file://"),name:F().optional(),_meta:Q0(F(),e()).optional()}),SA=A0.extend({method:b("roots/list"),params:I0.optional()}),C9=B0.extend({roots:u(TA)}),RA=R0.extend({method:b("notifications/roots/list_changed"),params:S0.optional()}),Hw=d([I6,O9,IA,T9,gU,vU,N9,NU,w9,IU,TU,I4,E9,T6,R6,C6,v6]),Uw=d([b6,E6,M9,RA,P4]),Aw=d([P6,S9,R9,_6,C9,S6,k6,l1]),Bw=d([I6,GA,NA,SA,T6,R6,C6,v6]),Kw=d([b6,E6,tU,RU,PU,rU,mU,P4,wA]),Dw=d([P6,KU,EA,lU,xU,VU,ZU,jU,x6,iU,S6,k6,l1]);class _ extends Error{constructor(Q,Y,X){super(`MCP error ${Q}: ${Y}`);this.code=Q,this.data=X,this.name="McpError"}static fromError(Q,Y,X){if(Q===h.UrlElicitationRequired&&X){let W=X;if(W.elicitations)return new Q$(W.elicitations,Y)}return new _(Q,Y,X)}}class Q$ extends _{constructor(Q,Y=`URL elicitation${Q.length>1?"s":""} required`){super(h.UrlElicitationRequired,Y,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function A1(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var CA=Symbol("Let zodToJsonSchema decide on which parser to use");var nw=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function k9(Q){let X=M6(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=UG(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function v9(Q,Y){let X=H1(Q,Y);if(!X.success)throw X.error;return X.data}var yA=60000;class x9{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(b6,(Y)=>{this._oncancel(Y)}),this.setNotificationHandler(E6,(Y)=>{this._onprogress(Y)}),this.setRequestHandler(I6,(Y)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(T6,async(Y,X)=>{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(R6,async(Y,X)=>{let W=async()=>{let G=Y.params.taskId;if(this._taskMessageQueue){let z;while(z=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(z.type==="response"||z.type==="error"){let J=z.message,H=J.id,U=this._requestResolvers.get(H);if(U)if(this._requestResolvers.delete(H),z.type==="response")U(J);else{let A=J,B=new _(A.error.code,A.error.message,A.error.data);U(B)}else{let A=z.type==="response"?"Response":"Error";this._onerror(Error(`${A} handler missing for request ${H}`))}continue}await this._transport?.send(z.message,{relatedRequestId:X.requestId})}}let $=await this._taskStore.getTask(G,X.sessionId);if(!$)throw new _(h.InvalidParams,`Task not found: ${G}`);if(!A1($.status))return await this._waitForTaskUpdate(G,X.signal),await W();if(A1($.status)){let z=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...z,_meta:{...z._meta,[U1]:{taskId:G}}}}return await W()};return await W()}),this.setRequestHandler(C6,async(Y,X)=>{try{let{tasks:W,nextCursor:G}=await this._taskStore.listTasks(Y.params?.cursor,X.sessionId);return{tasks:W,nextCursor:G,_meta:{}}}catch(W){throw new _(h.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(v6,async(Y,X)=>{try{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,`Task not found: ${Y.params.taskId}`);if(A1(W.status))throw new _(h.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(Y.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Y.params.taskId);let G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new _(h.InvalidParams,`Task not found after cancellation: ${Y.params.taskId}`);return{_meta:{},...G}}catch(W){if(W instanceof _)throw W;throw new _(h.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,Y,X,W,G=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,Y),startTime:Date.now(),timeout:Y,maxTotalTimeout:X,resetTimeoutOnProgress:G,onTimeout:W})}_resetTimeout(Q){let Y=this._timeoutInfo.get(Q);if(!Y)return!1;let X=Date.now()-Y.startTime;if(Y.maxTotalTimeout&&X>=Y.maxTotalTimeout)throw this._timeoutInfo.delete(Q),_.fromError(h.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Y.maxTotalTimeout,totalElapsed:X});return clearTimeout(Y.timeoutId),Y.timeoutId=setTimeout(Y.onTimeout,Y.timeout),!0}_cleanupTimeout(Q){let Y=this._timeoutInfo.get(Q);if(Y)clearTimeout(Y.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let Y=this.transport?.onclose;this._transport.onclose=()=>{Y?.(),this._onclose()};let X=this.transport?.onerror;this._transport.onerror=(G)=>{X?.(G),this._onerror(G)};let W=this._transport?.onmessage;this._transport.onmessage=(G,$)=>{if(W?.(G,$),V4(G)||nG(G))this._onresponse(G);else if(L9(G))this._onrequest(G,$);else if(iG(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let Y=_.fromError(h.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of Q.values())X(Y)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let Y=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(Y===void 0)return;Promise.resolve().then(()=>Y(Q)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(Q,Y){let X=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,G=Q.params?._meta?.[U1]?.taskId;if(X===void 0){let U={jsonrpc:"2.0",id:Q.id,error:{code:h.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId).catch((A)=>this._onerror(Error(`Failed to enqueue error response: ${A}`)));else W?.send(U).catch((A)=>this._onerror(Error(`Failed to send an error response: ${A}`)));return}let $=new AbortController;this._requestHandlerAbortControllers.set(Q.id,$);let z=mG(Q.params)?Q.params.task:void 0,J=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:$.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(U)=>{let A={relatedRequestId:Q.id};if(G)A.relatedTask={taskId:G};await this.notification(U,A)},sendRequest:async(U,A,B)=>{let K={...B,relatedRequestId:Q.id};if(G&&!K.relatedTask)K.relatedTask={taskId:G};let L=K.relatedTask?.taskId??G;if(L&&J)await J.updateTaskStatus(L,"input_required");return await this.request(U,A,K)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:J,taskRequestedTtl:z?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(z)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(U)=>{if($.signal.aborted)return;let A={result:U,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)},async(U)=>{if($.signal.aborted)return;let A={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(U.code)?U.code:h.InternalError,message:U.message??"Internal error",...U.data!==void 0&&{data:U.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)}).catch((U)=>this._onerror(Error(`Failed to send response: ${U}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:Y,...X}=Q.params,W=Number(Y),G=this._progressHandlers.get(W);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let $=this._responseHandlers.get(W),z=this._timeoutInfo.get(W);if(z&&$&&z.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(J){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),$(J);return}G(X)}_onresponse(Q){let Y=Number(Q.id),X=this._requestResolvers.get(Y);if(X){if(this._requestResolvers.delete(Y),V4(Q))X(Q);else{let $=new _(Q.error.code,Q.error.message,Q.error.data);X($)}return}let W=this._responseHandlers.get(Y);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(Y),this._cleanupTimeout(Y);let G=!1;if(V4(Q)&&Q.result&&typeof Q.result==="object"){let $=Q.result;if($.task&&typeof $.task==="object"){let z=$.task;if(typeof z.taskId==="string")G=!0,this._taskProgressTokens.set(z.taskId,Y)}}if(!G)this._progressHandlers.delete(Y);if(V4(Q))W(Q);else{let $=_.fromError(Q.error.code,Q.error.message,Q.error.data);W($)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,Y,X){let{task:W}=X??{};if(!W){try{yield{type:"result",result:await this.request(Q,Y,X)}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}return}let G;try{let $=await this.request(Q,l1,X);if($.task)G=$.task.taskId,yield{type:"taskCreated",task:$.task};else throw new _(h.InternalError,"Task creation did not return a task");while(!0){let z=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:z},A1(z.status)){if(z.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(z.status==="failed")yield{type:"error",error:new _(h.InternalError,`Task ${G} failed`)};else if(z.status==="cancelled")yield{type:"error",error:new _(h.InternalError,`Task ${G} was cancelled`)};return}if(z.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let J=z.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,J)),X?.signal?.throwIfAborted()}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$,task:z,relatedTask:J}=X??{};return new Promise((H,U)=>{let A=(N)=>{U(N)};if(!this._transport){A(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),z)this.assertTaskCapability(Q.method)}catch(N){A(N);return}X?.signal?.throwIfAborted();let B=this._requestMessageId++,K={...Q,jsonrpc:"2.0",id:B};if(X?.onprogress)this._progressHandlers.set(B,X.onprogress),K.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:B}};if(z)K.params={...K.params,task:z};if(J)K.params={...K.params,_meta:{...K.params?._meta||{},[U1]:J}};let L=(N)=>{this._responseHandlers.delete(B),this._progressHandlers.delete(B),this._cleanupTimeout(B),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:B,reason:String(N)}},{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((T)=>this._onerror(Error(`Failed to send cancellation: ${T}`)));let R=N instanceof _?N:new _(h.RequestTimeout,String(N));U(R)};this._responseHandlers.set(B,(N)=>{if(X?.signal?.aborted)return;if(N instanceof Error)return U(N);try{let R=H1(Y,N.result);if(!R.success)U(R.error);else H(R.data)}catch(R){U(R)}}),X?.signal?.addEventListener("abort",()=>{L(X?.signal?.reason)});let O=X?.timeout??yA,M=()=>L(_.fromError(h.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(B,O,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let Z=J?.taskId;if(Z){let N=(R)=>{let T=this._responseHandlers.get(B);if(T)T(R);else this._onerror(Error(`Response handler missing for side-channeled request ${B}`))};this._requestResolvers.set(B,N),this._enqueueTaskMessage(Z,{type:"request",message:K,timestamp:Date.now()}).catch((R)=>{this._cleanupTimeout(B),U(R)})}else this._transport.send(K,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((N)=>{this._cleanupTimeout(B),U(N)})})}async getTask(Q,Y){return this.request({method:"tasks/get",params:Q},S6,Y)}async getTaskResult(Q,Y,X){return this.request({method:"tasks/result",params:Q},Y,X)}async listTasks(Q,Y){return this.request({method:"tasks/list",params:Q},k6,Y)}async cancelTask(Q,Y){return this.request({method:"tasks/cancel",params:Q},dG,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let z={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[U1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:z,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!Y?.relatedRequestId&&!Y?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let z={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)z={...z,params:{...z.params,_meta:{...z.params?._meta||{},[U1]:Y.relatedTask}}};this._transport?.send(z,Y).catch((J)=>this._onerror(J))});return}let $={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)$={...$,params:{...$.params,_meta:{...$.params?._meta||{},[U1]:Y.relatedTask}}};await this._transport.send($,Y)}setRequestHandler(Q,Y){let X=k9(Q);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(W,G)=>{let $=v9(Q,W);return Promise.resolve(Y($,G))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,Y){let X=k9(Q);this._notificationHandlers.set(X,(W)=>{let G=v9(Q,W);return Promise.resolve(Y(G))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let Y=this._taskProgressTokens.get(Q);if(Y!==void 0)this._progressHandlers.delete(Y),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,Y,X){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,Y,X,W)}async _clearTaskQueue(Q,Y){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll(Q,Y);for(let W of X)if(W.type==="request"&&L9(W.message)){let G=W.message.id,$=this._requestResolvers.get(G);if($)$(new _(h.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,Y){let X=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)X=W.pollInterval}catch{}return new Promise((W,G)=>{if(Y.aborted){G(new _(h.InvalidRequest,"Request cancelled"));return}let $=setTimeout(W,X);Y.addEventListener("abort",()=>{clearTimeout($),G(new _(h.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,Y){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await X.createTask(W,Q.id,{method:Q.method,params:Q.params},Y)},getTask:async(W)=>{let G=await X.getTask(W,Y);if(!G)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(W,G,$)=>{await X.storeTaskResult(W,G,$,Y);let z=await X.getTask(W,Y);if(z){let J=P4.parse({method:"notifications/tasks/status",params:z});if(await this.notification(J),A1(z.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,$)=>{let z=await X.getTask(W,Y);if(!z)throw new _(h.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(A1(z.status))throw new _(h.InvalidParams,`Cannot update task "${W}" from terminal status "${z.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,$,Y);let J=await X.getTask(W,Y);if(J){let H=P4.parse({method:"notifications/tasks/status",params:J});if(await this.notification(H),A1(J.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function Y$(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function X$(Q,Y){let X={...Q};for(let W in Y){let G=W,$=Y[G];if($===void 0)continue;let z=X[G];if(Y$(z)&&Y$($))X[G]={...z,...$};else X[G]=$}return X}var v5=H8(TY(),1),x5=H8(k5(),1);function nM(){let Q=new v5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return x5.default(Q),Q}class uY{constructor(Q){this._ajv=Q??nM()}getValidator(Q){let Y="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(X)=>{if(Y(X))return{valid:!0,data:X,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(Y.errors)}}}}class hY{constructor(Q){this._server=Q}requestStream(Q,Y,X){return this._server.requestStream(Q,Y,X)}async getTask(Q,Y){return this._server.getTask({taskId:Q},Y)}async getTaskResult(Q,Y,X){return this._server.getTaskResult({taskId:Q},Y,X)}async listTasks(Q,Y){return this._server.listTasks(Q?{cursor:Q}:void 0,Y)}async cancelTask(Q,Y){return this._server.cancelTask({taskId:Q},Y)}}function _5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"tools/call":if(!Q.tools?.call)throw Error(`${X} does not support task creation for tools/call (required for ${Y})`);break;default:break}}function g5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${X} does not support task creation for sampling/createMessage (required for ${Y})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${X} does not support task creation for elicitation/create (required for ${Y})`);break;default:break}}class fY extends x9{constructor(Q,Y){super(Y);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(E4.options.map((X,W)=>[X,W])),this.isMessageIgnored=(X,W)=>{let G=this._loggingLevels.get(W);return G?this.LOG_LEVEL_SEVERITY.get(X)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=Y?.capabilities??{},this._instructions=Y?.instructions,this._jsonSchemaValidator=Y?.jsonSchemaValidator??new uY,this.setRequestHandler(O9,(X)=>this._oninitialize(X)),this.setNotificationHandler(M9,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(T9,async(X,W)=>{let G=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:$}=X.params,z=E4.safeParse($);if(z.success)this._loggingLevels.set(G,z.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new hY(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=X$(this._capabilities,Q)}setRequestHandler(Q,Y){let W=M6(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let G;if(h1(W)){let z=W;G=z._zod?.def?.value??z.value}else{let z=W;G=z._def?.value??z.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let z=async(J,H)=>{let U=H1(I4,J);if(!U.success){let L=U.error instanceof Error?U.error.message:String(U.error);throw new _(h.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:A}=U.data,B=await Promise.resolve(Y(J,H));if(A.task){let L=H1(l1,B);if(!L.success){let O=L.error instanceof Error?L.error.message:String(L.error);throw new _(h.InvalidParams,`Invalid task creation result: ${O}`)}return L.data}let K=H1(x6,B);if(!K.success){let L=K.error instanceof Error?K.error.message:String(K.error);throw new _(h.InvalidParams,`Invalid tools/call result: ${L}`)}return K.data};return super.setRequestHandler(Q,z)}return super.setRequestHandler(Q,Y)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){g5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;_5(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let Y=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:hG.includes(Y)?Y:K9,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"},P6)}async createMessage(Q,Y){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let X=Q.messages[Q.messages.length-1],W=Array.isArray(X.content)?X.content:[X.content],G=W.some((H)=>H.type==="tool_result"),$=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,z=$?Array.isArray($.content)?$.content:[$.content]:[],J=z.some((H)=>H.type==="tool_use");if(G){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!J)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(J){let H=new Set(z.filter((A)=>A.type==="tool_use").map((A)=>A.id)),U=new Set(W.filter((A)=>A.type==="tool_result").map((A)=>A.toolUseId));if(H.size!==U.size||![...H].every((A)=>U.has(A)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},R9,Y);return this.request({method:"sampling/createMessage",params:Q},S9,Y)}async elicitInput(Q,Y){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},_6,Y)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},G=await this.request({method:"elicitation/create",params:W},_6,Y);if(G.action==="accept"&&G.content&&W.requestedSchema)try{let z=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!z.valid)throw new _(h.InvalidParams,`Elicitation response content does not match requested schema: ${z.errorMessage}`)}catch($){if($ instanceof _)throw $;throw new _(h.InternalError,`Error validating elicitation response: ${$ instanceof Error?$.message:String($)}`)}return G}}}createElicitationCompletionNotifier(Q,Y){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},Y)}async listRoots(Q,Y){return this.request({method:"roots/list",params:Q},C9,Y)}async sendLoggingMessage(Q,Y){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,Y))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var y5={name:"@sequenzy/mcp",version:"0.0.82",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^5.8.0"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var lY=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],u5={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",landingPages:"/dashboard/company/{companyId}/landing-pages",landingPage:"/dashboard/company/{companyId}/landing-pages/{landingPageId}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function dM(Q){let X=(Q??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return X.length>0?X:"https://sequenzy.com"}function l0(Q){let Y=Q?.trim();return Y?Y:void 0}function r0(Q){return encodeURIComponent(Q)}function G0(Q,Y){return`${Q}${Y}`}function $0(Q,Y=""){return`/dashboard/company/${r0(Q)}${Y}`}function h5(Q,Y,X){return G0(Q,`${$0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function oM(Q,Y){let X=lY.map((W)=>[W,Y?h5(Q,Y,W):""]);return Object.fromEntries(X)}function M1(Q={},Y){let X=dM(Y),W=l0(Q.companyId),G={},$=oM(X,W);if(!W)return{appUrl:X,routeTemplates:u5,settingsTabValues:lY,urls:G,settingsUrls:$};G.dashboard=G0(X,$0(W)),G.campaigns=G0(X,$0(W,"/campaign")),G.landingPages=G0(X,$0(W,"/landing-pages")),G.sequences=G0(X,$0(W,"/sequences")),G.settings=G0(X,$0(W,"/settings")),G.emails=G0(X,$0(W,"/emails")),G.subscribers=G0(X,$0(W,"/subscribers")),G.sentEmails=G0(X,$0(W,"/sent-emails")),G.segments=G0(X,$0(W,"/segments")),G.metrics=G0(X,$0(W,"/metrics")),G.transactional=G0(X,$0(W,"/transactional"));let z=l0(Q.campaignId);if(z)G.campaign=G0(X,$0(W,`/campaign/${r0(z)}`)),G.campaignPreview=`${G.campaign}?step=review`;let J=l0(Q.landingPageId);if(J)G.landingPage=G0(X,$0(W,`/landing-pages/${r0(J)}`));let H=l0(Q.sequenceId);if(H)G.sequence=G0(X,$0(W,`/sequences/${r0(H)}`));let U=l0(Q.emailId)??l0(Q.templateId);if(U)G.email=G0(X,$0(W,`/emails/${r0(U)}`)),G.template=G.email;let A=l0(Q.transactionalId);if(A)G.transactionalEmail=G0(X,$0(W,`/transactional/${r0(A)}`));let B=l0(Q.emailSendId);if(B)G.emailSend=G0(X,$0(W,`/sent-emails/${r0(B)}`));let K=l0(Q.domainId);if(K)G.domain=G0(X,$0(W,`/settings/domain/${r0(K)}`)),G.domainVerify=`${G.domain}/verify`;let L=l0(Q.status);if(L)G.campaignList=G0(X,$0(W,`/campaign/list/${r0(L)}`)),G.sequenceList=G0(X,$0(W,`/sequences/list/${r0(L)}`));let O=l0(Q.settingsTab);if(O)G.settingsTab=h5(X,W,O);return{appUrl:X,routeTemplates:u5,settingsTabValues:lY,urls:G,settingsUrls:$}}var f5=[{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 l5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await D("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await D("GET","/api/v1/account"),W=w1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await D("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await D("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await D("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await D("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await D("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await D("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await D("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await D("GET","/api/v1/tags");break;case"sequenzy://health":Y=await D("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=M1();break;default:throw Error(`Unknown resource: ${Q}`)}return{contents:[{uri:Q,mimeType:"application/json",text:JSON.stringify(Y,null,2)}]}}catch(Y){return{contents:[{uri:Q,mimeType:"text/plain",text:x1(Y)}]}}}import{readFileSync as tM,statSync as aM}from"node:fs";import{basename as sM}from"node:path";var X8=' Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in the transactional send `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" } where the text before the colon is a {{merge tag}} path (nested paths like "order.total" or "event.plan" work) and the text after it is the comparison value. `field` may also be "attribute" (same "name:value" form) or "email"/"firstName"/"lastName" (the value is the plain comparison string). Operators: is, is_not, contains, not_contains, gt, gte, lt, lte, is_empty, is_not_empty. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block.',s4=`Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. For provider-migrated HTML from another email platform, prefer the \`html\` field instead; Sequenzy stores it as one raw HTML block to preserve the original design. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.${X8}`,Q4=`Replacement Sequenzy email blocks. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`.${X8}`,oY=`Sequenzy email blocks. Provide blocks or html for email steps. For migrated provider HTML, prefer \`html\`; Sequenzy stores it as one raw HTML block and does not recreate it as native blocks. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Blocks can include repeat blocks over array variables such as items.${X8}`,NQ="Complete Sequenzy landing page content JSON. Use this when replacing the page structure. The content must be the editor-compatible landing page schema with version, template, seo, theme, and blocks. Landing pages must include exactly one footer block and at most one form block.",eM="Optional template key for default content, such as from-scratch, waitlist, lead-magnet, launch, demo-request, webinar, newsletter, product-hunt, pricing-offer, agency-lead-gen, or feature-announcement.",m5=500,c5=500,V1={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},mY=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay"],p5={type:"object",description:"Optional send window for every email step in the sequence. When set, email actions that become due outside the window wait until the next allowed local time. Omit days to allow every day.",properties:{enabled:{type:"boolean",description:"Set false to disable the sending window when creating a sequence. For updates, prefer clearSendingWindow."},timezone:{type:"string",description:"IANA timezone for the window, e.g. Europe/Kiev or America/New_York."},startTime:{type:"string",description:"Earliest local send time in 24-hour HH:mm format, e.g. 08:00."},endTime:{type:"string",description:"Latest local send cutoff in 24-hour HH:mm format, e.g. 20:00. Must be later than startTime."},days:{type:"array",description:"Allowed local days. Use full names or short names such as monday, tuesday, mon, tue. Omit for every day.",items:{type:"string"}}},additionalProperties:!1},QV={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},tY={type:"object",description:"Wait until a date from the trigger event before this step. Use this for renewal reminders, appointment follow-ups, trial-expiry nudges, and other subscriber-specific dates. The field value must be an ISO date string or Unix timestamp.",properties:{field:{type:"string",description:"Dot-path into the trigger event properties, e.g. renews_at or booking.startsAt."},untilDateField:{type:"string",description:"Alias for field."},offset:QV,days:{type:"number",description:"Offset days shorthand. Ignored when offset is provided."},hours:{type:"number",description:"Offset hours shorthand. Ignored when offset is provided."},minutes:{type:"number",description:"Offset minutes shorthand. Ignored when offset is provided."},direction:{type:"string",enum:["before","after"],description:"Whether the offset applies before or after the resolved date. Defaults to after."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"Alias for direction."},missingAction:{type:"string",enum:["continue","exit"],description:"What to do if the event field is missing or invalid. Defaults to continue."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"Alias for missingAction."}},additionalProperties:!1},aY={type:"object",description:"Fixed delay before this step. For a dynamic wait-until-date delay, either set mode:'until_date' plus untilDateField here, or use waitUntil.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"},mode:{type:"string",enum:["duration","until_date"],description:"Use duration for a fixed wait, or until_date to resolve a date from the trigger event."},untilDateField:{type:"string",description:"For mode:'until_date', dot-path into the trigger event properties."},field:{type:"string",description:"Alias for untilDateField."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"For mode:'until_date', whether days/hours/minutes are before or after the event date. Defaults to after."},direction:{type:"string",enum:["before","after"],description:"Alias for untilOffsetDirection."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"For mode:'until_date', what to do when the field is missing or invalid. Defaults to continue."},missingAction:{type:"string",enum:["continue","exit"],description:"Alias for untilMissingAction."}},additionalProperties:!1},wQ=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],jQ=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","sequence.finished","sequence.failed"],YV=new Set(["get_account","get_app_urls","get_company","list_websites","check_website","get_integration_guide","get_subscriber","list_subscriber_notes","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_email_send","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_transactional_emails","get_transactional_email","get_stats","get_campaign_stats","get_sequence_stats","list_campaign_events","list_sequence_events","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_sequence","generate_subject_lines"]),XV=new Set(["select_company","create_company","update_company","create_api_key","add_website","add_subscriber","update_subscriber","add_subscriber_note","remove_subscriber","delete_subscriber_note","upsert_products","delete_product","attach_product_file","remove_product_file","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","delete_template","restart_ab_test","update_ab_test_variant","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_landing_page","update_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","update_sequence","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery"]),WV=new Set(["send_test_email","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","enable_sequence","resume_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery"]),GV=new Set(["remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","disable_sequence","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook"]);function $V(Q){let Y=YV.has(Q),X=XV.has(Q);if(Y===X)throw Error(`MCP tool "${Q}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:Y,destructiveHint:Y?!1:GV.has(Q),openWorldHint:WV.has(Q)}}function zV(Q){return{...Q,annotations:{...Q.annotations,...$V(Q.name)}}}var sY={status:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"],commerceProduct:["is","is_not","at_least","less_than_count"]},JV=Object.entries(sY).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),i5={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct","commerceProduct"],description:"Filter field. Use `event` for custom subscriber events, `segment` for saved segment membership, `stripeProduct`/`stripeCurrentProduct`/`stripeTrialProduct` for Stripe product-based segments, and `commerceProduct` for products purchased through commerce orders - the value is `provider:productId` (provider one of `shopify`, `woocommerce`, `api`; product ids are provider-scoped), optionally with an order-count threshold (`provider:productId:count`) for at_least/less_than_count; a bare product id matches the id on any provider. Engagement fields (`emailSent`, `emailDelivered`, `emailOpened`, `emailClicked`, `emailBounced`, `emailComplained`) accept a time range as the value or a specific campaign via `campaign:<campaign_id>`."},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${JV}.`},value:{type:"string",description:"Filter value. For custom attribute empty checks, use `attributeName:` such as `last_logged_in:`. Event examples: `saas.purchase:30d`, `saas.purchase:all`, or `saas.purchase:5:30d` for thresholds. Segment values are segment IDs. Stripe product examples: `prod_123` for bought/didn't buy/current/trialing, `prod_123:3` for payment thresholds, `prod_123:is_canceled` for products set to cancel, `prod_123:cancels_at:2026-05-26`, `prod_123:end_at:2026-05-26`, or `prod_123:start_at:7 days ago` for product-scoped dates. Engagement examples: `7d`, `30d`, `90d`, `180d`, `all` for rolling time windows, or `campaign:<campaign_id>` to scope to a specific sent campaign (use `list_campaigns` to find IDs)."}},required:["field","operator","value"],additionalProperties:!1},n5={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 eY(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(typeof Y!=="object"||Y===null)return Y;let X=Y;if(typeof X.id==="string"&&X.id.trim()!=="")return X;return{...X,id:crypto.randomUUID()}})}function Q8(Q){if(typeof Q!=="object"||Q===null)return Q;let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=eY([Y]);return Array.isArray(X)?X[0]:Y}if(Y.kind!=="group")return Q;return{...Y,id:typeof Y.id==="string"&&Y.id.trim()!==""?Y.id:crypto.randomUUID(),children:Array.isArray(Y.children)?Y.children.map(Q8):[]}}function HV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function UV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function r5(Q){if(Q==="all")return!0;let Y=Q.match(/^(\d+)d$/);if(!Y?.[1])return!1;let X=Number.parseInt(Y[1],10);return Number.isInteger(X)&&X>0}function AV(Q,Y){let X=Y.split(":");if(Q==="at_least"||Q==="less_than_count"){if(X.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let $=X.slice(0,-2).join(":").trim(),z=X.at(-2),J=X.at(-1),H=z===void 0?Number.NaN:Number.parseInt(z,10);return $&&Number.isInteger(H)&&H>0&&J!==void 0&&r5(J)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(X.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=X.slice(0,-1).join(":").trim(),G=X.at(-1);return W&&G!==void 0&&r5(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function BV(Q){let Y=Q.indexOf(":");if(Y===-1)return{productId:Q,subfilter:null,rawValue:null};let X=Q.substring(0,Y),W=Q.substring(Y+1),G=W.indexOf(":");if(G===-1)return{productId:X,subfilter:W,rawValue:null};return{productId:X,subfilter:W.substring(0,G),rawValue:W.substring(G+1)}}function KV(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function DV(Q){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(Q)}function LV(Q,Y){if(Y==="cancels_at"||Y==="cancel_at"||Y==="cancellation_at")return!0;if(Q==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(Y);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(Y)}function FV(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function qV(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let J=X.indexOf(":");if(J===-1)return null;let H=X.substring(0,J).trim(),U=Number.parseInt(X.substring(J+1).trim(),10);return H&&Number.isInteger(U)&&U>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(Q!=="stripeCurrentProduct"&&Q!=="stripeTrialProduct")return null;let{productId:W,subfilter:G,rawValue:$}=BV(X);if(!W.trim())return"Stripe product filters must include a product ID.";if(!G)return Y==="is"||Y==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let z=KV(G);if(DV(z))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!LV(Q,z))return`Unsupported Stripe product subfilter "${G}".`;if(!FV(Y))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return $?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var OV=new Set(["shopify","woocommerce","api"]);function MV(Q,Y){let X=Y.trim(),W=X.indexOf(":");if(W!==-1&&OV.has(X.substring(0,W).trim()))X=X.substring(W+1).trim();if(!X)return'Purchased Product filters must include a product ID, like "shopify:42".';if(Q!=="at_least"&&Q!=="less_than_count")return null;let G=X.lastIndexOf(":");if(G===-1)return null;let $=X.substring(0,G).trim(),z=Number.parseInt(X.substring(G+1).trim(),10);return $&&Number.isInteger(z)&&z>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function W8(Q){if(typeof Q!=="object"||Q===null)return"Segment filters must be objects.";let Y=Q,X=Y.field,W=Y.operator,G=Y.value;if(typeof X!=="string"||!(X in sY))return`Unsupported segment filter field "${String(X)}".`;if(typeof W!=="string")return`Segment filter "${X}" must include an operator.`;let $=sY[X];if(!$.includes(W))return`Operator "${W}" is not supported for ${X} filters. Use one of: ${$.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${X}" must include a value.`;if(X==="attribute"&&typeof G==="string"){if(!HV(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!UV(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let z=AV(W,G);if(z)return z}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let z=qV(X,W,G);if(z)return z}if(X==="commerceProduct"&&typeof G==="string"){let z=MV(W,G);if(z)return z}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map((J)=>J.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function G8(Q){if(typeof Q!=="object"||Q===null)return[];let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=W8(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap(G8);return[]}function N1(Q,Y,X){if(Y.html!==void 0&&Y.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`, not both.`);if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error(`\`blocks\` must be an array when calling \`${Q}\`.`);if(X?.requireContent&&Y.html===void 0&&Y.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`.`)}function ZQ(Q,Y){if(Y.labels===void 0)return;if(!Array.isArray(Y.labels))throw Error(`\`labels\` must be an array when calling \`${Q}\`.`);if(Y.labels.some((X)=>typeof X!=="string"||X.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${Q}\`.`)}function VV(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!Y&&!X)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=W8(G);return $?[$]:[]}):G8(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function NV(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(Q.name===void 0&&Q.filterJoinOperator===void 0&&!Y&&!X)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=W8(G);return $?[$]:[]}):X?G8(Q.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var cY=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection"];function pY(Q,Y,X){if(Y[X]!==void 0&&!z0(Y[X]))throw Error(`\`${X}\` must be an object when calling \`${Q}\`.`)}function d5(Q,Y,X){if(Y[X]!==void 0&&!Array.isArray(Y[X]))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`)}function ZV(Q){let Y=new Set(["companyId",...cY]),X=Object.keys(Q).filter((G)=>!Y.has(G));if(X.length>0)throw Error(`\`update_company\` accepts only company product-info fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);let W={};for(let G of cY)if(Q[G]!==void 0)W[G]=Q[G];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${cY.map((G)=>`\`${G}\``).join(", ")} when calling \`update_company\`.`);for(let G of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection"])if(Q[G]!==void 0&&typeof Q[G]!=="string")throw Error(`\`${G}\` must be a string when calling \`update_company\`.`);if(pY("update_company",Q,"brandColors"),pY("update_company",Q,"socialLinks"),pY("update_company",Q,"pricing"),d5("update_company",Q,"valueProps"),d5("update_company",Q,"testimonials"),typeof Q.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(Q.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");return W}function wV(Q){if(Q.clearEnrollmentFieldPath===!0&&Q.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(Q.clearSendingWindow===!0&&Q.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(Q.branch!==void 0&&Q.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");let Y={...Q};if(delete Y.clearEnrollmentFieldPath,delete Y.clearSendingWindow,Q.clearEnrollmentFieldPath===!0)Y.enrollmentFieldPath=null;if(Q.clearSendingWindow===!0)Y.sendingWindow=null;return Y}function jV(Q){N1("insert_sequence_step",Q,{requireContent:!0});let Y={subject:C("insert_sequence_step",Q,"subject")};for(let W of["name","previewText","html","blocks","delay","delayMs","waitUntil"])if(Q[W]!==void 0)Y[W]=Q[W];let X={steps:[Y]};if(Q.afterNodeId!==void 0)X.afterNodeId=Q.afterNodeId;return{...Q.confirmStructuralChange!==void 0&&{confirmStructuralChange:Q.confirmStructuralChange},insertSteps:X}}function PV(Q){let Y=w(Q,"subscriberId"),X=Q.fieldValues,W=X===void 0?void 0:Array.isArray(X)?X:void 0;if(X!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let G=W?.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0)??[];if(W?.some((J)=>typeof J!=="string")||W!==void 0&&G.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(Y!==void 0===G.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let $=w(Q,"fieldPath"),z=w(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...$!==void 0&&{fieldPath:$},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...z!==void 0&&{reason:z}}}function bV(Q){N1("create_campaign",Q),ZQ("create_campaign",Q);let Y=w(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0,G=Q.templateId!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(Y&&(X||W||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function IV(Q){if(w(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!z0(Q.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(Q.sendTimeOptimization!==void 0){if(typeof Q.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(Q.spreadOverHours!==void 0){if(typeof Q.spreadOverHours!=="number"||!Number.isInteger(Q.spreadOverHours)||Q.spreadOverHours<1||Q.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}}function iY(Q,Y,X){let W=new Set(["companyId","landingPageId","name","slug","content"]),G=Object.keys(Y).filter(($)=>!W.has($));if(G.length>0)throw Error(`\`${Q}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map(($)=>`\`${$}\``).join(", ")}.`);if(X.requireUpdate&&Y.name===void 0&&Y.slug===void 0&&Y.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${Q}\`.`);return{...Y.name!==void 0&&{name:Y.name},...Y.slug!==void 0&&{slug:Y.slug},...Y.content!==void 0&&{content:Y.content}}}function EV(Q){let Y=new Set(["companyId","domain","verify"]),X=Object.keys(Q).filter((W)=>!Y.has(W));if(X.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${X.length===1?"":"s"}: ${X.map((W)=>`\`${W}\``).join(", ")}.`);if(Q.domain===void 0&&Q.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...Q.domain!==void 0&&{domain:Q.domain},...typeof Q.verify==="boolean"&&{verify:Q.verify}}}function TV(Q){N1("create_transactional_email",Q);let Y=w(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(Y&&(X||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!Y&&!X&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var nY={type:"object",description:"A step to create inside a sequence path. Use type:'delay' for a standalone delay, type:'email' for an email, type:'create_discount' for a discount action, or type:'condition' for a condition gate.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","condition","webhook"],description:"Sequence 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","logic_condition","action_webhook"],description:"Advanced sequence 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/condition actions.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:oY,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},delay:aY,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:tY,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 SV(Q){if(!Q||typeof Q!=="object")return null;let Y=Q;if(Y.success!==!1)return null;if(typeof Y.error==="string")return Error(Y.error);if(Y.error&&typeof Y.error==="object"&&typeof Y.error.message==="string")return Error(Y.error.message);if(typeof Y.message==="string")return Error(Y.message);return Error("The tool returned an unsuccessful response.")}function z0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function o5(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function RV(Q){let Y=new URLSearchParams;if(typeof Q.query==="string"&&Q.query.trim()!=="")Y.set("query",Q.query.trim());if(Array.isArray(Q.tags)&&Q.tags.length>0)Y.set("tags",Q.tags.filter((X)=>typeof X==="string"&&X.trim()!=="").join(","));if(typeof Q.list==="string"&&Q.list.trim()!=="")Y.set("list",Q.list.trim());if(typeof Q.listId==="string"&&Q.listId.trim()!=="")Y.set("listId",Q.listId.trim());if(typeof Q.listName==="string"&&Q.listName.trim()!=="")Y.set("listName",Q.listName.trim());if(typeof Q.segmentId==="string"&&Q.segmentId.trim()!=="")Y.set("segmentId",Q.segmentId);if(typeof Q.status==="string"&&Q.status.trim()!=="")Y.set("status",Q.status.trim());return Y.set("page",String(Q.page)),Y.set("limit",String(Q.pageSize)),Y}async function CV(Q,Y){let X=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,W=Math.min(100,Math.max(1,X??100)),G=[],$=1,z=0,J=0,H=0;while(!0){let A=RV({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:$,pageSize:W}),B=await D("GET",`/api/v1/subscribers?${A.toString()}`,void 0,Y);z=B.pagination?.total??B.subscribers.length,J=B.pagination?.totalPages??1,H+=1,G.push(...B.subscribers??[]);let K=X!==void 0&&G.length>=X,L=B.pagination?$>=B.pagination.totalPages:(B.subscribers??[]).length<W;if(K||L)break;$+=1}let U=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:U,pagination:{page:1,limit:W,total:z,totalPages:J,fetchedPages:H},returned:U.length,truncated:X!==void 0&&z>0&&U.length<z}}function kV(Q){let Y=typeof Q.email==="string"&&Q.email.trim()!==""?Q.email.trim():void 0,X=typeof Q.externalId==="string"&&Q.externalId.trim()!==""?Q.externalId.trim():void 0;return{...Y?{email:Y}:{},...X?{externalId:X}:{}}}function C1(Q,Y){let X=kV(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function Y8(Q,Y){let X=new URLSearchParams;if(Y?.includeMachineEngagement)X.set("includeMachineEngagement","true");let W=X.toString(),G=W?`?${W}`:"";if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}${G}`;return X.set("externalId",String(Q.externalId)),`/api/v1/subscribers/external?${X.toString()}`}function t5(Q){if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}/notes`;let Y=new URLSearchParams;return Y.set("externalId",String(Q.externalId)),`/api/v1/subscribers/external/notes?${Y.toString()}`}async function rY(Q,Y,X){return D("GET",Y8(Q,X),void 0,Y)}function w(Q,Y){let X=Q[Y];if(typeof X!=="string")return;let W=X.trim();return W.length>0?W:void 0}function C(Q,Y,X){let W=w(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function m0(Q,Y,X,W){let G=w(Y,X);if(G===void 0)return;if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function dY(Q,Y,X,W){let G=C(Q,Y,X);if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function v1(Q,Y,X,W,G){let $=Y[X];if($===void 0)return;if(typeof $!=="number"||!Number.isInteger($)||$<W||$>G)throw Error(`\`${X}\` must be an integer between ${W} and ${G} when calling \`${Q}\`.`);return $}function vV(Q,Y){let X=[],W=m0(Q,Y,"eventType",mY);if(W)X.push(W);if(Y.eventTypes!==void 0){if(!Array.isArray(Y.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${Q}\`.`);Y.eventTypes.forEach((G,$)=>{if(typeof G!=="string")throw Error(`\`eventTypes\` item ${$+1} must be a string when calling \`${Q}\`.`);let z=G.trim();if(!mY.includes(z))throw Error(`\`eventTypes\` item ${$+1} must be one of ${mY.join(", ")} when calling \`${Q}\`.`);X.push(z)})}return[...new Set(X)]}function a5(Q,Y){let X=new URLSearchParams,W=vV(Q,Y);if(W.length>0)X.set("eventTypes",W.join(","));let G=m0(Q,Y,"period",["1h","24h","7d","30d","90d"]);if(G)X.set("period",G);let $=w(Y,"start");if($)X.set("start",$);let z=w(Y,"end");if(z)X.set("end",z);let J=v1(Q,Y,"page",1,1e6);if(J!==void 0)X.set("page",String(J));let H=v1(Q,Y,"limit",1,500);if(H!==void 0)X.set("limit",String(H));if(Y.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");return X}function s5(Q,Y){if(Y.events===void 0)return;if(!Array.isArray(Y.events))throw Error(`\`events\` must be an array when calling \`${Q}\`.`);let X=Y.events.map((W,G)=>{if(typeof W!=="string"||!jQ.includes(W))throw Error(`\`events\` item ${G+1} must be one of ${jQ.join(", ")} when calling \`${Q}\`.`);return W});if(X.length===0)throw Error(`\`events\` must include at least one event type when calling \`${Q}\`.`);return X}function e5(Q,Y){if(!Array.isArray(Y.emails))throw Error(`\`emails\` must be an array when calling \`${Q}\`.`);let X=[];if(Y.emails.forEach((W,G)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${Q}\`.`);let $=W.trim();if($.length>0)X.push($)}),X.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${Q}\`.`);if(X.length>m5)throw Error(`\`emails\` must include no more than ${m5} email addresses when calling \`${Q}\`. Split larger batches into multiple calls.`);return X}function QH(Q,Y,X,W){let G=Y[X];if(G===void 0)return;if(!Array.isArray(G))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`);let $=[];if(G.forEach((z,J)=>{if(typeof z!=="string")throw Error(`\`${X}\` item ${J+1} must be a string when calling \`${Q}\`.`);let H=z.trim();if(H.length>0)$.push(H)}),$.length===0)throw Error(`\`${X}\` must include at least one ${W} when calling \`${Q}\`.`);return $}function xV(Q){let X=QH("enroll_subscribers_in_sequence",Q,"emails","email address"),W=QH("enroll_subscribers_in_sequence",Q,"subscriberIds","subscriber ID"),G=(X?.length??0)+(W?.length??0);if(G===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(G>c5)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${c5} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let $=w(Q,"targetNodeId");return{...X!==void 0&&{emails:X},...W!==void 0&&{subscriberIds:W},...$!==void 0&&{targetNodeId:$}}}var _V={pdf:"application/pdf",epub:"application/epub+zip",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",txt:"text/plain",csv:"text/csv"};function gV(Q){let Y=Q.split(".").pop()?.toLowerCase()??"";return _V[Y]??null}var yV=104857600;async function uV(Q,Y){if(!B8())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let X=gV(Q);if(!X)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=aM(Q).size;if(W>yV)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=tM(Q),$=await D("POST","/api/v1/products/delivery/upload-url",{filename:sM(Q),contentType:X,fileSizeBytes:W},Y),z=await fetch($.uploadUrl,{method:"PUT",headers:{"Content-Type":X},body:G});if(!z.ok)throw Error(`File upload failed (${z.status})`);return{url:$.publicUrl,fileName:$.fileName,fileSizeBytes:W,mimeType:X}}async function $8(Q){let Y=w(Q,"companyId");if(Y)return Y;let X=w1();if(X)return X;try{return(await D("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function hV(Q,Y){let X=await $8(Y);if(!X)throw Error(`A company is required when calling \`${Q}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return X}function Y4(Q,Y){if(!z0(Q)||!Y)return Q;return{...Q,url:Y}}function YH(Q,Y){if(!z0(Q))return Q;return{...Q,...Y.campaign!==void 0&&{url:Y.campaign},...Y.campaignPreview!==void 0&&{previewUrl:Y.campaignPreview}}}function e4(Q,Y,X){if(!Array.isArray(Q)||!Y)return Q;return Q.map((W)=>{if(!z0(W))return W;let G=w(W,"id");if(!G)return W;let $=M1({companyId:Y,...X==="campaign"&&{campaignId:G},...X==="landingPage"&&{landingPageId:G},...X==="sequence"&&{sequenceId:G},...X==="template"&&{emailId:G},...X==="transactional"&&{transactionalId:G}});if(X==="campaign")return YH(W,$.urls);let z=X==="sequence"?$.urls.sequence:X==="landingPage"?$.urls.landingPage:X==="template"?$.urls.email:$.urls.transactionalEmail;return Y4(W,z)})}function fV(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!z0(Y))return Y;let X=w(Y,"id");if(!X)return Y;let W=M1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var XH=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","update_sequence","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function lV(Q,Y,X){if(!z0(X)||!XH.has(Q))return X;let W=z0(X.company)?X.company:void 0,$=w(X,"selectedCompanyId")??w(X,"currentCompanyId")??w(X,"companyId")??(W?w(W,"id"):void 0)??(W?w(W,"companyId"):void 0)??await $8(Y);if(!$)return X;let z=z0(X.campaign)?X.campaign:void 0,J=z0(X.sequence)?X.sequence:void 0,H=z0(X.landingPage)?X.landingPage:void 0,U=z0(X.template)?X.template:void 0,A=z0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,B={companyId:$,campaignId:w(Y,"campaignId")??w(X,"campaignId")??(z?w(z,"id"):void 0),landingPageId:w(Y,"landingPageId")??w(X,"landingPageId")??(H?w(H,"id"):void 0),sequenceId:w(Y,"sequenceId")??w(X,"sequenceId")??(J?w(J,"id"):void 0),emailId:w(X,"templateId")??(U?w(U,"id"):void 0)??(A?w(A,"emailId"):void 0)??w(Y,"templateId"),transactionalId:w(Y,"transactionalId")??(A?w(A,"id"):void 0)??w(Y,"idOrSlug"),emailSendId:w(Y,"emailSendId")??w(X,"emailSendId")??(z0(X.emailSend)?w(X.emailSend,"id"):void 0),status:w(Y,"status")},K=M1(B),L=W?M1({companyId:$}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:fV(X.companies)},...Array.isArray(X.campaigns)&&{campaigns:e4(X.campaigns,$,"campaign")},...Array.isArray(X.landingPages)&&{landingPages:e4(X.landingPages,$,"landingPage")},...Array.isArray(X.sequences)&&{sequences:e4(X.sequences,$,"sequence")},...Array.isArray(X.templates)&&{templates:e4(X.templates,$,"template")},...Array.isArray(X.transactional)&&{transactional:e4(X.transactional,$,"transactional")},...W&&L!==void 0&&{company:{...W,url:L.urls.dashboard,settingsUrl:L.urls.settings}},...z&&K.urls.campaign!==void 0&&{campaign:YH(z,K.urls)},...J&&K.urls.sequence!==void 0&&{sequence:Y4(J,K.urls.sequence)},...H&&K.urls.landingPage!==void 0&&{landingPage:Y4(H,K.urls.landingPage)},...U&&K.urls.email!==void 0&&{template:Y4(U,K.urls.email)},...A&&K.urls.transactionalEmail!==void 0&&{transactional:Y4(A,K.urls.transactionalEmail)},...z0(X.emailSend)&&K.urls.emailSend!==void 0&&{emailSend:Y4(X.emailSend,K.urls.emailSend)},appUrls:K.urls}}var mV={type:"boolean",description:"Whether the Sequenzy operation succeeded."},cV={type:"string",description:"Human-readable status, confirmation, or next-step message."},pV={type:"string",description:"Additional context about the result."};function E0(Q){return{type:"object",description:Q,additionalProperties:!0}}function iV(Q){return{type:"array",description:Q,items:E0("One item in the returned collection.")}}function k(Q){return{type:"string",description:Q}}function j0(Q){return{type:"number",description:Q}}function k1(Q){return{type:"boolean",description:Q}}function V(Q){return E0(`The ${Q} record returned by Sequenzy.`)}function p(Q){return iV(`List of ${Q} records returned by Sequenzy.`)}var nV={appUrls:E0("Dashboard URLs for relevant Sequenzy resources."),url:k("Primary dashboard URL for this result."),settingsUrl:k("Company settings URL when available.")},rV={success:mV,message:cV,note:pV,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:E0("One returned item.")},value:E0("Fallback object wrapper used only when a tool returns a non-object value.")},dV={get_account:{account:V("account"),companies:p("company"),currentCompanyId:k("Company ID selected by the authenticated API key, when available."),selectedCompanyId:k("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:k("Selected company ID."),companyName:k("Selected company name.")},get_app_urls:{dashboard:k("Company dashboard URL."),settings:k("Company settings URL."),campaign:k("Campaign editor URL."),landingPage:k("Landing page editor URL."),sequence:k("Sequence editor URL."),email:k("Email editor URL."),transactionalEmail:k("Transactional email URL."),emailSend:k("Sent email detail URL."),domain:k("Sending domain settings URL."),urls:E0("All generated URLs keyed by resource type.")},create_company:{company:V("company"),autoSelected:k1("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:V("company")},get_company:{company:V("company")},create_api_key:{apiKey:k("Newly created API key. This secret is returned only once."),key:k("Newly created API key if the API response uses the short key field.")},list_websites:{websites:p("sender website")},add_website:{website:V("sender website")},check_website:{website:V("sender website"),ready:k1("Whether the sender website is ready."),status:k("Current processing or verification status.")},get_integration_guide:{guide:V("integration guide"),code:k("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:E0("One setup step.")}},add_subscriber:{subscriber:V("subscriber")},update_subscriber:{subscriber:V("subscriber")},remove_subscriber:{subscriber:V("subscriber"),hardDeleted:k1("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:V("subscriber")},list_subscriber_notes:{notes:p("subscriber note")},add_subscriber_note:{note:V("subscriber note")},delete_subscriber_note:{id:k("Deleted subscriber note ID."),deleted:k1("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:p("subscriber"),pagination:E0("Pagination metadata."),returned:j0("Number of subscribers returned."),truncated:k1("Whether the result was truncated by the requested limit.")},list_products:{products:p("product")},upsert_products:{products:p("product"),created:j0("Number of products created."),updated:j0("Number of products updated.")},delete_product:{productId:k("Deleted product ID.")},attach_product_file:{product:V("product"),delivery:V("digital delivery file")},remove_product_file:{product:V("product")},sync_products:{job:V("product sync job"),jobId:k("Queued product sync job ID.")},list_tags:{tags:p("tag")},create_tag:{tag:V("tag")},update_tag:{tag:V("tag")},delete_tag:{tagId:k("Deleted tag ID.")},list_lists:{lists:p("list")},create_list:{list:V("list")},update_list:{list:V("list")},delete_list:{listId:k("Deleted list ID.")},add_subscribers_to_list:{list:V("list"),added:j0("Number of subscribers added to the list."),skipped:j0("Number of subscribers skipped.")},remove_subscribers_from_list:{list:V("list"),removed:j0("Number of subscribers removed from the list."),skipped:j0("Number of subscribers skipped.")},list_segments:{segments:p("segment")},create_segment:{segment:V("segment")},update_segment:{segment:V("segment")},delete_segment:{segmentId:k("Deleted segment ID.")},get_segment_count:{count:j0("Number of subscribers matching the segment."),segmentId:k("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:p("audience sync")},list_ad_accounts:{adAccounts:p("ad account")},create_audience_sync:{audienceSync:V("audience sync")},update_audience_sync:{audienceSync:V("audience sync")},delete_audience_sync:{audienceSyncId:k("Deleted audience sync ID.")},sync_audience_now:{audienceSync:V("audience sync"),job:V("audience sync job"),jobId:k("Queued audience sync job ID.")},list_templates:{templates:p("email template")},get_template:{template:V("email template")},create_template:{template:V("email template")},update_template:{template:V("email template")},delete_template:{templateId:k("Deleted template ID.")},list_ab_tests:{abTests:p("A/B test")},get_ab_test:{abTest:V("A/B test")},get_ab_test_stats:{abTest:V("A/B test"),stats:V("A/B test statistics")},restart_ab_test:{abTest:V("A/B test")},update_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},create_ab_test:{abTest:V("A/B test")},add_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},delete_ab_test_variant:{abTest:V("A/B test"),variantId:k("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:k("Deleted A/B test ID.")},list_campaigns:{campaigns:p("campaign")},get_campaign:{campaign:V("campaign")},get_email_send:{emailSend:V("email send")},create_campaign:{campaign:V("campaign")},update_campaign:{campaign:V("campaign")},schedule_campaign:{campaign:V("campaign"),scheduledAt:k("Scheduled send timestamp.")},send_test_email:{emailSend:V("test email send"),recipient:k("Test email recipient.")},cancel_campaign:{campaign:V("campaign")},pause_campaign:{campaign:V("campaign")},resume_campaign:{campaign:V("campaign")},delete_campaign:{campaignId:k("Deleted campaign ID.")},duplicate_campaign:{campaign:V("duplicated campaign")},resend_campaign_to_non_openers:{campaign:V("non-opener resend draft campaign"),estimatedNonOpenerCount:j0("Estimated number of subscribers who haven't opened the original campaign.")},list_landing_pages:{landingPages:p("landing page")},get_landing_page:{landingPage:V("landing page")},create_landing_page:{landingPage:V("landing page")},update_landing_page:{landingPage:V("landing page")},delete_landing_page:{landingPageId:k("Deleted landing page ID.")},publish_landing_page:{landingPage:V("landing page")},unpublish_landing_page:{landingPage:V("landing page")},connect_landing_page_domain:{landingPage:V("landing page"),domain:k("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:V("landing page"),domain:k("Landing page domain.")},list_sequences:{sequences:p("sequence")},get_sequence:{sequence:V("sequence")},create_sequence:{sequence:V("sequence")},update_sequence:{sequence:V("sequence")},insert_sequence_step:{sequence:V("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for the inserted step, including any delay node.",items:k("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:k("Inserted email template ID.")},insertedEmailCount:j0("Number of email steps inserted.")},enable_sequence:{sequence:V("sequence")},disable_sequence:{sequence:V("sequence")},pause_sequence_enrollments:{sequenceId:k("Sequence ID."),enrollmentPaused:k1("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:k("Sequence ID."),enrollmentPaused:k1("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:V("sequence"),enrollments:p("sequence enrollment"),enrolled:j0("Number of subscribers enrolled."),skipped:j0("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:V("sequence"),cancelled:j0("Number of enrollments cancelled."),skipped:j0("Number of enrollments skipped.")},delete_sequence:{sequenceId:k("Deleted sequence ID.")},list_transactional_emails:{transactional:p("transactional email")},get_transactional_email:{transactional:V("transactional email")},create_transactional_email:{transactional:V("transactional email")},update_transactional_email:{transactional:V("transactional email")},send_email:{emailSend:V("transactional email send"),transactional:V("transactional email")},get_stats:{stats:V("account or company statistics")},get_campaign_stats:{campaign:V("campaign"),stats:V("campaign statistics")},get_sequence_stats:{sequence:V("sequence"),stats:V("sequence statistics")},list_campaign_events:{events:p("campaign email event"),pagination:E0("Pagination metadata.")},list_sequence_events:{events:p("sequence email event"),pagination:E0("Pagination metadata.")},get_subscriber_activity:{activity:p("subscriber activity event"),subscribers:p("subscriber"),pagination:E0("Pagination metadata.")},list_team_members:{members:p("team member"),invitations:p("team invitation")},invite_team_member:{invitation:V("team invitation")},cancel_team_invitation:{invitationId:k("Cancelled invitation ID.")},list_conversations:{conversations:p("inbox conversation"),pagination:E0("Pagination metadata.")},get_conversation:{conversation:V("inbox conversation"),messages:p("conversation message")},reply_to_conversation:{conversation:V("inbox conversation"),message:V("conversation message")},update_conversation_status:{conversation:V("inbox conversation")},mark_conversation_read:{conversation:V("inbox conversation")},list_webhooks:{webhooks:p("outbound webhook")},create_webhook:{webhook:V("outbound webhook")},update_webhook:{webhook:V("outbound webhook")},delete_webhook:{webhookId:k("Deleted outbound webhook ID.")},test_webhook:{webhook:V("outbound webhook"),delivery:V("test webhook delivery")},list_webhook_deliveries:{deliveries:p("webhook delivery")},replay_webhook_delivery:{delivery:V("webhook delivery"),job:V("webhook replay job")},generate_email:{email:V("generated email"),html:k("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks.",items:E0("One generated email block.")},subject:k("Generated subject line."),previewText:k("Generated inbox preview text.")},generate_sequence:{sequence:V("generated sequence"),steps:p("generated sequence step")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:k("One generated subject line.")},variants:p("generated subject line variant")}};function oV(Q){let Y=dV[Q];if(Y===void 0)throw Error(`MCP tool "${Q}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${Q}\` MCP tool.`,properties:{...rV,...Y,...XH.has(Q)?nV:{}},additionalProperties:!0}}function tV(Q){return{...Q,outputSchema:oV(Q.name)}}function aV(Q){if(z0(Q))return Q;if(Array.isArray(Q))return{items:Q};return{value:Q}}var sV=[{name:"get_account",description:`Get current account information including available companies. IMPORTANT: If you have access to multiple companies, you MUST either:
|
|
29
29
|
1. Call select_company first to choose which company to work with, OR
|
|
30
30
|
2. Pass companyId explicitly in each tool call
|
|
31
31
|
|
|
@@ -143,7 +143,7 @@ IMPORTANT GUIDELINES:
|
|
|
143
143
|
IMPORTANT - PAYMENT PROVIDER INTEGRATION:
|
|
144
144
|
If the app uses Stripe, Polar, Paddle, Dodo, or Creem - tell the user to connect it in Sequenzy dashboard (Settings → Integrations).
|
|
145
145
|
Once connected, the native integration automatically handles:
|
|
146
|
-
- All saas.* events (purchase, cancelled, churn, payment_failed, etc.)
|
|
146
|
+
- All saas.* events (purchase, cancelled, trial_cancelled, churn, payment_failed, etc.)
|
|
147
147
|
- All status tags (customer, trial, cancelled, churned, past-due, etc.)
|
|
148
148
|
- Subscription attributes (MRR, plan name, billing interval)
|
|
149
149
|
|
|
@@ -179,7 +179,7 @@ BUILT-IN EVENTS (auto-fired by payment integrations):
|
|
|
179
179
|
- saas.churn - Subscription ended
|
|
180
180
|
- saas.payment_failed - Card declined/expired
|
|
181
181
|
- saas.upgrade, saas.downgrade - Plan changes
|
|
182
|
-
- saas.trial_started, saas.trial_will_end, saas.trial_ended - Trial lifecycle
|
|
182
|
+
- saas.trial_started, saas.trial_will_end, saas.trial_ended, saas.trial_cancelled - Trial lifecycle
|
|
183
183
|
- saas.refund - Refund issued
|
|
184
184
|
|
|
185
185
|
OTHER BUILT-IN EVENTS:
|