From 1e3b06250fb1ebe80a58a15eaa7fef5160a73f4b Mon Sep 17 00:00:00 2001 From: Lucas Woodward <31957045+SketchingDev@users.noreply.github.com> Date: Wed, 3 Jun 2026 21:47:42 +0100 Subject: [PATCH 1/3] Add generated-code to built artefects --- .gitattributes | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitattributes b/.gitattributes index 91b877d..cbaf56d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,2 @@ -servers/genesys-cloud-architect-mcp.js linguist-generated=true -bin/deploy-runner.js linguist-generated=true +servers/genesys-cloud-architect-mcp.js linguist-generated=true generated-code +bin/deploy-runner.js linguist-generated=true generated-code From ddfdfd0e178c8d3874363c500b3c3322c1f703b3 Mon Sep 17 00:00:00 2001 From: Lucas Woodward <31957045+SketchingDev@users.noreply.github.com> Date: Wed, 3 Jun 2026 21:49:40 +0100 Subject: [PATCH 2/3] Increase version --- package.json | 2 +- servers/genesys-cloud-architect-mcp.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 28aab86..6262b27 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "genesys-cloud-architect", - "version": "1.0.1", + "version": "1.0.2", "private": true, "packageManager": "pnpm@11.1.3+sha512.c85357fe17ca12dd23dd7071822666dfd7e3cb76fe214e3370b5ea2fb34f2a231185509b63e717f3cd0acb38dd3f8d82bcd5e8172400ae678b70ea4fbed0896d", "scripts": { diff --git a/servers/genesys-cloud-architect-mcp.js b/servers/genesys-cloud-architect-mcp.js index 1e66eac..d9adbb5 100644 --- a/servers/genesys-cloud-architect-mcp.js +++ b/servers/genesys-cloud-architect-mcp.js @@ -154,7 +154,7 @@ ${r.join(` `)}`:"";if(s?.success){let m=["Flow deployed successfully."];s.flowId&&m.push(`Flow ID: ${s.flowId}`),s.flowName&&m.push(`Flow Name: ${s.flowName}`),l({content:[{type:"text",text:m.join(` `)+g}]})}else{let m=s?.error??`Deploy runner exited with code ${h}`;l({isError:!0,content:[{type:"text",text:`Deploy failed: ${m}${g}`}]})}})})}});function pI(t){let e=t.toUpperCase();return e.endsWith("FLOW")?e:`${e}FLOW`}function iX(t,e){let i={};for(let n of e){let a=n.type??"UNKNOWN";i[a]||(i[a]=[]),i[a].push({id:n.id??"",name:n.name??"",...n.version?{version:n.version}:{},deleted:n.deleted??!1,updated:n.updated??!1})}return{flow:{id:t.id??"",name:t.name,type:pI(t.type??""),version:t.publishedVersion?.commitVersion??"1"},dependencies:i}}var dI=({architectApi:t})=>({config:{description:"Retrieves all dependencies consumed by a Genesys Cloud Architect flow. Returns the flow metadata and its dependencies grouped by type.",annotations:{title:"Flow Dependencies",readOnlyHint:!0,destructiveHint:!1},inputSchema:{flowId:Qi.string().min(1).describe("The Genesys Cloud Architect flow ID")}},handler:async({flowId:e})=>{try{let i;try{i=await t.getFlow(e)}catch{return{isError:!0,content:[{type:"text",text:`Flow "${e}" not found.`}]}}let n=pI(i.type??""),a=i.publishedVersion?.commitVersion??"1",r=[],s=1;for(;;){let l=await t.getArchitectDependencytrackingConsumedresources(i.id,a,n,{pageSize:100,pageNumber:s});if(l.entities&&r.push(...l.entities),!l.nextUri)break;s++}let o=iX(i,r);return{content:[{type:"text",text:JSON.stringify(o,null,2)}]}}catch(i){return{isError:!0,content:[{type:"text",text:`Failed to retrieve flow dependencies: ${i instanceof Error?i.message:String(i)}`}]}}}});var ry=Qi.object({GENESYS_REGION:Qi.string().min(1),GENESYS_CLIENT_ID:Qi.string().min(1),GENESYS_CLIENT_SECRET:Qi.string().min(1),DEPLOY_SCRIPT_PATH:Qi.string().min(1),PREVENT_LOGIN:Qi.enum(["TRUE","FALSE"]).default("FALSE").transform(t=>t==="TRUE")}).safeParse(process.env);if(!ry.success){let t=ry.error.issues.map(e=>e.path[0]).join(` `);console.error(`Missing required environment variables: - ${t}`),process.exit(1)}var Kt=ry.data,oy=new Cc({name:"genesys-cloud-architect",version:"1.0.1"}),hI=dI({architectApi:new sy.default.ArchitectApi});oy.registerTool("flow_dependencies",hI.config,hI.handler);var gI=cI({region:Kt.GENESYS_REGION,clientId:Kt.GENESYS_CLIENT_ID,clientSecret:Kt.GENESYS_CLIENT_SECRET,deployScriptPath:Kt.DEPLOY_SCRIPT_PATH});oy.registerTool("deploy_flow",gI.config,gI.handler);(async()=>{if(Kt.PREVENT_LOGIN)console.warn("Login for Platform API skipped. Calling tools will result in an auth failure.");else{let e=sy.default.ApiClient.instance;e.setEnvironment(Kt.GENESYS_REGION),await e.loginClientCredentialsGrant(Kt.GENESYS_CLIENT_ID,Kt.GENESYS_CLIENT_SECRET)}let t=new bc;await oy.connect(t)})().catch(t=>{console.error("Failed to start server:",t),process.exit(1)}); + ${t}`),process.exit(1)}var Kt=ry.data,oy=new Cc({name:"genesys-cloud-architect",version:"1.0.2"}),hI=dI({architectApi:new sy.default.ArchitectApi});oy.registerTool("flow_dependencies",hI.config,hI.handler);var gI=cI({region:Kt.GENESYS_REGION,clientId:Kt.GENESYS_CLIENT_ID,clientSecret:Kt.GENESYS_CLIENT_SECRET,deployScriptPath:Kt.DEPLOY_SCRIPT_PATH});oy.registerTool("deploy_flow",gI.config,gI.handler);(async()=>{if(Kt.PREVENT_LOGIN)console.warn("Login for Platform API skipped. Calling tools will result in an auth failure.");else{let e=sy.default.ApiClient.instance;e.setEnvironment(Kt.GENESYS_REGION),await e.loginClientCredentialsGrant(Kt.GENESYS_CLIENT_ID,Kt.GENESYS_CLIENT_SECRET)}let t=new bc;await oy.connect(t)})().catch(t=>{console.error("Failed to start server:",t),process.exit(1)}); /*! Bundled license information: mime-db/index.js: From 31fd920a3ad296e9ddd22af3c2681e217ca5d73e Mon Sep 17 00:00:00 2001 From: Lucas Woodward <31957045+SketchingDev@users.noreply.github.com> Date: Wed, 3 Jun 2026 22:07:25 +0100 Subject: [PATCH 3/3] Make small improvements --- bin/deploy-runner.js | 2 ++ servers/genesys-cloud-architect-mcp.js | 10 ++++++---- skills/write-flow/SKILL.md | 7 ++++++- src/deploy-runner/index.ts | 3 +++ src/mcp-server/tools/deploy-flow.ts | 16 +++++++++++++--- 5 files changed, 30 insertions(+), 8 deletions(-) diff --git a/bin/deploy-runner.js b/bin/deploy-runner.js index 32218b2..1cbcecc 100644 --- a/bin/deploy-runner.js +++ b/bin/deploy-runner.js @@ -116978,9 +116978,11 @@ import_node_https.default.get = function patchedGet(...args) { }; var origConsoleLog = console.log; var tracePrefix = "TRACE:"; +var SUPPRESSED_TRACES = [/Unknown feature being requested/]; function interceptTrace(text) { if (text.startsWith(tracePrefix)) { const msg = text.slice(tracePrefix.length).trim(); + if (SUPPRESSED_TRACES.some((p) => p.test(msg))) return true; traces.push(msg); emit("log", "info", msg); return true; diff --git a/servers/genesys-cloud-architect-mcp.js b/servers/genesys-cloud-architect-mcp.js index d9adbb5..0d17c88 100644 --- a/servers/genesys-cloud-architect-mcp.js +++ b/servers/genesys-cloud-architect-mcp.js @@ -142,17 +142,19 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. `:`[${n[l]}\r ]`;continue}a+=n[l],n[l]==="\\"?r=!0:s&&n[l]==="]"?s=!1:!s&&n[l]==="["&&(s=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return a}function _u(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===E.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,a)=>({...n,[a]:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",a]})??Ve(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let i={type:"object",additionalProperties:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return i;if(t.keyType?._def.typeName===E.ZodString&&t.keyType._def.checks?.length){let{type:n,...a}=qu(t.keyType._def,e);return{...i,propertyNames:a}}else{if(t.keyType?._def.typeName===E.ZodEnum)return{...i,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===E.ZodBranded&&t.keyType._def.type._def.typeName===E.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...a}=ku(t.keyType._def,e);return{...i,propertyNames:a}}}return i}function HS(t,e){if(e.mapStrategy==="record")return _u(t,e);let i=Y(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ve(e),n=Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ve(e);return{type:"array",maxItems:125,items:{type:"array",items:[i,n],minItems:2,maxItems:2}}}function RS(t){let e=t.values,n=Object.keys(t.values).filter(r=>typeof e[e[r]]!="number").map(r=>e[r]),a=Array.from(new Set(n.map(r=>typeof r)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:n}}function IS(t){return t.target==="openAi"?void 0:{not:Ve({...t,currentPath:[...t.currentPath,"not"]})}}function zS(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Zs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function GS(t,e){if(e.target==="openApi3")return DS(t,e);let i=t.options instanceof Map?Array.from(t.options.values()):t.options;if(i.every(n=>n._def.typeName in Zs&&(!n._def.checks||!n._def.checks.length))){let n=i.reduce((a,r)=>{let s=Zs[r._def.typeName];return s&&!a.includes(s)?[...a,s]:a},[]);return{type:n.length>1?n:n[0]}}else if(i.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=i.reduce((a,r)=>{let s=typeof r._def.value;switch(s){case"string":case"number":case"boolean":return[...a,s];case"bigint":return[...a,"integer"];case"object":if(r._def.value===null)return[...a,"null"];case"symbol":case"undefined":case"function":default:return a}},[]);if(n.length===i.length){let a=n.filter((r,s,o)=>o.indexOf(r)===s);return{type:a.length>1?a:a[0],enum:i.reduce((r,s)=>r.includes(s._def.value)?r:[...r,s._def.value],[])}}}else if(i.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:i.reduce((n,a)=>[...n,...a._def.values.filter(r=>!n.includes(r))],[])};return DS(t,e)}var DS=(t,e)=>{let i=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,a)=>Y(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${a}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return i.length?{anyOf:i}:void 0};function $S(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Zs[t.innerType._def.typeName],nullable:!0}:{type:[Zs[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let i=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return i&&{anyOf:[i,{type:"null"}]}}function NS(t,e){let i={type:"number"};if(!t.checks)return i;for(let n of t.checks)switch(n.kind){case"int":i.type="integer",am(i,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?me(i,"minimum",n.value,n.message,e):me(i,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(i.exclusiveMinimum=!0),me(i,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?me(i,"maximum",n.value,n.message,e):me(i,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(i.exclusiveMaximum=!0),me(i,"maximum",n.value,n.message,e));break;case"multipleOf":me(i,"multipleOf",n.value,n.message,e);break}return i}function US(t,e){let i=e.target==="openAi",n={type:"object",properties:{}},a=[],r=t.shape();for(let o in r){let l=r[o];if(l===void 0||l._def===void 0)continue;let u=S$(l);u&&i&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);let c=Y(l._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});c!==void 0&&(n.properties[o]=c,u||a.push(o))}a.length&&(n.required=a);let s=j$(t,e);return s!==void 0&&(n.additionalProperties=s),n}function j$(t,e){if(t.catchall._def.typeName!=="ZodNever")return Y(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function S$(t){try{return t.isOptional()}catch{return!0}}var LS=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Y(t.innerType._def,e);let i=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return i?{anyOf:[{not:Ve(e)},i]}:Ve(e)};var WS=(t,e)=>{if(e.pipeStrategy==="input")return Y(t.in._def,e);if(e.pipeStrategy==="output")return Y(t.out._def,e);let i=Y(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Y(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",i?"1":"0"]});return{allOf:[i,n].filter(a=>a!==void 0)}};function BS(t,e){return Y(t.type._def,e)}function FS(t,e){let n={type:"array",uniqueItems:!0,items:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&me(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&me(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function VS(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((i,n)=>Y(i._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((i,n)=>n===void 0?i:[...i,n],[]),additionalItems:Y(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((i,n)=>Y(i._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((i,n)=>n===void 0?i:[...i,n],[])}}function JS(t){return{not:Ve(t)}}function ZS(t){return Ve(t)}var KS=(t,e)=>Y(t.innerType._def,e);var QS=(t,e,i)=>{switch(e){case E.ZodString:return qu(t,i);case E.ZodNumber:return NS(t,i);case E.ZodObject:return US(t,i);case E.ZodBigInt:return SS(t,i);case E.ZodBoolean:return OS();case E.ZodDate:return rm(t,i);case E.ZodUndefined:return JS(i);case E.ZodNull:return zS(i);case E.ZodArray:return jS(t,i);case E.ZodUnion:case E.ZodDiscriminatedUnion:return GS(t,i);case E.ZodIntersection:return kS(t,i);case E.ZodTuple:return VS(t,i);case E.ZodRecord:return _u(t,i);case E.ZodLiteral:return qS(t,i);case E.ZodEnum:return ES(t);case E.ZodNativeEnum:return RS(t);case E.ZodNullable:return $S(t,i);case E.ZodOptional:return LS(t,i);case E.ZodMap:return HS(t,i);case E.ZodSet:return FS(t,i);case E.ZodLazy:return()=>t.getter()._def;case E.ZodPromise:return BS(t,i);case E.ZodNaN:case E.ZodNever:return IS(i);case E.ZodEffects:return MS(t,i);case E.ZodAny:return Ve(i);case E.ZodUnknown:return ZS(i);case E.ZodDefault:return TS(t,i);case E.ZodBranded:return ku(t,i);case E.ZodReadonly:return KS(t,i);case E.ZodCatch:return xS(t,i);case E.ZodPipeline:return WS(t,i);case E.ZodFunction:case E.ZodVoid:case E.ZodSymbol:return;default:return(n=>{})(e)}};function Y(t,e,i=!1){let n=e.seen.get(t);if(e.override){let o=e.override?.(t,e,n,i);if(o!==bS)return o}if(n&&!i){let o=O$(n,e);if(o!==void 0)return o}let a={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,a);let r=QS(t,t.typeName,e),s=typeof r=="function"?Y(r(),e):r;if(s&&x$(t,e,s),e.postProcess){let o=e.postProcess(s,t,e);return a.jsonSchema=s,o}return a.jsonSchema=s,s}var O$=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Eu(e.currentPath,t.path)};case"none":case"seen":return t.path.lengthe.currentPath[n]===i)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Ve(e)):e.$refStrategy==="seen"?Ve(e):void 0}},x$=(t,e,i)=>(t.description&&(i.description=t.description,e.markdownDescription&&(i.markdownDescription=t.description)),i);var lm=(t,e)=>{let i=PS(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,c])=>({...l,[u]:Y(c._def,{...i,currentPath:[...i.basePath,i.definitionPath,u]},!0)??Ve(i)}),{}):void 0,a=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,r=Y(t._def,a===void 0?i:{...i,currentPath:[...i.basePath,i.definitionPath,a]},!1)??Ve(i),s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(r.title=s),i.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[i.openAiAnyTypeName]||(n[i.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:i.$refStrategy==="relative"?"1":[...i.basePath,i.definitionPath,i.openAiAnyTypeName].join("/")}}));let o=a===void 0?n?{...r,[i.definitionPath]:n}:r:{$ref:[...i.$refStrategy==="relative"?[]:i.basePath,i.definitionPath,a].join("/"),[i.definitionPath]:{...n,[a]:r}};return i.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":(i.target==="jsonSchema2019-09"||i.target==="openAi")&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),i.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o};function T$(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function um(t,e){return ln(t)?qg(t,{target:T$(e?.target),io:e?.pipeStrategy??"input"}):lm(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function cm(t){let i=jt(t)?.method;if(!i)throw new Error("Schema is missing a method literal");let n=ru(i);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function pm(t,e){let i=Pt(t,e);if(!i.success)throw i.error;return i.data}var M$=6e4,Hu=class{constructor(e){this._options=e,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(hu,i=>{this._oncancel(i)}),this.setNotificationHandler(mu,i=>{this._onprogress(i)}),this.setRequestHandler(gu,i=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(fu,async(i,n)=>{let a=await this._taskStore.getTask(i.params.taskId,n.sessionId);if(!a)throw new L(V.InvalidParams,"Failed to retrieve task: Task not found");return{...a}}),this.setRequestHandler(vu,async(i,n)=>{let a=async()=>{let r=i.params.taskId;if(this._taskMessageQueue){let o;for(;o=await this._taskMessageQueue.dequeue(r,n.sessionId);){if(o.type==="response"||o.type==="error"){let l=o.message,u=l.id,c=this._requestResolvers.get(u);if(c)if(this._requestResolvers.delete(u),o.type==="response")c(l);else{let p=l,d=new L(p.error.code,p.error.message,p.error.data);c(d)}else{let p=o.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${u}`))}continue}await this._transport?.send(o.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(r,n.sessionId);if(!s)throw new L(V.InvalidParams,`Task not found: ${r}`);if(!Ot(s.status))return await this._waitForTaskUpdate(r,n.signal),await a();if(Ot(s.status)){let o=await this._taskStore.getTaskResult(r,n.sessionId);return this._clearTaskQueue(r),{...o,_meta:{...o._meta,[St]:{taskId:r}}}}return await a()};return await a()}),this.setRequestHandler(Cu,async(i,n)=>{try{let{tasks:a,nextCursor:r}=await this._taskStore.listTasks(i.params?.cursor,n.sessionId);return{tasks:a,nextCursor:r,_meta:{}}}catch(a){throw new L(V.InvalidParams,`Failed to list tasks: ${a instanceof Error?a.message:String(a)}`)}}),this.setRequestHandler(bu,async(i,n)=>{try{let a=await this._taskStore.getTask(i.params.taskId,n.sessionId);if(!a)throw new L(V.InvalidParams,`Task not found: ${i.params.taskId}`);if(Ot(a.status))throw new L(V.InvalidParams,`Cannot cancel task in terminal status: ${a.status}`);await this._taskStore.updateTaskStatus(i.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(i.params.taskId);let r=await this._taskStore.getTask(i.params.taskId,n.sessionId);if(!r)throw new L(V.InvalidParams,`Task not found after cancellation: ${i.params.taskId}`);return{_meta:{},...r}}catch(a){throw a instanceof L?a:new L(V.InvalidRequest,`Failed to cancel task: ${a instanceof Error?a.message:String(a)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,i,n,a,r=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(a,i),startTime:Date.now(),timeout:i,maxTotalTimeout:n,resetTimeoutOnProgress:r,onTimeout:a})}_resetTimeout(e){let i=this._timeoutInfo.get(e);if(!i)return!1;let n=Date.now()-i.startTime;if(i.maxTotalTimeout&&n>=i.maxTotalTimeout)throw this._timeoutInfo.delete(e),L.fromError(V.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:i.maxTotalTimeout,totalElapsed:n});return clearTimeout(i.timeoutId),i.timeoutId=setTimeout(i.onTimeout,i.timeout),!0}_cleanupTimeout(e){let i=this._timeoutInfo.get(e);i&&(clearTimeout(i.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let i=this.transport?.onclose;this._transport.onclose=()=>{i?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=r=>{n?.(r),this._onerror(r)};let a=this._transport?.onmessage;this._transport.onmessage=(r,s)=>{a?.(r,s),$s(r)||uS(r)?this._onresponse(r):Wg(r)?this._onrequest(r,s):lS(r)?this._onnotification(r):this._onerror(new Error(`Unknown message type: ${JSON.stringify(r)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let i=L.fromError(V.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(i)}_onerror(e){this.onerror?.(e)}_onnotification(e){let i=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;i!==void 0&&Promise.resolve().then(()=>i(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,i){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,a=this._transport,r=e.params?._meta?.[St]?.taskId;if(n===void 0){let c={jsonrpc:"2.0",id:e.id,error:{code:V.MethodNotFound,message:"Method not found"}};r&&this._taskMessageQueue?this._enqueueTaskMessage(r,{type:"error",message:c,timestamp:Date.now()},a?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):a?.send(c).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let o=rS(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,a?.sessionId):void 0,u={signal:s.signal,sessionId:a?.sessionId,_meta:e.params?._meta,sendNotification:async c=>{if(s.signal.aborted)return;let p={relatedRequestId:e.id};r&&(p.relatedTask={taskId:r}),await this.notification(c,p)},sendRequest:async(c,p,d)=>{if(s.signal.aborted)throw new L(V.ConnectionClosed,"Request was cancelled");let h={...d,relatedRequestId:e.id};r&&!h.relatedTask&&(h.relatedTask={taskId:r});let g=h.relatedTask?.taskId??r;return g&&l&&await l.updateTaskStatus(g,"input_required"),await this.request(c,p,h)},authInfo:i?.authInfo,requestId:e.id,requestInfo:i?.requestInfo,taskId:r,taskStore:l,taskRequestedTtl:o?.ttl,closeSSEStream:i?.closeSSEStream,closeStandaloneSSEStream:i?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async c=>{if(s.signal.aborted)return;let p={result:c,jsonrpc:"2.0",id:e.id};r&&this._taskMessageQueue?await this._enqueueTaskMessage(r,{type:"response",message:p,timestamp:Date.now()},a?.sessionId):await a?.send(p)},async c=>{if(s.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(c.code)?c.code:V.InternalError,message:c.message??"Internal error",...c.data!==void 0&&{data:c.data}}};r&&this._taskMessageQueue?await this._enqueueTaskMessage(r,{type:"error",message:p,timestamp:Date.now()},a?.sessionId):await a?.send(p)}).catch(c=>this._onerror(new Error(`Failed to send response: ${c}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===s&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:i,...n}=e.params,a=Number(i),r=this._progressHandlers.get(a);if(!r){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(a),o=this._timeoutInfo.get(a);if(o&&s&&o.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(l){this._responseHandlers.delete(a),this._progressHandlers.delete(a),this._cleanupTimeout(a),s(l);return}r(n)}_onresponse(e){let i=Number(e.id),n=this._requestResolvers.get(i);if(n){if(this._requestResolvers.delete(i),$s(e))n(e);else{let s=new L(e.error.code,e.error.message,e.error.data);n(s)}return}let a=this._responseHandlers.get(i);if(a===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(i),this._cleanupTimeout(i);let r=!1;if($s(e)&&e.result&&typeof e.result=="object"){let s=e.result;if(s.task&&typeof s.task=="object"){let o=s.task;typeof o.taskId=="string"&&(r=!0,this._taskProgressTokens.set(o.taskId,i))}}if(r||this._progressHandlers.delete(i),$s(e))a(e);else{let s=L.fromError(e.error.code,e.error.message,e.error.data);a(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,i,n){let{task:a}=n??{};if(!a){try{yield{type:"result",result:await this.request(e,i,n)}}catch(s){yield{type:"error",error:s instanceof L?s:new L(V.InternalError,String(s))}}return}let r;try{let s=await this.request(e,wr,n);if(s.task)r=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new L(V.InternalError,"Task creation did not return a task");for(;;){let o=await this.getTask({taskId:r},n);if(yield{type:"taskStatus",task:o},Ot(o.status)){o.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:r},i,n)}:o.status==="failed"?yield{type:"error",error:new L(V.InternalError,`Task ${r} failed`)}:o.status==="cancelled"&&(yield{type:"error",error:new L(V.InternalError,`Task ${r} was cancelled`)});return}if(o.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:r},i,n)};return}let l=o.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,l)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof L?s:new L(V.InternalError,String(s))}}}request(e,i,n){let{relatedRequestId:a,resumptionToken:r,onresumptiontoken:s,task:o,relatedTask:l}=n??{};return new Promise((u,c)=>{let p=y=>{c(y)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(y){p(y);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(h.params={...h.params,task:o}),l&&(h.params={...h.params,_meta:{...h.params?._meta||{},[St]:l}});let g=y=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(y)}},{relatedRequestId:a,resumptionToken:r,onresumptiontoken:s}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));let A=y instanceof L?y:new L(V.RequestTimeout,String(y));c(A)};this._responseHandlers.set(d,y=>{if(!n?.signal?.aborted){if(y instanceof Error)return c(y);try{let A=Pt(i,y.result);A.success?u(A.data):c(A.error)}catch(A){c(A)}}}),n?.signal?.addEventListener("abort",()=>{g(n?.signal?.reason)});let m=n?.timeout??M$,f=()=>g(L.fromError(V.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(d,m,n?.maxTotalTimeout,f,n?.resetTimeoutOnProgress??!1);let v=l?.taskId;if(v){let y=A=>{let b=this._responseHandlers.get(d);b?b(A):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,y),this._enqueueTaskMessage(v,{type:"request",message:h,timestamp:Date.now()}).catch(A=>{this._cleanupTimeout(d),c(A)})}else this._transport.send(h,{relatedRequestId:a,resumptionToken:r,onresumptiontoken:s}).catch(y=>{this._cleanupTimeout(d),c(y)})})}async getTask(e,i){return this.request({method:"tasks/get",params:e},wu,i)}async getTaskResult(e,i,n){return this.request({method:"tasks/result",params:e},i,n)}async listTasks(e,i){return this.request({method:"tasks/list",params:e},Au,i)}async cancelTask(e,i){return this.request({method:"tasks/cancel",params:e},dS,i)}async notification(e,i){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=i?.relatedTask?.taskId;if(n){let o={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[St]:i.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:o,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!i?.relatedRequestId&&!i?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let o={...e,jsonrpc:"2.0"};i?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[St]:i.relatedTask}}}),this._transport?.send(o,i).catch(l=>this._onerror(l))});return}let s={...e,jsonrpc:"2.0"};i?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[St]:i.relatedTask}}}),await this._transport.send(s,i)}setRequestHandler(e,i){let n=cm(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(a,r)=>{let s=pm(e,a);return Promise.resolve(i(s,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,i){let n=cm(e);this._notificationHandlers.set(n,a=>{let r=pm(e,a);return Promise.resolve(i(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let i=this._taskProgressTokens.get(e);i!==void 0&&(this._progressHandlers.delete(i),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,i,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let a=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,i,n,a)}async _clearTaskQueue(e,i){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,i);for(let a of n)if(a.type==="request"&&Wg(a.message)){let r=a.message.id,s=this._requestResolvers.get(r);s?(s(new L(V.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(r)):this._onerror(new Error(`Resolver missing for request ${r} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,i){let n=this._options?.defaultTaskPollInterval??1e3;try{let a=await this._taskStore?.getTask(e);a?.pollInterval&&(n=a.pollInterval)}catch{}return new Promise((a,r)=>{if(i.aborted){r(new L(V.InvalidRequest,"Request cancelled"));return}let s=setTimeout(a,n);i.addEventListener("abort",()=>{clearTimeout(s),r(new L(V.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,i){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async a=>{if(!e)throw new Error("No request provided");return await n.createTask(a,e.id,{method:e.method,params:e.params},i)},getTask:async a=>{let r=await n.getTask(a,i);if(!r)throw new L(V.InvalidParams,"Failed to retrieve task: Task not found");return r},storeTaskResult:async(a,r,s)=>{await n.storeTaskResult(a,r,s,i);let o=await n.getTask(a,i);if(o){let l=Bs.parse({method:"notifications/tasks/status",params:o});await this.notification(l),Ot(o.status)&&this._cleanupTaskProgressHandler(a)}},getTaskResult:a=>n.getTaskResult(a,i),updateTaskStatus:async(a,r,s)=>{let o=await n.getTask(a,i);if(!o)throw new L(V.InvalidParams,`Task "${a}" not found - it may have been cleaned up`);if(Ot(o.status))throw new L(V.InvalidParams,`Cannot update task "${a}" from terminal status "${o.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(a,r,s,i);let l=await n.getTask(a,i);if(l){let u=Bs.parse({method:"notifications/tasks/status",params:l});await this.notification(u),Ot(l.status)&&this._cleanupTaskProgressHandler(a)}},listTasks:a=>n.listTasks(a,i)}}};function YS(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function XS(t,e){let i={...t};for(let n in e){let a=n,r=e[a];if(r===void 0)continue;let s=i[a];YS(s)&&YS(r)?i[a]={...s,...r}:i[a]=r}return i}var WT=er(Yf(),1),BT=er(LT(),1);function qF(){let t=new WT.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,BT.default)(t),t}var mc=class{constructor(e){this._ajv=e??qF()}getValidator(e){let i="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>i(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(i.errors)}}};var fc=class{constructor(e){this._server=e}requestStream(e,i,n){return this._server.requestStream(e,i,n)}createMessageStream(e,i){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let a=e.messages[e.messages.length-1],r=Array.isArray(a.content)?a.content:[a.content],s=r.some(c=>c.type==="tool_result"),o=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=o?Array.isArray(o.content)?o.content:[o.content]:[],u=l.some(c=>c.type==="tool_use");if(s){if(r.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let c=new Set(l.filter(d=>d.type==="tool_use").map(d=>d.id)),p=new Set(r.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(c.size!==p.size||![...c].every(d=>p.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Js,i)}elicitInputStream(e,i){let n=this._server.getClientCapabilities(),a=e.mode??"form";switch(a){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let r=a==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:r},Ar,i)}async getTask(e,i){return this._server.getTask({taskId:e},i)}async getTaskResult(e,i,n){return this._server.getTaskResult({taskId:e},i,n)}async listTasks(e,i){return this._server.listTasks(e?{cursor:e}:void 0,i)}async cancelTask(e,i){return this._server.cancelTask({taskId:e},i)}};function FT(t,e,i){if(!t)throw new Error(`${i} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${i} does not support task creation for tools/call (required for ${e})`);break;default:break}}function VT(t,e,i){if(!t)throw new Error(`${i} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${i} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${i} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var wc=class extends Hu{constructor(e,i){super(i),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Vs.options.map((n,a)=>[n,a])),this.isMessageIgnored=(n,a)=>{let r=this._loggingLevels.get(a);return r?this.LOG_LEVEL_SEVERITY.get(n)this._oninitialize(n)),this.setNotificationHandler(Jg,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(im,async(n,a)=>{let r=a.sessionId||a.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,o=Vs.safeParse(s);return o.success&&this._loggingLevels.set(r,o.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new fc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=XS(this._capabilities,e)}setRequestHandler(e,i){let a=jt(e)?.method;if(!a)throw new Error("Schema is missing a method literal");let r;if(ln(a)){let o=a;r=o._zod?.def?.value??o.value}else{let o=a;r=o._def?.value??o.value}if(typeof r!="string")throw new Error("Schema method literal must be a string");if(r==="tools/call"){let o=async(l,u)=>{let c=Pt(Cr,l);if(!c.success){let g=c.error instanceof Error?c.error.message:String(c.error);throw new L(V.InvalidParams,`Invalid tools/call request: ${g}`)}let{params:p}=c.data,d=await Promise.resolve(i(l,u));if(p.task){let g=Pt(wr,d);if(!g.success){let m=g.error instanceof Error?g.error.message:String(g.error);throw new L(V.InvalidParams,`Invalid task creation result: ${m}`)}return g.data}let h=Pt(Tu,d);if(!h.success){let g=h.error instanceof Error?h.error.message:String(h.error);throw new L(V.InvalidParams,`Invalid tools/call result: ${g}`)}return h.data};return super.setRequestHandler(e,o)}return super.setRequestHandler(e,i)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){VT(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&FT(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let i=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:nS.includes(i)?i:Ug,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"},du)}async createMessage(e,i){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],a=Array.isArray(n.content)?n.content:[n.content],r=a.some(u=>u.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,o=s?Array.isArray(s.content)?s.content:[s.content]:[],l=o.some(u=>u.type==="tool_use");if(r){if(a.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(o.filter(p=>p.type==="tool_use").map(p=>p.id)),c=new Set(a.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(u.size!==c.size||![...u].every(p=>c.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},nm,i):this.request({method:"sampling/createMessage",params:e},Js,i)}async elicitInput(e,i){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let a=e;return this.request({method:"elicitation/create",params:a},Ar,i)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let a=e.mode==="form"?e:{...e,mode:"form"},r=await this.request({method:"elicitation/create",params:a},Ar,i);if(r.action==="accept"&&r.content&&a.requestedSchema)try{let o=this._jsonSchemaValidator.getValidator(a.requestedSchema)(r.content);if(!o.valid)throw new L(V.InvalidParams,`Elicitation response content does not match requested schema: ${o.errorMessage}`)}catch(s){throw s instanceof L?s:new L(V.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return r}}}createElicitationCompletionNotifier(e,i){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},i)}async listRoots(e,i){return this.request({method:"roots/list",params:e},tm,i)}async sendLoggingMessage(e,i){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,i))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}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 ZT=Symbol.for("mcp.completable");function sw(t){return!!t&&typeof t=="object"&&ZT in t}function KT(t){return t[ZT]?.complete}var JT;(function(t){t.Completable="McpCompletable"})(JT||(JT={}));var _F=/^[A-Za-z0-9._-]{1,128}$/;function HF(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!_F.test(t)){let i=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,a,r)=>r.indexOf(n)===a);return e.push(`Tool name contains invalid characters: ${i.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function RF(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let i of e)console.warn(` - ${i}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function ow(t){let e=HF(t);return RF(t,e.warnings),e.isValid}var vc=class{constructor(e){this._mcpServer=e}registerToolTask(e,i,n){let a={taskSupport:"required",...i.execution};if(a.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,i.title,i.description,i.inputSchema,i.outputSchema,i.annotations,a,i._meta,n)}};var Cc=class{constructor(e,i){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new wc(e,i)}get experimental(){return this._experimental||(this._experimental={tasks:new vc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Rt(xu)),this.server.assertCanSetRequestHandler(Rt(Cr)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(xu,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,i])=>{let n={name:e,title:i.title,description:i.description,inputSchema:(()=>{let a=mr(i.inputSchema);return a?um(a,{strictUnions:!0,pipeStrategy:"input"}):IF})(),annotations:i.annotations,execution:i.execution,_meta:i._meta};if(i.outputSchema){let a=mr(i.outputSchema);a&&(n.outputSchema=um(a,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Cr,async(e,i)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new L(V.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new L(V.InvalidParams,`Tool ${e.params.name} disabled`);let a=!!e.params.task,r=n.execution?.taskSupport,s="createTask"in n.handler;if((r==="required"||r==="optional")&&!s)throw new L(V.InternalError,`Tool ${e.params.name} has taskSupport '${r}' but was not registered with registerToolTask`);if(r==="required"&&!a)throw new L(V.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(r==="optional"&&!a&&s)return await this.handleAutomaticTaskPolling(n,e,i);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),l=await this.executeToolHandler(n,o,i);return a||await this.validateToolOutput(n,l,e.params.name),l}catch(n){if(n instanceof L&&n.code===V.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,i,n){if(!e.inputSchema)return;let r=mr(e.inputSchema)??e.inputSchema,s=await tu(r,i);if(!s.success){let o="error"in s?s.error:"Unknown error",l=au(o);throw new L(V.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return s.data}async validateToolOutput(e,i,n){if(!e.outputSchema||!("content"in i)||i.isError)return;if(!i.structuredContent)throw new L(V.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let a=mr(e.outputSchema),r=await tu(a,i.structuredContent);if(!r.success){let s="error"in r?r.error:"Unknown error",o=au(s);throw new L(V.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${o}`)}}async executeToolHandler(e,i,n){let a=e.handler;if("createTask"in a){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(e.inputSchema){let o=a;return await Promise.resolve(o.createTask(i,s))}else{let o=a;return await Promise.resolve(o.createTask(s))}}if(e.inputSchema){let s=a;return await Promise.resolve(s(i,n))}else{let s=a;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(e,i,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let a=await this.validateToolInput(e,i.params.arguments,i.params.name),r=e.handler,s={...n,taskStore:n.taskStore},o=a?await Promise.resolve(r.createTask(a,s)):await Promise.resolve(r.createTask(s)),l=o.task.taskId,u=o.task,c=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(d=>setTimeout(d,c));let p=await n.taskStore.getTask(l);if(!p)throw new L(V.InternalError,`Task ${l} not found during polling`);u=p}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Rt(Mu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Mu,async e=>{switch(e.params.ref.type){case"ref/prompt":return vS(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return CS(e),this.handleResourceCompletion(e,e.params.ref);default:throw new L(V.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,i){let n=this._registeredPrompts[i.name];if(!n)throw new L(V.InvalidParams,`Prompt ${i.name} not found`);if(!n.enabled)throw new L(V.InvalidParams,`Prompt ${i.name} disabled`);if(!n.argsSchema)return Oo;let r=jt(n.argsSchema)?.[e.params.argument.name];if(!sw(r))return Oo;let s=KT(r);if(!s)return Oo;let o=await s(e.params.argument.value,e.params.context);return YT(o)}async handleResourceCompletion(e,i){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===i.uri);if(!n){if(this._registeredResources[i.uri])return Oo;throw new L(V.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let a=n.resourceTemplate.completeCallback(e.params.argument.name);if(!a)return Oo;let r=await a(e.params.argument.value,e.params.context);return YT(r)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Rt(yu)),this.server.assertCanSetRequestHandler(Rt(Pu)),this.server.assertCanSetRequestHandler(Rt(ju)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(yu,async(e,i)=>{let n=Object.entries(this._registeredResources).filter(([r,s])=>s.enabled).map(([r,s])=>({uri:r,name:s.name,...s.metadata})),a=[];for(let r of Object.values(this._registeredResourceTemplates)){if(!r.resourceTemplate.listCallback)continue;let s=await r.resourceTemplate.listCallback(i);for(let o of s.resources)a.push({...r.metadata,...o})}return{resources:[...n,...a]}}),this.server.setRequestHandler(Pu,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([i,n])=>({name:i,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(ju,async(e,i)=>{let n=new URL(e.params.uri),a=this._registeredResources[n.toString()];if(a){if(!a.enabled)throw new L(V.InvalidParams,`Resource ${n} disabled`);return a.readCallback(n,i)}for(let r of Object.values(this._registeredResourceTemplates)){let s=r.resourceTemplate.uriTemplate.match(n.toString());if(s)return r.readCallback(n,s,i)}throw new L(V.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Rt(Su)),this.server.assertCanSetRequestHandler(Rt(Ou)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Su,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,i])=>({name:e,title:i.title,description:i.description,arguments:i.argsSchema?zF(i.argsSchema):void 0}))})),this.server.setRequestHandler(Ou,async(e,i)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new L(V.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new L(V.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let a=mr(n.argsSchema),r=await tu(a,e.params.arguments);if(!r.success){let l="error"in r?r.error:"Unknown error",u=au(l);throw new L(V.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let s=r.data,o=n.callback;return await Promise.resolve(o(s,i))}else{let a=n.callback;return await Promise.resolve(a(i))}}),this._promptHandlersInitialized=!0)}resource(e,i,...n){let a;typeof n[0]=="object"&&(a=n.shift());let r=n[0];if(typeof i=="string"){if(this._registeredResources[i])throw new Error(`Resource ${i} is already registered`);let s=this._createRegisteredResource(e,void 0,i,a,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,i,a,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,i,n,a){if(typeof i=="string"){if(this._registeredResources[i])throw new Error(`Resource ${i} is already registered`);let r=this._createRegisteredResource(e,n.title,i,n,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let r=this._createRegisteredResourceTemplate(e,n.title,i,n,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}}_createRegisteredResource(e,i,n,a,r){let s={name:e,title:i,metadata:a,readCallback:r,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:o=>{typeof o.uri<"u"&&o.uri!==n&&(delete this._registeredResources[n],o.uri&&(this._registeredResources[o.uri]=s)),typeof o.name<"u"&&(s.name=o.name),typeof o.title<"u"&&(s.title=o.title),typeof o.metadata<"u"&&(s.metadata=o.metadata),typeof o.callback<"u"&&(s.readCallback=o.callback),typeof o.enabled<"u"&&(s.enabled=o.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(e,i,n,a,r){let s={resourceTemplate:n,title:i,metadata:a,readCallback:r,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=s)),typeof u.title<"u"&&(s.title=u.title),typeof u.template<"u"&&(s.resourceTemplate=u.template),typeof u.metadata<"u"&&(s.metadata=u.metadata),typeof u.callback<"u"&&(s.readCallback=u.callback),typeof u.enabled<"u"&&(s.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=s;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(e,i,n,a,r){let s={title:i,description:n,argsSchema:a===void 0?void 0:va(a),callback:r,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:o=>{typeof o.name<"u"&&o.name!==e&&(delete this._registeredPrompts[e],o.name&&(this._registeredPrompts[o.name]=s)),typeof o.title<"u"&&(s.title=o.title),typeof o.description<"u"&&(s.description=o.description),typeof o.argsSchema<"u"&&(s.argsSchema=va(o.argsSchema)),typeof o.callback<"u"&&(s.callback=o.callback),typeof o.enabled<"u"&&(s.enabled=o.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=s,a&&Object.values(a).some(l=>{let u=l instanceof lu?l._def?.innerType:l;return sw(u)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(e,i,n,a,r,s,o,l,u){ow(e);let c={title:i,description:n,inputSchema:QT(a),outputSchema:QT(r),annotations:s,execution:o,_meta:l,handler:u,enabled:!0,disable:()=>c.update({enabled:!1}),enable:()=>c.update({enabled:!0}),remove:()=>c.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&ow(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=c)),typeof p.title<"u"&&(c.title=p.title),typeof p.description<"u"&&(c.description=p.description),typeof p.paramsSchema<"u"&&(c.inputSchema=va(p.paramsSchema)),typeof p.outputSchema<"u"&&(c.outputSchema=va(p.outputSchema)),typeof p.callback<"u"&&(c.handler=p.callback),typeof p.annotations<"u"&&(c.annotations=p.annotations),typeof p._meta<"u"&&(c._meta=p._meta),typeof p.enabled<"u"&&(c.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=c,this.setToolRequestHandlers(),this.sendToolListChanged(),c}tool(e,...i){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,a,r,s;if(typeof i[0]=="string"&&(n=i.shift()),i.length>1){let l=i[0];if(lw(l))a=i.shift(),i.length>1&&typeof i[0]=="object"&&i[0]!==null&&!lw(i[0])&&(s=i.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=i.shift()}}let o=i[0];return this._createRegisteredTool(e,void 0,n,a,r,s,{taskSupport:"forbidden"},void 0,o)}registerTool(e,i,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:a,description:r,inputSchema:s,outputSchema:o,annotations:l,_meta:u}=i;return this._createRegisteredTool(e,a,r,s,o,l,{taskSupport:"forbidden"},u,n)}prompt(e,...i){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof i[0]=="string"&&(n=i.shift());let a;i.length>1&&(a=i.shift());let r=i[0],s=this._createRegisteredPrompt(e,void 0,n,a,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(e,i,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:a,description:r,argsSchema:s}=i,o=this._createRegisteredPrompt(e,a,r,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,i){return this.server.sendLoggingMessage(e,i)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var IF={type:"object",properties:{}};function XT(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function eM(t){return"_def"in t||"_zod"in t||XT(t)}function lw(t){return typeof t!="object"||t===null||eM(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(XT)}function QT(t){if(t){if(lw(t))return va(t);if(!eM(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function zF(t){let e=jt(t);return e?Object.entries(e).map(([i,n])=>{let a=yj(n),r=Pj(n);return{name:i,description:a,required:!r}}):[]}function Rt(t){let i=jt(t)?.method;if(!i)throw new Error("Schema is missing a method literal");let n=ru(i);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function YT(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Oo={completion:{values:[],hasMore:!1}};var uw=er(require("node:process"),1);var Ac=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(` `);if(e===-1)return null;let i=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),DF(i)}clear(){this._buffer=void 0}};function DF(t){return cS.parse(JSON.parse(t))}function iM(t){return JSON.stringify(t)+` -`}var bc=class{constructor(e=uw.default.stdin,i=uw.default.stdout){this._stdin=e,this._stdout=i,this._readBuffer=new Ac,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(i=>{let n=iM(e);this._stdout.write(n)?i():this._stdout.once("drain",i)})}};var sy=er(sI());var lI=require("node:child_process"),uI=er(require("node:fs")),ay=er(require("node:path"));var oI=12e4,cI=t=>({config:{description:"Deploys a Genesys Cloud Architect flow from a TypeScript file. The file must export an async buildFlow(scripting) function that creates and saves the flow using the Architect Scripting SDK.",annotations:{title:"Deploy Flow",readOnlyHint:!1,destructiveHint:!0},inputSchema:{flowFile:Qi.string().min(1).describe("Path to the TypeScript flow file")}},handler:async({flowFile:e})=>{let i=ay.default.resolve(e);if(!uI.default.existsSync(i))return{isError:!0,content:[{type:"text",text:`Flow file not found: ${i}`}]};let n=[t.deployScriptPath,"--flow-file",i];return new Promise(a=>{let r=[],s,o=!1,l=h=>{o||(o=!0,clearTimeout(c),a(h))},u=(0,lI.spawn)("node",n,{env:{...process.env,GENESYS_REGION:t.region,GENESYS_CLIENT_ID:t.clientId,GENESYS_CLIENT_SECRET:t.clientSecret},cwd:ay.default.dirname(i),stdio:["ignore","pipe","pipe"]}),c=setTimeout(()=>{u.kill("SIGTERM"),l({isError:!0,content:[{type:"text",text:`Deploy timed out after ${oI/1e3}s. +`}var bc=class{constructor(e=uw.default.stdin,i=uw.default.stdout){this._stdin=e,this._stdout=i,this._readBuffer=new Ac,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(i=>{let n=iM(e);this._stdout.write(n)?i():this._stdout.once("drain",i)})}};var sy=er(sI());var lI=require("node:child_process"),uI=er(require("node:fs")),ay=er(require("node:path"));var oI=12e4,cI=t=>({config:{description:`Deploys a Genesys Cloud Architect flow from a TypeScript file. The file must export an async buildFlow(scripting) function that creates and saves the flow using the Architect Scripting SDK. The project's package.json must have "type": "module" for the ES module import to work.`,annotations:{title:"Deploy Flow",readOnlyHint:!1,destructiveHint:!0},inputSchema:{flowFile:Qi.string().min(1).describe("Path to the TypeScript flow file")}},handler:async({flowFile:e})=>{let i=ay.default.resolve(e);if(!uI.default.existsSync(i))return{isError:!0,content:[{type:"text",text:`Flow file not found: ${i}`}]};let n=[t.deployScriptPath,"--flow-file",i];return new Promise(a=>{let r=[],s,o=!1,l=h=>{o||(o=!0,clearTimeout(c),a(h))},u=(0,lI.spawn)("node",n,{env:{...process.env,GENESYS_REGION:t.region,GENESYS_CLIENT_ID:t.clientId,GENESYS_CLIENT_SECRET:t.clientSecret},cwd:ay.default.dirname(i),stdio:["ignore","pipe","pipe"]}),c=setTimeout(()=>{u.kill("SIGTERM"),l({isError:!0,content:[{type:"text",text:`Deploy timed out after ${oI/1e3}s. Logs: ${r.join(` `)}`}]})},oI),p="";u.stdout.on("data",h=>{p+=h.toString();let g=p.split(` -`);p=g.pop()??"";for(let m of g)if(m.trim())try{let f=JSON.parse(m);f.type==="log"?r.push(`[${f.level}] ${f.message}`):f.type==="result"&&(s=f)}catch{r.push(m)}});let d="";u.stderr.on("data",h=>{d+=h.toString()}),u.on("close",h=>{if(p.trim())try{let m=JSON.parse(p.trim());m.type==="result"?s=m:m.type==="log"&&r.push(`[${m.level}] ${m.message}`)}catch{p.trim()&&r.push(p.trim())}d.trim()&&r.push(`[stderr] ${d.trim()}`);let g=r.length?` +`);p=g.pop()??"";for(let m of g)if(m.trim())try{let f=JSON.parse(m);f.type==="log"?r.push(`[${f.level}] ${f.message}`):f.type==="result"&&(s=f)}catch{r.push(m)}});let d="";u.stderr.on("data",h=>{d+=h.toString()}),u.on("close",h=>{if(p.trim())try{let f=JSON.parse(p.trim());f.type==="result"?s=f:f.type==="log"&&r.push(`[${f.level}] ${f.message}`)}catch{p.trim()&&r.push(p.trim())}let g=d.split(` +`).filter(f=>!f.includes("url.parse()")&&!f.includes("[DEP0169]")).join(` +`).trim();g&&r.push(`[stderr] ${g}`);let m=r.length?` Logs: ${r.join(` -`)}`:"";if(s?.success){let m=["Flow deployed successfully."];s.flowId&&m.push(`Flow ID: ${s.flowId}`),s.flowName&&m.push(`Flow Name: ${s.flowName}`),l({content:[{type:"text",text:m.join(` -`)+g}]})}else{let m=s?.error??`Deploy runner exited with code ${h}`;l({isError:!0,content:[{type:"text",text:`Deploy failed: ${m}${g}`}]})}})})}});function pI(t){let e=t.toUpperCase();return e.endsWith("FLOW")?e:`${e}FLOW`}function iX(t,e){let i={};for(let n of e){let a=n.type??"UNKNOWN";i[a]||(i[a]=[]),i[a].push({id:n.id??"",name:n.name??"",...n.version?{version:n.version}:{},deleted:n.deleted??!1,updated:n.updated??!1})}return{flow:{id:t.id??"",name:t.name,type:pI(t.type??""),version:t.publishedVersion?.commitVersion??"1"},dependencies:i}}var dI=({architectApi:t})=>({config:{description:"Retrieves all dependencies consumed by a Genesys Cloud Architect flow. Returns the flow metadata and its dependencies grouped by type.",annotations:{title:"Flow Dependencies",readOnlyHint:!0,destructiveHint:!1},inputSchema:{flowId:Qi.string().min(1).describe("The Genesys Cloud Architect flow ID")}},handler:async({flowId:e})=>{try{let i;try{i=await t.getFlow(e)}catch{return{isError:!0,content:[{type:"text",text:`Flow "${e}" not found.`}]}}let n=pI(i.type??""),a=i.publishedVersion?.commitVersion??"1",r=[],s=1;for(;;){let l=await t.getArchitectDependencytrackingConsumedresources(i.id,a,n,{pageSize:100,pageNumber:s});if(l.entities&&r.push(...l.entities),!l.nextUri)break;s++}let o=iX(i,r);return{content:[{type:"text",text:JSON.stringify(o,null,2)}]}}catch(i){return{isError:!0,content:[{type:"text",text:`Failed to retrieve flow dependencies: ${i instanceof Error?i.message:String(i)}`}]}}}});var ry=Qi.object({GENESYS_REGION:Qi.string().min(1),GENESYS_CLIENT_ID:Qi.string().min(1),GENESYS_CLIENT_SECRET:Qi.string().min(1),DEPLOY_SCRIPT_PATH:Qi.string().min(1),PREVENT_LOGIN:Qi.enum(["TRUE","FALSE"]).default("FALSE").transform(t=>t==="TRUE")}).safeParse(process.env);if(!ry.success){let t=ry.error.issues.map(e=>e.path[0]).join(` +`)}`:"";if(s?.success){let f=["Flow deployed successfully."];s.flowId&&f.push(`Flow ID: ${s.flowId}`),s.flowName&&f.push(`Flow Name: ${s.flowName}`),l({content:[{type:"text",text:f.join(` +`)+m}]})}else{let f=s?.error??`Deploy runner exited with code ${h}`;l({isError:!0,content:[{type:"text",text:`Deploy failed: ${f}${m}`}]})}})})}});function pI(t){let e=t.toUpperCase();return e.endsWith("FLOW")?e:`${e}FLOW`}function iX(t,e){let i={};for(let n of e){let a=n.type??"UNKNOWN";i[a]||(i[a]=[]),i[a].push({id:n.id??"",name:n.name??"",...n.version?{version:n.version}:{},deleted:n.deleted??!1,updated:n.updated??!1})}return{flow:{id:t.id??"",name:t.name,type:pI(t.type??""),version:t.publishedVersion?.commitVersion??"1"},dependencies:i}}var dI=({architectApi:t})=>({config:{description:"Retrieves all dependencies consumed by a Genesys Cloud Architect flow. Returns the flow metadata and its dependencies grouped by type.",annotations:{title:"Flow Dependencies",readOnlyHint:!0,destructiveHint:!1},inputSchema:{flowId:Qi.string().min(1).describe("The Genesys Cloud Architect flow ID")}},handler:async({flowId:e})=>{try{let i;try{i=await t.getFlow(e)}catch{return{isError:!0,content:[{type:"text",text:`Flow "${e}" not found.`}]}}let n=pI(i.type??""),a=i.publishedVersion?.commitVersion??"1",r=[],s=1;for(;;){let l=await t.getArchitectDependencytrackingConsumedresources(i.id,a,n,{pageSize:100,pageNumber:s});if(l.entities&&r.push(...l.entities),!l.nextUri)break;s++}let o=iX(i,r);return{content:[{type:"text",text:JSON.stringify(o,null,2)}]}}catch(i){return{isError:!0,content:[{type:"text",text:`Failed to retrieve flow dependencies: ${i instanceof Error?i.message:String(i)}`}]}}}});var ry=Qi.object({GENESYS_REGION:Qi.string().min(1),GENESYS_CLIENT_ID:Qi.string().min(1),GENESYS_CLIENT_SECRET:Qi.string().min(1),DEPLOY_SCRIPT_PATH:Qi.string().min(1),PREVENT_LOGIN:Qi.enum(["TRUE","FALSE"]).default("FALSE").transform(t=>t==="TRUE")}).safeParse(process.env);if(!ry.success){let t=ry.error.issues.map(e=>e.path[0]).join(` `);console.error(`Missing required environment variables: ${t}`),process.exit(1)}var Kt=ry.data,oy=new Cc({name:"genesys-cloud-architect",version:"1.0.2"}),hI=dI({architectApi:new sy.default.ArchitectApi});oy.registerTool("flow_dependencies",hI.config,hI.handler);var gI=cI({region:Kt.GENESYS_REGION,clientId:Kt.GENESYS_CLIENT_ID,clientSecret:Kt.GENESYS_CLIENT_SECRET,deployScriptPath:Kt.DEPLOY_SCRIPT_PATH});oy.registerTool("deploy_flow",gI.config,gI.handler);(async()=>{if(Kt.PREVENT_LOGIN)console.warn("Login for Platform API skipped. Calling tools will result in an auth failure.");else{let e=sy.default.ApiClient.instance;e.setEnvironment(Kt.GENESYS_REGION),await e.loginClientCredentialsGrant(Kt.GENESYS_CLIENT_ID,Kt.GENESYS_CLIENT_SECRET)}let t=new bc;await oy.connect(t)})().catch(t=>{console.error("Failed to start server:",t),process.exit(1)}); /*! Bundled license information: diff --git a/skills/write-flow/SKILL.md b/skills/write-flow/SKILL.md index a7d46b0..59daf0a 100644 --- a/skills/write-flow/SKILL.md +++ b/skills/write-flow/SKILL.md @@ -31,6 +31,10 @@ The user's project must have the Architect Scripting SDK installed for type chec npm install --save-dev purecloud-flow-scripting-api-sdk-javascript ``` +## Deploy only (existing flow file) + +If the user already has a flow file and just wants to deploy it, skip straight to **step 5** — call the `deploy_flow` MCP tool with the file path. Only fall back to steps 1–4 if deployment fails or the user asks for help writing/fixing the flow. + ## Workflow ### 1. Understand the requirement @@ -38,9 +42,10 @@ npm install --save-dev purecloud-flow-scripting-api-sdk-javascript Ask the user: - **Flow type**: inbound call, inbound chat, inbound email, inbound message (SMS), or workflow - **What it should do**: routing, menus, greetings, queue transfers, data lookups, etc. -- **Queue names**: which Genesys Cloud queues to route to (must exist in the org) - **Flow name**: what to name the flow in Architect +Only ask about queue names if the user's description involves queue transfers. Not every flow routes to a queue. + ### 2. Read the relevant references Before writing any flow code, read these reference files from this skill: diff --git a/src/deploy-runner/index.ts b/src/deploy-runner/index.ts index 7a48f1b..5ba7b8c 100644 --- a/src/deploy-runner/index.ts +++ b/src/deploy-runner/index.ts @@ -110,9 +110,12 @@ const origGet = https.get; const origConsoleLog = console.log; const tracePrefix = "TRACE:"; +const SUPPRESSED_TRACES = [/Unknown feature being requested/]; + function interceptTrace(text: string): boolean { if (text.startsWith(tracePrefix)) { const msg = text.slice(tracePrefix.length).trim(); + if (SUPPRESSED_TRACES.some((p) => p.test(msg))) return true; traces.push(msg); emit("log", "info", msg); return true; diff --git a/src/mcp-server/tools/deploy-flow.ts b/src/mcp-server/tools/deploy-flow.ts index 0fafe3e..806dff8 100644 --- a/src/mcp-server/tools/deploy-flow.ts +++ b/src/mcp-server/tools/deploy-flow.ts @@ -28,7 +28,8 @@ export const deployFlow: ToolFactory = (toolConfig) => ({ description: "Deploys a Genesys Cloud Architect flow from a TypeScript file. " + "The file must export an async buildFlow(scripting) function that " + - "creates and saves the flow using the Architect Scripting SDK.", + "creates and saves the flow using the Architect Scripting SDK. " + + 'The project\'s package.json must have "type": "module" for the ES module import to work.', annotations: { title: "Deploy Flow", readOnlyHint: false, @@ -140,8 +141,17 @@ export const deployFlow: ToolFactory = (toolConfig) => ({ } } - if (stderrBuf.trim()) { - logs.push(`[stderr] ${stderrBuf.trim()}`); + const filteredStderr = stderrBuf + .split("\n") + .filter( + (l) => + !l.includes("url.parse()") && + !l.includes("[DEP0169]"), + ) + .join("\n") + .trim(); + if (filteredStderr) { + logs.push(`[stderr] ${filteredStderr}`); } const logOutput = logs.length