@zuplo/runtime 6.65.6 → 6.65.7

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/out/esm/index.js CHANGED
@@ -241,7 +241,7 @@ data: ${o}
241
241
  `;break;case"id":c=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new da(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:w}));break;default:r(new da(`Unknown field "${b.length>20?`${b.slice(0,20)}\u2026`:b}"`,{type:"unknown-field",field:b,value:y,line:w}));break}}s(m,"processField");function g(){u.length>0&&e({id:c,event:l||void 0,data:u.endsWith(`
242
242
  `)?u.slice(0,-1):u}),c=void 0,u="",l=""}s(g,"dispatchEvent");function h(b={}){i&&b.consume&&p(i),a=!0,c=void 0,u="",l="",i=""}return s(h,"reset"),{feed:d,reset:h}}s(Av,"createParser");function SE(t){let e=[],r="",n=0;for(;n<t.length;){let o=t.indexOf("\r",n),i=t.indexOf(`
243
243
  `,n),a=-1;if(o!==-1&&i!==-1?a=Math.min(o,i):o!==-1?o===t.length-1?a=-1:a=o:i!==-1&&(a=i),a===-1){r=t.slice(n);break}else{let c=t.slice(n,a);e.push(c),n=a+1,t[n-1]==="\r"&&t[n]===`
244
- `&&n++}}return[e,r]}s(SE,"splitLines");var pa=class extends TransformStream{static{s(this,"EventSourceParserStream")}constructor({onError:e,onRetry:r,onComment:n}={}){let o;super({start(i){o=Av({onEvent:s(a=>{i.enqueue(a)},"onEvent"),onError(a){e==="terminate"?i.error(a):typeof e=="function"&&e(a)},onRetry:r,onComment:n})},transform(i){o.feed(i)}})}};var ma=class{static{s(this,"HTTPClientTransport")}url;timeout;headers;fetch;logger;sessionId;messageHandler;errorCallback;closeCallback;isConnected=!1;constructor(e){this.url=e.url,this.timeout=e.timeout||3e4,this.headers={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...e.headers},this.fetch=e.fetch||globalThis.fetch,this.logger=e.logger||nr(),e.enableSessions&&this.logger.debug("Session support not yet implemented for HTTP client transport")}setHeaders(e){this.headers={...this.headers,...e}}async connect(){try{new URL(this.url),this.isConnected=!0,this.logger.info("HTTP Client Transport connected to:",this.url)}catch{let r=new Error(`Invalid URL: ${this.url}`);throw this.errorCallback&&this.errorCallback(r),r}}async send(e){if(!this.isConnected)throw new Error("Transport not connected. Call connect() first.");let r;try{let n={...this.headers};this.sessionId&&(n["Mcp-Session-Id"]=this.sessionId);let o=new AbortController;r=setTimeout(()=>o.abort(),this.timeout);let i=await this.fetch(this.url,{method:"POST",headers:{...this.headers,...this.sessionId&&{"Mcp-Session-Id":this.sessionId}},body:JSON.stringify(e),signal:o.signal});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);(i.headers.get("Content-Type")||"").includes("text/event-stream")?await this.handleSSEResponse(i):await this.handleJSONResponse(i)}catch(n){if(n instanceof Error&&n.name==="AbortError")throw this.errorCallback&&this.errorCallback(n),new Error(`Request timeout after ${this.timeout}ms`);let o=new Error(`A client error occurred: ${n}`);throw this.errorCallback&&this.errorCallback(o),o}finally{r&&clearTimeout(r)}}onMessage(e){this.messageHandler=e}async close(){this.logger.debug("Closing HTTP Client Transport"),this.isConnected=!1,this.messageHandler=void 0,this.closeCallback&&this.closeCallback(),this.logger.info("HTTP Client Transport closed")}onClose(e){this.closeCallback=e}onError(e){this.errorCallback=e}getSessionId(){return this.sessionId}setSessionId(e){this.sessionId=e,this.logger.debug("Session ID set:",e?"***":"undefined")}async handleJSONResponse(e){let r=await e.text();if(!r.trim()){this.logger.debug("Received empty response");return}let n;try{n=JSON.parse(r)}catch{throw new Error(`Invalid JSON response: ${r}`)}this.logger.debug("Received JSON-RPC response:",n),this.messageHandler&&await this.messageHandler(n)}async handleSSEResponse(e){if(!e.body)throw new Error("SSE response has no body");this.logger.debug("Handling SSE response");let r=s(o=>{if(!o.event||o.event==="message")try{let i=JSON.parse(o.data);this.logger.debug("Received SSE message:",i),this.messageHandler&&this.messageHandler(i)}catch(i){this.logger.warn("Failed to parse SSE message data:",o.data,i)}},"onEvent"),n=e.body.pipeThrough(new TextDecoderStream).pipeThrough(new pa).getReader();try{for(;;){let{done:o,value:i}=await n.read();if(o)return;r(i)}}catch(o){throw this.logger.error("Error processing SSE stream:",o),new Error(`SSE stream error: ${o}`)}}};import{AsyncLocalStorage as kE}from"node:async_hooks";var Em=new kE;function fa(t,e,r){return Em.run({headers:t,zuploContext:e},r)}s(fa,"runWithInvokeContext");function Jo(){return Em.getStore()?.headers??{}}s(Jo,"getInvokeHeaders");function dr(){let t=Em.getStore();if(!t)throw new Error("No Zuplo context available in current execution context");return t.zuploContext}s(dr,"getInvokeContext");var ga=class{constructor(e,r,n=!1,o){this.baseUrl=e;this.originToolName=r;this.debugMode=n;this.originHeaders=o}static{s(this,"ProxyMcpToolExecutor")}async execute(e){let r=dr(),n=Date.now(),o=new la({name:"Zuplo MCP Gateway Proxy Client",version:"0.0.1"});try{this.debugMode&&r.log.debug("Proxying MCP tool call",{originToolName:this.originToolName,baseUrl:this.baseUrl,args:e});let i=new ma({url:this.baseUrl});i.setHeaders({"Content-Type":"application/json",...Jo(),...this.originHeaders??{}});let a,c=Date.now();try{await o.connect(i),await o.initialize(),a=await o.callTool(this.originToolName,e)}catch(l){throw new Error(`could not call tool: ${this.originToolName}`,l)}let u=Date.now()-c;return this.debugMode&&r.log.debug("Proxy MCP response received",{originToolName:this.originToolName,upstreamElapsedMs:u,proxyResult:a}),a}catch(i){let a=Date.now()-n,c=i instanceof Error?`${i.name}: ${i.message}`:String(i);return r.log.error("Proxy MCP tool execution failed",{originToolName:this.originToolName,baseUrl:this.baseUrl,totalElapsedMs:a,err:i}),{content:[{type:"text",text:`Tool execution failed for '${this.originToolName}': ${c}`}],isError:!0}}finally{await o.disconnect()}}};var Qo=class{static{s(this,"R")}type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(t,e,r,n,o,i){this.type=t,this.name=e,this.prefix=r,this.value=n,this.suffix=o,this.modifier=i}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},TE=/[$_\p{ID_Start}]/u,_E=/[$_\u200C\u200D\p{ID_Continue}]/u,Om=".*";function EE(t,e){return(e?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(t)}s(EE,"Re");function Mv(t,e=!1){let r=[],n=0;for(;n<t.length;){let o=t[n],i=s(function(a){if(!e)throw new TypeError(a);r.push({type:"INVALID_CHAR",index:n,value:t[n++]})},"c");if(o==="*"){r.push({type:"ASTERISK",index:n,value:t[n++]});continue}if(o==="+"||o==="?"){r.push({type:"OTHER_MODIFIER",index:n,value:t[n++]});continue}if(o==="\\"){r.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(o==="{"){r.push({type:"OPEN",index:n,value:t[n++]});continue}if(o==="}"){r.push({type:"CLOSE",index:n,value:t[n++]});continue}if(o===":"){let a="",c=n+1;for(;c<t.length;){let u=t.substr(c,1);if(c===n+1&&TE.test(u)||c!==n+1&&_E.test(u)){a+=t[c++];continue}break}if(!a){i(`Missing parameter name at ${n}`);continue}r.push({type:"NAME",index:n,value:a}),n=c;continue}if(o==="("){let a=1,c="",u=n+1,l=!1;if(t[u]==="?"){i(`Pattern cannot start with "?" at ${u}`);continue}for(;u<t.length;){if(!EE(t[u],!1)){i(`Invalid character '${t[u]}' at ${u}.`),l=!0;break}if(t[u]==="\\"){c+=t[u++]+t[u++];continue}if(t[u]===")"){if(a--,a===0){u++;break}}else if(t[u]==="("&&(a++,t[u+1]!=="?")){i(`Capturing groups are not allowed at ${u}`),l=!0;break}c+=t[u++]}if(l)continue;if(a){i(`Unbalanced pattern at ${n}`);continue}if(!c){i(`Missing pattern at ${n}`);continue}r.push({type:"REGEX",index:n,value:c}),n=u;continue}r.push({type:"CHAR",index:n,value:t[n++]})}return r.push({type:"END",index:n,value:""}),r}s(Mv,"v");function Dv(t,e={}){let r=Mv(t);e.delimiter??="/#?",e.prefixes??="./";let n=`[^${ht(e.delimiter)}]+?`,o=[],i=0,a=0,c="",u=new Set,l=s(S=>{if(a<r.length&&r[a].type===S)return r[a++].value},"a"),d=s(()=>l("OTHER_MODIFIER")??l("ASTERISK"),"f"),p=s(S=>{let O=l(S);if(O!==void 0)return O;let{type:T,index:k}=r[a];throw new TypeError(`Unexpected ${T} at ${k}, expected ${S}`)},"d"),m=s(()=>{let S="",O;for(;O=l("CHAR")??l("ESCAPED_CHAR");)S+=O;return S},"T"),g=s(S=>S,"Se"),h=e.encodePart||g,b="",y=s(S=>{b+=S},"U"),w=s(()=>{b.length&&(o.push(new Qo(3,"","",h(b),"",3)),b="")},"$"),v=s((S,O,T,k,N)=>{let U=3;switch(N){case"?":U=1;break;case"*":U=0;break;case"+":U=2;break}if(!O&&!T&&U===3){y(S);return}if(w(),!O&&!T){if(!S)return;o.push(new Qo(3,"","",h(S),"",U));return}let Z;T?T==="*"?Z=Om:Z=T:Z=n;let A=2;Z===n?(A=1,Z=""):Z===Om&&(A=0,Z="");let C;if(O?C=O:T&&(C=i++),u.has(C))throw new TypeError(`Duplicate name '${C}'.`);u.add(C),o.push(new Qo(A,C,h(S),Z,h(k),U))},"V");for(;a<r.length;){let S=l("CHAR"),O=l("NAME"),T=l("REGEX");if(!O&&!T&&(T=l("ASTERISK")),O||T){let N=S??"";e.prefixes.indexOf(N)===-1&&(y(N),N=""),w();let U=d();v(N,O,T,"",U);continue}let k=S??l("ESCAPED_CHAR");if(k){y(k);continue}if(l("OPEN")){let N=m(),U=l("NAME"),Z=l("REGEX");!U&&!Z&&(Z=l("ASTERISK"));let A=m();p("CLOSE");let C=d();v(N,U,Z,A,C);continue}w(),p("END")}return o}s(Dv,"D");function ht(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}s(ht,"S");function Nv(t){return t&&t.ignoreCase?"ui":"u"}s(Nv,"X");function CE(t,e,r){return Uv(Dv(t,r),e,r)}s(CE,"Z");function un(t){switch(t){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}s(un,"k");function Uv(t,e,r={}){r.delimiter??="/#?",r.prefixes??="./",r.sensitive??=!1,r.strict??=!1,r.end??=!0,r.start??=!0,r.endsWith="";let n=r.start?"^":"";for(let c of t){if(c.type===3){c.modifier===3?n+=ht(c.value):n+=`(?:${ht(c.value)})${un(c.modifier)}`;continue}e&&e.push(c.name);let u=`[^${ht(r.delimiter)}]+?`,l=c.value;if(c.type===1?l=u:c.type===0&&(l=Om),!c.prefix.length&&!c.suffix.length){c.modifier===3||c.modifier===1?n+=`(${l})${un(c.modifier)}`:n+=`((?:${l})${un(c.modifier)})`;continue}if(c.modifier===3||c.modifier===1){n+=`(?:${ht(c.prefix)}(${l})${ht(c.suffix)})`,n+=un(c.modifier);continue}n+=`(?:${ht(c.prefix)}`,n+=`((?:${l})(?:`,n+=ht(c.suffix),n+=ht(c.prefix),n+=`(?:${l}))*)${ht(c.suffix)})`,c.modifier===0&&(n+="?")}let o=`[${ht(r.endsWith)}]|$`,i=`[${ht(r.delimiter)}]`;if(r.end)return r.strict||(n+=`${i}?`),r.endsWith.length?n+=`(?=${o})`:n+="$",new RegExp(n,Nv(r));r.strict||(n+=`(?:${i}(?=${o}))?`);let a=!1;if(t.length){let c=t[t.length-1];c.type===3&&c.modifier===3&&(a=r.delimiter.indexOf(c)>-1)}return a||(n+=`(?=${i}|${o})`),new RegExp(n,Nv(r))}s(Uv,"F");var mr={delimiter:"",prefixes:"",sensitive:!0,strict:!0},OE={delimiter:".",prefixes:"",sensitive:!0,strict:!0},$E={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function AE(t,e){return t.length?t[0]==="/"?!0:!e||t.length<2?!1:(t[0]=="\\"||t[0]=="{")&&t[1]=="/":!1}s(AE,"J");function jv(t,e){return t.startsWith(e)?t.substring(e.length,t.length):t}s(jv,"Q");function NE(t,e){return t.endsWith(e)?t.substr(0,t.length-e.length):t}s(NE,"Ee");function zv(t){return!t||t.length<2?!1:t[0]==="["||(t[0]==="\\"||t[0]==="{")&&t[1]==="["}s(zv,"W");var Zv=["ftp","file","http","https","ws","wss"];function qv(t){if(!t)return!0;for(let e of Zv)if(t.test(e))return!0;return!1}s(qv,"N");function LE(t,e){if(t=jv(t,"#"),e||t==="")return t;let r=new URL("https://example.com");return r.hash=t,r.hash?r.hash.substring(1,r.hash.length):""}s(LE,"te");function ME(t,e){if(t=jv(t,"?"),e||t==="")return t;let r=new URL("https://example.com");return r.search=t,r.search?r.search.substring(1,r.search.length):""}s(ME,"re");function DE(t,e){return e||t===""?t:zv(t)?Bv(t):Hv(t)}s(DE,"ne");function UE(t,e){if(e||t==="")return t;let r=new URL("https://example.com");return r.password=t,r.password}s(UE,"se");function jE(t,e){if(e||t==="")return t;let r=new URL("https://example.com");return r.username=t,r.username}s(jE,"ie");function zE(t,e,r){if(r||t==="")return t;if(e&&!Zv.includes(e))return new URL(`${e}:${t}`).pathname;let n=t[0]=="/";return t=new URL(n?t:"/-"+t,"https://example.com").pathname,n||(t=t.substring(2,t.length)),t}s(zE,"ae");function ZE(t,e,r){return Fv(e)===t&&(t=""),r||t===""?t:Gv(t)}s(ZE,"oe");function qE(t,e){return t=NE(t,":"),e||t===""?t:$m(t)}s(qE,"ce");function Fv(t){switch(t){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}s(Fv,"_");function $m(t){if(t==="")return t;if(/^[-+.A-Za-z0-9]*$/.test(t))return t.toLowerCase();throw new TypeError(`Invalid protocol '${t}'.`)}s($m,"y");function FE(t){if(t==="")return t;let e=new URL("https://example.com");return e.username=t,e.username}s(FE,"le");function HE(t){if(t==="")return t;let e=new URL("https://example.com");return e.password=t,e.password}s(HE,"fe");function Hv(t){if(t==="")return t;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(t))throw new TypeError(`Invalid hostname '${t}'`);let e=new URL("https://example.com");return e.hostname=t,e.hostname}s(Hv,"z");function Bv(t){if(t==="")return t;if(/[^0-9a-fA-F[\]:]/g.test(t))throw new TypeError(`Invalid IPv6 hostname '${t}'`);return t.toLowerCase()}s(Bv,"j");function Gv(t){if(t===""||/^[0-9]*$/.test(t)&&parseInt(t)<=65535)return t;throw new TypeError(`Invalid port '${t}'.`)}s(Gv,"K");function BE(t){if(t==="")return t;let e=new URL("https://example.com");return e.pathname=t[0]!=="/"?"/-"+t:t,t[0]!=="/"?e.pathname.substring(2,e.pathname.length):e.pathname}s(BE,"he");function GE(t){return t===""?t:new URL(`data:${t}`).pathname}s(GE,"ue");function VE(t){if(t==="")return t;let e=new URL("https://example.com");return e.search=t,e.search.substring(1,e.search.length)}s(VE,"de");function JE(t){if(t==="")return t;let e=new URL("https://example.com");return e.hash=t,e.hash.substring(1,e.hash.length)}s(JE,"pe");var WE=class{static{s(this,"H")}#e;#t=[];#n={};#r=0;#o=1;#i=0;#s=0;#c=0;#u=0;#l=!1;constructor(t){this.#e=t}get result(){return this.#n}parse(){for(this.#t=Mv(this.#e,!0);this.#r<this.#t.length;this.#r+=this.#o){if(this.#o=1,this.#t[this.#r].type==="END"){if(this.#s===0){this.#w(),this.#m()?this.#a(9,1):this.#f()?this.#a(8,1):this.#a(7,0);continue}else if(this.#s===2){this.#g(5);continue}this.#a(10,0);break}if(this.#c>0)if(this.#k())this.#c-=1;else continue;if(this.#S()){this.#c+=1;continue}switch(this.#s){case 0:this.#v()&&this.#g(1);break;case 1:if(this.#v()){this.#E();let t=7,e=1;this.#R()?(t=2,e=3):this.#l&&(t=2),this.#a(t,e)}break;case 2:this.#y()?this.#g(3):(this.#b()||this.#f()||this.#m())&&this.#g(5);break;case 3:this.#P()?this.#a(4,1):this.#y()&&this.#a(5,1);break;case 4:this.#y()&&this.#a(5,1);break;case 5:this.#T()?this.#u+=1:this.#_()&&(this.#u-=1),this.#I()&&!this.#u?this.#a(6,1):this.#b()?this.#a(7,0):this.#f()?this.#a(8,1):this.#m()&&this.#a(9,1);break;case 6:this.#b()?this.#a(7,0):this.#f()?this.#a(8,1):this.#m()&&this.#a(9,1);break;case 7:this.#f()?this.#a(8,1):this.#m()&&this.#a(9,1);break;case 8:this.#m()&&this.#a(9,1);break;case 9:break;case 10:break}}this.#n.hostname!==void 0&&this.#n.port===void 0&&(this.#n.port="")}#a(t,e){switch(this.#s){case 0:break;case 1:this.#n.protocol=this.#p();break;case 2:break;case 3:this.#n.username=this.#p();break;case 4:this.#n.password=this.#p();break;case 5:this.#n.hostname=this.#p();break;case 6:this.#n.port=this.#p();break;case 7:this.#n.pathname=this.#p();break;case 8:this.#n.search=this.#p();break;case 9:this.#n.hash=this.#p();break;case 10:break}this.#s!==0&&t!==10&&([1,2,3,4].includes(this.#s)&&[6,7,8,9].includes(t)&&(this.#n.hostname??=""),[1,2,3,4,5,6].includes(this.#s)&&[8,9].includes(t)&&(this.#n.pathname??=this.#l?"/":""),[1,2,3,4,5,6,7].includes(this.#s)&&t===9&&(this.#n.search??="")),this.#x(t,e)}#x(t,e){this.#s=t,this.#i=this.#r+e,this.#r+=e,this.#o=0}#w(){this.#r=this.#i,this.#o=0}#g(t){this.#w(),this.#s=t}#h(t){return t<0&&(t=this.#t.length-t),t<this.#t.length?this.#t[t]:this.#t[this.#t.length-1]}#d(t,e){let r=this.#h(t);return r.value===e&&(r.type==="CHAR"||r.type==="ESCAPED_CHAR"||r.type==="INVALID_CHAR")}#v(){return this.#d(this.#r,":")}#R(){return this.#d(this.#r+1,"/")&&this.#d(this.#r+2,"/")}#y(){return this.#d(this.#r,"@")}#P(){return this.#d(this.#r,":")}#I(){return this.#d(this.#r,":")}#b(){return this.#d(this.#r,"/")}#f(){if(this.#d(this.#r,"?"))return!0;if(this.#t[this.#r].value!=="?")return!1;let t=this.#h(this.#r-1);return t.type!=="NAME"&&t.type!=="REGEX"&&t.type!=="CLOSE"&&t.type!=="ASTERISK"}#m(){return this.#d(this.#r,"#")}#S(){return this.#t[this.#r].type=="OPEN"}#k(){return this.#t[this.#r].type=="CLOSE"}#T(){return this.#d(this.#r,"[")}#_(){return this.#d(this.#r,"]")}#p(){let t=this.#t[this.#r],e=this.#h(this.#i).index;return this.#e.substring(e,t.index)}#E(){let t={};Object.assign(t,mr),t.encodePart=$m;let e=CE(this.#p(),void 0,t);this.#l=qv(e)}},Cm=["protocol","username","password","hostname","port","pathname","search","hash"],pr="*";function Lv(t,e){if(typeof t!="string")throw new TypeError("parameter 1 is not of type 'string'.");let r=new URL(t,e);return{protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search!==""?r.search.substring(1,r.search.length):void 0,hash:r.hash!==""?r.hash.substring(1,r.hash.length):void 0}}s(Lv,"ge");function Kt(t,e){return e?Ko(t):t}s(Kt,"b");function Wo(t,e,r){let n;if(typeof e.baseURL=="string")try{n=new URL(e.baseURL),e.protocol===void 0&&(t.protocol=Kt(n.protocol.substring(0,n.protocol.length-1),r)),!r&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&(t.username=Kt(n.username,r)),!r&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&e.password===void 0&&(t.password=Kt(n.password,r)),e.protocol===void 0&&e.hostname===void 0&&(t.hostname=Kt(n.hostname,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&(t.port=Kt(n.port,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&(t.pathname=Kt(n.pathname,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&(t.search=Kt(n.search.substring(1,n.search.length),r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&e.hash===void 0&&(t.hash=Kt(n.hash.substring(1,n.hash.length),r))}catch{throw new TypeError(`invalid baseURL '${e.baseURL}'.`)}if(typeof e.protocol=="string"&&(t.protocol=qE(e.protocol,r)),typeof e.username=="string"&&(t.username=jE(e.username,r)),typeof e.password=="string"&&(t.password=UE(e.password,r)),typeof e.hostname=="string"&&(t.hostname=DE(e.hostname,r)),typeof e.port=="string"&&(t.port=ZE(e.port,t.protocol,r)),typeof e.pathname=="string"){if(t.pathname=e.pathname,n&&!AE(t.pathname,r)){let o=n.pathname.lastIndexOf("/");o>=0&&(t.pathname=Kt(n.pathname.substring(0,o+1),r)+t.pathname)}t.pathname=zE(t.pathname,t.protocol,r)}return typeof e.search=="string"&&(t.search=ME(e.search,r)),typeof e.hash=="string"&&(t.hash=LE(e.hash,r)),t}s(Wo,"w");function Ko(t){return t.replace(/([+*?:{}()\\])/g,"\\$1")}s(Ko,"C");function KE(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}s(KE,"Oe");function QE(t,e){e.delimiter??="/#?",e.prefixes??="./",e.sensitive??=!1,e.strict??=!1,e.end??=!0,e.start??=!0,e.endsWith="";let r=".*",n=`[^${KE(e.delimiter)}]+?`,o=/[$_\u200C\u200D\p{ID_Continue}]/u,i="";for(let a=0;a<t.length;++a){let c=t[a];if(c.type===3){if(c.modifier===3){i+=Ko(c.value);continue}i+=`{${Ko(c.value)}}${un(c.modifier)}`;continue}let u=c.hasCustomName(),l=!!c.suffix.length||!!c.prefix.length&&(c.prefix.length!==1||!e.prefixes.includes(c.prefix)),d=a>0?t[a-1]:null,p=a<t.length-1?t[a+1]:null;if(!l&&u&&c.type===1&&c.modifier===3&&p&&!p.prefix.length&&!p.suffix.length)if(p.type===3){let m=p.value.length>0?p.value[0]:"";l=o.test(m)}else l=!p.hasCustomName();if(!l&&!c.prefix.length&&d&&d.type===3){let m=d.value[d.value.length-1];l=e.prefixes.includes(m)}l&&(i+="{"),i+=Ko(c.prefix),u&&(i+=`:${c.name}`),c.type===2?i+=`(${c.value})`:c.type===1?u||(i+=`(${n})`):c.type===0&&(!u&&(!d||d.type===3||d.modifier!==3||l||c.prefix!=="")?i+="*":i+=`(${r})`),c.type===1&&u&&c.suffix.length&&o.test(c.suffix[0])&&(i+="\\"),i+=Ko(c.suffix),l&&(i+="}"),c.modifier!==3&&(i+=un(c.modifier))}return i}s(QE,"ke");var ha=class{static{s(this,"me")}#e;#t={};#n={};#r={};#o={};#i=!1;constructor(t={},e,r){try{let n;if(typeof e=="string"?n=e:r=e,typeof t=="string"){let c=new WE(t);if(c.parse(),t=c.result,n===void 0&&typeof t.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");t.baseURL=n}else{if(!t||typeof t!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(n)throw new TypeError("parameter 1 is not of type 'string'.")}typeof r>"u"&&(r={ignoreCase:!1});let o={ignoreCase:r.ignoreCase===!0},i={pathname:pr,protocol:pr,username:pr,password:pr,hostname:pr,port:pr,search:pr,hash:pr};this.#e=Wo(i,t,!0),Fv(this.#e.protocol)===this.#e.port&&(this.#e.port="");let a;for(a of Cm){if(!(a in this.#e))continue;let c={},u=this.#e[a];switch(this.#n[a]=[],a){case"protocol":Object.assign(c,mr),c.encodePart=$m;break;case"username":Object.assign(c,mr),c.encodePart=FE;break;case"password":Object.assign(c,mr),c.encodePart=HE;break;case"hostname":Object.assign(c,OE),zv(u)?c.encodePart=Bv:c.encodePart=Hv;break;case"port":Object.assign(c,mr),c.encodePart=Gv;break;case"pathname":qv(this.#t.protocol)?(Object.assign(c,$E,o),c.encodePart=BE):(Object.assign(c,mr,o),c.encodePart=GE);break;case"search":Object.assign(c,mr,o),c.encodePart=VE;break;case"hash":Object.assign(c,mr,o),c.encodePart=JE;break}try{this.#o[a]=Dv(u,c),this.#t[a]=Uv(this.#o[a],this.#n[a],c),this.#r[a]=QE(this.#o[a],c),this.#i=this.#i||this.#o[a].some(l=>l.type===2)}catch{throw new TypeError(`invalid ${a} pattern '${this.#e[a]}'.`)}}}catch(n){throw new TypeError(`Failed to construct 'URLPattern': ${n.message}`)}}test(t={},e){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return!1;try{typeof t=="object"?r=Wo(r,t,!1):r=Wo(r,Lv(t,e),!1)}catch{return!1}let n;for(n of Cm)if(!this.#t[n].exec(r[n]))return!1;return!0}exec(t={},e){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return;try{typeof t=="object"?r=Wo(r,t,!1):r=Wo(r,Lv(t,e),!1)}catch{return null}let n={};e?n.inputs=[t,e]:n.inputs=[t];let o;for(o of Cm){let i=this.#t[o].exec(r[o]);if(!i)return null;let a={};for(let[c,u]of this.#n[o].entries())if(typeof u=="string"||typeof u=="number"){let l=i[c+1];a[u]=l}n[o]={input:r[o]??"",groups:a}}return n}static compareComponent(t,e,r){let n=s((c,u)=>{for(let l of["type","modifier","prefix","value","suffix"]){if(c[l]<u[l])return-1;if(c[l]!==u[l])return 1}return 0},"o"),o=new Qo(3,"","","","",3),i=new Qo(0,"","","","",3),a=s((c,u)=>{let l=0;for(;l<Math.min(c.length,u.length);++l){let d=n(c[l],u[l]);if(d)return d}return c.length===u.length?0:n(c[l]??o,u[l]??o)},"s");return!e.#r[t]&&!r.#r[t]?0:e.#r[t]&&!r.#r[t]?a(e.#o[t],[i]):!e.#r[t]&&r.#r[t]?a([i],r.#o[t]):a(e.#o[t],r.#o[t])}get protocol(){return this.#r.protocol}get username(){return this.#r.username}get password(){return this.#r.password}get hostname(){return this.#r.hostname}get port(){return this.#r.port}get pathname(){return this.#r.pathname}get search(){return this.#r.search}get hash(){return this.#r.hash}get hasRegExpGroups(){return this.#i}};var ya=class{static{s(this,"UrlPatternBuilder")}pattern;pathParams={};searchParams=new URLSearchParams;expectedPathParams=new Set;seenPathParams=new Set;constructor(e){this.pattern=new ha({pathname:e});let r=/:(\w+)(\([^)]*\))?[*+?]?/g,n;for(;(n=r.exec(e))!==null;)this.expectedPathParams.add(n[1])}addParameter(e,r,n){let o=this.getParameterValue(e,r,n);if(o!=null)switch(e.in){case"path":if(!this.expectedPathParams.has(e.name))throw new x(`path parameter '${e.name}' missing from pattern '${this.pattern.pathname}'`);this.seenPathParams.add(e.name),this.addPathParameter(e.name,o);break;case"query":this.addQueryParameter(e.name,o);break;default:break}}getParameterValue(e,r,n){switch(e.in){case"path":return r?.[e.name];case"query":return n?.[e.name];default:return}}addPathParameter(e,r){this.pathParams[e]=String(r)}addQueryParameter(e,r){Array.isArray(r)?r.forEach(n=>{n!=null&&this.searchParams.append(e,String(n))}):typeof r=="object"&&r!==null?this.searchParams.append(e,JSON.stringify(r)):this.searchParams.append(e,String(r))}toString(){let e=[...this.expectedPathParams].filter(i=>!this.seenPathParams.has(i));if(e.length>0)throw new x(`missing path parameters in OpenAPI spec: ${e.join(", ")}`);let r=this.pattern.pathname.replace(/:(\w+)(\([^)]*\))?([*+?])?/g,(i,a)=>this.pathParams[a]?encodeURIComponent(this.pathParams[a]):i),n=this.cleanupUrlPatternSyntax(r),o=this.searchParams.toString();return o?`${n}?${o}`:n}cleanupUrlPatternSyntax(e){return e.replace(/\{\/\}\?/g,"").replace(/\{\/\}[*+]/g,"/").replace(/\{\/\}/g,"/").replace(/(\{[^}]*\})[?*+]/g,"$1").replace(/\\:/g,":")}};var ba=class{constructor(e){this.routeData=e}static{s(this,"McpUrlBuilder")}build(e,r){let n=this.routeData.pathPattern?this.routeData.pathPattern:this.routeData.path,o=this.routeData.raw()?.parameters||[],i=new ya(n);for(let a of o)i.addParameter(a,e,r);return i.toString()}};De();De();De();var wa=class t{static{s(this,"ZodFormatSchemaRegistry")}static formatter=new Map([["email",()=>f.email()],["uri",()=>f.url()],["url",()=>f.url()],["date",()=>f.iso.date()],["date-time",()=>f.iso.datetime()],["time",()=>f.iso.time()],["ipv4",()=>f.ipv4()],["ipv6",()=>f.ipv6()],["uuid",()=>f.guid()],["int32",()=>f.int32()],["int64",()=>f.int64()],["float",()=>f.number()],["double",()=>f.number()]]);static get(e){return t.formatter.get(e)}static register(e,r){t.formatter.set(e,r)}},ln=class t{static{s(this,"OpenApiToZodTranspiler")}static typeTranspilers=new Map([["string",this.transpileString.bind(this)],["number",this.transpileNumber.bind(this)],["integer",this.transpileInteger.bind(this)],["boolean",this.transpileBoolean.bind(this)],["array",this.transpileArray.bind(this)],["object",this.transpileObject.bind(this)],["null",this.transpileNull.bind(this)]]);static run(e,r){let n={path:[],definitions:{},visitedRefs:new Set,...r};return t.transpileSchema(e,n)}static transpileSchema(e,r){if(!e)return f.unknown();try{if("$ref"in e)return t.resolveReference(e.$ref,r);if(e.allOf)return t.transpileAllOf(e.allOf,r);if(e.oneOf)return t.transpileOneOf(e.oneOf,r);if(e.anyOf)return t.transpileAnyOf(e.anyOf,r);if(e.not)return t.transpileNot(e.not,r);let n=t.transpileByType(e,r);return n=t.applyCommonModifiers(n,e),n}catch(n){let o=r.path.join(".");throw new Error(`Failed to transpile schema at path "${o}": ${n.message}`)}}static transpileByType(e,r){let n=e.type;!n&&e.properties&&(n="object");let o=t.typeTranspilers.get(n||"unknown");return o?o(e,r):f.unknown()}static transpileString(e,r){if(e.enum)return f.enum(e.enum);let n=e.format?wa.get(e.format):null,o=n?n():f.string();if(o instanceof f.ZodString){let i=o;return e.minLength!==void 0&&(i=i.min(e.minLength)),e.maxLength!==void 0&&(i=i.max(e.maxLength)),e.pattern&&(i=i.regex(new RegExp(e.pattern))),i}else e.minLength||e.maxLength||e.pattern;return o}static applyNumericConstraints(e,r,n){let o=e;if(r.minimum!==void 0&&(o=o.min(r.minimum)),r.maximum!==void 0&&(o=o.max(r.maximum)),r.exclusiveMinimum!==void 0){let i;if(typeof r.exclusiveMinimum=="number")i=r.exclusiveMinimum;else if(r.minimum!==void 0)i=r.minimum+Number.EPSILON;else throw new Error(`exclusiveMinimum requires minimum to be set at path "${n.path.join(".")}"`);o=o.gt(i)}if(r.exclusiveMaximum!==void 0){let i;if(typeof r.exclusiveMaximum=="number")i=r.exclusiveMaximum;else if(r.maximum!==void 0)i=r.maximum-Number.EPSILON;else throw new Error(`exclusiveMaximum requires maximum to be set at path "${n.path.join(".")}"`);o=o.lt(i)}return o}static transpileNumber(e,r){let n=f.number();return t.applyNumericConstraints(n,{...e,type:"number"},r)}static transpileInteger(e,r){let n=f.int();return t.applyNumericConstraints(n,{...e,type:"number"},r)}static transpileBoolean(e,r){return f.boolean()}static transpileArray(e,r){let n=e.items?t.transpileSchema(e.items,{...r,path:[...r.path,"items"]}):f.unknown(),o=f.array(n);return e.minItems!==void 0&&(o=o.min(e.minItems)),e.maxItems!==void 0&&(o=o.max(e.maxItems)),e.uniqueItems&&(o=o.refine(i=>new Set(i).size===i.length,{message:"Array must contain unique items"})),o}static transpileObject(e,r){let n;if(e.properties){let o={},i=new Set(e.required||[]);for(let[c,u]of Object.entries(e.properties)){let l={...r,path:[...r.path,c]},d=t.transpileSchema(u,l);i.has(c)||(d=d.optional()),o[c]=d}let a=f.object(o);e.additionalProperties===!1?a=a.strict():(e.additionalProperties,a=a.passthrough()),n=a}else if(e.additionalProperties===!1)n=f.object({}).strict();else if(typeof e.additionalProperties=="object"){let o=t.transpileSchema(e.additionalProperties,r);n=f.record(f.string(),o)}else n=f.unknown();return(e.minProperties!==void 0||e.maxProperties!==void 0)&&(n=n.refine(o=>{let i=Object.keys(o).length;return!(e.minProperties!==void 0&&i<e.minProperties||e.maxProperties!==void 0&&i>e.maxProperties)},{message:t.buildPropertyCountErrorMessage(e.minProperties,e.maxProperties)})),n}static buildPropertyCountErrorMessage(e,r){return e!==void 0&&r!==void 0?`Object must have between ${e} and ${r} properties`:e!==void 0?`Object must have at least ${e} properties`:`Object must have at most ${r} properties`}static transpileNull(e,r){return f.null()}static transpileAllOf(e,r){return e.map((o,i)=>t.transpileSchema(o,{...r,path:[...r.path,`allOf[${i}]`]})).reduce((o,i)=>o.and(i))}static transpileOneOf(e,r){let n=e.map((o,i)=>t.transpileSchema(o,{...r,path:[...r.path,`oneOf[${i}]`]}));return n.length===0?f.never():n.length===1?n[0]:f.union(n)}static transpileAnyOf(e,r){return t.transpileOneOf(e,r)}static transpileNot(e,r){let n=t.transpileSchema(e,{...r,path:[...r.path,"not"]});return f.unknown().refine(o=>!n.safeParse(o).success,{message:"Value must not match the schema"})}static resolveReference(e,r){if(r.visitedRefs?.has(e))return f.lazy(()=>t.resolveReference(e,r));r.visitedRefs?.add(e);let n=e.split("/");if(n[0]==="#"&&n[1]==="definitions"&&r.definitions){let o=r.definitions[n[2]];if(o)return t.transpileSchema(o,r)}throw new Error(`Unable to resolve reference: ${e}`)}static applyCommonModifiers(e,r){let n=e;return r.nullable&&(n=n.nullable()),r.default!==void 0&&(n=n.default(r.default)),r.description&&(n=n.describe(r.description)),r.examples&&r.examples.length>0&&(n=n.meta({examples:r.examples})),n}static registerTypeTranspiler(e,r){t.typeTranspilers.set(e,r)}static registerFormatSchema(e,r){wa.register(e,r)}};var va=class{constructor(e){this.schema=e}static{s(this,"JSONSchemaBuilder")}build(){return ln.run(this.schema)}},xa=class{constructor(e,r){this.routeData=e;this.contentType=r}static{s(this,"RequestBodySchemaBuilder")}build(){let e=this.routeData.raw()?.requestBody;if(!e?.content?.[this.contentType])return null;let r=e.content[this.contentType].schema;return r?ln.run(r):null}},Ra=class{constructor(e){this.parameters=e}static{s(this,"ParameterSchemaBuilder")}build(){if(this.parameters.length===0)return null;let e={};for(let r of this.parameters)e[r.name]=this.buildParameterSchema(r);return f.object(e)}buildParameterSchema(e){let r;e.schema?r=ln.run(e.schema):r=f.string(),e.required||(r=r.optional()),e.description&&(r=r.describe(e.description));let n=[];if(e.schema?.example!==void 0&&n.push(e.schema.example),e.schema?.examples!==void 0&&Array.isArray(e.schema.examples)&&n.push(...e.schema.examples),e.examples&&(Array.isArray(e.examples)?n.push(...e.examples):typeof e.examples=="object"&&Object.values(e.examples).forEach(o=>{o?.value!==void 0&&n.push(o.value)})),e.example!==void 0&&n.push(e.example),n.length>0){let o=[...new Set(n.map(i=>JSON.stringify(i)))].map(i=>JSON.parse(i));r=r.meta({examples:o})}return r}};var Or=class t{static{s(this,"UniversalValidatorBuilder")}root=null;components={};static withRoot(e){let r=new t;return r.root=e,r}withBody(e){return e&&(this.components.body=e),this}withQueryParams(e){return e&&(this.components.queryParams=e),this}withPathParams(e){return e&&(this.components.pathParams=e),this}withHeaders(e){return e&&(this.components.headers=e),this}build(){return this.root?this.buildFromSchema(this.root):Object.keys(this.components).length>0?this.buildFromComponents():this.buildEmptyValidator()}buildFromSchema(e){let r=f.toJSONSchema(e);return new lr(r,n=>{let o=e.safeParse(n);return o.success?{success:!0,data:o.data,errorData:null}:{success:!1,data:null,errorMessage:f.prettifyError(o.error),errorData:f.treeifyError(o.error)}})}buildFromComponents(){let e=f.object(this.components),r=f.toJSONSchema(e);return new lr(r,n=>{let o=e.safeParse(n);return o.success?{success:!0,data:o.data,errorData:null}:{success:!1,data:null,errorMessage:f.prettifyError(o.error),errorData:f.treeifyError(o.error)}})}buildEmptyValidator(){let e={type:"object",properties:{},required:[],additionalProperties:!1};return new lr(e,r=>({success:!0,data:r,errorData:null}))}},$r=class t{static{s(this,"SchemaBuilderFactory")}static createJsonSchemaBuilder(e){return new va(e)}static createRequestBodyBuilder(e,r){return new xa(e,r)}static createParameterBuilder(e,r){let n=r?e.filter(o=>o.in===r):e;return new Ra(n)}static createValidatorBuilder(e,r){let n=new Or,o=e.raw()?.parameters||[];if(r){let u=t.createRequestBodyBuilder(e,r);n.withBody(u.build())}let i=t.createParameterBuilder(o,"query");n.withQueryParams(i.build());let a=t.createParameterBuilder(o,"path");n.withPathParams(a.build());let c=t.createParameterBuilder(o,"header");return n.withHeaders(c.build()),n}static createPromptValidatorBuilder(e){let r=new Or,o=e.raw()?.requestBody;if(!o?.content||!o.content["application/json"])return r;let a=t.createRequestBodyBuilder(e,"application/json");return Or.withRoot(a.build())}static createObjectValidatorBuilder(e){let r=new Or;if(!e||Object.keys(e).length===0)return r;let n=t.createJsonSchemaBuilder(e);return Or.withRoot(n.build())}};var dn=class t{static{s(this,"ZuploMcpServer")}static instances=new Map;static async getInstance({opts:e,context:r,key:n,origins:o}){let i=e.debugMode??!1,a=t.instances.get(n);if(a)i&&r.log.debug("MCP Server warm reuse",{routeKey:n});else{let c=Date.now();if(a=new t(e,r,o??[]),a.registerFromOperations(a.opts.operations??[]),a.registerToolsFromFileSources(a.opts.files??[]),a.registerPromptsFromFileSources(a.opts.prompts??[]),a.registerResourcesFromFileSources(a.opts.resources??[]),await a.registerProxyTools(a.origins??[]),await a.transport.connect(),a.server.withTransport(a.transport),t.instances.set(n,a),i){let u=a.server.getTools(),l=u?u.size:0,d=a.server.getPromptDefinitions(),p=d?d.length:0,m=a.server.getResourceDefinitions(),g=m?m.length:0,h=Date.now()-c;r.log.debug("MCP Server cold start",{routeKey:n,toolCount:l,promptCount:p,resourceCount:g,totalElapsedMs:h,debugMode:i,includeOutputSchema:a.includeOutputSchema,includeStructuredContent:a.includeStructuredContent})}}return a}transport;server;opts;origins;context;registeredToolNames;registeredPromptNames;registeredResourceNames;includeOutputSchema;includeStructuredContent;debugMode;constructor(e,r,n){this.debugMode=e.debugMode??!1;let o;this.debugMode?o=r.log:o=new to,this.context=r,this.opts=e,this.origins=n??[],this.server=new aa({name:e.name??"Zuplo MCP Server",version:e.version??"0.0.0",logger:o}),this.transport=new ca({logger:o}),this.includeOutputSchema=e.includeOutputSchema??!1,this.includeStructuredContent=e.includeStructuredContent??!1,this.registeredToolNames=new Set,this.registeredPromptNames=new Set,this.registeredResourceNames=new Set}async handleRequest(e,r){let n=Date.now();try{let o=await e.clone().json().catch(()=>({}));switch(this.debugMode&&r.log.debug("MCP Server request start",{method:o.method,requestId:o.id,routePath:r.route?.path}),o.method){case"tools/list":if(this.debugMode){let c=this.server.getTools(),u=c?Array.from(c.keys()):[];r.log.debug("MCP Server list tools request",{toolCount:u.length,toolNames:u})}break;case"tools/call":r.custom.mcpCallToolRequest=o;break;case"prompts/list":if(this.debugMode){let c=this.server.getPromptDefinitions(),u=c?c.map(l=>l.name):[];r.log.debug("MCP Server list prompts request",{promptCount:u.length,promptNames:u})}break;case"resources/list":if(this.debugMode){let c=this.server.getResourceDefinitions(),u=c?c.map(l=>l.name):[];r.log.debug("MCP Server list resources request",{resourceCount:u.length,resourceNames:u})}break}let i=await this.transport.handleRequest(e),a=Date.now()-n;if(this.debugMode){let c=await i.clone().json().catch(()=>({}));r.log.debug("MCP Server response complete",{status:i.status,requestMethod:o.method,requestId:o.id,totalElapsedMs:a,respData:c})}return i}catch(o){let i=Date.now()-n;return r.log.error("MCP server internal error",{elapsedMs:i,err:o}),new Response("Internal error",{status:500})}}generatePromptDescriptionFromSpec(e){let r=e.raw();return r?.description?r.description:r?.summary?r.summary:`Generate content for operation for ${e.path}`}static getOperationsMetadataForFile(e){let{routes:r}=Re.instance.routeData,n=r.filter(i=>i.metadata?.filepath===e);if(n.length===0)throw new Error(`MCP Tool configuration error: No routes found for file path ${e}. Verify that the OpenAPI file exists and is properly loaded in your Gateway configuration with routes.`);let o=new Map;for(let i of n){let a=i?.raw().operationId;if(a){o.set(a,{routeConfig:i});let c=i?.raw(),u=c["x-zuplo-mcp-tool"],l=c["x-zuplo-mcp-prompt"],d=c["x-zuplo-mcp-graphql"],p=c["x-zuplo-mcp-resource"],m=c["x-zuplo-route"]?.mcp;(u||l||d||p||m)&&o.set(a,{routeConfig:i,toolExtension:u||void 0,promptExtension:l||void 0,graphqlExtension:d||void 0,resourceExtension:p||void 0,routeMcpExtension:m||void 0})}}return o}registerFromOperations(e){let r=new Map;for(let n of e){let o=r.get(n.file)??[];o.push(n.id),r.set(n.file,o)}for(let[n,o]of r.entries()){let i=t.getOperationsMetadataForFile(n);for(let a of o){let c=i.get(a);if(!c)throw new Error(`MCP configuration error: Could not find operation with ID "${a}" in file ${n}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:u,routeMcpExtension:l}=c;switch(l?.type){case"tool":this.registerTool(u,a,l);break;case"prompt":this.registerPrompt(u,a,l);break;case"resource":this.registerResource(u,a,l);break;case"graphql":this.registerGraphQLTools(a,u,l);break;default:this.context.log.warn(`Could not find "x-zuplo-route.mcp" configuration for operation: "${a}". Creating tool with fallback name and description`),this.registerTool(u,a,l)}}}}registerPromptsFromFileSources(e){for(let r of e){let n=t.getOperationsMetadataForFile(r.path),o=new Set;for(let i of r.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP prompt with operation ID: "${i}" from file: "${r.path}" with: "options.prompts" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=n.get(i);if(!a)throw new Error(`MCP Prompt configuration error: Could not find operation with ID "${i}" in file ${r.path}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:c,promptExtension:u}=a,l=u?.name??i;if(o.has(l))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${l}". Prompt names must be unique across all configured prompts.`);o.add(l);let d=u?.description??this.generatePromptDescriptionFromSpec(c);if(!(u?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP prompt disabled by extension",{promptName:l,operationId:i});continue}this.registerPromptForOperation(l,d,c,i)}}}registerPromptForOperation(e,r,n,o){try{if(n.handler?.export==="mcpServerHandler")return;let a=$r.createPromptValidatorBuilder(n).build();this.server.addPrompt({name:e,description:r,validator:a,generator:s(async c=>{let u=dr(),l=Date.now();try{this.debugMode&&u.log.debug("MCP prompt invoked",{promptName:e,operationId:n.raw()?.operationId,path:n.path,args:c});let d=this.buildToolUrl(n,{body:c}),p=this.buildToolRequest("POST","application/json",{body:c});this.debugMode&&u.log.debug("MCP prompt downstream call",{promptName:e,url:d,method:"POST",bodyPreview:c});let m=Date.now(),g=await u.invokeRoute(d,p),h=Date.now()-m,b=await g.json();if(!g.ok)throw new Error(`Route returned ${g.status}: ${b}`);let y;try{if(y=b.messages||b,!Array.isArray(y))throw new Error("Response must contain a 'messages' array or be an array of messages")}catch(v){throw new Error(`Invalid JSON response or missing messages array: ${v instanceof Error?v.message:String(v)}`)}let w=Date.now()-l;return this.debugMode&&u.log.debug("MCP prompt response complete",{promptName:e,operationId:n.raw()?.operationId,status:g.status,elapsedMs:w,downstreamElapsedMs:h,messageCount:y.length}),y}catch(d){let p=Date.now()-l,m=d instanceof Error?`${d.name}: ${d.message}`:String(d);throw u.log.error("MCP prompt invocation failed",{promptName:e,operationId:n.raw()?.operationId,path:n.path,elapsedMs:p,err:d}),new Error(`MCP tool call failed for tool '${e}': ${m}`)}},"generator")}),this.debugMode&&this.context.log.debug("MCP prompt registered from file source",{promptName:e,operationId:o,path:n.path})}catch(i){throw this.context.log.error("Failed to register MCP prompt",{promptName:e,operationId:o,error:i instanceof Error?i.message:String(i)}),new Error(`Failed to register prompt "${e}" for operation "${o}": ${i instanceof Error?i.message:String(i)}`)}}registerResourcesFromFileSources(e){let r=new Set;for(let n of e){let o=t.getOperationsMetadataForFile(n.path);for(let i of n.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP resource with operation ID: "${i}" from file: "${n.path}" with: "options.resources" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=o.get(i);if(!a)throw new Error(`MCP Resource configuration error: Could not find operation with ID "${i}" in file ${n.path}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:c,resourceExtension:u}=a;if(!(u?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP resource disabled by extension",{operationId:i});continue}if(!c.methods||c.methods.length===0)throw new Error(`MCP Resource configuration error: Operation "${i}" has no HTTP methods defined. Resources must use GET method.`);if(c.methods.length>1)throw new Error(`MCP Resource configuration error: Operation "${i}" has multiple HTTP methods (${c.methods.join(", ")}). Resources must use exactly one method and it must be GET.`);let d=c.methods[0].toUpperCase();if(d!=="GET")throw new Error(`MCP Resource configuration error: Operation "${i}" uses ${d} method. Resources are read-only and must use GET method only.`);let p=u?.name?.trim()||i.trim()||"";if(!p)throw new Error(`MCP Resource configuration error: Could not determine resource name for operation "${i}". Ensure the operation has an operationId or provide a name in x-zuplo-mcp-resource extension.`);if(r.has(p))throw new Error(`MCP Resource configuration error: Duplicate resource name "${p}". Resource names must be unique across all configured resources.`);r.add(p);let m=u?.description?.trim()||c.raw()?.description?.trim()||c.raw()?.summary?.trim()||`Resource for ${p}`,g=u?.uri?.trim()||`mcp://resources/${encodeURIComponent(p)}`,h=u?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(p,g,m,c,i,h)}}}registerResourceForOperation(e,r,n,o,i,a,c){try{if(o.handler?.export==="mcpServerHandler")return;this.server.addResource(e,r,{title:e,description:n,mimeType:a,...c&&{_meta:c}},async()=>{let u=dr(),l=Date.now();try{this.debugMode&&u.log.debug("MCP resource invoked",{resourceName:e,operationId:o.raw()?.operationId,path:o.path,uri:r});let d=this.buildToolUrl(o,{}),p=this.buildToolRequest("GET",null,{});this.debugMode&&u.log.debug("MCP resource downstream call",{resourceName:e,url:d,method:"GET"});let m=Date.now(),g=await u.invokeRoute(d,p),h=Date.now()-m,b=await g.text(),y=Date.now()-l;return this.debugMode&&u.log.debug("MCP resource response complete",{resourceName:e,operationId:o.raw()?.operationId,status:g.status,elapsedMs:y,downstreamElapsedMs:h,declaredMimeType:a,contentLength:b.length}),{contents:[{uri:r,declaredMimeType:a,text:b}]}}catch(d){let p=Date.now()-l,m=d instanceof Error?`${d.name}: ${d.message}`:String(d);throw u.log.error("MCP resource invocation failed",{resourceName:e,operationId:o.raw()?.operationId,path:o.path,elapsedMs:p,err:d}),new Error(`MCP resource call failed for resource '${e}': ${m}`)}}),this.debugMode&&this.context.log.debug("MCP resource registered from file source",{resourceName:e,operationId:i,path:o.path,uri:r,mimeType:a||"auto-detected"})}catch(u){throw this.context.log.error("Failed to register MCP resource",{resourceName:e,operationId:i,error:u instanceof Error?u.message:String(u)}),new Error(`Failed to register resource "${e}" for operation "${i}": ${u instanceof Error?u.message:String(u)}`)}}registerTool(e,r,n){if(!(n?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP tool disabled by x-zuplo-route.mcp configuration",{operationId:r});return}let i=n?.name?.trim()||r;if(this.registeredToolNames.has(i))throw new Error(`MCP Tool configuration error: Tool name conflict detected for operation: "${r}". The tool name "${i}" is already in use. Provide a unique 'name' in the x-zuplo-route.mcp configuration for operation "${r}".`);this.registeredToolNames.add(i);let a=n?.description?.trim()||e.raw().description?.trim()||e.raw().summary?.trim()||`Executes tool: ${i}`,c=n?.includeOutputSchema??this.includeOutputSchema??!1,u=n?.includeStructuredContent??this.includeStructuredContent??!1;if(e.methods.length!=1)throw new Error(`MCP tool configuration error: multiple methods "${e.methods.join(", ")}" on operation "${r}" not permitted. Only tools with a singular method are permitted.`);this.registerToolsForMethod({routeData:e,method:e.methods[0],name:i,description:a,includeOutputSchema:c,includeStructuredContent:u,annotations:n?.annotations,_meta:n?._meta})}registerPrompt(e,r,n){if(!(n?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP prompt disabled by x-zuplo-route.mcp",{operationId:r});return}let i=n?.name?.trim()||r;if(this.registeredPromptNames.has(i))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${i}" for operation ID "${r}". Prompt names must be unique across all configured prompts.`);this.registeredPromptNames.add(i);let a=n?.description?.trim()||this.generatePromptDescriptionFromSpec(e);this.registerPromptForOperation(i,a,e,r)}registerResource(e,r,n){if(!(n?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP resource disabled by x-zuplo-route.mcp",{operationId:r});return}if(!e.methods||e.methods.length===0)throw new Error(`MCP Resource configuration error: Operation "${r}" has no HTTP methods defined. Resources must use GET method.`);if(e.methods.length>1)throw new Error(`MCP Resource configuration error: Operation "${r}" has multiple HTTP methods (${e.methods.join(", ")}). Resources must use exactly one method and it must be GET.`);let i=e.methods[0].toUpperCase();if(i!=="GET")throw new Error(`MCP Resource configuration error: Operation "${r}" uses ${i} method. Resources are read-only and must use GET method only.`);let a=n?.name?.trim()||r;if(this.registeredResourceNames.has(a))throw new Error(`MCP Resource configuration error: Duplicate resource name "${a}". Resource names must be unique across all configured resources.`);this.registeredResourceNames.add(a);let c=n?.description?.trim()||e.raw()?.description?.trim()||e.raw()?.summary?.trim()||`Resource for ${a}`,u=n?.uri?.trim()||`mcp://resources/${encodeURIComponent(a)}`,l=n?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(a,u,c,e,r,l,n?._meta)}registerToolsFromFileSources(e){let r=new Set;for(let n of e){let o=t.getOperationsMetadataForFile(n.path);this.debugMode&&this.context.log.debug("Processing file source",{path:n.path,operationIds:n.operationIds,availableOperationIds:Array.from(o.keys())});for(let i of n.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP tool with operation ID: "${i}" from file: "${n.path}" with: "options.files" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=o.get(i);if(!a)throw new Error(`MCP Tool configuration error: Operation ID "${i}" not found in OpenAPI spec at ${n.path}. Available operation IDs: ${Array.from(o.keys()).join(", ")}`);if(a.toolExtension?.enabled===!1){this.debugMode&&this.context.log.debug("Skipping disabled tool",{operationId:i,path:n.path});continue}let c=a.toolExtension?.name?.trim()??i,u=(a.toolExtension?.description?.trim()||null)??(a.routeConfig.raw().description?.trim()||null)??(a.routeConfig.raw().summary?.trim()||null)??`Executes tool: ${c}`;if(!u)throw new Error(`MCP Tool configuration error: no tool description found for operationId: "${i}" in file "${n.path}"`);if(r.has(c))throw new Error(`MCP Tool configuration error: Tool name conflict detected. The name "${c}" is already in use. Consider providing a unique 'name' in the x-zuplo-mcp-tool extension for operation "${i}".`);r.add(c);let l=a.toolExtension?.includeOutputSchema??this.includeOutputSchema??!1,d=a.toolExtension?.includeStructuredContent??this.includeStructuredContent??!1;if(a.routeConfig.methods.length!=1)throw new Error(`MCP tool configuration error: multiple methods "${a.routeConfig.methods.join(", ")}" on operation "${i}" not permitted. Only tools with one singular method is permitted.`);a.graphqlExtension?(a.graphqlExtension.enabled??!0)&&this.registerGraphQLTools(i,a.routeConfig,{type:"graphql",introspectionTool:{name:a.graphqlExtension.introspectionToolName??"",description:a.graphqlExtension.introspectionToolDescription??""},executeTool:{name:a.graphqlExtension.executeToolName??"",description:a.graphqlExtension.executeToolDescription??""}}):this.registerToolsForMethod({routeData:a.routeConfig,method:a.routeConfig.methods[0],name:c,description:u,includeOutputSchema:l,includeStructuredContent:d})}}}registerGraphQLTools(e,r,n){let o=n?.introspectionTool?.name?.trim()||`${e}_introspect`,i=n?.executeTool?.name?.trim()||`${e}_execute_query`;if(this.registeredToolNames.has(o))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The introspection tool name "${o}" is already in use. Provide a unique tool name.`);if(this.registeredToolNames.has(i))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The execute tool name "${i}" is already in use. Provide a unique 'executeToolName' in the x-zuplo-graphql extension.`);this.registeredToolNames.add(o),this.registeredToolNames.add(i);let a=n?.introspectionTool?.description??`Get the GraphQL schema for ${e}`,c=n?.executeTool?.description??`Execute a GraphQL query on ${e}`,u=r.path,d=$r.createObjectValidatorBuilder({}).build();this.server.addTool({name:o,description:a,validator:d,handler:s(async()=>{let m=dr(),g=Date.now();try{this.debugMode&&m.log.debug("MCP GraphQL introspection tool invoked",{toolName:o,operationId:e,path:u});let h=ua(),b=this.buildToolUrl(r,{}),y=this.buildToolRequest("POST","application/json",{body:{query:h}}),w=Date.now(),v=await m.invokeRoute(b,y),S=Date.now()-w,O=await v.text(),T=Date.now()-g;this.debugMode&&(v.ok?m.log.debug("MCP GraphQL introspection tool ok response",{toolName:o,operationId:e,status:v.status,elapsedMs:T,downstreamElapsedMs:S}):m.log.debug("MCP GraphQL introspection tool 'isError' response",{toolName:o,operationId:e,status:v.status,elapsedMs:T,downstreamElapsedMs:S,response:O}));let k;try{k=JSON.parse(O)}catch(N){this.debugMode&&m.log.debug("MCP GraphQL introspection structuredContent JSON parse failed",{toolName:o,body:O,parseErr:N})}return{content:[{type:"text",text:O}],...k&&{structuredContent:k},isError:!v.ok}}catch(h){let b=Date.now()-g,y=h instanceof Error?`${h.name}: ${h.message}`:String(h);throw m.log.error("MCP GraphQL introspection tool invocation failed",{toolName:o,operationId:e,path:u,elapsedMs:b,err:h}),new Error(`MCP GraphQL introspection tool call failed for '${o}': ${y}`)}},"handler")});let p={type:"object",properties:{query:{type:"string",description:"The GraphQL query to execute"},variables:{type:"object",description:"Optional variables for the GraphQL query"}},required:["query"],additionalProperties:!1};this.server.addTool({name:i,description:c,validator:new lr(p,m=>typeof m=="object"&&m!==null&&"query"in m&&typeof m?.query=="string"?{success:!0,data:m,errorData:null}:{success:!1,data:null,errorMessage:"Invalid input: query field is required and must be a string",errorData:null}),handler:s(async m=>{let g=dr(),h=Date.now();try{this.debugMode&&g.log.debug("MCP GraphQL execute tool invoked",{toolName:i,operationId:e,path:u,queryPreview:m.query.substring(0,100)});let b=this.buildToolUrl(r,{}),y={query:m.query};m.variables&&(y.variables=m.variables);let w=this.buildToolRequest("POST","application/json",{body:y}),v=Date.now(),S=await g.invokeRoute(b,w),O=Date.now()-v,T=await S.text(),k=Date.now()-h;this.debugMode&&(S.ok?g.log.debug("MCP GraphQL execute tool ok response",{toolName:i,operationId:e,status:S.status,elapsedMs:k,downstreamElapsedMs:O}):g.log.debug("MCP GraphQL execute tool 'isError' response",{toolName:i,operationId:e,status:S.status,elapsedMs:k,downstreamElapsedMs:O,response:T}));let N;try{N=JSON.parse(T)}catch(U){this.debugMode&&g.log.debug("MCP GraphQL execute structuredContent JSON parse failed",{toolName:i,body:T,parseErr:U})}return{content:[{type:"text",text:T}],...N&&{structuredContent:N},isError:!S.ok}}catch(b){let y=Date.now()-h,w=b instanceof Error?`${b.name}: ${b.message}`:String(b);throw g.log.error("MCP GraphQL execute tool invocation failed",{toolName:i,operationId:e,path:u,elapsedMs:y,err:b}),new Error(`MCP GraphQL execute tool call failed for '${i}': ${w}`)}},"handler")}),this.debugMode&&this.context.log.debug("MCP GraphQL tools registered",{operationId:e,introspectionToolName:o,executeToolName:i,path:u})}registerToolsForMethod({routeData:e,method:r,name:n,description:o,includeOutputSchema:i,includeStructuredContent:a,annotations:c,_meta:u}){if(e.handler?.export!=="mcpServerHandler")if(e.raw().requestBody?.content)for(let l of Object.keys(e.raw().requestBody?.content)){let p=Object.keys(e.raw().requestBody?.content).length>1?`${n}_${l.replace(/[^\w]/g,"_")}`:n;this.registerGenericToolSpec({name:p,description:o,routeData:e,method:r,contentType:l,includeOutputSchema:i,includeStructuredContent:a,annotations:c,_meta:u})}else this.registerGenericToolSpec({name:n,description:o,routeData:e,method:r,contentType:null,includeOutputSchema:i,includeStructuredContent:a,annotations:c,_meta:u})}registerGenericToolSpec({name:e,description:r,routeData:n,method:o,contentType:i,includeOutputSchema:a,includeStructuredContent:c,annotations:u,_meta:l}){let d=this.buildUniversalValidator(n,i);if(!d)throw new Error(`MCP Tool registration error: Could not build parameter validator for ${o.toUpperCase()} ${n.path}. This may indicate an issue with the OpenAPI parameter definitions for this route.`);let p=a?this.extractOutputSchema(n):void 0;try{this.server.addTool({name:e,description:r,validator:d,...p&&{outputSchema:p},...u&&{annotations:u},...l&&{_meta:l},handler:s(async(m,g)=>{let h=dr(),b=Date.now();try{this.debugMode&&h.log.debug("MCP tool invoked",{toolName:e,operationId:n.raw()?.operationId,method:o,path:n.path,args:m});let y=this.buildToolUrl(n,m),w=this.buildToolRequest(o,i,m);this.debugMode&&h.log.debug("MCP tool downstream call",{toolName:e,url:y,method:o,headers:w.headers?Object.keys(w.headers).join(", "):"",bodyPreview:m.body}),h.analyticsContext.addAnalyticsEvent(1,$e.MCP_TOOL_USAGE,{toolName:e,toolPath:n.path,toolMethod:o,toolOperationId:n.raw()?.operationId??"unknown"});let v=Date.now(),S=await h.invokeRoute(y,w),O=Date.now()-v,T=await S.text(),k;if(c)try{k=JSON.parse(T)}catch(U){this.debugMode&&h.log.debug("MCP tool structuredContent JSON parse failed",{toolName:e,body:T,parseErr:U})}let N=Date.now()-b;return this.debugMode&&(S.ok?h.log.debug("MCP tool ok response",{toolName:e,operationId:n.raw()?.operationId,status:S.status,elapsedMs:N,downstreamElapsedMs:O}):h.log.debug("MCP tool 'isError' response",{toolName:e,operationId:n.raw()?.operationId,status:S.status,elapsedMs:N,downstreamElapsedMs:O,response:T})),{content:[{type:"text",text:T}],...k&&{structuredContent:k},isError:!S.ok,_meta:h.custom.mcpCallToolResponse?._meta??{}}}catch(y){let w=Date.now()-b,v=y instanceof Error?`${y.name}: ${y.message}`:String(y);return h.log.error("MCP server tool invocation failed",{toolName:e,operationId:n.raw()?.operationId,method:o,path:n.path,elapsedMs:w,err:y}),{content:[{type:"text",text:`MCP tool call failed for tool '${e}': ${v}`}],isError:!0}}},"handler")}),this.debugMode&&this.context.log.debug("MCP tool registered",{toolName:e,method:o.toUpperCase(),path:n.path,operationId:n.raw()?.operationId,contentType:i||"none",includeOutputSchema:a,includeStructuredContent:c,hasValidator:!!d,hasOutputSchema:!!p})}catch(m){throw new Error(`Failed to add tool ${o} ${n.path}`,m)}}async registerProxyTools(e){let r=new Set;for(let n of e){if(n.enabled===!1){this.debugMode&&this.context.log.debug("Skipping disabled origin",{origin:n.name});continue}let o=n.toolNamePrefix??"";this.debugMode&&this.context.log.debug("Registering origin tools",{origin:n.name,baseUrl:n.baseUrl,toolCount:n.tools.length,toolNamePrefix:o||"none",tools:n.tools});for(let i of n.tools){let a=`${o}${i.name}`;if(r.has(a))throw new Error(`MCP origin configuration error: Tool name conflict detected. The name "${a}" is already in use. Consider using different tool names or toolNamePrefix for origin "${n.name}".`);r.add(a);let u=$r.createObjectValidatorBuilder(i.inputSchema).build();try{let l=new ga(n.baseUrl,i.name,this.debugMode,n.headers);this.server.addTool({name:a,description:i.description,validator:u,handler:s(async d=>await l.execute(d),"handler")}),this.debugMode&&this.context.log.debug("origin tool registered",{localToolName:a,originToolName:i.name,origin:n.name,baseUrl:n.baseUrl})}catch(l){throw new Error(`Failed to register origin tool ${a} from ${n.name}`,{cause:l})}}}this.debugMode&&e.length>0&&this.context.log.debug("origin tool registration complete",{totaloOigins:e.length,totalOriginTools:r.size,originToolNames:Array.from(r)})}buildToolUrl(e,r){return new ba(e).build(r.pathParams,r.queryParams)}buildToolRequest(e,r,n){let o=this.buildToolHeaders(e,r,n),i={method:e,headers:o};return this.shouldIncludeBody(e,r,n)&&(i.body=this.serializeBody(n.body,r)),i}buildToolHeaders(e,r,n){let o={...Jo()};return n.headers&&Object.entries(n.headers).forEach(([i,a])=>{o[i.toLowerCase()]=a}),r&&n.body!==void 0&&(o["content-type"]=r),this.isBodyMethod(e||"")&&n.body!==void 0&&!o["content-type"]&&(o["content-type"]="application/json"),o}shouldIncludeBody(e,r,n){return n.body===void 0?!1:this.isBodyMethod(e)?!0:r!==null}isBodyMethod(e){return["POST","PUT","PATCH"].includes(e.toUpperCase())}serializeBody(e,r){return JSON.stringify(e)}buildUniversalValidator(e,r){try{let o=$r.createValidatorBuilder(e,r).build();return this.debugMode&&this.context.log.debug("MCP validator built successfully",{method:e.methods?.[0],path:e.path,contentType:r||"none",operationId:e.raw()?.operationId}),o}catch(n){let o=n instanceof Error?n.message:String(n);throw this.context.log.warn("MCP validator build failed",{method:e.methods?.[0],path:e.path,contentType:r||"none",operationId:e.raw()?.operationId,error:o}),n}}extractOutputSchema(e){try{let r=e.raw(),n=r?.responses;if(!n){this.context.log.warn("No responses found in OpenAPI spec for outputSchema",{path:e.path,operationId:r?.operationId});return}for(let o of Object.keys(n))if(o.startsWith("2")){let a=n[o]?.content;if(a){for(let c of["application/json","application/json; charset=utf-8"])if(a[c]?.schema){let u=a[c].schema;return this.debugMode&&this.context.log.debug("Output schema extracted successfully",{path:e.path,operationId:r?.operationId,statusCode:o,contentType:c,schemaKeys:u&&typeof u=="object"?Object.keys(u).join(", "):"none"}),u}}}this.debugMode&&this.context.log.debug("No OpenAPI spec 2xx responses fond for outputSchema",{path:e.path,operationId:r?.operationId,statusCodes:Object.keys(n).join(", ")});return}catch(r){this.context.log.warn("Failed to extract outputSchema",{path:e.path,operationId:e.raw()?.operationId,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0});return}}};async function Vv(t,e,r,n){let o=P.instance.zuploEdgeApiUrl;if(!o)throw new x("Zuplo edge API URL not configured");let i=Se.ZUPLO_SERVICE_BUCKET_ID;if(!i)throw new x("ZUPLO_SERVICE_BUCKET_ID env not configured");let a=P.instance.authApiJWT;if(!a)throw new x("Zuplo auth API JWT not configured");let c=`${o}/zups/v1/buckets/${i}/mcp/configurations/${r}/servers/access`,u={sub:t,slug:e},l=await z.fetch(c,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(u)});return l.status===403?!1:l.ok?(await l.json()).allowed:(n.log.error(`Unexpected response from MCP gateway at <${i} ${r}> access check: ${l.status} ${l.statusText}`),!1)}s(Vv,"checkVirtualServerAccess");var Jv=10,Wv=3e4,Ar=class{static{s(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,r){if(typeof r=="number"){let n=r;this.#n=n*1e3,this.#o=Wv,this.#r=Jv}else{let n=r;this.#n=n.ttlSeconds*1e3,this.#o=n.loaderTimeoutSeconds?n.loaderTimeoutSeconds*1e3:Wv,this.#r=Jv}this.#t=e}#s(e){return e.expiry<=new Date}#c(e){let r=this.#i[e];return!(r===void 0||r===0)}#u(e){let r=this.#e.get(e);if(r&&!this.#s(r))return r.data}async get(e){let r=this.#u(e);if(r)return this.#l(e),r;if(this.#c(e))try{await YE(()=>this.#u(e)!==void 0||!this.#c(e),this.#o+this.#r+1,this.#r);let n=this.#u(e);if(n)return n}catch{}return this.#a(e)}#l(e){if(!this.#c(e)){let r=this.#a(e);tr().waitUntil(r)}}async#a(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let r=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(r===void 0)throw new x(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:r,expiry:new Date(Date.now()+this.#n)}),r}finally{this.#i[e]--}}};async function YE(t,e,r){let n=Date.now();for(;!t();){let o=Date.now()-n;if(o>e)throw new x(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(r)}}s(YE,"waitUntilTrue");var XE={ttlSeconds:600,loaderTimeoutSeconds:30},Kv=new Ar(async()=>{let t=P.instance.zuploEdgeApiUrl;if(!t)throw new x("Zuplo edge API URL not configured");let e=P.instance.authApiJWT;if(!e)throw new x("Zuplo auth API JWT not configured");let r=P.instance.deploymentName;if(!r)throw new x("Deployment name not configured");let n=Se.ZUPLO_SERVICE_BUCKET_ID;if(!n)throw new x("ZUPLO_SERVICE_BUCKET_ID env not configured");let o=`${t}/zups/v1/buckets/${n}/mcp/resolve`,i=await z.fetch(o,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-Agent":P.instance.systemUserAgent,"Content-Type":"application/json"},body:JSON.stringify({deployment:r})});if(!i.ok){let u=await i.text().catch(()=>"");throw new x(`Failed to resolve MCP gateway configuration from ${o}: ${i.status} ${i.statusText}${u?` - ${u}`:""}`)}let a=await i.json(),c=a.mcpGatewayConfig;if(c.configurationId=a.configurationId,!c||typeof c!="object")throw new x("Invalid MCP gateway configuration: not an object");if(!Array.isArray(c.servers))throw new x("Invalid MCP gateway configuration: servers must be an array");return c},XE);async function eC(t,e){if(R("handler.mcp-gateway"),e.route.methods.some(h=>h.toUpperCase()!=="POST"))throw new x(`Invalid route config: mcpGatewayHandler may only use POST. Route '${e.route.path}' declares methods: [${e.route.methods.join(", ")}]`);let r=e.route?.handler?.options??{},n=await Kv.get("NO_KEY");e.log.debug(`Loaded configuration with ${n.servers?.length??0} servers`);let o=t.params.slug;if(!o)throw new Error("No MCP gateway slug provided in request");let i=n.servers.find(h=>h.slug===o);if(!i)throw new Error(`No MCP server configuration found for slug: ${o}`);if(!t.user?.sub)throw W.getLogger(e).error(`No user provided in request in MCP Gateway<${n.configurationId}>. This should not happen.`),new x(`MCP Gateway<${n.configurationId}>: No user provided in request. }
244
+ `&&n++}}return[e,r]}s(SE,"splitLines");var pa=class extends TransformStream{static{s(this,"EventSourceParserStream")}constructor({onError:e,onRetry:r,onComment:n}={}){let o;super({start(i){o=Av({onEvent:s(a=>{i.enqueue(a)},"onEvent"),onError(a){e==="terminate"?i.error(a):typeof e=="function"&&e(a)},onRetry:r,onComment:n})},transform(i){o.feed(i)}})}};var ma=class{static{s(this,"HTTPClientTransport")}url;timeout;headers;fetch;logger;sessionId;messageHandler;errorCallback;closeCallback;isConnected=!1;constructor(e){this.url=e.url,this.timeout=e.timeout||3e4,this.headers={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...e.headers},this.fetch=e.fetch||globalThis.fetch,this.logger=e.logger||nr(),e.enableSessions&&this.logger.debug("Session support not yet implemented for HTTP client transport")}setHeaders(e){this.headers={...this.headers,...e}}async connect(){try{new URL(this.url),this.isConnected=!0,this.logger.info("HTTP Client Transport connected to:",this.url)}catch{let r=new Error(`Invalid URL: ${this.url}`);throw this.errorCallback&&this.errorCallback(r),r}}async send(e){if(!this.isConnected)throw new Error("Transport not connected. Call connect() first.");let r;try{let n={...this.headers};this.sessionId&&(n["Mcp-Session-Id"]=this.sessionId);let o=new AbortController;r=setTimeout(()=>o.abort(),this.timeout);let i=await this.fetch(this.url,{method:"POST",headers:{...this.headers,...this.sessionId&&{"Mcp-Session-Id":this.sessionId}},body:JSON.stringify(e),signal:o.signal});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);(i.headers.get("Content-Type")||"").includes("text/event-stream")?await this.handleSSEResponse(i):await this.handleJSONResponse(i)}catch(n){if(n instanceof Error&&n.name==="AbortError")throw this.errorCallback&&this.errorCallback(n),new Error(`Request timeout after ${this.timeout}ms`);let o=new Error(`A client error occurred: ${n}`);throw this.errorCallback&&this.errorCallback(o),o}finally{r&&clearTimeout(r)}}onMessage(e){this.messageHandler=e}async close(){this.logger.debug("Closing HTTP Client Transport"),this.isConnected=!1,this.messageHandler=void 0,this.closeCallback&&this.closeCallback(),this.logger.info("HTTP Client Transport closed")}onClose(e){this.closeCallback=e}onError(e){this.errorCallback=e}getSessionId(){return this.sessionId}setSessionId(e){this.sessionId=e,this.logger.debug("Session ID set:",e?"***":"undefined")}async handleJSONResponse(e){let r=await e.text();if(!r.trim()){this.logger.debug("Received empty response");return}let n;try{n=JSON.parse(r)}catch{throw new Error(`Invalid JSON response: ${r}`)}this.logger.debug("Received JSON-RPC response:",n),this.messageHandler&&await this.messageHandler(n)}async handleSSEResponse(e){if(!e.body)throw new Error("SSE response has no body");this.logger.debug("Handling SSE response");let r=s(o=>{if(!o.event||o.event==="message")try{let i=JSON.parse(o.data);this.logger.debug("Received SSE message:",i),this.messageHandler&&this.messageHandler(i)}catch(i){this.logger.warn("Failed to parse SSE message data:",o.data,i)}},"onEvent"),n=e.body.pipeThrough(new TextDecoderStream).pipeThrough(new pa).getReader();try{for(;;){let{done:o,value:i}=await n.read();if(o)return;r(i)}}catch(o){throw this.logger.error("Error processing SSE stream:",o),new Error(`SSE stream error: ${o}`)}}};import{AsyncLocalStorage as kE}from"node:async_hooks";var Em=new kE;function fa(t,e,r){return Em.run({headers:t,zuploContext:e},r)}s(fa,"runWithInvokeContext");function Jo(){return Em.getStore()?.headers??{}}s(Jo,"getInvokeHeaders");function dr(){let t=Em.getStore();if(!t)throw new Error("No Zuplo context available in current execution context");return t.zuploContext}s(dr,"getInvokeContext");var ga=class{constructor(e,r,n=!1,o){this.baseUrl=e;this.originToolName=r;this.debugMode=n;this.originHeaders=o}static{s(this,"ProxyMcpToolExecutor")}async execute(e){let r=dr(),n=Date.now(),o=new la({name:"Zuplo MCP Gateway Proxy Client",version:"0.0.1"});try{this.debugMode&&r.log.debug("Proxying MCP tool call",{originToolName:this.originToolName,baseUrl:this.baseUrl,args:e});let i=new ma({url:this.baseUrl});i.setHeaders({"Content-Type":"application/json",...Jo(),...this.originHeaders??{}});let a,c=Date.now();try{await o.connect(i),await o.initialize(),a=await o.callTool(this.originToolName,e)}catch(l){throw new Error(`could not call tool: ${this.originToolName}`,l)}let u=Date.now()-c;return this.debugMode&&r.log.debug("Proxy MCP response received",{originToolName:this.originToolName,upstreamElapsedMs:u,proxyResult:a}),a}catch(i){let a=Date.now()-n,c=i instanceof Error?`${i.name}: ${i.message}`:String(i);return r.log.error("Proxy MCP tool execution failed",{originToolName:this.originToolName,baseUrl:this.baseUrl,totalElapsedMs:a,err:i}),{content:[{type:"text",text:`Tool execution failed for '${this.originToolName}': ${c}`}],isError:!0}}finally{await o.disconnect()}}};var Qo=class{static{s(this,"R")}type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(t,e,r,n,o,i){this.type=t,this.name=e,this.prefix=r,this.value=n,this.suffix=o,this.modifier=i}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},TE=/[$_\p{ID_Start}]/u,_E=/[$_\u200C\u200D\p{ID_Continue}]/u,Om=".*";function EE(t,e){return(e?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(t)}s(EE,"Re");function Mv(t,e=!1){let r=[],n=0;for(;n<t.length;){let o=t[n],i=s(function(a){if(!e)throw new TypeError(a);r.push({type:"INVALID_CHAR",index:n,value:t[n++]})},"c");if(o==="*"){r.push({type:"ASTERISK",index:n,value:t[n++]});continue}if(o==="+"||o==="?"){r.push({type:"OTHER_MODIFIER",index:n,value:t[n++]});continue}if(o==="\\"){r.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(o==="{"){r.push({type:"OPEN",index:n,value:t[n++]});continue}if(o==="}"){r.push({type:"CLOSE",index:n,value:t[n++]});continue}if(o===":"){let a="",c=n+1;for(;c<t.length;){let u=t.substr(c,1);if(c===n+1&&TE.test(u)||c!==n+1&&_E.test(u)){a+=t[c++];continue}break}if(!a){i(`Missing parameter name at ${n}`);continue}r.push({type:"NAME",index:n,value:a}),n=c;continue}if(o==="("){let a=1,c="",u=n+1,l=!1;if(t[u]==="?"){i(`Pattern cannot start with "?" at ${u}`);continue}for(;u<t.length;){if(!EE(t[u],!1)){i(`Invalid character '${t[u]}' at ${u}.`),l=!0;break}if(t[u]==="\\"){c+=t[u++]+t[u++];continue}if(t[u]===")"){if(a--,a===0){u++;break}}else if(t[u]==="("&&(a++,t[u+1]!=="?")){i(`Capturing groups are not allowed at ${u}`),l=!0;break}c+=t[u++]}if(l)continue;if(a){i(`Unbalanced pattern at ${n}`);continue}if(!c){i(`Missing pattern at ${n}`);continue}r.push({type:"REGEX",index:n,value:c}),n=u;continue}r.push({type:"CHAR",index:n,value:t[n++]})}return r.push({type:"END",index:n,value:""}),r}s(Mv,"v");function Dv(t,e={}){let r=Mv(t);e.delimiter??="/#?",e.prefixes??="./";let n=`[^${ht(e.delimiter)}]+?`,o=[],i=0,a=0,c="",u=new Set,l=s(S=>{if(a<r.length&&r[a].type===S)return r[a++].value},"a"),d=s(()=>l("OTHER_MODIFIER")??l("ASTERISK"),"f"),p=s(S=>{let O=l(S);if(O!==void 0)return O;let{type:T,index:k}=r[a];throw new TypeError(`Unexpected ${T} at ${k}, expected ${S}`)},"d"),m=s(()=>{let S="",O;for(;O=l("CHAR")??l("ESCAPED_CHAR");)S+=O;return S},"T"),g=s(S=>S,"Se"),h=e.encodePart||g,b="",y=s(S=>{b+=S},"U"),w=s(()=>{b.length&&(o.push(new Qo(3,"","",h(b),"",3)),b="")},"$"),v=s((S,O,T,k,N)=>{let U=3;switch(N){case"?":U=1;break;case"*":U=0;break;case"+":U=2;break}if(!O&&!T&&U===3){y(S);return}if(w(),!O&&!T){if(!S)return;o.push(new Qo(3,"","",h(S),"",U));return}let Z;T?T==="*"?Z=Om:Z=T:Z=n;let A=2;Z===n?(A=1,Z=""):Z===Om&&(A=0,Z="");let C;if(O?C=O:T&&(C=i++),u.has(C))throw new TypeError(`Duplicate name '${C}'.`);u.add(C),o.push(new Qo(A,C,h(S),Z,h(k),U))},"V");for(;a<r.length;){let S=l("CHAR"),O=l("NAME"),T=l("REGEX");if(!O&&!T&&(T=l("ASTERISK")),O||T){let N=S??"";e.prefixes.indexOf(N)===-1&&(y(N),N=""),w();let U=d();v(N,O,T,"",U);continue}let k=S??l("ESCAPED_CHAR");if(k){y(k);continue}if(l("OPEN")){let N=m(),U=l("NAME"),Z=l("REGEX");!U&&!Z&&(Z=l("ASTERISK"));let A=m();p("CLOSE");let C=d();v(N,U,Z,A,C);continue}w(),p("END")}return o}s(Dv,"D");function ht(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}s(ht,"S");function Nv(t){return t&&t.ignoreCase?"ui":"u"}s(Nv,"X");function CE(t,e,r){return Uv(Dv(t,r),e,r)}s(CE,"Z");function un(t){switch(t){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}s(un,"k");function Uv(t,e,r={}){r.delimiter??="/#?",r.prefixes??="./",r.sensitive??=!1,r.strict??=!1,r.end??=!0,r.start??=!0,r.endsWith="";let n=r.start?"^":"";for(let c of t){if(c.type===3){c.modifier===3?n+=ht(c.value):n+=`(?:${ht(c.value)})${un(c.modifier)}`;continue}e&&e.push(c.name);let u=`[^${ht(r.delimiter)}]+?`,l=c.value;if(c.type===1?l=u:c.type===0&&(l=Om),!c.prefix.length&&!c.suffix.length){c.modifier===3||c.modifier===1?n+=`(${l})${un(c.modifier)}`:n+=`((?:${l})${un(c.modifier)})`;continue}if(c.modifier===3||c.modifier===1){n+=`(?:${ht(c.prefix)}(${l})${ht(c.suffix)})`,n+=un(c.modifier);continue}n+=`(?:${ht(c.prefix)}`,n+=`((?:${l})(?:`,n+=ht(c.suffix),n+=ht(c.prefix),n+=`(?:${l}))*)${ht(c.suffix)})`,c.modifier===0&&(n+="?")}let o=`[${ht(r.endsWith)}]|$`,i=`[${ht(r.delimiter)}]`;if(r.end)return r.strict||(n+=`${i}?`),r.endsWith.length?n+=`(?=${o})`:n+="$",new RegExp(n,Nv(r));r.strict||(n+=`(?:${i}(?=${o}))?`);let a=!1;if(t.length){let c=t[t.length-1];c.type===3&&c.modifier===3&&(a=r.delimiter.indexOf(c)>-1)}return a||(n+=`(?=${i}|${o})`),new RegExp(n,Nv(r))}s(Uv,"F");var mr={delimiter:"",prefixes:"",sensitive:!0,strict:!0},OE={delimiter:".",prefixes:"",sensitive:!0,strict:!0},$E={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function AE(t,e){return t.length?t[0]==="/"?!0:!e||t.length<2?!1:(t[0]=="\\"||t[0]=="{")&&t[1]=="/":!1}s(AE,"J");function jv(t,e){return t.startsWith(e)?t.substring(e.length,t.length):t}s(jv,"Q");function NE(t,e){return t.endsWith(e)?t.substr(0,t.length-e.length):t}s(NE,"Ee");function zv(t){return!t||t.length<2?!1:t[0]==="["||(t[0]==="\\"||t[0]==="{")&&t[1]==="["}s(zv,"W");var Zv=["ftp","file","http","https","ws","wss"];function qv(t){if(!t)return!0;for(let e of Zv)if(t.test(e))return!0;return!1}s(qv,"N");function LE(t,e){if(t=jv(t,"#"),e||t==="")return t;let r=new URL("https://example.com");return r.hash=t,r.hash?r.hash.substring(1,r.hash.length):""}s(LE,"te");function ME(t,e){if(t=jv(t,"?"),e||t==="")return t;let r=new URL("https://example.com");return r.search=t,r.search?r.search.substring(1,r.search.length):""}s(ME,"re");function DE(t,e){return e||t===""?t:zv(t)?Bv(t):Hv(t)}s(DE,"ne");function UE(t,e){if(e||t==="")return t;let r=new URL("https://example.com");return r.password=t,r.password}s(UE,"se");function jE(t,e){if(e||t==="")return t;let r=new URL("https://example.com");return r.username=t,r.username}s(jE,"ie");function zE(t,e,r){if(r||t==="")return t;if(e&&!Zv.includes(e))return new URL(`${e}:${t}`).pathname;let n=t[0]=="/";return t=new URL(n?t:"/-"+t,"https://example.com").pathname,n||(t=t.substring(2,t.length)),t}s(zE,"ae");function ZE(t,e,r){return Fv(e)===t&&(t=""),r||t===""?t:Gv(t)}s(ZE,"oe");function qE(t,e){return t=NE(t,":"),e||t===""?t:$m(t)}s(qE,"ce");function Fv(t){switch(t){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}s(Fv,"_");function $m(t){if(t==="")return t;if(/^[-+.A-Za-z0-9]*$/.test(t))return t.toLowerCase();throw new TypeError(`Invalid protocol '${t}'.`)}s($m,"y");function FE(t){if(t==="")return t;let e=new URL("https://example.com");return e.username=t,e.username}s(FE,"le");function HE(t){if(t==="")return t;let e=new URL("https://example.com");return e.password=t,e.password}s(HE,"fe");function Hv(t){if(t==="")return t;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(t))throw new TypeError(`Invalid hostname '${t}'`);let e=new URL("https://example.com");return e.hostname=t,e.hostname}s(Hv,"z");function Bv(t){if(t==="")return t;if(/[^0-9a-fA-F[\]:]/g.test(t))throw new TypeError(`Invalid IPv6 hostname '${t}'`);return t.toLowerCase()}s(Bv,"j");function Gv(t){if(t===""||/^[0-9]*$/.test(t)&&parseInt(t)<=65535)return t;throw new TypeError(`Invalid port '${t}'.`)}s(Gv,"K");function BE(t){if(t==="")return t;let e=new URL("https://example.com");return e.pathname=t[0]!=="/"?"/-"+t:t,t[0]!=="/"?e.pathname.substring(2,e.pathname.length):e.pathname}s(BE,"he");function GE(t){return t===""?t:new URL(`data:${t}`).pathname}s(GE,"ue");function VE(t){if(t==="")return t;let e=new URL("https://example.com");return e.search=t,e.search.substring(1,e.search.length)}s(VE,"de");function JE(t){if(t==="")return t;let e=new URL("https://example.com");return e.hash=t,e.hash.substring(1,e.hash.length)}s(JE,"pe");var WE=class{static{s(this,"H")}#e;#t=[];#n={};#r=0;#o=1;#i=0;#s=0;#c=0;#u=0;#l=!1;constructor(t){this.#e=t}get result(){return this.#n}parse(){for(this.#t=Mv(this.#e,!0);this.#r<this.#t.length;this.#r+=this.#o){if(this.#o=1,this.#t[this.#r].type==="END"){if(this.#s===0){this.#w(),this.#m()?this.#a(9,1):this.#f()?this.#a(8,1):this.#a(7,0);continue}else if(this.#s===2){this.#g(5);continue}this.#a(10,0);break}if(this.#c>0)if(this.#k())this.#c-=1;else continue;if(this.#S()){this.#c+=1;continue}switch(this.#s){case 0:this.#v()&&this.#g(1);break;case 1:if(this.#v()){this.#E();let t=7,e=1;this.#R()?(t=2,e=3):this.#l&&(t=2),this.#a(t,e)}break;case 2:this.#y()?this.#g(3):(this.#b()||this.#f()||this.#m())&&this.#g(5);break;case 3:this.#P()?this.#a(4,1):this.#y()&&this.#a(5,1);break;case 4:this.#y()&&this.#a(5,1);break;case 5:this.#T()?this.#u+=1:this.#_()&&(this.#u-=1),this.#I()&&!this.#u?this.#a(6,1):this.#b()?this.#a(7,0):this.#f()?this.#a(8,1):this.#m()&&this.#a(9,1);break;case 6:this.#b()?this.#a(7,0):this.#f()?this.#a(8,1):this.#m()&&this.#a(9,1);break;case 7:this.#f()?this.#a(8,1):this.#m()&&this.#a(9,1);break;case 8:this.#m()&&this.#a(9,1);break;case 9:break;case 10:break}}this.#n.hostname!==void 0&&this.#n.port===void 0&&(this.#n.port="")}#a(t,e){switch(this.#s){case 0:break;case 1:this.#n.protocol=this.#p();break;case 2:break;case 3:this.#n.username=this.#p();break;case 4:this.#n.password=this.#p();break;case 5:this.#n.hostname=this.#p();break;case 6:this.#n.port=this.#p();break;case 7:this.#n.pathname=this.#p();break;case 8:this.#n.search=this.#p();break;case 9:this.#n.hash=this.#p();break;case 10:break}this.#s!==0&&t!==10&&([1,2,3,4].includes(this.#s)&&[6,7,8,9].includes(t)&&(this.#n.hostname??=""),[1,2,3,4,5,6].includes(this.#s)&&[8,9].includes(t)&&(this.#n.pathname??=this.#l?"/":""),[1,2,3,4,5,6,7].includes(this.#s)&&t===9&&(this.#n.search??="")),this.#x(t,e)}#x(t,e){this.#s=t,this.#i=this.#r+e,this.#r+=e,this.#o=0}#w(){this.#r=this.#i,this.#o=0}#g(t){this.#w(),this.#s=t}#h(t){return t<0&&(t=this.#t.length-t),t<this.#t.length?this.#t[t]:this.#t[this.#t.length-1]}#d(t,e){let r=this.#h(t);return r.value===e&&(r.type==="CHAR"||r.type==="ESCAPED_CHAR"||r.type==="INVALID_CHAR")}#v(){return this.#d(this.#r,":")}#R(){return this.#d(this.#r+1,"/")&&this.#d(this.#r+2,"/")}#y(){return this.#d(this.#r,"@")}#P(){return this.#d(this.#r,":")}#I(){return this.#d(this.#r,":")}#b(){return this.#d(this.#r,"/")}#f(){if(this.#d(this.#r,"?"))return!0;if(this.#t[this.#r].value!=="?")return!1;let t=this.#h(this.#r-1);return t.type!=="NAME"&&t.type!=="REGEX"&&t.type!=="CLOSE"&&t.type!=="ASTERISK"}#m(){return this.#d(this.#r,"#")}#S(){return this.#t[this.#r].type=="OPEN"}#k(){return this.#t[this.#r].type=="CLOSE"}#T(){return this.#d(this.#r,"[")}#_(){return this.#d(this.#r,"]")}#p(){let t=this.#t[this.#r],e=this.#h(this.#i).index;return this.#e.substring(e,t.index)}#E(){let t={};Object.assign(t,mr),t.encodePart=$m;let e=CE(this.#p(),void 0,t);this.#l=qv(e)}},Cm=["protocol","username","password","hostname","port","pathname","search","hash"],pr="*";function Lv(t,e){if(typeof t!="string")throw new TypeError("parameter 1 is not of type 'string'.");let r=new URL(t,e);return{protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search!==""?r.search.substring(1,r.search.length):void 0,hash:r.hash!==""?r.hash.substring(1,r.hash.length):void 0}}s(Lv,"ge");function Kt(t,e){return e?Ko(t):t}s(Kt,"b");function Wo(t,e,r){let n;if(typeof e.baseURL=="string")try{n=new URL(e.baseURL),e.protocol===void 0&&(t.protocol=Kt(n.protocol.substring(0,n.protocol.length-1),r)),!r&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&(t.username=Kt(n.username,r)),!r&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&e.password===void 0&&(t.password=Kt(n.password,r)),e.protocol===void 0&&e.hostname===void 0&&(t.hostname=Kt(n.hostname,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&(t.port=Kt(n.port,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&(t.pathname=Kt(n.pathname,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&(t.search=Kt(n.search.substring(1,n.search.length),r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&e.hash===void 0&&(t.hash=Kt(n.hash.substring(1,n.hash.length),r))}catch{throw new TypeError(`invalid baseURL '${e.baseURL}'.`)}if(typeof e.protocol=="string"&&(t.protocol=qE(e.protocol,r)),typeof e.username=="string"&&(t.username=jE(e.username,r)),typeof e.password=="string"&&(t.password=UE(e.password,r)),typeof e.hostname=="string"&&(t.hostname=DE(e.hostname,r)),typeof e.port=="string"&&(t.port=ZE(e.port,t.protocol,r)),typeof e.pathname=="string"){if(t.pathname=e.pathname,n&&!AE(t.pathname,r)){let o=n.pathname.lastIndexOf("/");o>=0&&(t.pathname=Kt(n.pathname.substring(0,o+1),r)+t.pathname)}t.pathname=zE(t.pathname,t.protocol,r)}return typeof e.search=="string"&&(t.search=ME(e.search,r)),typeof e.hash=="string"&&(t.hash=LE(e.hash,r)),t}s(Wo,"w");function Ko(t){return t.replace(/([+*?:{}()\\])/g,"\\$1")}s(Ko,"C");function KE(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}s(KE,"Oe");function QE(t,e){e.delimiter??="/#?",e.prefixes??="./",e.sensitive??=!1,e.strict??=!1,e.end??=!0,e.start??=!0,e.endsWith="";let r=".*",n=`[^${KE(e.delimiter)}]+?`,o=/[$_\u200C\u200D\p{ID_Continue}]/u,i="";for(let a=0;a<t.length;++a){let c=t[a];if(c.type===3){if(c.modifier===3){i+=Ko(c.value);continue}i+=`{${Ko(c.value)}}${un(c.modifier)}`;continue}let u=c.hasCustomName(),l=!!c.suffix.length||!!c.prefix.length&&(c.prefix.length!==1||!e.prefixes.includes(c.prefix)),d=a>0?t[a-1]:null,p=a<t.length-1?t[a+1]:null;if(!l&&u&&c.type===1&&c.modifier===3&&p&&!p.prefix.length&&!p.suffix.length)if(p.type===3){let m=p.value.length>0?p.value[0]:"";l=o.test(m)}else l=!p.hasCustomName();if(!l&&!c.prefix.length&&d&&d.type===3){let m=d.value[d.value.length-1];l=e.prefixes.includes(m)}l&&(i+="{"),i+=Ko(c.prefix),u&&(i+=`:${c.name}`),c.type===2?i+=`(${c.value})`:c.type===1?u||(i+=`(${n})`):c.type===0&&(!u&&(!d||d.type===3||d.modifier!==3||l||c.prefix!=="")?i+="*":i+=`(${r})`),c.type===1&&u&&c.suffix.length&&o.test(c.suffix[0])&&(i+="\\"),i+=Ko(c.suffix),l&&(i+="}"),c.modifier!==3&&(i+=un(c.modifier))}return i}s(QE,"ke");var ha=class{static{s(this,"me")}#e;#t={};#n={};#r={};#o={};#i=!1;constructor(t={},e,r){try{let n;if(typeof e=="string"?n=e:r=e,typeof t=="string"){let c=new WE(t);if(c.parse(),t=c.result,n===void 0&&typeof t.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");t.baseURL=n}else{if(!t||typeof t!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(n)throw new TypeError("parameter 1 is not of type 'string'.")}typeof r>"u"&&(r={ignoreCase:!1});let o={ignoreCase:r.ignoreCase===!0},i={pathname:pr,protocol:pr,username:pr,password:pr,hostname:pr,port:pr,search:pr,hash:pr};this.#e=Wo(i,t,!0),Fv(this.#e.protocol)===this.#e.port&&(this.#e.port="");let a;for(a of Cm){if(!(a in this.#e))continue;let c={},u=this.#e[a];switch(this.#n[a]=[],a){case"protocol":Object.assign(c,mr),c.encodePart=$m;break;case"username":Object.assign(c,mr),c.encodePart=FE;break;case"password":Object.assign(c,mr),c.encodePart=HE;break;case"hostname":Object.assign(c,OE),zv(u)?c.encodePart=Bv:c.encodePart=Hv;break;case"port":Object.assign(c,mr),c.encodePart=Gv;break;case"pathname":qv(this.#t.protocol)?(Object.assign(c,$E,o),c.encodePart=BE):(Object.assign(c,mr,o),c.encodePart=GE);break;case"search":Object.assign(c,mr,o),c.encodePart=VE;break;case"hash":Object.assign(c,mr,o),c.encodePart=JE;break}try{this.#o[a]=Dv(u,c),this.#t[a]=Uv(this.#o[a],this.#n[a],c),this.#r[a]=QE(this.#o[a],c),this.#i=this.#i||this.#o[a].some(l=>l.type===2)}catch{throw new TypeError(`invalid ${a} pattern '${this.#e[a]}'.`)}}}catch(n){throw new TypeError(`Failed to construct 'URLPattern': ${n.message}`)}}test(t={},e){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return!1;try{typeof t=="object"?r=Wo(r,t,!1):r=Wo(r,Lv(t,e),!1)}catch{return!1}let n;for(n of Cm)if(!this.#t[n].exec(r[n]))return!1;return!0}exec(t={},e){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return;try{typeof t=="object"?r=Wo(r,t,!1):r=Wo(r,Lv(t,e),!1)}catch{return null}let n={};e?n.inputs=[t,e]:n.inputs=[t];let o;for(o of Cm){let i=this.#t[o].exec(r[o]);if(!i)return null;let a={};for(let[c,u]of this.#n[o].entries())if(typeof u=="string"||typeof u=="number"){let l=i[c+1];a[u]=l}n[o]={input:r[o]??"",groups:a}}return n}static compareComponent(t,e,r){let n=s((c,u)=>{for(let l of["type","modifier","prefix","value","suffix"]){if(c[l]<u[l])return-1;if(c[l]!==u[l])return 1}return 0},"o"),o=new Qo(3,"","","","",3),i=new Qo(0,"","","","",3),a=s((c,u)=>{let l=0;for(;l<Math.min(c.length,u.length);++l){let d=n(c[l],u[l]);if(d)return d}return c.length===u.length?0:n(c[l]??o,u[l]??o)},"s");return!e.#r[t]&&!r.#r[t]?0:e.#r[t]&&!r.#r[t]?a(e.#o[t],[i]):!e.#r[t]&&r.#r[t]?a([i],r.#o[t]):a(e.#o[t],r.#o[t])}get protocol(){return this.#r.protocol}get username(){return this.#r.username}get password(){return this.#r.password}get hostname(){return this.#r.hostname}get port(){return this.#r.port}get pathname(){return this.#r.pathname}get search(){return this.#r.search}get hash(){return this.#r.hash}get hasRegExpGroups(){return this.#i}};var ya=class{static{s(this,"UrlPatternBuilder")}pattern;pathParams={};searchParams=new URLSearchParams;expectedPathParams=new Set;seenPathParams=new Set;constructor(e){this.pattern=new ha({pathname:e});let r=/:(\w+)(\([^)]*\))?[*+?]?/g,n;for(;(n=r.exec(e))!==null;)this.expectedPathParams.add(n[1])}addParameter(e,r,n){let o=this.getParameterValue(e,r,n);if(o!=null)switch(e.in){case"path":if(!this.expectedPathParams.has(e.name))throw new x(`path parameter '${e.name}' missing from pattern '${this.pattern.pathname}'`);this.seenPathParams.add(e.name),this.addPathParameter(e.name,o);break;case"query":this.addQueryParameter(e.name,o);break;default:break}}getParameterValue(e,r,n){switch(e.in){case"path":return r?.[e.name];case"query":return n?.[e.name];default:return}}addPathParameter(e,r){this.pathParams[e]=String(r)}addQueryParameter(e,r){Array.isArray(r)?r.forEach(n=>{n!=null&&this.searchParams.append(e,String(n))}):typeof r=="object"&&r!==null?this.searchParams.append(e,JSON.stringify(r)):this.searchParams.append(e,String(r))}toString(){let e=[...this.expectedPathParams].filter(i=>!this.seenPathParams.has(i));if(e.length>0)throw new x(`missing path parameters in OpenAPI spec: ${e.join(", ")}`);let r=this.pattern.pathname.replace(/:(\w+)(\([^)]*\))?([*+?])?/g,(i,a)=>this.pathParams[a]?encodeURIComponent(this.pathParams[a]):i),n=this.cleanupUrlPatternSyntax(r),o=this.searchParams.toString();return o?`${n}?${o}`:n}cleanupUrlPatternSyntax(e){return e.replace(/\{\/\}\?/g,"").replace(/\{\/\}[*+]/g,"/").replace(/\{\/\}/g,"/").replace(/(\{[^}]*\})[?*+]/g,"$1").replace(/\\:/g,":")}};var ba=class{constructor(e){this.routeData=e}static{s(this,"McpUrlBuilder")}build(e,r){let n=this.routeData.pathPattern?this.routeData.pathPattern:this.routeData.path,o=this.routeData.raw()?.parameters||[],i=new ya(n);for(let a of o)i.addParameter(a,e,r);return i.toString()}};De();De();De();var wa=class t{static{s(this,"ZodFormatSchemaRegistry")}static formatter=new Map([["email",()=>f.email()],["uri",()=>f.url()],["url",()=>f.url()],["date",()=>f.iso.date()],["date-time",()=>f.iso.datetime()],["time",()=>f.iso.time()],["ipv4",()=>f.ipv4()],["ipv6",()=>f.ipv6()],["uuid",()=>f.guid()],["int32",()=>f.int32()],["int64",()=>f.int64()],["float",()=>f.number()],["double",()=>f.number()]]);static get(e){return t.formatter.get(e)}static register(e,r){t.formatter.set(e,r)}},ln=class t{static{s(this,"OpenApiToZodTranspiler")}static typeTranspilers=new Map([["string",this.transpileString.bind(this)],["number",this.transpileNumber.bind(this)],["integer",this.transpileInteger.bind(this)],["boolean",this.transpileBoolean.bind(this)],["array",this.transpileArray.bind(this)],["object",this.transpileObject.bind(this)],["null",this.transpileNull.bind(this)]]);static run(e,r){let n={path:[],definitions:{},visitedRefs:new Set,...r};return t.transpileSchema(e,n)}static transpileSchema(e,r){if(!e)return f.unknown();try{if("$ref"in e)return t.resolveReference(e.$ref,r);if(e.allOf)return t.transpileAllOf(e.allOf,r);if(e.oneOf)return t.transpileOneOf(e.oneOf,r);if(e.anyOf)return t.transpileAnyOf(e.anyOf,r);if(e.not)return t.transpileNot(e.not,r);let n=t.transpileByType(e,r);return n=t.applyCommonModifiers(n,e),n}catch(n){let o=r.path.join(".");throw new Error(`Failed to transpile schema at path "${o}": ${n.message}`)}}static transpileByType(e,r){let n=e.type;!n&&e.properties&&(n="object");let o=t.typeTranspilers.get(n||"unknown");return o?o(e,r):f.unknown()}static transpileString(e,r){if(e.enum)return f.enum(e.enum);let n=e.format?wa.get(e.format):null,o=n?n():f.string();if(o instanceof f.ZodString){let i=o;return e.minLength!==void 0&&(i=i.min(e.minLength)),e.maxLength!==void 0&&(i=i.max(e.maxLength)),e.pattern&&(i=i.regex(new RegExp(e.pattern))),i}else e.minLength||e.maxLength||e.pattern;return o}static applyNumericConstraints(e,r,n){let o=e;if(r.minimum!==void 0&&(o=o.min(r.minimum)),r.maximum!==void 0&&(o=o.max(r.maximum)),r.exclusiveMinimum!==void 0){let i;if(typeof r.exclusiveMinimum=="number")i=r.exclusiveMinimum;else if(r.minimum!==void 0)i=r.minimum+Number.EPSILON;else throw new Error(`exclusiveMinimum requires minimum to be set at path "${n.path.join(".")}"`);o=o.gt(i)}if(r.exclusiveMaximum!==void 0){let i;if(typeof r.exclusiveMaximum=="number")i=r.exclusiveMaximum;else if(r.maximum!==void 0)i=r.maximum-Number.EPSILON;else throw new Error(`exclusiveMaximum requires maximum to be set at path "${n.path.join(".")}"`);o=o.lt(i)}return o}static transpileNumber(e,r){let n=f.number();return t.applyNumericConstraints(n,{...e,type:"number"},r)}static transpileInteger(e,r){let n=f.int();return t.applyNumericConstraints(n,{...e,type:"number"},r)}static transpileBoolean(e,r){return f.boolean()}static transpileArray(e,r){let n=e.items?t.transpileSchema(e.items,{...r,path:[...r.path,"items"]}):f.unknown(),o=f.array(n);return e.minItems!==void 0&&(o=o.min(e.minItems)),e.maxItems!==void 0&&(o=o.max(e.maxItems)),e.uniqueItems&&(o=o.refine(i=>new Set(i).size===i.length,{message:"Array must contain unique items"})),o}static transpileObject(e,r){let n;if(e.properties){let o={},i=new Set(e.required||[]);for(let[c,u]of Object.entries(e.properties)){let l={...r,path:[...r.path,c]},d=t.transpileSchema(u,l);i.has(c)||(d=d.optional()),o[c]=d}let a=f.object(o);e.additionalProperties===!1?a=a.strict():(e.additionalProperties,a=a.passthrough()),n=a}else if(e.additionalProperties===!1)n=f.object({}).strict();else if(typeof e.additionalProperties=="object"){let o=t.transpileSchema(e.additionalProperties,r);n=f.record(f.string(),o)}else n=f.unknown();return(e.minProperties!==void 0||e.maxProperties!==void 0)&&(n=n.refine(o=>{let i=Object.keys(o).length;return!(e.minProperties!==void 0&&i<e.minProperties||e.maxProperties!==void 0&&i>e.maxProperties)},{message:t.buildPropertyCountErrorMessage(e.minProperties,e.maxProperties)})),n}static buildPropertyCountErrorMessage(e,r){return e!==void 0&&r!==void 0?`Object must have between ${e} and ${r} properties`:e!==void 0?`Object must have at least ${e} properties`:`Object must have at most ${r} properties`}static transpileNull(e,r){return f.null()}static transpileAllOf(e,r){return e.map((o,i)=>t.transpileSchema(o,{...r,path:[...r.path,`allOf[${i}]`]})).reduce((o,i)=>o.and(i))}static transpileOneOf(e,r){let n=e.map((o,i)=>t.transpileSchema(o,{...r,path:[...r.path,`oneOf[${i}]`]}));return n.length===0?f.never():n.length===1?n[0]:f.union(n)}static transpileAnyOf(e,r){return t.transpileOneOf(e,r)}static transpileNot(e,r){let n=t.transpileSchema(e,{...r,path:[...r.path,"not"]});return f.unknown().refine(o=>!n.safeParse(o).success,{message:"Value must not match the schema"})}static resolveReference(e,r){if(r.visitedRefs?.has(e))return f.lazy(()=>t.resolveReference(e,r));r.visitedRefs?.add(e);let n=e.split("/");if(n[0]==="#"&&n[1]==="definitions"&&r.definitions){let o=r.definitions[n[2]];if(o)return t.transpileSchema(o,r)}throw new Error(`Unable to resolve reference: ${e}`)}static applyCommonModifiers(e,r){let n=e;return r.nullable&&(n=n.nullable()),r.default!==void 0&&(n=n.default(r.default)),r.description&&(n=n.describe(r.description)),r.examples&&r.examples.length>0&&(n=n.meta({examples:r.examples})),n}static registerTypeTranspiler(e,r){t.typeTranspilers.set(e,r)}static registerFormatSchema(e,r){wa.register(e,r)}};var va=class{constructor(e){this.schema=e}static{s(this,"JSONSchemaBuilder")}build(){return ln.run(this.schema)}},xa=class{constructor(e,r){this.routeData=e;this.contentType=r}static{s(this,"RequestBodySchemaBuilder")}build(){let e=this.routeData.raw()?.requestBody;if(!e?.content?.[this.contentType])return null;let r=e.content[this.contentType].schema;return r?ln.run(r):null}},Ra=class{constructor(e){this.parameters=e}static{s(this,"ParameterSchemaBuilder")}build(){if(this.parameters.length===0)return null;let e={};for(let r of this.parameters)e[r.name]=this.buildParameterSchema(r);return f.object(e)}buildParameterSchema(e){let r;e.schema?r=ln.run(e.schema):r=f.string(),e.required||(r=r.optional()),e.description&&(r=r.describe(e.description));let n=[];if(e.schema?.example!==void 0&&n.push(e.schema.example),e.schema?.examples!==void 0&&Array.isArray(e.schema.examples)&&n.push(...e.schema.examples),e.examples&&(Array.isArray(e.examples)?n.push(...e.examples):typeof e.examples=="object"&&Object.values(e.examples).forEach(o=>{o?.value!==void 0&&n.push(o.value)})),e.example!==void 0&&n.push(e.example),n.length>0){let o=[...new Set(n.map(i=>JSON.stringify(i)))].map(i=>JSON.parse(i));r=r.meta({examples:o})}return r}};var Or=class t{static{s(this,"UniversalValidatorBuilder")}root=null;components={};static withRoot(e){let r=new t;return r.root=e,r}withBody(e){return e&&(this.components.body=e),this}withQueryParams(e){return e&&(this.components.queryParams=e),this}withPathParams(e){return e&&(this.components.pathParams=e),this}withHeaders(e){return e&&(this.components.headers=e),this}build(){return this.root?this.buildFromSchema(this.root):Object.keys(this.components).length>0?this.buildFromComponents():this.buildEmptyValidator()}buildFromSchema(e){let r=f.toJSONSchema(e);return new lr(r,n=>{let o=e.safeParse(n);return o.success?{success:!0,data:o.data,errorData:null}:{success:!1,data:null,errorMessage:f.prettifyError(o.error),errorData:f.treeifyError(o.error)}})}buildFromComponents(){let e=f.object(this.components),r=f.toJSONSchema(e);return new lr(r,n=>{let o=e.safeParse(n);return o.success?{success:!0,data:o.data,errorData:null}:{success:!1,data:null,errorMessage:f.prettifyError(o.error),errorData:f.treeifyError(o.error)}})}buildEmptyValidator(){let e={type:"object",properties:{},required:[],additionalProperties:!1};return new lr(e,r=>({success:!0,data:r,errorData:null}))}},$r=class t{static{s(this,"SchemaBuilderFactory")}static createJsonSchemaBuilder(e){return new va(e)}static createRequestBodyBuilder(e,r){return new xa(e,r)}static createParameterBuilder(e,r){let n=r?e.filter(o=>o.in===r):e;return new Ra(n)}static createValidatorBuilder(e,r){let n=new Or,o=e.raw()?.parameters||[];if(r){let u=t.createRequestBodyBuilder(e,r);n.withBody(u.build())}let i=t.createParameterBuilder(o,"query");n.withQueryParams(i.build());let a=t.createParameterBuilder(o,"path");n.withPathParams(a.build());let c=t.createParameterBuilder(o,"header");return n.withHeaders(c.build()),n}static createPromptValidatorBuilder(e){let r=new Or,o=e.raw()?.requestBody;if(!o?.content||!o.content["application/json"])return r;let a=t.createRequestBodyBuilder(e,"application/json");return Or.withRoot(a.build())}static createObjectValidatorBuilder(e){let r=new Or;if(!e||Object.keys(e).length===0)return r;let n=t.createJsonSchemaBuilder(e);return Or.withRoot(n.build())}};var dn=class t{static{s(this,"ZuploMcpServer")}static instances=new Map;static async getInstance({opts:e,context:r,key:n,origins:o}){let i=e.debugMode??!1,a=t.instances.get(n);if(a)i&&r.log.debug("MCP Server warm reuse",{routeKey:n});else{let c=Date.now();if(a=new t(e,r,o??[]),a.registerFromOperations(a.opts.operations??[]),a.registerToolsFromFileSources(a.opts.files??[]),a.registerPromptsFromFileSources(a.opts.prompts??[]),a.registerResourcesFromFileSources(a.opts.resources??[]),await a.registerProxyTools(a.origins??[]),await a.transport.connect(),a.server.withTransport(a.transport),t.instances.set(n,a),i){let u=a.server.getTools(),l=u?u.size:0,d=a.server.getPromptDefinitions(),p=d?d.length:0,m=a.server.getResourceDefinitions(),g=m?m.length:0,h=Date.now()-c;r.log.debug("MCP Server cold start",{routeKey:n,toolCount:l,promptCount:p,resourceCount:g,totalElapsedMs:h,debugMode:i,includeOutputSchema:a.includeOutputSchema,includeStructuredContent:a.includeStructuredContent})}}return a}transport;server;opts;origins;context;registeredToolNames;registeredPromptNames;registeredResourceNames;includeOutputSchema;includeStructuredContent;debugMode;constructor(e,r,n){this.debugMode=e.debugMode??!1;let o;this.debugMode?o=r.log:o=new to,this.context=r,this.opts=e,this.origins=n??[],this.server=new aa({name:e.name??"Zuplo MCP Server",version:e.version??"0.0.0",logger:o}),this.transport=new ca({logger:o}),this.includeOutputSchema=e.includeOutputSchema??!1,this.includeStructuredContent=e.includeStructuredContent??!1,this.registeredToolNames=new Set,this.registeredPromptNames=new Set,this.registeredResourceNames=new Set}async handleRequest(e,r){let n=Date.now();try{let o=await e.clone().json().catch(()=>({}));switch(this.debugMode&&r.log.debug("MCP Server request start",{method:o.method,requestId:o.id,routePath:r.route?.path}),o.method){case"tools/list":if(this.debugMode){let c=this.server.getTools(),u=c?Array.from(c.keys()):[];r.log.debug("MCP Server list tools request",{toolCount:u.length,toolNames:u})}break;case"tools/call":r.custom.mcpCallToolRequest=o;break;case"prompts/list":if(this.debugMode){let c=this.server.getPromptDefinitions(),u=c?c.map(l=>l.name):[];r.log.debug("MCP Server list prompts request",{promptCount:u.length,promptNames:u})}break;case"resources/list":if(this.debugMode){let c=this.server.getResourceDefinitions(),u=c?c.map(l=>l.name):[];r.log.debug("MCP Server list resources request",{resourceCount:u.length,resourceNames:u})}break}let i=await this.transport.handleRequest(e),a=Date.now()-n;if(this.debugMode){let c=await i.clone().json().catch(()=>({}));r.log.debug("MCP Server response complete",{status:i.status,requestMethod:o.method,requestId:o.id,totalElapsedMs:a,respData:c})}return i}catch(o){let i=Date.now()-n;return r.log.error("MCP server internal error",{elapsedMs:i,err:o}),new Response("Internal error",{status:500})}}generatePromptDescriptionFromSpec(e){let r=e.raw();return r?.description?r.description:r?.summary?r.summary:`Generate content for operation for ${e.path}`}static getOperationsMetadataForFile(e){let{routes:r}=Re.instance.routeData,n=r.filter(i=>i.metadata?.filepath===e);if(n.length===0)throw new Error(`MCP Tool configuration error: No routes found for file path ${e}. Verify that the OpenAPI file exists and is properly loaded in your Gateway configuration with routes.`);let o=new Map;for(let i of n){let a=i?.raw().operationId;if(a){o.set(a,{routeConfig:i});let c=i?.raw(),u=c["x-zuplo-mcp-tool"],l=c["x-zuplo-mcp-prompt"],d=c["x-zuplo-mcp-graphql"],p=c["x-zuplo-mcp-resource"],m=c["x-zuplo-route"]?.mcp;(u||l||d||p||m)&&o.set(a,{routeConfig:i,toolExtension:u||void 0,promptExtension:l||void 0,graphqlExtension:d||void 0,resourceExtension:p||void 0,routeMcpExtension:m||void 0})}}return o}registerFromOperations(e){let r=new Map;for(let n of e){let o=r.get(n.file)??[];o.push(n.id),r.set(n.file,o)}for(let[n,o]of r.entries()){let i=t.getOperationsMetadataForFile(n);for(let a of o){let c=i.get(a);if(!c)throw new Error(`MCP configuration error: Could not find operation with ID "${a}" in file ${n}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:u,routeMcpExtension:l}=c;switch(l?.type){case"tool":this.registerTool(u,a,l);break;case"prompt":this.registerPrompt(u,a,l);break;case"resource":this.registerResource(u,a,l);break;case"graphql":this.registerGraphQLTools(a,u,l);break;default:this.context.log.warn(`Could not find "x-zuplo-route.mcp" configuration for operation: "${a}". Creating tool with fallback name and description`),this.registerTool(u,a,l)}}}}registerPromptsFromFileSources(e){for(let r of e){let n=t.getOperationsMetadataForFile(r.path),o=new Set;for(let i of r.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP prompt with operation ID: "${i}" from file: "${r.path}" with: "options.prompts" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=n.get(i);if(!a)throw new Error(`MCP Prompt configuration error: Could not find operation with ID "${i}" in file ${r.path}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:c,promptExtension:u}=a,l=u?.name??i;if(o.has(l))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${l}". Prompt names must be unique across all configured prompts.`);o.add(l);let d=u?.description??this.generatePromptDescriptionFromSpec(c);if(!(u?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP prompt disabled by extension",{promptName:l,operationId:i});continue}this.registerPromptForOperation(l,d,c,i)}}}registerPromptForOperation(e,r,n,o){try{if(n.handler?.export==="mcpServerHandler")return;let a=$r.createPromptValidatorBuilder(n).build();this.server.addPrompt({name:e,description:r,validator:a,generator:s(async c=>{let u=dr(),l=Date.now();try{this.debugMode&&u.log.debug("MCP prompt invoked",{promptName:e,operationId:n.raw()?.operationId,path:n.path,args:c});let d=this.buildToolUrl(n,{body:c}),p=this.buildToolRequest("POST","application/json",{body:c});this.debugMode&&u.log.debug("MCP prompt downstream call",{promptName:e,url:d,method:"POST",bodyPreview:c});let m=Date.now(),g=await u.invokeRoute(d,p),h=Date.now()-m,b=await g.json();if(!g.ok)throw new Error(`Route returned ${g.status}: ${b}`);let y;try{if(y=b.messages||b,!Array.isArray(y))throw new Error("Response must contain a 'messages' array or be an array of messages")}catch(v){throw new Error(`Invalid JSON response or missing messages array: ${v instanceof Error?v.message:String(v)}`)}let w=Date.now()-l;return this.debugMode&&u.log.debug("MCP prompt response complete",{promptName:e,operationId:n.raw()?.operationId,status:g.status,elapsedMs:w,downstreamElapsedMs:h,messageCount:y.length}),y}catch(d){let p=Date.now()-l,m=d instanceof Error?`${d.name}: ${d.message}`:String(d);throw u.log.error("MCP prompt invocation failed",{promptName:e,operationId:n.raw()?.operationId,path:n.path,elapsedMs:p,err:d}),new Error(`MCP tool call failed for tool '${e}': ${m}`)}},"generator")}),this.debugMode&&this.context.log.debug("MCP prompt registered from file source",{promptName:e,operationId:o,path:n.path})}catch(i){throw this.context.log.error("Failed to register MCP prompt",{promptName:e,operationId:o,error:i instanceof Error?i.message:String(i)}),new Error(`Failed to register prompt "${e}" for operation "${o}": ${i instanceof Error?i.message:String(i)}`)}}registerResourcesFromFileSources(e){let r=new Set;for(let n of e){let o=t.getOperationsMetadataForFile(n.path);for(let i of n.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP resource with operation ID: "${i}" from file: "${n.path}" with: "options.resources" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=o.get(i);if(!a)throw new Error(`MCP Resource configuration error: Could not find operation with ID "${i}" in file ${n.path}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:c,resourceExtension:u}=a;if(!(u?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP resource disabled by extension",{operationId:i});continue}if(!c.methods||c.methods.length===0)throw new Error(`MCP Resource configuration error: Operation "${i}" has no HTTP methods defined. Resources must use GET method.`);if(c.methods.length>1)throw new Error(`MCP Resource configuration error: Operation "${i}" has multiple HTTP methods (${c.methods.join(", ")}). Resources must use exactly one method and it must be GET.`);let d=c.methods[0].toUpperCase();if(d!=="GET")throw new Error(`MCP Resource configuration error: Operation "${i}" uses ${d} method. Resources are read-only and must use GET method only.`);let p=u?.name?.trim()||i.trim()||"";if(!p)throw new Error(`MCP Resource configuration error: Could not determine resource name for operation "${i}". Ensure the operation has an operationId or provide a name in x-zuplo-mcp-resource extension.`);if(r.has(p))throw new Error(`MCP Resource configuration error: Duplicate resource name "${p}". Resource names must be unique across all configured resources.`);r.add(p);let m=u?.description?.trim()||c.raw()?.description?.trim()||c.raw()?.summary?.trim()||`Resource for ${p}`,g=u?.uri?.trim()||`mcp://resources/${encodeURIComponent(p)}`,h=u?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(p,g,m,c,i,h)}}}registerResourceForOperation(e,r,n,o,i,a,c){try{if(o.handler?.export==="mcpServerHandler")return;this.server.addResource(e,r,{title:e,description:n,mimeType:a,...c&&{_meta:c}},async()=>{let u=dr(),l=Date.now();try{this.debugMode&&u.log.debug("MCP resource invoked",{resourceName:e,operationId:o.raw()?.operationId,path:o.path,uri:r});let d=this.buildToolUrl(o,{}),p=this.buildToolRequest("GET",null,{});this.debugMode&&u.log.debug("MCP resource downstream call",{resourceName:e,url:d,method:"GET"});let m=Date.now(),g=await u.invokeRoute(d,p),h=Date.now()-m,b=await g.text(),y=Date.now()-l;return this.debugMode&&u.log.debug("MCP resource response complete",{resourceName:e,operationId:o.raw()?.operationId,status:g.status,elapsedMs:y,downstreamElapsedMs:h,declaredMimeType:a,contentLength:b.length}),{contents:[{uri:r,mimeType:a,text:b,...c&&{_meta:c}}]}}catch(d){let p=Date.now()-l,m=d instanceof Error?`${d.name}: ${d.message}`:String(d);throw u.log.error("MCP resource invocation failed",{resourceName:e,operationId:o.raw()?.operationId,path:o.path,elapsedMs:p,err:d}),new Error(`MCP resource call failed for resource '${e}': ${m}`)}}),this.debugMode&&this.context.log.debug("MCP resource registered from file source",{resourceName:e,operationId:i,path:o.path,uri:r,mimeType:a||"auto-detected"})}catch(u){throw this.context.log.error("Failed to register MCP resource",{resourceName:e,operationId:i,error:u instanceof Error?u.message:String(u)}),new Error(`Failed to register resource "${e}" for operation "${i}": ${u instanceof Error?u.message:String(u)}`)}}registerTool(e,r,n){if(!(n?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP tool disabled by x-zuplo-route.mcp configuration",{operationId:r});return}let i=n?.name?.trim()||r;if(this.registeredToolNames.has(i))throw new Error(`MCP Tool configuration error: Tool name conflict detected for operation: "${r}". The tool name "${i}" is already in use. Provide a unique 'name' in the x-zuplo-route.mcp configuration for operation "${r}".`);this.registeredToolNames.add(i);let a=n?.description?.trim()||e.raw().description?.trim()||e.raw().summary?.trim()||`Executes tool: ${i}`,c=n?.includeOutputSchema??this.includeOutputSchema??!1,u=n?.includeStructuredContent??this.includeStructuredContent??!1;if(e.methods.length!=1)throw new Error(`MCP tool configuration error: multiple methods "${e.methods.join(", ")}" on operation "${r}" not permitted. Only tools with a singular method are permitted.`);this.registerToolsForMethod({routeData:e,method:e.methods[0],name:i,description:a,includeOutputSchema:c,includeStructuredContent:u,annotations:n?.annotations,_meta:n?._meta})}registerPrompt(e,r,n){if(!(n?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP prompt disabled by x-zuplo-route.mcp",{operationId:r});return}let i=n?.name?.trim()||r;if(this.registeredPromptNames.has(i))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${i}" for operation ID "${r}". Prompt names must be unique across all configured prompts.`);this.registeredPromptNames.add(i);let a=n?.description?.trim()||this.generatePromptDescriptionFromSpec(e);this.registerPromptForOperation(i,a,e,r)}registerResource(e,r,n){if(!(n?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP resource disabled by x-zuplo-route.mcp",{operationId:r});return}if(!e.methods||e.methods.length===0)throw new Error(`MCP Resource configuration error: Operation "${r}" has no HTTP methods defined. Resources must use GET method.`);if(e.methods.length>1)throw new Error(`MCP Resource configuration error: Operation "${r}" has multiple HTTP methods (${e.methods.join(", ")}). Resources must use exactly one method and it must be GET.`);let i=e.methods[0].toUpperCase();if(i!=="GET")throw new Error(`MCP Resource configuration error: Operation "${r}" uses ${i} method. Resources are read-only and must use GET method only.`);let a=n?.name?.trim()||r;if(this.registeredResourceNames.has(a))throw new Error(`MCP Resource configuration error: Duplicate resource name "${a}". Resource names must be unique across all configured resources.`);this.registeredResourceNames.add(a);let c=n?.description?.trim()||e.raw()?.description?.trim()||e.raw()?.summary?.trim()||`Resource for ${a}`,u=n?.uri?.trim()||`mcp://resources/${encodeURIComponent(a)}`,l=n?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(a,u,c,e,r,l,n?._meta)}registerToolsFromFileSources(e){let r=new Set;for(let n of e){let o=t.getOperationsMetadataForFile(n.path);this.debugMode&&this.context.log.debug("Processing file source",{path:n.path,operationIds:n.operationIds,availableOperationIds:Array.from(o.keys())});for(let i of n.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP tool with operation ID: "${i}" from file: "${n.path}" with: "options.files" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=o.get(i);if(!a)throw new Error(`MCP Tool configuration error: Operation ID "${i}" not found in OpenAPI spec at ${n.path}. Available operation IDs: ${Array.from(o.keys()).join(", ")}`);if(a.toolExtension?.enabled===!1){this.debugMode&&this.context.log.debug("Skipping disabled tool",{operationId:i,path:n.path});continue}let c=a.toolExtension?.name?.trim()??i,u=(a.toolExtension?.description?.trim()||null)??(a.routeConfig.raw().description?.trim()||null)??(a.routeConfig.raw().summary?.trim()||null)??`Executes tool: ${c}`;if(!u)throw new Error(`MCP Tool configuration error: no tool description found for operationId: "${i}" in file "${n.path}"`);if(r.has(c))throw new Error(`MCP Tool configuration error: Tool name conflict detected. The name "${c}" is already in use. Consider providing a unique 'name' in the x-zuplo-mcp-tool extension for operation "${i}".`);r.add(c);let l=a.toolExtension?.includeOutputSchema??this.includeOutputSchema??!1,d=a.toolExtension?.includeStructuredContent??this.includeStructuredContent??!1;if(a.routeConfig.methods.length!=1)throw new Error(`MCP tool configuration error: multiple methods "${a.routeConfig.methods.join(", ")}" on operation "${i}" not permitted. Only tools with one singular method is permitted.`);a.graphqlExtension?(a.graphqlExtension.enabled??!0)&&this.registerGraphQLTools(i,a.routeConfig,{type:"graphql",introspectionTool:{name:a.graphqlExtension.introspectionToolName??"",description:a.graphqlExtension.introspectionToolDescription??""},executeTool:{name:a.graphqlExtension.executeToolName??"",description:a.graphqlExtension.executeToolDescription??""}}):this.registerToolsForMethod({routeData:a.routeConfig,method:a.routeConfig.methods[0],name:c,description:u,includeOutputSchema:l,includeStructuredContent:d})}}}registerGraphQLTools(e,r,n){let o=n?.introspectionTool?.name?.trim()||`${e}_introspect`,i=n?.executeTool?.name?.trim()||`${e}_execute_query`;if(this.registeredToolNames.has(o))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The introspection tool name "${o}" is already in use. Provide a unique tool name.`);if(this.registeredToolNames.has(i))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The execute tool name "${i}" is already in use. Provide a unique 'executeToolName' in the x-zuplo-graphql extension.`);this.registeredToolNames.add(o),this.registeredToolNames.add(i);let a=n?.introspectionTool?.description??`Get the GraphQL schema for ${e}`,c=n?.executeTool?.description??`Execute a GraphQL query on ${e}`,u=r.path,d=$r.createObjectValidatorBuilder({}).build();this.server.addTool({name:o,description:a,validator:d,handler:s(async()=>{let m=dr(),g=Date.now();try{this.debugMode&&m.log.debug("MCP GraphQL introspection tool invoked",{toolName:o,operationId:e,path:u});let h=ua(),b=this.buildToolUrl(r,{}),y=this.buildToolRequest("POST","application/json",{body:{query:h}}),w=Date.now(),v=await m.invokeRoute(b,y),S=Date.now()-w,O=await v.text(),T=Date.now()-g;this.debugMode&&(v.ok?m.log.debug("MCP GraphQL introspection tool ok response",{toolName:o,operationId:e,status:v.status,elapsedMs:T,downstreamElapsedMs:S}):m.log.debug("MCP GraphQL introspection tool 'isError' response",{toolName:o,operationId:e,status:v.status,elapsedMs:T,downstreamElapsedMs:S,response:O}));let k;try{k=JSON.parse(O)}catch(N){this.debugMode&&m.log.debug("MCP GraphQL introspection structuredContent JSON parse failed",{toolName:o,body:O,parseErr:N})}return{content:[{type:"text",text:O}],...k&&{structuredContent:k},isError:!v.ok}}catch(h){let b=Date.now()-g,y=h instanceof Error?`${h.name}: ${h.message}`:String(h);throw m.log.error("MCP GraphQL introspection tool invocation failed",{toolName:o,operationId:e,path:u,elapsedMs:b,err:h}),new Error(`MCP GraphQL introspection tool call failed for '${o}': ${y}`)}},"handler")});let p={type:"object",properties:{query:{type:"string",description:"The GraphQL query to execute"},variables:{type:"object",description:"Optional variables for the GraphQL query"}},required:["query"],additionalProperties:!1};this.server.addTool({name:i,description:c,validator:new lr(p,m=>typeof m=="object"&&m!==null&&"query"in m&&typeof m?.query=="string"?{success:!0,data:m,errorData:null}:{success:!1,data:null,errorMessage:"Invalid input: query field is required and must be a string",errorData:null}),handler:s(async m=>{let g=dr(),h=Date.now();try{this.debugMode&&g.log.debug("MCP GraphQL execute tool invoked",{toolName:i,operationId:e,path:u,queryPreview:m.query.substring(0,100)});let b=this.buildToolUrl(r,{}),y={query:m.query};m.variables&&(y.variables=m.variables);let w=this.buildToolRequest("POST","application/json",{body:y}),v=Date.now(),S=await g.invokeRoute(b,w),O=Date.now()-v,T=await S.text(),k=Date.now()-h;this.debugMode&&(S.ok?g.log.debug("MCP GraphQL execute tool ok response",{toolName:i,operationId:e,status:S.status,elapsedMs:k,downstreamElapsedMs:O}):g.log.debug("MCP GraphQL execute tool 'isError' response",{toolName:i,operationId:e,status:S.status,elapsedMs:k,downstreamElapsedMs:O,response:T}));let N;try{N=JSON.parse(T)}catch(U){this.debugMode&&g.log.debug("MCP GraphQL execute structuredContent JSON parse failed",{toolName:i,body:T,parseErr:U})}return{content:[{type:"text",text:T}],...N&&{structuredContent:N},isError:!S.ok}}catch(b){let y=Date.now()-h,w=b instanceof Error?`${b.name}: ${b.message}`:String(b);throw g.log.error("MCP GraphQL execute tool invocation failed",{toolName:i,operationId:e,path:u,elapsedMs:y,err:b}),new Error(`MCP GraphQL execute tool call failed for '${i}': ${w}`)}},"handler")}),this.debugMode&&this.context.log.debug("MCP GraphQL tools registered",{operationId:e,introspectionToolName:o,executeToolName:i,path:u})}registerToolsForMethod({routeData:e,method:r,name:n,description:o,includeOutputSchema:i,includeStructuredContent:a,annotations:c,_meta:u}){if(e.handler?.export!=="mcpServerHandler")if(e.raw().requestBody?.content)for(let l of Object.keys(e.raw().requestBody?.content)){let p=Object.keys(e.raw().requestBody?.content).length>1?`${n}_${l.replace(/[^\w]/g,"_")}`:n;this.registerGenericToolSpec({name:p,description:o,routeData:e,method:r,contentType:l,includeOutputSchema:i,includeStructuredContent:a,annotations:c,_meta:u})}else this.registerGenericToolSpec({name:n,description:o,routeData:e,method:r,contentType:null,includeOutputSchema:i,includeStructuredContent:a,annotations:c,_meta:u})}registerGenericToolSpec({name:e,description:r,routeData:n,method:o,contentType:i,includeOutputSchema:a,includeStructuredContent:c,annotations:u,_meta:l}){let d=this.buildUniversalValidator(n,i);if(!d)throw new Error(`MCP Tool registration error: Could not build parameter validator for ${o.toUpperCase()} ${n.path}. This may indicate an issue with the OpenAPI parameter definitions for this route.`);let p=a?this.extractOutputSchema(n):void 0;try{this.server.addTool({name:e,description:r,validator:d,...p&&{outputSchema:p},...u&&{annotations:u},...l&&{_meta:l},handler:s(async(m,g)=>{let h=dr(),b=Date.now();try{this.debugMode&&h.log.debug("MCP tool invoked",{toolName:e,operationId:n.raw()?.operationId,method:o,path:n.path,args:m});let y=this.buildToolUrl(n,m),w=this.buildToolRequest(o,i,m);this.debugMode&&h.log.debug("MCP tool downstream call",{toolName:e,url:y,method:o,headers:w.headers?Object.keys(w.headers).join(", "):"",bodyPreview:m.body}),h.analyticsContext.addAnalyticsEvent(1,$e.MCP_TOOL_USAGE,{toolName:e,toolPath:n.path,toolMethod:o,toolOperationId:n.raw()?.operationId??"unknown"});let v=Date.now(),S=await h.invokeRoute(y,w),O=Date.now()-v,T=await S.text(),k;if(c)try{k=JSON.parse(T)}catch(U){this.debugMode&&h.log.debug("MCP tool structuredContent JSON parse failed",{toolName:e,body:T,parseErr:U})}let N=Date.now()-b;return this.debugMode&&(S.ok?h.log.debug("MCP tool ok response",{toolName:e,operationId:n.raw()?.operationId,status:S.status,elapsedMs:N,downstreamElapsedMs:O}):h.log.debug("MCP tool 'isError' response",{toolName:e,operationId:n.raw()?.operationId,status:S.status,elapsedMs:N,downstreamElapsedMs:O,response:T})),{content:[{type:"text",text:T}],...k&&{structuredContent:k},isError:!S.ok,_meta:h.custom.mcpCallToolResponse?._meta??{}}}catch(y){let w=Date.now()-b,v=y instanceof Error?`${y.name}: ${y.message}`:String(y);return h.log.error("MCP server tool invocation failed",{toolName:e,operationId:n.raw()?.operationId,method:o,path:n.path,elapsedMs:w,err:y}),{content:[{type:"text",text:`MCP tool call failed for tool '${e}': ${v}`}],isError:!0}}},"handler")}),this.debugMode&&this.context.log.debug("MCP tool registered",{toolName:e,method:o.toUpperCase(),path:n.path,operationId:n.raw()?.operationId,contentType:i||"none",includeOutputSchema:a,includeStructuredContent:c,hasValidator:!!d,hasOutputSchema:!!p})}catch(m){throw new Error(`Failed to add tool ${o} ${n.path}`,m)}}async registerProxyTools(e){let r=new Set;for(let n of e){if(n.enabled===!1){this.debugMode&&this.context.log.debug("Skipping disabled origin",{origin:n.name});continue}let o=n.toolNamePrefix??"";this.debugMode&&this.context.log.debug("Registering origin tools",{origin:n.name,baseUrl:n.baseUrl,toolCount:n.tools.length,toolNamePrefix:o||"none",tools:n.tools});for(let i of n.tools){let a=`${o}${i.name}`;if(r.has(a))throw new Error(`MCP origin configuration error: Tool name conflict detected. The name "${a}" is already in use. Consider using different tool names or toolNamePrefix for origin "${n.name}".`);r.add(a);let u=$r.createObjectValidatorBuilder(i.inputSchema).build();try{let l=new ga(n.baseUrl,i.name,this.debugMode,n.headers);this.server.addTool({name:a,description:i.description,validator:u,handler:s(async d=>await l.execute(d),"handler")}),this.debugMode&&this.context.log.debug("origin tool registered",{localToolName:a,originToolName:i.name,origin:n.name,baseUrl:n.baseUrl})}catch(l){throw new Error(`Failed to register origin tool ${a} from ${n.name}`,{cause:l})}}}this.debugMode&&e.length>0&&this.context.log.debug("origin tool registration complete",{totaloOigins:e.length,totalOriginTools:r.size,originToolNames:Array.from(r)})}buildToolUrl(e,r){return new ba(e).build(r.pathParams,r.queryParams)}buildToolRequest(e,r,n){let o=this.buildToolHeaders(e,r,n),i={method:e,headers:o};return this.shouldIncludeBody(e,r,n)&&(i.body=this.serializeBody(n.body,r)),i}buildToolHeaders(e,r,n){let o={...Jo()};return n.headers&&Object.entries(n.headers).forEach(([i,a])=>{o[i.toLowerCase()]=a}),r&&n.body!==void 0&&(o["content-type"]=r),this.isBodyMethod(e||"")&&n.body!==void 0&&!o["content-type"]&&(o["content-type"]="application/json"),o}shouldIncludeBody(e,r,n){return n.body===void 0?!1:this.isBodyMethod(e)?!0:r!==null}isBodyMethod(e){return["POST","PUT","PATCH"].includes(e.toUpperCase())}serializeBody(e,r){return JSON.stringify(e)}buildUniversalValidator(e,r){try{let o=$r.createValidatorBuilder(e,r).build();return this.debugMode&&this.context.log.debug("MCP validator built successfully",{method:e.methods?.[0],path:e.path,contentType:r||"none",operationId:e.raw()?.operationId}),o}catch(n){let o=n instanceof Error?n.message:String(n);throw this.context.log.warn("MCP validator build failed",{method:e.methods?.[0],path:e.path,contentType:r||"none",operationId:e.raw()?.operationId,error:o}),n}}extractOutputSchema(e){try{let r=e.raw(),n=r?.responses;if(!n){this.context.log.warn("No responses found in OpenAPI spec for outputSchema",{path:e.path,operationId:r?.operationId});return}for(let o of Object.keys(n))if(o.startsWith("2")){let a=n[o]?.content;if(a){for(let c of["application/json","application/json; charset=utf-8"])if(a[c]?.schema){let u=a[c].schema;return this.debugMode&&this.context.log.debug("Output schema extracted successfully",{path:e.path,operationId:r?.operationId,statusCode:o,contentType:c,schemaKeys:u&&typeof u=="object"?Object.keys(u).join(", "):"none"}),u}}}this.debugMode&&this.context.log.debug("No OpenAPI spec 2xx responses fond for outputSchema",{path:e.path,operationId:r?.operationId,statusCodes:Object.keys(n).join(", ")});return}catch(r){this.context.log.warn("Failed to extract outputSchema",{path:e.path,operationId:e.raw()?.operationId,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0});return}}};async function Vv(t,e,r,n){let o=P.instance.zuploEdgeApiUrl;if(!o)throw new x("Zuplo edge API URL not configured");let i=Se.ZUPLO_SERVICE_BUCKET_ID;if(!i)throw new x("ZUPLO_SERVICE_BUCKET_ID env not configured");let a=P.instance.authApiJWT;if(!a)throw new x("Zuplo auth API JWT not configured");let c=`${o}/zups/v1/buckets/${i}/mcp/configurations/${r}/servers/access`,u={sub:t,slug:e},l=await z.fetch(c,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(u)});return l.status===403?!1:l.ok?(await l.json()).allowed:(n.log.error(`Unexpected response from MCP gateway at <${i} ${r}> access check: ${l.status} ${l.statusText}`),!1)}s(Vv,"checkVirtualServerAccess");var Jv=10,Wv=3e4,Ar=class{static{s(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,r){if(typeof r=="number"){let n=r;this.#n=n*1e3,this.#o=Wv,this.#r=Jv}else{let n=r;this.#n=n.ttlSeconds*1e3,this.#o=n.loaderTimeoutSeconds?n.loaderTimeoutSeconds*1e3:Wv,this.#r=Jv}this.#t=e}#s(e){return e.expiry<=new Date}#c(e){let r=this.#i[e];return!(r===void 0||r===0)}#u(e){let r=this.#e.get(e);if(r&&!this.#s(r))return r.data}async get(e){let r=this.#u(e);if(r)return this.#l(e),r;if(this.#c(e))try{await YE(()=>this.#u(e)!==void 0||!this.#c(e),this.#o+this.#r+1,this.#r);let n=this.#u(e);if(n)return n}catch{}return this.#a(e)}#l(e){if(!this.#c(e)){let r=this.#a(e);tr().waitUntil(r)}}async#a(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let r=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(r===void 0)throw new x(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:r,expiry:new Date(Date.now()+this.#n)}),r}finally{this.#i[e]--}}};async function YE(t,e,r){let n=Date.now();for(;!t();){let o=Date.now()-n;if(o>e)throw new x(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(r)}}s(YE,"waitUntilTrue");var XE={ttlSeconds:600,loaderTimeoutSeconds:30},Kv=new Ar(async()=>{let t=P.instance.zuploEdgeApiUrl;if(!t)throw new x("Zuplo edge API URL not configured");let e=P.instance.authApiJWT;if(!e)throw new x("Zuplo auth API JWT not configured");let r=P.instance.deploymentName;if(!r)throw new x("Deployment name not configured");let n=Se.ZUPLO_SERVICE_BUCKET_ID;if(!n)throw new x("ZUPLO_SERVICE_BUCKET_ID env not configured");let o=`${t}/zups/v1/buckets/${n}/mcp/resolve`,i=await z.fetch(o,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-Agent":P.instance.systemUserAgent,"Content-Type":"application/json"},body:JSON.stringify({deployment:r})});if(!i.ok){let u=await i.text().catch(()=>"");throw new x(`Failed to resolve MCP gateway configuration from ${o}: ${i.status} ${i.statusText}${u?` - ${u}`:""}`)}let a=await i.json(),c=a.mcpGatewayConfig;if(c.configurationId=a.configurationId,!c||typeof c!="object")throw new x("Invalid MCP gateway configuration: not an object");if(!Array.isArray(c.servers))throw new x("Invalid MCP gateway configuration: servers must be an array");return c},XE);async function eC(t,e){if(R("handler.mcp-gateway"),e.route.methods.some(h=>h.toUpperCase()!=="POST"))throw new x(`Invalid route config: mcpGatewayHandler may only use POST. Route '${e.route.path}' declares methods: [${e.route.methods.join(", ")}]`);let r=e.route?.handler?.options??{},n=await Kv.get("NO_KEY");e.log.debug(`Loaded configuration with ${n.servers?.length??0} servers`);let o=t.params.slug;if(!o)throw new Error("No MCP gateway slug provided in request");let i=n.servers.find(h=>h.slug===o);if(!i)throw new Error(`No MCP server configuration found for slug: ${o}`);if(!t.user?.sub)throw W.getLogger(e).error(`No user provided in request in MCP Gateway<${n.configurationId}>. This should not happen.`),new x(`MCP Gateway<${n.configurationId}>: No user provided in request. }
245
245
  `);if(!await Vv(t.user?.sub,o,n.configurationId,e))throw new Error(`User does not have access to MCP server: ${o}`);let c={name:i.name,debugMode:r.debugMode},l=new TextEncoder().encode(JSON.stringify(i)),d=await crypto.subtle.digest("SHA-256",l),p=new Uint8Array(d),m=Array.from(p).map(h=>h.toString(16).padStart(2,"0")).join(""),g=`mcp-origin-config:${o}:${m.substring(0,32)}`;return e.log.debug(`Using MCP server key: ${g}`),tC({request:t,context:e,opts:c,key:g,origins:i.origins})}s(eC,"mcpGatewayHandler");async function tC({request:t,context:e,opts:r,key:n,origins:o}){let i={};t.headers.forEach((c,u)=>{i[u]=c});let a=await dn.getInstance({opts:r,context:e,key:n,origins:o});return fa(i,e,()=>a.handleRequest(t,e))}s(tC,"mcpServerProxyHandler");async function rC(t,e){if(R("handler.mcp-server"),e.route.methods.some(a=>a.toUpperCase()!=="POST"))throw new x(`Invalid route config: mcpServerHandler may only use POST. Route '${e.route.path}' declares methods: [${e.route.methods.join(", ")}]`);let r={};t.headers.forEach((a,c)=>{r[c]=a});let n=e.route?.handler?.options??{},o=e.route?.path??"unknown-route",i=await dn.getInstance({opts:n,context:e,key:o});return fa(r,e,()=>i.handleRequest(t,e))}s(rC,"mcpServerHandler");var nC=[502,503,504];async function pn(t,e){if(nC.includes(t.status)){let r=W.getLogger(e),o=await t.clone().text(),i={};for(let[a,c]of t.headers)i[a]=c;r.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:i})}}s(pn,"logBadGatewayResponses");var Am;function fr(t){if(Am===void 0){let r=P.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),Am=r}return t.log[Am]}s(fr,"getHandlerUserLogFunction");async function oC(t,e){R("handler.open-api");let r=P.instance.build.BUILD_ID,{buildAssetsUrl:n}=P.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new x("Open API Spec Handler must have 'openApiFilePath' specified");let a=iC(i);if(!a.isValid)throw new x(a.error);let c=`${n}/${r}${i.substring(1)}`,u=await z.fetch(c,{method:t.method,body:t.body,headers:t.headers});if(u.status!==200)return D.notFound(t,e,{detail:"OpenAPI file could not be found."});let l={"content-type":"application/json",vary:"Accept-Encoding"};P.instance.isDeno||(l["content-encoding"]=u.headers.get("content-encoding")||"");let d=new Response(u.body,{headers:l,status:u.status,statusText:u.statusText});return pn(d,e),d}s(oC,"openApiSpecHandler");var iC=s(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function sC(t,e){R("handler.redirect");let r=e.route.handler.options;if(!r.location)throw new x("Redirect Handler must have 'location' specified");let n=r.status??302;return new Response(null,{status:n,headers:{location:r.location}})}s(sC,"redirectHandler");async function aC(t){if(R("handler.zuplo-service-proxy"),Object.entries(t.params).length!==1)throw new x("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(t.params.path,P.instance.zuploEdgeApiUrl),r=new Headers(t.headers);return r.set("Authorization",`Bearer ${P.instance.authApiJWT}`),z.fetch(e,{method:t.method,headers:r,body:t.body})}s(aC,"zuploServiceProxy");function cC(t,e){let r=t.endsWith("/"),n=e.startsWith("/");return r&&n?`${t.substring(0,t.length-1)}${e}`:!r&&!n?`${t}/${e}`:`${t}${e}`}s(cC,"join");async function uC(t,e){R("handler.url-forward");let r=fr(e),n=e.route.handler.options,o=n.forwardSearch!==!1,i;if(P.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?i=n.followRedirects===!0?"follow":"manual":typeof n.followRedirects<"u"&&R("handler.url-forward.follow-redirects"),!n.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!n||typeof n.__rewriteFunction!="function")throw new x("Invalid options for this route");let a=rr(e),c=new URL(t.url),u=n.__rewriteFunction(t,a),l=cC(u,c.pathname),d=o?`${l}${c.search}`:l.toString(),p=Date.now();r(`URL Forwarding to '${d}'`);let m=t.body;if(i==="follow"&&t.body)try{m=await t.arrayBuffer()}catch(b){throw new Error(`Failed to buffer request body for redirect handling: ${b}`)}let g=await fetch(d,{method:t.method,body:m,headers:t.headers,redirect:i,zuplo:n.mtlsCertificate?{mtlsCertificate:n.mtlsCertificate}:void 0}),h=Date.now()-p;return r(`URL Forward received response ${g.status} - ${g.statusText} in ${h}ms`),pn(g,e),g}s(uC,"urlForwardHandler");var lC=s((t,e)=>{let r=new URL(t),n=new URL(e);for(let[o,i]of n.searchParams.entries())r.searchParams.append(o,i);return r.toString()},"addQuery");async function dC(t,e){R("handler.url-rewrite");let r=fr(e),n=e.route.handler.options,o=n.forwardSearch!==!1,i=n.followRedirects??!1;if(!n||typeof n.__rewriteFunction!="function")throw new x("Invalid options for this route");let a=rr(e),c=n.__rewriteFunction(t,a),u=o?lC(c,t.url):c,l=Date.now();r(`URL Rewriting to '${u}'`);let d=await fetch(u.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:i?"follow":"manual",zuplo:n.mtlsCertificate?{mtlsCertificate:n.mtlsCertificate}:void 0}),p=Date.now()-l;return r(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),pn(d,e),d}s(dC,"urlRewriteHandler");function pC(t,e,r){t.addEventListener("close",()=>{e.close()}),e.addEventListener("close",()=>{t.close()}),t.addEventListener("error",n=>{r.log.error(`Incoming WebSocket error: ${JSON.stringify(n)}`),e.send(JSON.stringify(n))}),e.addEventListener("error",n=>{r.log.error(`Outgoing WebSocket error: ${JSON.stringify(n)}`),t.send(JSON.stringify(n))}),t.addEventListener("message",n=>{e.send(n.data)}),e.addEventListener("message",n=>{t.send(n.data)})}s(pC,"wireUpPassthrough");async function mC(t,e){R("handler.websocket");let r=e.route.handler.options,n=fr(e);if(!r||!r.rewritePattern)throw new x("WebSocket Handler must have option 'rewritePattern' specified");let o=t.headers.get("Upgrade");if(!o||o!=="websocket")return D.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new x("Invalid options for this route");let i=rr(e),a=r.__rewriteFunction(t,i);if(n(`Attempting WebSocket connection to '${a}'`),P.instance.isDeno){if(!t.originalRequest)throw new Error("Original websocket request is not available");let c=new WebSocket(a);await new Promise((d,p)=>{let m=s(()=>{h(),n("WebSocket connection established with upstream"),d()},"onOpen"),g=s(b=>{h(),n(`WebSocket connection error: ${b}`),p(new Error("Upstream open failed"))},"onErr"),h=s(()=>{c.removeEventListener("open",m),c.removeEventListener("error",g)},"cleanup");c.addEventListener("open",m),c.addEventListener("error",g)}).catch(d=>{throw new Error(`Failed to open outgoing socket: ${d.message}`)});let{socket:u,response:l}=globalThis.Deno.upgradeWebSocket(t.originalRequest);return pC(u,c,e),l}else{a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:t.method,headers:t.headers,body:t.body});if(c.status!==101||!c.webSocket){let u=await c.text(),l=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${u}'`;throw new Error(l)}return n(`WebSocket connected, received response ${c.status} - ${c.statusText}`),new Response(null,{status:101,webSocket:c.webSocket})}}s(mC,"webSocketHandler");var Nm=s((t,e)=>t.map((n,o)=>{let i;if(typeof n.module=="object"&&(i=n.module[n.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${o+1}, export name: ${n.export}`;throw new x(`${a} - Websocket policy must be a valid function (${c})`)}return i}),"getWebSocketPolicyFunctions"),Qv=s(async(t,e,r,n,o,i)=>{let a=t.data;if(i&&i.length>0){let c=[...i];for(;c.length>0;){let u=c.shift();if(!u)return a;if(a=await u(a,r,e,n,o),a===void 0)return}}return a},"webSocketPolicyProcessor");async function fC(t,e,r){r(`Attempting WebSocket connection to '${e}'`);let n=new WebSocket(e);await new Promise((a,c)=>{let u=s(()=>{d(),r("WebSocket connection established with upstream"),a()},"onOpen"),l=s(p=>{d(),r(`WebSocket connection error: ${p}`),c(new Error("Upstream open failed"))},"onErr"),d=s(()=>{n.removeEventListener("open",u),n.removeEventListener("error",l)},"cleanup");n.addEventListener("open",u),n.addEventListener("error",l)}).catch(a=>{throw new Error(`Failed to open outgoing socket: ${a.message}`)});let{socket:o,response:i}=globalThis.Deno.upgradeWebSocket(t);return{clientSocket:o,outgoingSocket:n,response:i}}s(fC,"getDenoClientAndServerSockets");async function gC(t,e,r){r(`Attempting WebSocket connection to '${e}'`);let n=await fetch(e,{method:t.method,headers:t.headers,body:t.body});if(n.status!==101||!n.webSocket){let u=await n.text(),l=`WebSocket connection error - ${n.status}: ${n.statusText}, content: '${u}'`;throw new Error(l)}let o=new WebSocketPair,[i,a]=Object.values(o);r(`WebSocket connected, received response ${n.status} - ${n.statusText}`),n.webSocket.accept(),a.accept();let c=new Response(null,{status:101,webSocket:i});return{clientSocket:i,outgoingSocket:n.webSocket,serverSocket:a,response:c}}s(gC,"getCfClientAndServerSockets");function Yv(t,e,r,n,o,i){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",a=>{n.log.error(`WebSocket error: ${JSON.stringify(a)}, direction: ${i}`),e.send(JSON.stringify(a))}),t.addEventListener("message",a=>{try{let u=s(async l=>{let d=await Qv(l,t,e,r,n,o);d!==void 0&&e.send(d)},"innerPipeline")(a).catch(n.log.error);n.waitUntil(u)}catch(c){n.log.error(c)}})}s(Yv,"wireUpListeners");async function hC(t,e){R("handler.websocket-pipeline");let r=e.route.handler.options,n=fr(e);if(!r||!r.rewritePattern)throw new x("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=t.headers.get("Upgrade");if(!o||o!=="websocket")return D.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new x("Invalid options for this route");let i=rr(e),a=r.__rewriteFunction(t,i),c=r.policies?.inbound?Nm(r.policies.inbound,"inbound"):[],u=r.policies?.outbound?Nm(r.policies.outbound,"outbound"):[],l,d,p,m;if(P.instance.isDeno){if(!t.originalRequest)throw new Error("Original websocket request is not available");let g=await fC(t.originalRequest,a,n);p=g.clientSocket,l=p,d=g.outgoingSocket,m=g.response}else{a=a.replace(/^(ws)/,"http");let g=await gC(t,a,n);l=g.serverSocket,d=g.outgoingSocket,p=g.clientSocket,m=g.response}return Yv(l,d,t,e,c,"inbound"),Yv(d,l,t,e,u,"outbound"),m}s(hC,"webSocketPipelineHandler");var Lm=class extends Ne{constructor(r){super();this.options=r}static{s(this,"AWSLoggingPlugin")}getTransport(){return new Mm(this.options)}},Mm=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;environmentStage;logGroupName;logStreamName;region;fields;batcher=new ce("aws-log-transport",10,async e=>{if(e.length===0)return;let r=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let n=await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:r,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}});n.ok||await fe({level:"error",messages:[`Failed to send logs to AWS: ${n.status} - ${n.statusText}`]},n)}catch{await fe({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}});constructor({accessKeyId:e,logStreamName:r,logGroupName:n,secretAccessKey:o,region:i,fields:a}){R("logging.aws"),this.awsClient=new Jr({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=n,this.logStreamName=r,this.region=i,this.environmentType=P.instance.loggingEnvironmentType,this.environmentStage=P.instance.loggingEnvironmentStage,this.environment=P.instance.deploymentName,this.fields=a??{}}log(e,r){e.messages.forEach(n=>{let o={timestamp:Date.now(),message:JSON.stringify(Object.assign({data:it(n),severity:e.level,source:e.logSource,environment:this.environment,atomicCounter:e.vectorClock,requestId:e.requestId,environmentType:this.environmentType,environmentStage:this.environmentStage,rayId:e.rayId===null?void 0:e.rayId},this.fields,r.properties??{}))};this.batcher.enqueue(o)}),r.waitUntil(this.batcher.waitUntilFlushed())}};var Dm=class extends Ne{constructor(r){super();this.options=r}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new Um(this.options)}},Um=class{static{s(this,"DynaTraceTransport")}constructor(e){R("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=P.instance.loggingEnvironmentType,this.#o=P.instance.loggingEnvironmentStage,this.#n=P.instance.deploymentName,this.#i=e.fields??{}}#e;#t;#n;#r;#o;#i;log(e,r){e.messages.forEach(n=>{let o=Object.assign({timestamp:new Date().toISOString(),message:it(n),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.atomicCounter":e.vectorClock,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId},this.#i,r.properties??{});this.batcher.enqueue(o)}),r.waitUntil(this.batcher.waitUntilFlushed())}#s=s(async e=>{if(e.length!==0)try{let r=await z.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});r.ok||await fe({level:"error",messages:[`Failed to send logs to Dynatrace: ${r.status} - ${r.statusText}`]},r)}catch{await fe({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ce("dyna-trace-log-transport",10,this.#s)};var jm=class extends Ne{constructor(r){super();this.options=r}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Zm(this.options)}},zm=class{static{s(this,"LokiStream")}constructor(e,r,n,o,i,a){this.level=e,this.environment=r,this.environmentType=n,this.environmentStage=o,this.requestId=a,this.job=i}job;level;environment;environmentType;environmentStage;requestId;equals=s(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function yC(t,e){return btoa(`${t}:${e}`)}s(yC,"createBasicDigest");var Zm=class{static{s(this,"LokiTransport")}constructor(e){R("logging.loki"),this.#n=e.url,this.#r=yC(e.username,e.password),this.#i=P.instance.loggingEnvironmentType,this.#s=P.instance.loggingEnvironmentStage,this.#o=P.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo",this.#c=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;#c;log(e,r){let n=new zm(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let i=Object.assign({stream:n,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:it(o),nanoSecondEpoch:`${e.timestamp.getTime()}000000`},this.#c,r.properties??{});this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}#u=s(e=>{let r={streams:[]};return e.forEach(n=>{let o=r.streams.find(i=>i.stream.equals(n.stream));o||(o={stream:n.stream,values:[]},r.streams.push(o)),o.values.push(this.#e>1?[n.nanoSecondEpoch,n.message,{requestId:n.requestId,rayId:n.rayId,atomicCounter:JSON.stringify(n.atomicCounter)}]:[n.nanoSecondEpoch,n.message])}),r},"#convertToLokiStreamsBatch");#l=s(async e=>{if(e.length===0)return;let r=this.#u(e);try{let n=await z.fetch(this.#n,{method:"POST",body:JSON.stringify(r),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}});n.ok||await fe({level:"error",messages:[`Failed to send logs to Loki: ${n.status} - ${n.statusText}`]},n)}catch{await fe({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ce("loki-log-transport",10,this.#l)};var qm=class extends Ne{constructor(r){super();this.options=r}static{s(this,"NewRelicLoggingPlugin")}getTransport(){return new Fm(this.options)}},Fm=class{static{s(this,"NewRelicTransport")}constructor(e){R("logging.newrelic"),this.#e=e.url??"https://log-api.newrelic.com/log/v1",this.#t=e.apiKey,this.#r=P.instance.loggingEnvironmentType,this.#o=P.instance.loggingEnvironmentStage,this.#n=P.instance.deploymentName,this.#i=e.fields??{},this.#s=e.service??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,r){e.messages.forEach(n=>{let o=Object.assign({message:it(n),level:e.level,timestamp:Date.now(),service:this.#s,request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#n,environment_stage:this.#o,environment_type:this.#r,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource},this.#i,r.properties??{});this.batcher.enqueue(o)}),r.waitUntil(this.batcher.waitUntilFlushed())}#c=s(async e=>{if(e.length!==0)try{let r=await z.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json","Api-Key":this.#t}});r.ok||await fe({level:"error",messages:[`Failed to send logs to New Relic: ${r.status} - ${r.statusText}`]},r)}catch{await fe({level:"error",messages:["Failed to connect to New Relic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ce("new-relic-log-transport",10,this.#c)};var Hm=class extends Ne{constructor(r){super();this.options=r}static{s(this,"SplunkLoggingPlugin")}getTransport(){return new Bm(this.options)}},Bm=class{static{s(this,"SplunkTransport")}constructor(e){R("logging.splunk"),this.#e=e.url,this.#t=e.token,this.#r=P.instance.loggingEnvironmentType,this.#o=P.instance.loggingEnvironmentStage,this.#n=P.instance.deploymentName,this.#i=e.fields??{},this.#s=e.index??"main",this.#c=e.sourcetype??"json",this.#u=e.host??"zuplo-api",this.#l=e.channel}#e;#t;#n;#r;#o;#i;#s;#c;#u;#l;log(e,r){e.messages.forEach(n=>{let i={event:{message:it(n),level:e.level,timestamp:new Date().toISOString(),request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#n,environment_stage:this.#o,environment_type:this.#r,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource,...this.#i,...r.properties??{}},sourcetype:this.#c,host:this.#u,index:this.#s,time:Math.floor(Date.now()/1e3)};this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}#a=s(async e=>{if(e.length!==0)try{for(let r of e){let n={"Content-Type":"application/json",Authorization:`Splunk ${this.#t}`};this.#l&&(n["X-Splunk-Request-Channel"]=this.#l);let o=await z.fetch(this.#e,{method:"POST",body:JSON.stringify(r),headers:n});if(!o.ok){let i=await o.text();await fe({level:"error",messages:[`Failed to send logs to Splunk: ${o.status} - ${o.statusText}`,`Response: ${i}`]},o)}}}catch(r){await fe({level:"error",messages:["Failed to connect to Splunk logging service. Check that the URL is correct.",`Error: ${r instanceof Error?r.message:String(r)}`]})}},"#dispatchFunction");batcher=new ce("splunk-log-transport",10,this.#a)};var Gm=class extends Ne{constructor(r){super();this.options=r}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Vm(this.options)}},Vm=class{static{s(this,"SumoLogicTransport")}constructor(e){R("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=P.instance.loggingEnvironmentType,this.#r=P.instance.loggingEnvironmentStage,this.#t=P.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;log(e,r){e.messages.forEach(n=>{let o=Object.assign({timestamp:new Date().toISOString(),message:it(n),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId},this.#s,r.properties??{});this.batcher.enqueue(o)}),r.waitUntil(this.batcher.waitUntilFlushed())}#c=s(async e=>{if(e.length===0)return;let r=e.map(o=>JSON.stringify(o)).join(`
246
246
  `),n=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&n.set("X-Sumo-Name",this.#i),this.#o&&n.set("X-Sumo-Category",this.#o);try{let o=await z.fetch(this.#e,{method:"POST",body:r,headers:n});o.ok||await fe({level:"error",messages:[`Failed to send logs to Sumologic: ${o.status} - ${o.statusText}`]},o)}catch{await fe({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ce("sumo-logic-log-transport",10,this.#c)};var bC="d3a5b78f823648f5b1df4fe269d41172",Jm=class extends Ne{constructor(r){super();this.options=r}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Wm(this.options)}},Wm=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){R("logging.vmware-loginsight");let r;try{r=new URL(e.url),r.pathname==="/"&&(r.pathname=`/api/v1/events/ingest/${e.agentId??bC}`)}catch{throw new x(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=r.toString(),this.#r=P.instance.loggingEnvironmentType,this.#o=P.instance.loggingEnvironmentStage,this.#n=P.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([n,o])=>({name:n,content:o})))}#e;#t;#n;#r;#o;#i;#s;log(e,r){let n=this.buildEntry(e,r);this.batcher.enqueue(n),r.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,r){let n=Nh(e.messages);this.#t?.forEach(i=>{n=n.replaceAll(i[0],i[1])});let o={timestamp:Date.now(),text:n,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&o.fields.push({name:"environment",content:this.#n}),this.#s&&o.fields.push(...this.#s),r.properties&&Object.entries(r.properties).forEach(([i,a])=>{let c=Mi(a);c&&o.fields.push({name:i,content:c})}),r.custom&&Object.entries(r.custom).forEach(([i,a])=>{let c=Mi(a);c&&o.fields.push({name:i,content:c})}),this.#i&&(o=this.#i(o)),o}#c=s(async e=>{if(e.length!==0)try{let r=await z.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});r.ok||await fe({level:"error",messages:[`Failed to send logs to Log Insight: ${r.status} - ${r.statusText}`]},r)}catch{await fe({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ce("vmware-log-insights-log-transport",10,this.#c)};var Km=class{static{s(this,"ZuploMcpSdk")}context;constructor(e){this.context=e}getRawCallToolRequest(){let e=null;return this.context.custom.mcpCallToolRequest&&(e=this.context.custom.mcpCallToolRequest),this.context.parentContext?.custom.mcpCallToolRequest&&(e=this.context.parentContext.custom.mcpCallToolRequest),e}setRawCallToolResult(e){if(this.context.parentContext?.custom.mcpCallToolRequest){this.context.parentContext.custom.mcpCallToolResponse=e;return}this.context.custom.mcpCallToolResponse=e}};var Qm=new WeakMap,wC={tags:[]},Ym=class extends _t{constructor(r){super();this.options=r;R("metrics.datadog")}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new Xm(this.options)}static setContext(r,n){let o=Qm.get(r);o||(o=wC);let i=Object.assign({...o},n);Qm.set(r,i)}},Xm=class{static{s(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,r){this.#i===void 0&&(this.#i=new ce("data-dog-metrics-transport",10,this.dispatchFunction,W.getLogger(r)));let n=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Qm.get(r)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let i=e.systemRouteName||e.routePath;o.push(`path:${i}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:n,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:n,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:n,value:e.responseContentLength}],tags:o}),r.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let r=JSON.stringify({series:e}),n=await z.fetch(this.#t,{method:"POST",body:r,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});n.ok||await fe({level:"error",messages:["Failed to send metrics to DataDog."]},n)}catch{await fe({level:"error",messages:["Failed to connect to DataDog metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var ef=new WeakMap,vC={dimensions:[]},tf=class extends _t{constructor(r){super();this.options=r;R("metrics.dynatrace")}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new rf(this.options)}static setContext(r,n){let o=ef.get(r);o||(o=vC);let i=Object.assign({...o},n);ef.set(r,i)}},rf=class{static{s(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,r){this.#r===void 0&&(this.#r=new ce("dynatrace-metrics-transport",10,this.dispatchFunction,W.getLogger(r)));let n=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(ef.get(r)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let i=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${n}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${n}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${n}`),r.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let r=e.join(`
247
247
  `),n=await z.fetch(this.#e,{method:"POST",body:r,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});n.ok||await fe({level:"error",messages:["Failed to send metrics to Dynatrace."]},n)}catch{await fe({level:"error",messages:["Failed to connect to Dynatrace metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var nf=new WeakMap,xC={attributes:{}},of=class extends _t{constructor(r){super();this.options=r;R("metrics.newrelic")}static{s(this,"NewRelicMetricsPlugin")}getTransport(){return new sf(this.options)}static setContext(r,n){let o=nf.get(r);o||(o=xC);let i=Object.assign({...o},n);nf.set(r,i)}},sf=class{static{s(this,"NewRelicMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://metric-api.newrelic.com/metric/v1",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.attributes??{service:"zuplo"}}pushMetrics(e,r){this.#i===void 0&&(this.#i=new ce("new-relic-metrics-transport",10,this.dispatchFunction,W.getLogger(r)));let n=Math.floor(e.timestamp.getTime()),o={...this.#r,...nf.get(r)?.attributes};if(this.#o.country&&(o.country=e.country),this.#o.httpMethod&&(o.httpMethod=e.method),this.#o.statusCode&&(o.statusCode=e.statusCode.toString()),this.#o.path){let i=e.systemRouteName||e.routePath;o.path=i}this.#n.latency&&this.#i.enqueue({name:"zuplo.request.latency",type:"gauge",value:e.durationMs,timestamp:n,attributes:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({name:"zuplo.request.content_length",type:"gauge",value:e.requestContentLength,timestamp:n,attributes:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({name:"zuplo.response.content_length",type:"gauge",value:e.responseContentLength,timestamp:n,attributes:o}),r.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let r=JSON.stringify([{metrics:e}]),n=await _e({retries:3,retryDelayMs:300,logger:z.console},this.#t,{method:"POST",body:r,headers:{"Content-Type":"application/json","Api-Key":this.#e}});n.ok||await fe({level:"error",messages:[`Failed to send metrics to New Relic. Status: ${n.status} ${n.statusText}`]},n)}catch(r){await fe({level:"error",messages:["Failed to connect to New Relic metrics service. Check that the URL is correct.",`Error: ${r instanceof Error?r.message:String(r)}`]})}},"dispatchFunction")};var af=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,R("audit-logs.datastax")}#e;writeLogBatch=s(async e=>{await Promise.allSettled(e.map(async r=>{await z.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(r)})}))},"writeLogBatch")};var cf=class extends Ae{static{s(this,"AuditLogPlugin")}constructor(e,r){super(),this.#e=e,this.#t=r,R("audit-logs")}#e;#t;async initialize(e){new uf(e,this.#e,this.#t)}},Xv=s(t=>{let e={};return t.forEach((r,n)=>{e[n]=r}),e},"serializableHeaders"),RC={requestFilter:s(async()=>!0,"requestFilter"),include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},uf=class{static{s(this,"AuditPluginImpl")}constructor(e,r,n){this.#t=r;let o={...RC};n?.requestFilter&&(o.requestFilter=n.requestFilter),n?.include?.request&&Object.assign(o,n.include.request),n?.include?.response&&Object.assign(o,n.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new ce("audit-log",10,this.#r)}#e;#t;#n;#r=s(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#o=s(async(e,r,n,o,i,a)=>{try{let c={timestamp:o,durationMs:i,routePath:n.route.path,requestId:n.requestId,userSub:a,request:{url:r.url,method:r.method,headers:this.#e.include?.request?.headers?Xv(r.headers):void 0,body:this.#e.include?.request?.body?await r.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?Xv(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(c),n.waitUntil(this.#n.waitUntilFlushed())}catch(c){n.log.error(c)}},"#asyncPrepLogs");#i=s(async(e,r)=>{try{if(!await this.#e.requestFilter(e,r))return e;let o=new Date,i=Date.now(),a=e.clone();return r.addResponseSendingFinalHook(async(c,u)=>{let l=Date.now(),d=c.clone(),p=this.#o(d,a,r,o,l-i,u.user?.sub).catch(m=>{r.log.error(m)});r.waitUntil(p)}),e}catch(n){return r.log.error(n),e}},"#auditHook")};import{importJWK as PC,SignJWT as IC}from"jose";var ex=!1,Yo=class t extends Ae{static{s(this,"JwtServicePlugin")}#e;static#t=void 0;static#n=void 0;static#r=void 0;static#o=void 0;static async signJwt({audience:e,subject:r,expiresIn:n=t.#r,...o}){if(!t.#n){let u=P.instance.authPrivateKey;if(!u)throw new x("JwtServicePlugin - Cannot sign JWT. Private key configured for this Zuplo project.");try{t.#n=await PC(JSON.parse(u),"EdDSA")}catch(l){throw new x("JwtServicePlugin - Failed to import private key. Ensure it is a valid JWK format.",{cause:l})}}if(!t.#t)throw new x("JwtServicePlugin - Cannot sign JWT. The issuer URL is not configured. Ensure the plugin is initialized.");if(!t.#r)throw new x("JwtServicePlugin - Cannot sign JWT. The token expiration is not configured. Ensure the plugin is initialized.");let i=n??t.#r,a=typeof i=="number"?new Date(Date.now()+i*1e3):i,c=new IC(o).setProtectedHeader({alg:"EdDSA"}).setIssuer(t.#t).setIssuedAt(new Date).setExpirationTime(a);return e&&c.setAudience(e),r&&c.setSubject(r),await c.sign(t.#n)}constructor(e){if(super(),ex)throw new x("JwtServicePlugin - Only one instance of JwtServicePlugin can be created. Ensure you are not creating multiple instances in your code.");R("plugin.jwt-service"),ex=!0,this.#e=e?.basePath??"/__zuplo/issuer",t.#r=e?.expiresIn??"1h",this.#e.endsWith("/")&&(this.#e=this.#e.slice(0,-1))}registerRoutes({runtimeSettings:e,router:r}){let n=e.api.urls?.defaultUrl;if(!n)throw new x("JwtServicePlugin - Cannot determine issuer URL. Ensure the API is properly configured.");let o=new URL(this.#e,n).toString();t.#t=o,r.addPluginRoute({methods:["GET"],path:`${this.#e}/.well-known/openid-configuration`,handler:s(async()=>{let i={issuer:o,jwks_uri:`${o}/.well-known/jwks.json`,id_token_signing_alg_values_supported:["EdDSA"],subject_types_supported:["public"]};return new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json","Cache-Control":"public, max-age=15, stale-while-revalidate=15, stale-if-error=86400"}})},"handler")}),r.addPluginRoute({methods:["GET"],path:`${this.#e}/.well-known/jwks.json`,handler:s(async()=>{if(!t.#o)try{let i=P.instance.authPublicKey;if(!i)throw new x("JwtServicePlugin - Public key is not configured for this Zuplo project");let a={keys:[JSON.parse(i)]};t.#o=JSON.stringify(a)}catch(i){throw new x("JwtServicePlugin - Failed to export public key as JWK.",{cause:i})}return new Response(t.#o,{headers:{"Content-Type":"application/json","Cache-Control":"public, max-age=15, stale-while-revalidate=15, stale-if-error=86400"}})},"handler")})}};var mn=class extends Ae{static{s(this,"OAuthProtectedResourceBasePlugin")}createOauthProtectedResourceHandler(){return async(e,r)=>{let n=new URL(e.url),o=e.params.resourcePath,i=o?`${n.origin}/${o}`:n.origin,a=await this.getMetadataOptions(e,r),c={resource:i,authorization_servers:a.authorizationServers,resource_name:a.resourceName};return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}}registerRoutes(e){let{router:r}=e;r.addPluginRoute({methods:["GET"],path:"/.well-known/oauth-protected-resource/:resourcePath*",handler:this.createOauthProtectedResourceHandler(),corsPolicy:"anything-goes",processors:[qr]})}};var lf=class extends mn{static{s(this,"McpGatewayOAuthProtectedResourcePlugin")}authServers;resource;constructor(){super();let e=P.instance.isLocalDevelopment?"http://localhost:8080":P.instance.zuploEdgeApiUrl;this.authServers=[e],this.resource="https://mcp-gateway.zuplo.com/"}async getMetadataOptions(e,r){let n=e.params.resourcePath;return{authorizationServers:this.authServers,resource:this.resource,resourceName:"Zuplo MCP Gateway"}}};var Xo=class extends mn{static{s(this,"OAuthProtectedResourcePlugin")}options;constructor(e){super(),this.options=e}async getMetadataOptions(e,r){return{authorizationServers:this.options.authorizationServers,resourceName:this.options.resourceName}}};var df={None:0,JsonEscape:1},ei=class{constructor(e,r={}){this.stream=e;this.options=r;this.placeholder=`__STREAM_TOKEN_${crypto.randomUUID()}__`}static{s(this,"StreamToken")}placeholder;getRawStream(){return this.stream}getOptions(){return this.options}getSafeToken(){return this.placeholder}async getContent(){if(!this.stream)return this.options.useEmptyStringIfNull?"":null;let e=this.stream.getReader(),r=[];try{for(;;){let{done:c,value:u}=await e.read();if(c)break;r.push(u)}}finally{e.releaseLock()}let n=r.reduce((c,u)=>c+u.length,0),o=new Uint8Array(n),i=0;for(let c of r)o.set(c,i),i+=c.length;let a=new TextDecoder().decode(o);return this.options.base64Encode&&(a=btoa(a)),a}},Pa=class{static{s(this,"StreamBuilder")}template;tokens;flags;constructor(e){this.template=e.template,this.tokens=e.tokens,this.flags=e.flags}escapeJsonString(e){return e.replace(/[\\\"\n\r\t\f\b]/g,r=>{switch(r){case"\\":return"\\\\";case'"':return'\\"';case`