@decocms/mesh 2.35.0 → 2.37.0

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.
Files changed (137) hide show
  1. package/dist/client/assets/{AlertCircle-BRWDZx_r.js → AlertCircle-lJsd1WSR.js} +1 -1
  2. package/dist/client/assets/{ArrowLeft-hhVT4Kgt.js → ArrowLeft-NyGN8FtU.js} +1 -1
  3. package/dist/client/assets/{ArrowUp-07dwm1MA.js → ArrowUp-Cfl4EAcS.js} +1 -1
  4. package/dist/client/assets/{Check-n_KiNdp_.js → Check-DmxydjBL.js} +1 -1
  5. package/dist/client/assets/{ChevronDown-BDe2LrLc.js → ChevronDown-C6ZdTyfO.js} +1 -1
  6. package/dist/client/assets/{Code01-DPGq6TT6.js → Code01-CtKfiTDD.js} +1 -1
  7. package/dist/client/assets/{Copy01-dSgWMnr9.js → Copy01-BMcgKhFM.js} +1 -1
  8. package/dist/client/assets/{CpuChip02-D4-bIMj_.js → CpuChip02-CJ6MB_gs.js} +1 -1
  9. package/dist/client/assets/{DotsHorizontal-C5FFxgpO.js → DotsHorizontal-BUtSXkqI.js} +1 -1
  10. package/dist/client/assets/{DotsVertical-_ZO_fNF7.js → DotsVertical-Dz9n-5F-.js} +1 -1
  11. package/dist/client/assets/{Download01-H-0ecpIj.js → Download01-xZY3OR1j.js} +1 -1
  12. package/dist/client/assets/{Edit01-nGCAvXPD.js → Edit01-BT4G_YIy.js} +1 -1
  13. package/dist/client/assets/{File06-CbLEGD6l.js → File06-uEDwGa2p.js} +1 -1
  14. package/dist/client/assets/{FilterLines-CRZrobVY.js → FilterLines-CAbmAqd-.js} +1 -1
  15. package/dist/client/assets/{FlipBackward-DEk7agK1.js → FlipBackward-CGc38rD2.js} +1 -1
  16. package/dist/client/assets/{GitBranch01-8cUKFct3.js → GitBranch01-Ca-8ywjS.js} +1 -1
  17. package/dist/client/assets/{Grid01-D_y10H_F.js → Grid01-D-48LkYB.js} +1 -1
  18. package/dist/client/assets/{Home02-CcZBoBXH.js → Home02-D4_hiRAj.js} +1 -1
  19. package/dist/client/assets/{Image01-DAeUMBHm.js → Image01-9m5NEF--.js} +1 -1
  20. package/dist/client/assets/{Inbox01-DYU61nmV.js → Inbox01-C3nQFXch.js} +1 -1
  21. package/dist/client/assets/{InfoCircle-B5w8XDv3.js → InfoCircle-nF74NMP8.js} +1 -1
  22. package/dist/client/assets/{Key01-BMvQCi5l.js → Key01-xCvKojzf.js} +1 -1
  23. package/dist/client/assets/{LinkExternal01-Bi1B9G37.js → LinkExternal01-DyfF0hfT.js} +1 -1
  24. package/dist/client/assets/{List-AGMu6Jg9.js → List-CbDyi-_I.js} +1 -1
  25. package/dist/client/assets/{Loading01-mNUVI85L.js → Loading01-CN4PjLYm.js} +1 -1
  26. package/dist/client/assets/{Lock01-B3WHG0KG.js → Lock01-WemfJe2M.js} +1 -1
  27. package/dist/client/assets/{Play-Cf7Any1j.js → Play-_NYO0aZO.js} +1 -1
  28. package/dist/client/assets/{Plus-BBofXpHO.js → Plus-D1XC-LWM.js} +1 -1
  29. package/dist/client/assets/{SearchMd-BCAxnQkD.js → SearchMd-BgsYwh_0.js} +1 -1
  30. package/dist/client/assets/{Terminal-rmcOb2qR.js → Terminal-DNQvnGyj.js} +1 -1
  31. package/dist/client/assets/{Trash01-r91jWYrx.js → Trash01-XWQVxRUg.js} +1 -1
  32. package/dist/client/assets/{Upload01-CHkKcKN6.js → Upload01-Bx3FQ-WR.js} +1 -1
  33. package/dist/client/assets/{X-C-LXD8Fs.js → X-BHMn15uu.js} +1 -1
  34. package/dist/client/assets/{XClose-Cuyiwbqc.js → XClose-DrrGYZAf.js} +1 -1
  35. package/dist/client/assets/agent-detail-BSaqEYBm.js +1 -0
  36. package/dist/client/assets/{agents-fnv41ET7.js → agents-Cax61kmw.js} +1 -1
  37. package/dist/client/assets/{alert-dialog-b2qaVWQf.js → alert-dialog-BXDbbD3T.js} +1 -1
  38. package/dist/client/assets/{auth-catchall-CT8C3FiC.js → auth-catchall-BzJ9XgEE.js} +1 -1
  39. package/dist/client/assets/{avatar-CJ18d1Yr.js → avatar-DszQRzwK.js} +1 -1
  40. package/dist/client/assets/{badge-BLC7Dsve.js → badge-ZMieXKPf.js} +1 -1
  41. package/dist/client/assets/{binder-BG1MkJXb.js → binder-sRiH1ogE.js} +1 -1
  42. package/dist/client/assets/{button-CWaK1hUN.js → button-Bu5b3WTW.js} +1 -1
  43. package/dist/client/assets/{card-7SgaoQef.js → card-huVl9i-i.js} +1 -1
  44. package/dist/client/assets/{checkbox-BWBpAWkB.js → checkbox-DLuP_uee.js} +1 -1
  45. package/dist/client/assets/{collection-detail-DUhOfUr0.js → collection-detail-Bq6ZFqnT.js} +2 -2
  46. package/dist/client/assets/{collection-display-button-DKWP6xRi.js → collection-display-button-Cb5uS-rc.js} +1 -1
  47. package/dist/client/assets/{collection-header-I0z7H0ZC.js → collection-header-CemM_w2D.js} +1 -1
  48. package/dist/client/assets/{collection-page-EuoaVB95.js → collection-page-VnMc_pGz.js} +1 -1
  49. package/dist/client/assets/{collection-search-CP09UmnI.js → collection-search-BVQF86eY.js} +1 -1
  50. package/dist/client/assets/{collection-tab-Cyh1pe9u.js → collection-tab-ClpFqQOx.js} +1 -1
  51. package/dist/client/assets/{collection-table-wrapper--qQDqi3a.js → collection-table-wrapper-HRrsYLN0.js} +1 -1
  52. package/dist/client/assets/{connection-card-dyAZPnBc.js → connection-card-DiYaoNe1.js} +1 -1
  53. package/dist/client/assets/connection-detail-c39fzg2m.js +1 -0
  54. package/dist/client/assets/{connections-DBGBr_4l.js → connections-CixvFZTx.js} +1 -1
  55. package/dist/client/assets/{constants-D7TSocv6.js → constants-C9jqRuDQ.js} +1 -1
  56. package/dist/client/assets/constants-Gfu8WPug.js +1 -0
  57. package/dist/client/assets/{create-organization-dialog-DrmGwR9J.js → create-organization-dialog-CeY4ItWb.js} +1 -1
  58. package/dist/client/assets/{dialog-CkzeDWMv.js → dialog-CZLL2sHo.js} +1 -1
  59. package/dist/client/assets/{dropdown-menu-eADXqdeC.js → dropdown-menu-BI7MuzMw.js} +1 -1
  60. package/dist/client/assets/{dynamic-plugin-layout-ObC7Ud51.js → dynamic-plugin-layout-D1oi470P.js} +1 -1
  61. package/dist/client/assets/{empty-state-zP-KbGlv.js → empty-state-BQfx1mwp.js} +1 -1
  62. package/dist/client/assets/{empty-state-CfCSwnz1.js → empty-state-CgeXBI1W.js} +1 -1
  63. package/dist/client/assets/{env-vars-editor-BI1TwkmM.js → env-vars-editor-4EC6mCOl.js} +1 -1
  64. package/dist/client/assets/{error-boundary-CG0YZ4B8.js → error-boundary-BaL_ffEC.js} +1 -1
  65. package/dist/client/assets/{extract-connection-data-DjJgYZHM.js → extract-connection-data-DHRsnn5P.js} +1 -1
  66. package/dist/client/assets/{file-browser-FetvDlId.js → file-browser-_UBJPTIe.js} +2 -2
  67. package/dist/client/assets/{form-BJcgMy55.js → form-CoBL4_XN.js} +1 -1
  68. package/dist/client/assets/{grid-view-DAtPq1rk.js → grid-view-D2Vn-CMC.js} +1 -1
  69. package/dist/client/assets/{home-563KzJx_.js → home-D2LI09X7.js} +1 -1
  70. package/dist/client/assets/{index-BipFUdjC.js → index-B84yJOSG.js} +2 -2
  71. package/dist/client/assets/{index-CJvrv3U6.js → index-BMTlZmWp.js} +1 -1
  72. package/dist/client/assets/{index--CSmLs4y.js → index-CbebK-uV.js} +1 -1
  73. package/dist/client/assets/{index-q_aACm4R.js → index-DJl8OcA5.js} +1 -1
  74. package/dist/client/assets/{index-BMtR19Aw.js → index-DtkdBBYP.js} +67 -68
  75. package/dist/client/assets/{index-D8uhOq5u.js → index-xK97rkRU.js} +1 -1
  76. package/dist/client/assets/{infiniteQueryObserver-FEDpWaxK.js → infiniteQueryObserver-BPcOZkH7.js} +1 -1
  77. package/dist/client/assets/{input-CJlzp_V5.js → input-CHbrtiSE.js} +1 -1
  78. package/dist/client/assets/{layout-BHCzoCFv.js → layout-BZs9w_M3.js} +1 -1
  79. package/dist/client/assets/localstorage-keys-Dzdim8m6.js +1 -0
  80. package/dist/client/assets/{login-DdZmNh4a.js → login-L-IHcABm.js} +1 -1
  81. package/dist/client/assets/{mcp-oauth-Da5yE9aW.js → mcp-oauth-BxZXA3Xr.js} +1 -1
  82. package/dist/client/assets/{mcp-server-card-CYYL-dXF.js → mcp-server-card-MC8v04QK.js} +1 -1
  83. package/dist/client/assets/{mcp-server-detail-C2G-xpe0.js → mcp-server-detail-zNAPbUAw.js} +2 -2
  84. package/dist/client/assets/{members-FKAvc6la.js → members-DJdUGw0D.js} +1 -1
  85. package/dist/client/assets/{monaco-editor-DkDnm6Tx.js → monaco-editor-C3ascXjJ.js} +1 -1
  86. package/dist/client/assets/{monitoring-6KAEGPPJ.js → monitoring-JAuBbZfp.js} +1 -1
  87. package/dist/client/assets/{oauth-callback-IuYTWMST.js → oauth-callback-BcGogxXg.js} +1 -1
  88. package/dist/client/assets/page-BxPZxw8o.js +21 -0
  89. package/dist/client/assets/{page-C36S8a5W.js → page-CUrPd-rM.js} +1 -1
  90. package/dist/client/assets/{pin-to-sidebar-button-WVVRk2lw.js → pin-to-sidebar-button-DSKZ2Fdq.js} +1 -1
  91. package/dist/client/assets/{plugin-empty-state-ByA0OkEn.js → plugin-empty-state-Cuv_BgUO.js} +1 -1
  92. package/dist/client/assets/{plugin-header-D5yHZtXf.js → plugin-header-DPgrCf4u.js} +1 -1
  93. package/dist/client/assets/{plugins-OwUnN1ka.js → plugins-CJ0UbjgM.js} +1 -1
  94. package/dist/client/assets/{popover-CshCl6w-.js → popover-BxnPal23.js} +1 -1
  95. package/dist/client/assets/{registry-utils-D7Dqr6wv.js → registry-utils-aIrZuCgt.js} +1 -1
  96. package/dist/client/assets/{resizable-B1zLCIJb.js → resizable-CaoQeLjg.js} +1 -1
  97. package/dist/client/assets/{resource-tabs-CRbf__IW.js → resource-tabs-CPGMnxBP.js} +1 -1
  98. package/dist/client/assets/{select-4bCSDmWU.js → select-B908g1mB.js} +1 -1
  99. package/dist/client/assets/{settings-CR5PvLr2.js → settings-LRlnP2Lc.js} +1 -1
  100. package/dist/client/assets/shell-layout-DRozOWy1.js +3 -0
  101. package/dist/client/assets/{spinner-BipWRp7l.js → spinner-CsK38Tsy.js} +1 -1
  102. package/dist/client/assets/{switch-C_F_zeuN.js → switch-CUTLvBMT.js} +1 -1
  103. package/dist/client/assets/{textarea-BZmzcANs.js → textarea-CbUKoeLq.js} +1 -1
  104. package/dist/client/assets/{tool-set-selector-DMyguAVM.js → tool-set-selector-fEQOYxCL.js} +1 -1
  105. package/dist/client/assets/{tools-list-CM9pIRwn.js → tools-list-CX7oXeq_.js} +1 -1
  106. package/dist/client/assets/{tooltip-D3Kw0HUb.js → tooltip-Dk0Jzfvj.js} +1 -1
  107. package/dist/client/assets/{typewriter-title-zajICLfm.js → typewriter-title-DPdfdL2f.js} +1 -1
  108. package/dist/client/assets/{use-binding-Ba3v4zMi.js → use-binding-D-hqNLrQ.js} +1 -1
  109. package/dist/client/assets/{use-collections-BQHGs5iU.js → use-collections-A_XW_jU_.js} +1 -1
  110. package/dist/client/assets/{use-connection-D03dTvtG.js → use-connection-BIIOhc_X.js} +1 -1
  111. package/dist/client/assets/{use-create-virtual-mcp-Cpzz-1zf.js → use-create-virtual-mcp-DWkiDqVu.js} +1 -1
  112. package/dist/client/assets/{use-list-state-B0KtA_q9.js → use-list-state-C8RoL1ci.js} +1 -1
  113. package/dist/client/assets/{use-members-CHh5MLEe.js → use-members-C93PMRIh.js} +1 -1
  114. package/dist/client/assets/{use-mobile-Q27OeJ4I.js → use-mobile-DIF2qUK5.js} +1 -1
  115. package/dist/client/assets/{use-organization-settings-CRV4VKdj.js → use-organization-settings-BGsA2C0p.js} +1 -1
  116. package/dist/client/assets/{use-virtual-mcp-CJ7FNu85.js → use-virtual-mcp-ygO0Mzk-.js} +1 -1
  117. package/dist/client/assets/useInfiniteQuery-BHxWaPEq.js +1 -0
  118. package/dist/client/assets/{useMutation-BJoWTtTW.js → useMutation-BW_aGPem.js} +1 -1
  119. package/dist/client/assets/useQuery-CgyESPOI.js +1 -0
  120. package/dist/client/assets/{value-C0VGfi9E.js → value-BL9_bCwS.js} +1 -1
  121. package/dist/client/assets/{view-mode-toggle-BkNnvYv5.js → view-mode-toggle-ByWv0ljG.js} +1 -1
  122. package/dist/client/assets/{virtual-mcp-BBuKM0Zd.js → virtual-mcp-vOZXwxjs.js} +1 -1
  123. package/dist/client/assets/{workflow-CxGNxRFo.js → workflow-CpI2biho.js} +1 -1
  124. package/dist/client/index.html +1 -1
  125. package/dist/server/cli.js +153 -119
  126. package/dist/server/migrate.js +2 -2
  127. package/dist/server/server.js +118 -84
  128. package/package.json +1 -1
  129. package/dist/client/assets/agent-detail-Cgt9QWk4.js +0 -1
  130. package/dist/client/assets/connection-detail-BmS-s06n.js +0 -1
  131. package/dist/client/assets/constants-DSSgefWZ.js +0 -1
  132. package/dist/client/assets/localstorage-keys-CqdQQHDa.js +0 -1
  133. package/dist/client/assets/page-C9G8C61g.js +0 -21
  134. package/dist/client/assets/shell-layout-FpAzDkjt.js +0 -3
  135. package/dist/client/assets/use-virtual-mcp-system-prompt-BfXjv37Y.js +0 -1
  136. package/dist/client/assets/useInfiniteQuery-shmHdaex.js +0 -1
  137. package/dist/client/assets/useQuery-CcFgJIAV.js +0 -1
@@ -381,7 +381,7 @@ ${G}
381
381
  `;break;case"id":K=O.includes("\x00")?void 0:O;break;case"retry":/^\d+$/.test(O)?J(parseInt(O,10)):Q(new e00(`Invalid \`retry\` value: "${O}"`,{type:"invalid-retry",value:O,line:w}));break;default:Q(new e00(`Unknown field "${N.length>20?`${N.slice(0,20)}\u2026`:N}"`,{type:"unknown-field",field:N,value:O,line:w}));break}}function z(){$.length>0&&Y({id:K,event:H||void 0,data:$.endsWith(`
382
382
  `)?$.slice(0,-1):$}),K=void 0,$="",H=""}function D(N={}){Z&&N.consume&&V(Z),W=!0,K=void 0,$="",H="",Z=""}return{feed:F,reset:D}}function YA6(X){let Y=[],Q="",J=0;for(;J<X.length;){let G=X.indexOf("\r",J),Z=X.indexOf(`
383
383
  `,J),W=-1;if(G!==-1&&Z!==-1?W=Math.min(G,Z):G!==-1?G===X.length-1?W=-1:W=G:Z!==-1&&(W=Z),W===-1){Q=X.slice(J);break}else{let K=X.slice(J,W);Y.push(K),J=W+1,X[J-1]==="\r"&&X[J]===`
384
- `&&J++}}return[Y,Q]}var e00;var X40=g(()=>{e00=class e00 extends Error{constructor(X,Y){super(X),this.name="ParseError",this.type=Y.type,this.field=Y.field,this.value=Y.value,this.line=Y.line}}});var Y40;var s64=g(()=>{X40();Y40=class Y40 extends TransformStream{constructor({onError:X,onRetry:Y,onComment:Q}={}){let J;super({start(G){J=_k({onEvent:(Z)=>{G.enqueue(Z)},onError(Z){X==="terminate"?G.error(Z):typeof X=="function"&&X(Z)},onRetry:Y,onComment:Q})},transform(G){J.feed(G)}})}}});class qU{constructor(X,Y){this._hasCompletedAuthFlow=!1,this._url=X,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=Y?.requestInit,this._authProvider=Y?.authProvider,this._fetch=Y?.fetch,this._fetchWithInit=wk(Y?.fetch,Y?.requestInit),this._sessionId=Y?.sessionId,this._reconnectionOptions=Y?.reconnectionOptions??QA6}async _authThenStart(){if(!this._authProvider)throw new yY("No auth provider");let X;try{X=await XW(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(Y){throw this.onerror?.(Y),Y}if(X!=="AUTHORIZED")throw new yY;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let X={};if(this._authProvider){let Q=await this._authProvider.tokens();if(Q)X.Authorization=`Bearer ${Q.access_token}`}if(this._sessionId)X["mcp-session-id"]=this._sessionId;if(this._protocolVersion)X["mcp-protocol-version"]=this._protocolVersion;let Y=ZU(this._requestInit?.headers);return new Headers({...X,...Y})}async _startOrAuthSse(X){let{resumptionToken:Y}=X;try{let Q=await this._commonHeaders();if(Q.set("Accept","text/event-stream"),Y)Q.set("last-event-id",Y);let J=await(this._fetch??fetch)(this._url,{method:"GET",headers:Q,signal:this._abortController?.signal});if(!J.ok){if(await J.body?.cancel(),J.status===401&&this._authProvider)return await this._authThenStart();if(J.status===405)return;throw new o3(J.status,`Failed to open SSE stream: ${J.statusText}`)}this._handleSseStream(J.body,X,!0)}catch(Q){throw this.onerror?.(Q),Q}}_getNextReconnectionDelay(X){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let Y=this._reconnectionOptions.initialReconnectionDelay,Q=this._reconnectionOptions.reconnectionDelayGrowFactor,J=this._reconnectionOptions.maxReconnectionDelay;return Math.min(Y*Math.pow(Q,X),J)}_scheduleReconnection(X,Y=0){let Q=this._reconnectionOptions.maxRetries;if(Y>=Q){this.onerror?.(Error(`Maximum reconnection attempts (${Q}) exceeded.`));return}let J=this._getNextReconnectionDelay(Y);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(X).catch((G)=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${G instanceof Error?G.message:String(G)}`)),this._scheduleReconnection(X,Y+1)})},J)}_handleSseStream(X,Y,Q){if(!X)return;let{onresumptiontoken:J,replayMessageId:G}=Y,Z,W=!1,K=!1;(async()=>{try{let H=X.pipeThrough(new TextDecoderStream).pipeThrough(new Y40({onRetry:(q)=>{this._serverRetryMs=q}})).getReader();while(!0){let{value:q,done:z}=await H.read();if(z)break;if(q.id)Z=q.id,W=!0,J?.(q.id);if(!q.data)continue;if(!q.event||q.event==="message")try{let D=UQ.parse(JSON.parse(q.data));if(eJ(D)){if(K=!0,G!==void 0)D.id=G}this.onmessage?.(D)}catch(D){this.onerror?.(D)}}if((Q||W)&&!K&&this._abortController&&!this._abortController.signal.aborted)this._scheduleReconnection({resumptionToken:Z,onresumptiontoken:J,replayMessageId:G},0)}catch(H){if(this.onerror?.(Error(`SSE stream disconnected: ${H}`)),(Q||W)&&!K&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:Z,onresumptiontoken:J,replayMessageId:G},0)}catch(q){this.onerror?.(Error(`Failed to reconnect: ${q instanceof Error?q.message:String(q)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(X){if(!this._authProvider)throw new yY("No auth provider");if(await XW(this._authProvider,{serverUrl:this._url,authorizationCode:X,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new yY("Failed to authorize")}async close(){if(this._reconnectionTimeout)clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0;this._abortController?.abort(),this.onclose?.()}async send(X,Y){try{let{resumptionToken:Q,onresumptiontoken:J}=Y||{};if(Q){this._startOrAuthSse({resumptionToken:Q,replayMessageId:IG(X)?X.id:void 0}).catch((V)=>this.onerror?.(V));return}let G=await this._commonHeaders();G.set("content-type","application/json"),G.set("accept","application/json, text/event-stream");let Z={...this._requestInit,method:"POST",headers:G,body:JSON.stringify(X),signal:this._abortController?.signal},W=await(this._fetch??fetch)(this._url,Z),K=W.headers.get("mcp-session-id");if(K)this._sessionId=K;if(!W.ok){let V=await W.text().catch(()=>null);if(W.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new o3(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:q,scope:z}=VU(W);if(this._resourceMetadataUrl=q,this._scope=z,await XW(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new yY;return this._hasCompletedAuthFlow=!0,this.send(X)}if(W.status===403&&this._authProvider){let{resourceMetadataUrl:q,scope:z,error:D}=VU(W);if(D==="insufficient_scope"){let N=W.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===N)throw new o3(403,"Server returned 403 after trying upscoping");if(z)this._scope=z;if(q)this._resourceMetadataUrl=q;if(this._lastUpscopingHeader=N??void 0,await XW(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new yY;return this.send(X)}}throw new o3(W.status,`Error POSTing to endpoint: ${V}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,W.status===202){if(await W.body?.cancel(),qs0(X))this._startOrAuthSse({resumptionToken:void 0}).catch((V)=>this.onerror?.(V));return}let H=(Array.isArray(X)?X:[X]).filter((V)=>("method"in V)&&("id"in V)&&V.id!==void 0).length>0,F=W.headers.get("content-type");if(H)if(F?.includes("text/event-stream"))this._handleSseStream(W.body,{onresumptiontoken:J},!1);else if(F?.includes("application/json")){let V=await W.json(),q=Array.isArray(V)?V.map((z)=>UQ.parse(z)):[UQ.parse(V)];for(let z of q)this.onmessage?.(z)}else throw await W.body?.cancel(),new o3(-1,`Unexpected content type: ${F}`);else await W.body?.cancel()}catch(Q){throw this.onerror?.(Q),Q}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let X=await this._commonHeaders(),Y={...this._requestInit,method:"DELETE",headers:X,signal:this._abortController?.signal},Q=await(this._fetch??fetch)(this._url,Y);if(await Q.body?.cancel(),!Q.ok&&Q.status!==405)throw new o3(Q.status,`Failed to terminate session: ${Q.statusText}`);this._sessionId=void 0}catch(X){throw this.onerror?.(X),X}}setProtocolVersion(X){this._protocolVersion=X}get protocolVersion(){return this._protocolVersion}async resumeStream(X,Y){await this._startOrAuthSse({resumptionToken:X,onresumptiontoken:Y?.onresumptiontoken})}}var QA6,o3;var yk=g(()=>{zQ();s00();s64();QA6={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2};o3=class o3 extends Error{constructor(X,Y){super(`Streamable HTTP error: ${Y}`);this.code=X}}});var Q40=g(()=>{yk()});var fk=g(()=>{Lk();x3();Q40()});function J40(X){return{id:s3.REGISTRY(X),title:"Deco Store",description:"Official deco MCP registry with curated integrations",connection_type:"HTTP",connection_url:"https://api.decocms.com/mcp/registry",icon:"https://assets.decocache.com/decocms/00ccf6c3-9e13-4517-83b0-75ab84554bb9/596364c63320075ca58483660156b6d9de9b526e.png",app_name:"deco-registry",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"registry"}}}function G40(){return{id:"community-registry",title:"MCP Registry",description:"Community MCP registry with thousands of handy MCPs",connection_type:"HTTP",connection_url:"https://sites-registry.decocache.com/mcp",icon:"https://assets.decocache.com/decocms/cd7ca472-0f72-463a-b0de-6e44bdd0f9b4/mcp.png",app_name:"mcp-registry",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"registry"}}}function W40(X,Y){return{id:s3.SELF(Y),title:"Mesh MCP",description:"The MCP for the mesh API",connection_type:"HTTP",connection_url:`${X}/mcp/self`,icon:"https://assets.decocache.com/mcp/09e44283-f47d-4046-955f-816d227c626f/app.png",app_name:"@deco/management-mcp",connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"self"}}}var s3;var bk=g(()=>{s3={SELF:(X)=>`${X}_self`,REGISTRY:(X)=>`${X}_registry`,COMMUNITY_REGISTRY:(X)=>`${X}_community-registry`}});var t64=g(()=>{Dt();uS();fk();bk()});var e64=g(()=>{x3()});var X14=g(()=>{x3()});var Y14=g(()=>{Ot();uS();fk();bk()});var Q14=g(()=>{uS();t64();fk();Mt();e64();X14();Y14()});var EA6,jA6,IA6,CA6,hk,J14,G14;var W14=g(()=>{o0();EA6=L.object({authorizationEndpoint:L.string().url(),tokenEndpoint:L.string().url(),introspectionEndpoint:L.string().url().optional(),clientId:L.string(),clientSecret:L.string().optional(),scopes:L.array(L.string()),grantType:L.enum(["authorization_code","client_credentials"])}),jA6=L.object({name:L.string(),description:L.string().optional(),inputSchema:L.record(L.string(),L.unknown()),outputSchema:L.record(L.string(),L.unknown()).optional()}),IA6=L.object({headers:L.record(L.string(),L.string()).optional()}),CA6=L.object({command:L.string().describe("Command to run (e.g., 'npx', 'node')"),args:L.array(L.string()).optional().describe("Command arguments"),cwd:L.string().optional().describe("Working directory"),envVars:L.record(L.string(),L.string()).optional().describe("Environment variables (encrypted in storage)")}),hk=L.object({id:L.string().describe("Unique identifier for the connection"),title:L.string().describe("Human-readable name for the connection"),created_at:L.string().describe("When the connection was created"),updated_at:L.string().describe("When the connection was last updated"),created_by:L.string().describe("User ID who created the connection"),updated_by:L.string().optional().describe("User ID who last updated the connection"),organization_id:L.string().describe("Organization ID this connection belongs to"),description:L.string().nullable().describe("Description of the connection"),icon:L.string().nullable().describe("Icon URL for the connection"),app_name:L.string().nullable().describe("Associated app name"),app_id:L.string().nullable().describe("Associated app ID"),connection_type:L.enum(["HTTP","SSE","Websocket","STDIO","VIRTUAL"]).describe("Type of connection"),connection_url:L.string().nullable().describe("URL for HTTP/SSE/WebSocket connections. virtual://$id for VIRTUAL. Null for STDIO."),connection_token:L.string().nullable().describe("Authentication token (for HTTP connections)"),connection_headers:L.union([CA6,IA6]).nullable().describe("Connection parameters. HTTP: { headers }. STDIO: { command, args, cwd, envVars }"),oauth_config:EA6.nullable().describe("OAuth configuration"),configuration_state:L.record(L.string(),L.unknown()).nullable().describe("Configuration state (decrypted)"),configuration_scopes:L.array(L.string()).nullable().optional().describe("Configuration scopes"),metadata:L.record(L.string(),L.unknown()).nullable().describe("Additional metadata (includes repository info)"),tools:L.array(jA6).nullable().describe("Discovered tools from MCP"),bindings:L.array(L.string()).nullable().describe("Detected bindings"),status:L.enum(["active","inactive","error"]).describe("Current status")}),J14=hk.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_url:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}),G14=hk.partial()});var F40,RA6,Z14,K14,$14;var H14=g(()=>{o0();F40=L.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),RA6=L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:L.array(L.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:L.array(L.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),Z14=L.object({id:L.string().describe("Unique identifier for the virtual MCP"),title:L.string().describe("Human-readable name for the virtual MCP"),description:L.string().nullable().describe("Description of the virtual MCP"),icon:L.string().nullable().optional().describe("Icon URL for the virtual MCP"),created_at:L.string().describe("When the virtual MCP was created"),updated_at:L.string().describe("When the virtual MCP was last updated"),created_by:L.string().describe("User ID who created the virtual MCP"),updated_by:L.string().optional().describe("User ID who last updated the virtual MCP"),organization_id:L.string().describe("Organization ID this virtual MCP belongs to"),tool_selection_mode:F40.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:L.enum(["active","inactive"]).describe("Current status"),connections:L.array(RA6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),K14=L.object({title:L.string().min(1).max(255).describe("Name for the virtual MCP"),description:L.string().nullable().optional().describe("Optional description"),tool_selection_mode:F40.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:L.string().nullable().optional().describe("Optional icon URL"),status:L.enum(["active","inactive"]).optional().default("active").describe("Initial status"),connections:L.array(L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:L.array(L.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:L.array(L.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).describe("Connections to include/exclude (can be empty for exclusion mode)")}),$14=L.object({title:L.string().min(1).max(255).optional().describe("New name"),description:L.string().nullable().optional().describe("New description (null to clear)"),tool_selection_mode:F40.optional().describe("New tool selection mode"),icon:L.string().nullable().optional().describe("New icon URL (null to clear)"),status:L.enum(["active","inactive"]).optional().describe("New status"),connections:L.array(L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:L.array(L.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:L.array(L.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var F14=g(()=>{W14();H14()});var V40=g(()=>{Ot();Q14();F14();Q40();x3();bk()});function Mw(X){return X!==null&&X!==void 0&&"command"in X}function xk(X){if(!X||!X.startsWith("virtual://"))return null;return X.replace("virtual://","")}function gk(X){return`virtual://${X}`}var fA6,bA6,hA6,xA6,gA6,NJ,B14,D14;var ZK=g(()=>{o0();fA6=L.object({authorizationEndpoint:L.string().url(),tokenEndpoint:L.string().url(),introspectionEndpoint:L.string().url().optional(),clientId:L.string(),clientSecret:L.string().optional(),scopes:L.array(L.string()),grantType:L.enum(["authorization_code","client_credentials"])}),bA6=L.object({title:L.string().optional(),readOnlyHint:L.boolean().optional(),destructiveHint:L.boolean().optional(),idempotentHint:L.boolean().optional(),openWorldHint:L.boolean().optional()}),hA6=L.object({name:L.string(),description:L.string().optional(),inputSchema:L.record(L.string(),L.unknown()),outputSchema:L.record(L.string(),L.unknown()).optional(),annotations:bA6.optional(),_meta:L.record(L.string(),L.unknown()).optional()}),xA6=L.object({headers:L.record(L.string(),L.string()).optional()}),gA6=L.object({command:L.string().describe("Command to run (e.g., 'npx', 'node')"),args:L.array(L.string()).optional().describe("Command arguments"),cwd:L.string().optional().describe("Working directory"),envVars:L.record(L.string(),L.string()).optional().describe("Environment variables (encrypted in storage)")}),NJ=L.object({id:L.string().describe("Unique identifier for the connection"),title:L.string().describe("Human-readable name for the connection"),created_at:L.string().describe("When the connection was created"),updated_at:L.string().describe("When the connection was last updated"),created_by:L.string().describe("User ID who created the connection"),updated_by:L.string().optional().describe("User ID who last updated the connection"),organization_id:L.string().describe("Organization ID this connection belongs to"),description:L.string().nullable().describe("Description of the connection"),icon:L.string().nullable().describe("Icon URL for the connection"),app_name:L.string().nullable().describe("Associated app name"),app_id:L.string().nullable().describe("Associated app ID"),connection_type:L.enum(["HTTP","SSE","Websocket","STDIO","VIRTUAL"]).describe("Type of connection"),connection_url:L.string().nullable().describe("URL for HTTP/SSE/WebSocket connections. virtual://$id for VIRTUAL. Null for STDIO."),connection_token:L.string().nullable().describe("Authentication token (for HTTP connections)"),connection_headers:L.union([gA6,xA6]).nullable().describe("Connection parameters. HTTP: { headers }. STDIO: { command, args, cwd, envVars }"),oauth_config:fA6.nullable().describe("OAuth configuration"),configuration_state:L.record(L.string(),L.unknown()).nullable().describe("Configuration state (decrypted)"),configuration_scopes:L.array(L.string()).nullable().optional().describe("Configuration scopes"),metadata:L.record(L.string(),L.unknown()).nullable().describe("Additional metadata (includes repository info)"),tools:L.array(hA6).nullable().describe("Discovered tools from MCP"),bindings:L.array(L.string()).nullable().describe("Detected bindings"),status:L.enum(["active","inactive","error"]).describe("Current status")}),B14=NJ.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_url:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}),D14=NJ.partial()});var N14="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as O14}from"crypto";function mA6(X){if(!t3||t3.length<X)t3=Buffer.allocUnsafe(X*uA6),O14.getRandomValues(t3),UU=0;else if(UU+X>t3.length)O14.getRandomValues(t3),UU=0;UU+=X}function L14(X=21){mA6(X|=0);let Y="";for(let Q=UU-X;Q<UU;Q++)Y+=N14[t3[Q]&63];return Y}var uA6=128,t3,UU;var w14=()=>{};function zU(X){return`${X}_${L14()}`}var uk=g(()=>{w14()});function dA6(X){let Y=globalThis.DOMException;return typeof Y=="function"?new Y(X,"SyntaxError"):SyntaxError(X)}function B40(X){return X instanceof Error?"errors"in X&&Array.isArray(X.errors)?X.errors.map(B40).join(", "):("cause"in X)&&X.cause instanceof Error?`${X}: ${B40(X.cause)}`:X.message:`${X}`}function M14(X){return{type:X.type,message:X.message,code:X.code,defaultPrevented:X.defaultPrevented,cancelable:X.cancelable,timeStamp:X.timeStamp}}function pA6(){let X="document"in globalThis?globalThis.document:void 0;return X&&typeof X=="object"&&"baseURI"in X&&typeof X.baseURI=="string"?X.baseURI:void 0}var z40,T14=(X)=>{throw TypeError(X)},T40=(X,Y,Q)=>Y.has(X)||T14("Cannot "+Q),P6=(X,Y,Q)=>(T40(X,Y,"read from private field"),Q?Q.call(X):Y.get(X)),Y9=(X,Y,Q)=>Y.has(X)?T14("Cannot add the same private member more than once"):Y instanceof WeakSet?Y.add(X):Y.set(X,Q),F8=(X,Y,Q,J)=>(T40(X,Y,"write to private field"),Y.set(X,Q),Q),YW=(X,Y,Q)=>(T40(X,Y,"access private method"),Q),fY,e3,BU,mk,lk,Aw,OU,Ew,KK,DU,LU,NU,Pw,$5,D40,N40,O40,P14,L40,w40,Tw,M40,P40,wU;var A14=g(()=>{X40();z40=class z40 extends Event{constructor(X,Y){var Q,J;super(X),this.code=(Q=Y==null?void 0:Y.code)!=null?Q:void 0,this.message=(J=Y==null?void 0:Y.message)!=null?J:void 0}[Symbol.for("nodejs.util.inspect.custom")](X,Y,Q){return Q(M14(this),Y)}[Symbol.for("Deno.customInspect")](X,Y){return X(M14(this),Y)}};wU=class wU extends EventTarget{constructor(X,Y){var Q,J;super(),Y9(this,$5),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Y9(this,fY),Y9(this,e3),Y9(this,BU),Y9(this,mk),Y9(this,lk),Y9(this,Aw),Y9(this,OU),Y9(this,Ew,null),Y9(this,KK),Y9(this,DU),Y9(this,LU,null),Y9(this,NU,null),Y9(this,Pw,null),Y9(this,N40,async(G)=>{var Z;P6(this,DU).reset();let{body:W,redirected:K,status:$,headers:H}=G;if($===204){YW(this,$5,Tw).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(K?F8(this,BU,new URL(G.url)):F8(this,BU,void 0),$!==200){YW(this,$5,Tw).call(this,`Non-200 status code (${$})`,$);return}if(!(H.get("content-type")||"").startsWith("text/event-stream")){YW(this,$5,Tw).call(this,'Invalid content type, expected "text/event-stream"',$);return}if(P6(this,fY)===this.CLOSED)return;F8(this,fY,this.OPEN);let F=new Event("open");if((Z=P6(this,Pw))==null||Z.call(this,F),this.dispatchEvent(F),typeof W!="object"||!W||!("getReader"in W)){YW(this,$5,Tw).call(this,"Invalid response body, expected a web ReadableStream",$),this.close();return}let V=new TextDecoder,q=W.getReader(),z=!0;do{let{done:D,value:N}=await q.read();N&&P6(this,DU).feed(V.decode(N,{stream:!D})),D&&(z=!1,P6(this,DU).reset(),YW(this,$5,M40).call(this))}while(z)}),Y9(this,O40,(G)=>{F8(this,KK,void 0),!(G.name==="AbortError"||G.type==="aborted")&&YW(this,$5,M40).call(this,B40(G))}),Y9(this,L40,(G)=>{typeof G.id=="string"&&F8(this,Ew,G.id);let Z=new MessageEvent(G.event||"message",{data:G.data,origin:P6(this,BU)?P6(this,BU).origin:P6(this,e3).origin,lastEventId:G.id||""});P6(this,NU)&&(!G.event||G.event==="message")&&P6(this,NU).call(this,Z),this.dispatchEvent(Z)}),Y9(this,w40,(G)=>{F8(this,Aw,G)}),Y9(this,P40,()=>{F8(this,OU,void 0),P6(this,fY)===this.CONNECTING&&YW(this,$5,D40).call(this)});try{if(X instanceof URL)F8(this,e3,X);else if(typeof X=="string")F8(this,e3,new URL(X,pA6()));else throw Error("Invalid URL")}catch{throw dA6("An invalid or illegal string was specified")}F8(this,DU,_k({onEvent:P6(this,L40),onRetry:P6(this,w40)})),F8(this,fY,this.CONNECTING),F8(this,Aw,3000),F8(this,lk,(Q=Y==null?void 0:Y.fetch)!=null?Q:globalThis.fetch),F8(this,mk,(J=Y==null?void 0:Y.withCredentials)!=null?J:!1),YW(this,$5,D40).call(this)}get readyState(){return P6(this,fY)}get url(){return P6(this,e3).href}get withCredentials(){return P6(this,mk)}get onerror(){return P6(this,LU)}set onerror(X){F8(this,LU,X)}get onmessage(){return P6(this,NU)}set onmessage(X){F8(this,NU,X)}get onopen(){return P6(this,Pw)}set onopen(X){F8(this,Pw,X)}addEventListener(X,Y,Q){let J=Y;super.addEventListener(X,J,Q)}removeEventListener(X,Y,Q){let J=Y;super.removeEventListener(X,J,Q)}close(){P6(this,OU)&&clearTimeout(P6(this,OU)),P6(this,fY)!==this.CLOSED&&(P6(this,KK)&&P6(this,KK).abort(),F8(this,fY,this.CLOSED),F8(this,KK,void 0))}};fY=new WeakMap,e3=new WeakMap,BU=new WeakMap,mk=new WeakMap,lk=new WeakMap,Aw=new WeakMap,OU=new WeakMap,Ew=new WeakMap,KK=new WeakMap,DU=new WeakMap,LU=new WeakMap,NU=new WeakMap,Pw=new WeakMap,$5=new WeakSet,D40=function(){F8(this,fY,this.CONNECTING),F8(this,KK,new AbortController),P6(this,lk)(P6(this,e3),YW(this,$5,P14).call(this)).then(P6(this,N40)).catch(P6(this,O40))},N40=new WeakMap,O40=new WeakMap,P14=function(){var X;let Y={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...P6(this,Ew)?{"Last-Event-ID":P6(this,Ew)}:void 0},cache:"no-store",signal:(X=P6(this,KK))==null?void 0:X.signal};return"window"in globalThis&&(Y.credentials=this.withCredentials?"include":"same-origin"),Y},L40=new WeakMap,w40=new WeakMap,Tw=function(X,Y){var Q;P6(this,fY)!==this.CLOSED&&F8(this,fY,this.CLOSED);let J=new z40("error",{code:Y,message:X});(Q=P6(this,LU))==null||Q.call(this,J),this.dispatchEvent(J)},M40=function(X,Y){var Q;if(P6(this,fY)===this.CLOSED)return;F8(this,fY,this.CONNECTING);let J=new z40("error",{code:Y,message:X});(Q=P6(this,LU))==null||Q.call(this,J),this.dispatchEvent(J),F8(this,OU,setTimeout(P6(this,P40),P6(this,Aw)))},P40=new WeakMap,wU.CONNECTING=0,wU.OPEN=1,wU.CLOSED=2});class jw{constructor(X,Y){this._url=X,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=Y?.eventSourceInit,this._requestInit=Y?.requestInit,this._authProvider=Y?.authProvider,this._fetch=Y?.fetch,this._fetchWithInit=wk(Y?.fetch,Y?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new yY("No auth provider");let X;try{X=await XW(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(Y){throw this.onerror?.(Y),Y}if(X!=="AUTHORIZED")throw new yY;return await this._startOrAuth()}async _commonHeaders(){let X={};if(this._authProvider){let Q=await this._authProvider.tokens();if(Q)X.Authorization=`Bearer ${Q.access_token}`}if(this._protocolVersion)X["mcp-protocol-version"]=this._protocolVersion;let Y=ZU(this._requestInit?.headers);return new Headers({...X,...Y})}_startOrAuth(){let X=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((Y,Q)=>{this._eventSource=new wU(this._url.href,{...this._eventSourceInit,fetch:async(J,G)=>{let Z=await this._commonHeaders();Z.set("Accept","text/event-stream");let W=await X(J,{...G,headers:Z});if(W.status===401&&W.headers.has("www-authenticate")){let{resourceMetadataUrl:K,scope:$}=VU(W);this._resourceMetadataUrl=K,this._scope=$}return W}}),this._abortController=new AbortController,this._eventSource.onerror=(J)=>{if(J.code===401&&this._authProvider){this._authThenStart().then(Y,Q);return}let G=new E14(J.code,J.message,J);Q(G),this.onerror?.(G)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",(J)=>{let G=J;try{if(this._endpoint=new URL(G.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(Z){Q(Z),this.onerror?.(Z),this.close();return}Y()}),this._eventSource.onmessage=(J)=>{let G=J,Z;try{Z=UQ.parse(JSON.parse(G.data))}catch(W){this.onerror?.(W);return}this.onmessage?.(Z)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(X){if(!this._authProvider)throw new yY("No auth provider");if(await XW(this._authProvider,{serverUrl:this._url,authorizationCode:X,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new yY("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(X){if(!this._endpoint)throw Error("Not connected");try{let Y=await this._commonHeaders();Y.set("content-type","application/json");let Q={...this._requestInit,method:"POST",headers:Y,body:JSON.stringify(X),signal:this._abortController?.signal},J=await(this._fetch??fetch)(this._endpoint,Q);if(!J.ok){let G=await J.text().catch(()=>null);if(J.status===401&&this._authProvider){let{resourceMetadataUrl:Z,scope:W}=VU(J);if(this._resourceMetadataUrl=Z,this._scope=W,await XW(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new yY;return this.send(X)}throw Error(`Error POSTing to endpoint (HTTP ${J.status}): ${G}`)}await J.body?.cancel()}catch(Y){throw this.onerror?.(Y),Y}}setProtocolVersion(X){this._protocolVersion=X}}var E14;var A40=g(()=>{A14();zQ();s00();E14=class E14 extends Error{constructor(X,Y,Q){super(`SSE error: ${Y}`);this.code=X,this.event=Q}}});var S14=j((qP1,R14)=>{R14.exports=C14;C14.sync=nA6;var j14=U0("fs");function cA6(X,Y){var Q=Y.pathExt!==void 0?Y.pathExt:process.env.PATHEXT;if(!Q)return!0;if(Q=Q.split(";"),Q.indexOf("")!==-1)return!0;for(var J=0;J<Q.length;J++){var G=Q[J].toLowerCase();if(G&&X.substr(-G.length).toLowerCase()===G)return!0}return!1}function I14(X,Y,Q){if(!X.isSymbolicLink()&&!X.isFile())return!1;return cA6(Y,Q)}function C14(X,Y,Q){j14.stat(X,function(J,G){Q(J,J?!1:I14(G,X,Y))})}function nA6(X,Y){return I14(j14.statSync(X),X,Y)}});var f14=j((UP1,y14)=>{y14.exports=k14;k14.sync=iA6;var v14=U0("fs");function k14(X,Y,Q){v14.stat(X,function(J,G){Q(J,J?!1:_14(G,Y))})}function iA6(X,Y){return _14(v14.statSync(X),Y)}function _14(X,Y){return X.isFile()&&aA6(X,Y)}function aA6(X,Y){var{mode:Q,uid:J,gid:G}=X,Z=Y.uid!==void 0?Y.uid:process.getuid&&process.getuid(),W=Y.gid!==void 0?Y.gid:process.getgid&&process.getgid(),K=parseInt("100",8),$=parseInt("010",8),H=parseInt("001",8),F=K|$,V=Q&H||Q&$&&G===W||Q&K&&J===Z||Q&F&&Z===0;return V}});var h14=j((BP1,b14)=>{var zP1=U0("fs"),dk;if(process.platform==="win32"||global.TESTING_WINDOWS)dk=S14();else dk=f14();b14.exports=E40;E40.sync=rA6;function E40(X,Y,Q){if(typeof Y==="function")Q=Y,Y={};if(!Q){if(typeof Promise!=="function")throw TypeError("callback not provided");return new Promise(function(J,G){E40(X,Y||{},function(Z,W){if(Z)G(Z);else J(W)})})}dk(X,Y||{},function(J,G){if(J){if(J.code==="EACCES"||Y&&Y.ignoreErrors)J=null,G=!1}Q(J,G)})}function rA6(X,Y){try{return dk.sync(X,Y||{})}catch(Q){if(Y&&Y.ignoreErrors||Q.code==="EACCES")return!1;else throw Q}}});var p14=j((DP1,d14)=>{var MU=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",x14=U0("path"),oA6=MU?";":":",g14=h14(),u14=(X)=>Object.assign(Error(`not found: ${X}`),{code:"ENOENT"}),m14=(X,Y)=>{let Q=Y.colon||oA6,J=X.match(/\//)||MU&&X.match(/\\/)?[""]:[...MU?[process.cwd()]:[],...(Y.path||process.env.PATH||"").split(Q)],G=MU?Y.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",Z=MU?G.split(Q):[""];if(MU){if(X.indexOf(".")!==-1&&Z[0]!=="")Z.unshift("")}return{pathEnv:J,pathExt:Z,pathExtExe:G}},l14=(X,Y,Q)=>{if(typeof Y==="function")Q=Y,Y={};if(!Y)Y={};let{pathEnv:J,pathExt:G,pathExtExe:Z}=m14(X,Y),W=[],K=(H)=>new Promise((F,V)=>{if(H===J.length)return Y.all&&W.length?F(W):V(u14(X));let q=J[H],z=/^".*"$/.test(q)?q.slice(1,-1):q,D=x14.join(z,X),N=!z&&/^\.[\\\/]/.test(X)?X.slice(0,2)+D:D;F($(N,H,0))}),$=(H,F,V)=>new Promise((q,z)=>{if(V===G.length)return q(K(F+1));let D=G[V];g14(H+D,{pathExt:Z},(N,O)=>{if(!N&&O)if(Y.all)W.push(H+D);else return q(H+D);return q($(H,F,V+1))})});return Q?K(0).then((H)=>Q(null,H),Q):K(0)},sA6=(X,Y)=>{Y=Y||{};let{pathEnv:Q,pathExt:J,pathExtExe:G}=m14(X,Y),Z=[];for(let W=0;W<Q.length;W++){let K=Q[W],$=/^".*"$/.test(K)?K.slice(1,-1):K,H=x14.join($,X),F=!$&&/^\.[\\\/]/.test(X)?X.slice(0,2)+H:H;for(let V=0;V<J.length;V++){let q=F+J[V];try{if(g14.sync(q,{pathExt:G}))if(Y.all)Z.push(q);else return q}catch(z){}}}if(Y.all&&Z.length)return Z;if(Y.nothrow)return null;throw u14(X)};d14.exports=l14;l14.sync=sA6});var n14=j((NP1,j40)=>{var c14=(X={})=>{let Y=X.env||process.env;if((X.platform||process.platform)!=="win32")return"PATH";return Object.keys(Y).reverse().find((J)=>J.toUpperCase()==="PATH")||"Path"};j40.exports=c14;j40.exports.default=c14});var o14=j((OP1,r14)=>{var i14=U0("path"),tA6=p14(),eA6=n14();function a14(X,Y){let Q=X.options.env||process.env,J=process.cwd(),G=X.options.cwd!=null,Z=G&&process.chdir!==void 0&&!process.chdir.disabled;if(Z)try{process.chdir(X.options.cwd)}catch(K){}let W;try{W=tA6.sync(X.command,{path:Q[eA6({env:Q})],pathExt:Y?i14.delimiter:void 0})}catch(K){}finally{if(Z)process.chdir(J)}if(W)W=i14.resolve(G?X.options.cwd:"",W);return W}function XE6(X){return a14(X)||a14(X,!0)}r14.exports=XE6});var s14=j((JE6,C40)=>{var I40=/([()\][%!^"`<>&|;, *?])/g;function YE6(X){return X=X.replace(I40,"^$1"),X}function QE6(X,Y){if(X=`${X}`,X=X.replace(/(?=(\\+?)?)\1"/g,"$1$1\\\""),X=X.replace(/(?=(\\+?)?)\1$/,"$1$1"),X=`"${X}"`,X=X.replace(I40,"^$1"),Y)X=X.replace(I40,"^$1");return X}JE6.command=YE6;JE6.argument=QE6});var e14=j((LP1,t14)=>{t14.exports=/^#!(.*)/});var Y84=j((wP1,X84)=>{var ZE6=e14();X84.exports=(X="")=>{let Y=X.match(ZE6);if(!Y)return null;let[Q,J]=Y[0].replace(/#! ?/,"").split(" "),G=Q.split("/").pop();if(G==="env")return J;return J?`${G} ${J}`:G}});var J84=j((MP1,Q84)=>{var R40=U0("fs"),KE6=Y84();function $E6(X){let Q=Buffer.alloc(150),J;try{J=R40.openSync(X,"r"),R40.readSync(J,Q,0,150,0),R40.closeSync(J)}catch(G){}return KE6(Q.toString())}Q84.exports=$E6});var K84=j((PP1,Z84)=>{var HE6=U0("path"),G84=o14(),W84=s14(),FE6=J84(),VE6=process.platform==="win32",qE6=/\.(?:com|exe)$/i,UE6=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function zE6(X){X.file=G84(X);let Y=X.file&&FE6(X.file);if(Y)return X.args.unshift(X.file),X.command=Y,G84(X);return X.file}function BE6(X){if(!VE6)return X;let Y=zE6(X),Q=!qE6.test(Y);if(X.options.forceShell||Q){let J=UE6.test(Y);X.command=HE6.normalize(X.command),X.command=W84.command(X.command),X.args=X.args.map((Z)=>W84.argument(Z,J));let G=[X.command].concat(X.args).join(" ");X.args=["/d","/s","/c",`"${G}"`],X.command=process.env.comspec||"cmd.exe",X.options.windowsVerbatimArguments=!0}return X}function DE6(X,Y,Q){if(Y&&!Array.isArray(Y))Q=Y,Y=null;Y=Y?Y.slice(0):[],Q=Object.assign({},Q);let J={command:X,args:Y,options:Q,file:void 0,original:{command:X,args:Y}};return Q.shell?J:BE6(J)}Z84.exports=DE6});var F84=j((TP1,H84)=>{var S40=process.platform==="win32";function v40(X,Y){return Object.assign(Error(`${Y} ${X.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${Y} ${X.command}`,path:X.command,spawnargs:X.args})}function NE6(X,Y){if(!S40)return;let Q=X.emit;X.emit=function(J,G){if(J==="exit"){let Z=$84(G,Y);if(Z)return Q.call(X,"error",Z)}return Q.apply(X,arguments)}}function $84(X,Y){if(S40&&X===1&&!Y.file)return v40(Y.original,"spawn");return null}function OE6(X,Y){if(S40&&X===1&&!Y.file)return v40(Y.original,"spawnSync");return null}H84.exports={hookChildProcess:NE6,verifyENOENT:$84,verifyENOENTSync:OE6,notFoundError:v40}});var U84=j((AP1,PU)=>{var V84=U0("child_process"),k40=K84(),_40=F84();function q84(X,Y,Q){let J=k40(X,Y,Q),G=V84.spawn(J.command,J.args,J.options);return _40.hookChildProcess(G,J),G}function LE6(X,Y,Q){let J=k40(X,Y,Q),G=V84.spawnSync(J.command,J.args,J.options);return G.error=G.error||_40.verifyENOENTSync(G.status,J),G}PU.exports=q84;PU.exports.spawn=q84;PU.exports.sync=LE6;PU.exports._parse=k40;PU.exports._enoent=_40});class y40{append(X){this._buffer=this._buffer?Buffer.concat([this._buffer,X]):X}readMessage(){if(!this._buffer)return null;let X=this._buffer.indexOf(`
384
+ `&&J++}}return[Y,Q]}var e00;var X40=g(()=>{e00=class e00 extends Error{constructor(X,Y){super(X),this.name="ParseError",this.type=Y.type,this.field=Y.field,this.value=Y.value,this.line=Y.line}}});var Y40;var s64=g(()=>{X40();Y40=class Y40 extends TransformStream{constructor({onError:X,onRetry:Y,onComment:Q}={}){let J;super({start(G){J=_k({onEvent:(Z)=>{G.enqueue(Z)},onError(Z){X==="terminate"?G.error(Z):typeof X=="function"&&X(Z)},onRetry:Y,onComment:Q})},transform(G){J.feed(G)}})}}});class qU{constructor(X,Y){this._hasCompletedAuthFlow=!1,this._url=X,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=Y?.requestInit,this._authProvider=Y?.authProvider,this._fetch=Y?.fetch,this._fetchWithInit=wk(Y?.fetch,Y?.requestInit),this._sessionId=Y?.sessionId,this._reconnectionOptions=Y?.reconnectionOptions??QA6}async _authThenStart(){if(!this._authProvider)throw new yY("No auth provider");let X;try{X=await XW(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(Y){throw this.onerror?.(Y),Y}if(X!=="AUTHORIZED")throw new yY;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let X={};if(this._authProvider){let Q=await this._authProvider.tokens();if(Q)X.Authorization=`Bearer ${Q.access_token}`}if(this._sessionId)X["mcp-session-id"]=this._sessionId;if(this._protocolVersion)X["mcp-protocol-version"]=this._protocolVersion;let Y=ZU(this._requestInit?.headers);return new Headers({...X,...Y})}async _startOrAuthSse(X){let{resumptionToken:Y}=X;try{let Q=await this._commonHeaders();if(Q.set("Accept","text/event-stream"),Y)Q.set("last-event-id",Y);let J=await(this._fetch??fetch)(this._url,{method:"GET",headers:Q,signal:this._abortController?.signal});if(!J.ok){if(await J.body?.cancel(),J.status===401&&this._authProvider)return await this._authThenStart();if(J.status===405)return;throw new o3(J.status,`Failed to open SSE stream: ${J.statusText}`)}this._handleSseStream(J.body,X,!0)}catch(Q){throw this.onerror?.(Q),Q}}_getNextReconnectionDelay(X){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let Y=this._reconnectionOptions.initialReconnectionDelay,Q=this._reconnectionOptions.reconnectionDelayGrowFactor,J=this._reconnectionOptions.maxReconnectionDelay;return Math.min(Y*Math.pow(Q,X),J)}_scheduleReconnection(X,Y=0){let Q=this._reconnectionOptions.maxRetries;if(Y>=Q){this.onerror?.(Error(`Maximum reconnection attempts (${Q}) exceeded.`));return}let J=this._getNextReconnectionDelay(Y);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(X).catch((G)=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${G instanceof Error?G.message:String(G)}`)),this._scheduleReconnection(X,Y+1)})},J)}_handleSseStream(X,Y,Q){if(!X)return;let{onresumptiontoken:J,replayMessageId:G}=Y,Z,W=!1,K=!1;(async()=>{try{let H=X.pipeThrough(new TextDecoderStream).pipeThrough(new Y40({onRetry:(q)=>{this._serverRetryMs=q}})).getReader();while(!0){let{value:q,done:z}=await H.read();if(z)break;if(q.id)Z=q.id,W=!0,J?.(q.id);if(!q.data)continue;if(!q.event||q.event==="message")try{let D=UQ.parse(JSON.parse(q.data));if(eJ(D)){if(K=!0,G!==void 0)D.id=G}this.onmessage?.(D)}catch(D){this.onerror?.(D)}}if((Q||W)&&!K&&this._abortController&&!this._abortController.signal.aborted)this._scheduleReconnection({resumptionToken:Z,onresumptiontoken:J,replayMessageId:G},0)}catch(H){if(this.onerror?.(Error(`SSE stream disconnected: ${H}`)),(Q||W)&&!K&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:Z,onresumptiontoken:J,replayMessageId:G},0)}catch(q){this.onerror?.(Error(`Failed to reconnect: ${q instanceof Error?q.message:String(q)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(X){if(!this._authProvider)throw new yY("No auth provider");if(await XW(this._authProvider,{serverUrl:this._url,authorizationCode:X,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new yY("Failed to authorize")}async close(){if(this._reconnectionTimeout)clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0;this._abortController?.abort(),this.onclose?.()}async send(X,Y){try{let{resumptionToken:Q,onresumptiontoken:J}=Y||{};if(Q){this._startOrAuthSse({resumptionToken:Q,replayMessageId:IG(X)?X.id:void 0}).catch((V)=>this.onerror?.(V));return}let G=await this._commonHeaders();G.set("content-type","application/json"),G.set("accept","application/json, text/event-stream");let Z={...this._requestInit,method:"POST",headers:G,body:JSON.stringify(X),signal:this._abortController?.signal},W=await(this._fetch??fetch)(this._url,Z),K=W.headers.get("mcp-session-id");if(K)this._sessionId=K;if(!W.ok){let V=await W.text().catch(()=>null);if(W.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new o3(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:q,scope:z}=VU(W);if(this._resourceMetadataUrl=q,this._scope=z,await XW(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new yY;return this._hasCompletedAuthFlow=!0,this.send(X)}if(W.status===403&&this._authProvider){let{resourceMetadataUrl:q,scope:z,error:D}=VU(W);if(D==="insufficient_scope"){let N=W.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===N)throw new o3(403,"Server returned 403 after trying upscoping");if(z)this._scope=z;if(q)this._resourceMetadataUrl=q;if(this._lastUpscopingHeader=N??void 0,await XW(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new yY;return this.send(X)}}throw new o3(W.status,`Error POSTing to endpoint: ${V}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,W.status===202){if(await W.body?.cancel(),qs0(X))this._startOrAuthSse({resumptionToken:void 0}).catch((V)=>this.onerror?.(V));return}let H=(Array.isArray(X)?X:[X]).filter((V)=>("method"in V)&&("id"in V)&&V.id!==void 0).length>0,F=W.headers.get("content-type");if(H)if(F?.includes("text/event-stream"))this._handleSseStream(W.body,{onresumptiontoken:J},!1);else if(F?.includes("application/json")){let V=await W.json(),q=Array.isArray(V)?V.map((z)=>UQ.parse(z)):[UQ.parse(V)];for(let z of q)this.onmessage?.(z)}else throw await W.body?.cancel(),new o3(-1,`Unexpected content type: ${F}`);else await W.body?.cancel()}catch(Q){throw this.onerror?.(Q),Q}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let X=await this._commonHeaders(),Y={...this._requestInit,method:"DELETE",headers:X,signal:this._abortController?.signal},Q=await(this._fetch??fetch)(this._url,Y);if(await Q.body?.cancel(),!Q.ok&&Q.status!==405)throw new o3(Q.status,`Failed to terminate session: ${Q.statusText}`);this._sessionId=void 0}catch(X){throw this.onerror?.(X),X}}setProtocolVersion(X){this._protocolVersion=X}get protocolVersion(){return this._protocolVersion}async resumeStream(X,Y){await this._startOrAuthSse({resumptionToken:X,onresumptiontoken:Y?.onresumptiontoken})}}var QA6,o3;var yk=g(()=>{zQ();s00();s64();QA6={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2};o3=class o3 extends Error{constructor(X,Y){super(`Streamable HTTP error: ${Y}`);this.code=X}}});var Q40=g(()=>{yk()});var fk=g(()=>{Lk();x3();Q40()});function J40(X){return{id:s3.REGISTRY(X),title:"Deco Store",description:"Official deco MCP registry with curated integrations",connection_type:"HTTP",connection_url:"https://api.decocms.com/mcp/registry",icon:"https://assets.decocache.com/decocms/00ccf6c3-9e13-4517-83b0-75ab84554bb9/596364c63320075ca58483660156b6d9de9b526e.png",app_name:"deco-registry",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"registry"}}}function G40(){return{id:"community-registry",title:"MCP Registry",description:"Community MCP registry with thousands of handy MCPs",connection_type:"HTTP",connection_url:"https://sites-registry.decocache.com/mcp",icon:"https://assets.decocache.com/decocms/cd7ca472-0f72-463a-b0de-6e44bdd0f9b4/mcp.png",app_name:"mcp-registry",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"registry"}}}function W40(X,Y){return{id:s3.SELF(Y),title:"Mesh MCP",description:"The MCP for the mesh API",connection_type:"HTTP",connection_url:`${X}/mcp/self`,icon:"https://assets.decocache.com/mcp/09e44283-f47d-4046-955f-816d227c626f/app.png",app_name:"@deco/management-mcp",connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"self"}}}var s3;var bk=g(()=>{s3={SELF:(X)=>`${X}_self`,REGISTRY:(X)=>`${X}_registry`,COMMUNITY_REGISTRY:(X)=>`${X}_community-registry`}});var t64=g(()=>{Dt();uS();fk();bk()});var e64=g(()=>{x3()});var X14=g(()=>{x3()});var Y14=g(()=>{Ot();uS();fk();bk()});var Q14=g(()=>{uS();t64();fk();Mt();e64();X14();Y14()});var EA6,jA6,IA6,CA6,hk,J14,G14;var W14=g(()=>{o0();EA6=L.object({authorizationEndpoint:L.string().url(),tokenEndpoint:L.string().url(),introspectionEndpoint:L.string().url().optional(),clientId:L.string(),clientSecret:L.string().optional(),scopes:L.array(L.string()),grantType:L.enum(["authorization_code","client_credentials"])}),jA6=L.object({name:L.string(),description:L.string().optional(),inputSchema:L.record(L.string(),L.unknown()),outputSchema:L.record(L.string(),L.unknown()).optional()}),IA6=L.object({headers:L.record(L.string(),L.string()).optional()}),CA6=L.object({command:L.string().describe("Command to run (e.g., 'npx', 'node')"),args:L.array(L.string()).optional().describe("Command arguments"),cwd:L.string().optional().describe("Working directory"),envVars:L.record(L.string(),L.string()).optional().describe("Environment variables (encrypted in storage)")}),hk=L.object({id:L.string().describe("Unique identifier for the connection"),title:L.string().describe("Human-readable name for the connection"),created_at:L.string().describe("When the connection was created"),updated_at:L.string().describe("When the connection was last updated"),created_by:L.string().describe("User ID who created the connection"),updated_by:L.string().optional().describe("User ID who last updated the connection"),organization_id:L.string().describe("Organization ID this connection belongs to"),description:L.string().nullable().describe("Description of the connection"),icon:L.string().nullable().describe("Icon URL for the connection"),app_name:L.string().nullable().describe("Associated app name"),app_id:L.string().nullable().describe("Associated app ID"),connection_type:L.enum(["HTTP","SSE","Websocket","STDIO","VIRTUAL"]).describe("Type of connection"),connection_url:L.string().nullable().describe("URL for HTTP/SSE/WebSocket connections. virtual://$id for VIRTUAL. Null for STDIO."),connection_token:L.string().nullable().describe("Authentication token (for HTTP connections)"),connection_headers:L.union([CA6,IA6]).nullable().describe("Connection parameters. HTTP: { headers }. STDIO: { command, args, cwd, envVars }"),oauth_config:EA6.nullable().describe("OAuth configuration"),configuration_state:L.record(L.string(),L.unknown()).nullable().describe("Configuration state (decrypted)"),configuration_scopes:L.array(L.string()).nullable().optional().describe("Configuration scopes"),metadata:L.record(L.string(),L.unknown()).nullable().describe("Additional metadata (includes repository info)"),tools:L.array(jA6).nullable().describe("Discovered tools from MCP"),bindings:L.array(L.string()).nullable().describe("Detected bindings"),status:L.enum(["active","inactive","error"]).describe("Current status")}),J14=hk.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_url:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}),G14=hk.partial()});var F40,RA6,Z14,K14,$14;var H14=g(()=>{o0();F40=L.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),RA6=L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:L.array(L.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:L.array(L.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),Z14=L.object({id:L.string().describe("Unique identifier for the virtual MCP"),title:L.string().describe("Human-readable name for the virtual MCP"),description:L.string().nullable().describe("Description of the virtual MCP"),icon:L.string().nullable().optional().describe("Icon URL for the virtual MCP"),created_at:L.string().describe("When the virtual MCP was created"),updated_at:L.string().describe("When the virtual MCP was last updated"),created_by:L.string().describe("User ID who created the virtual MCP"),updated_by:L.string().optional().describe("User ID who last updated the virtual MCP"),organization_id:L.string().describe("Organization ID this virtual MCP belongs to"),tool_selection_mode:F40.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:L.enum(["active","inactive"]).describe("Current status"),metadata:L.object({instructions:L.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:L.array(RA6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),K14=L.object({title:L.string().min(1).max(255).describe("Name for the virtual MCP"),description:L.string().nullable().optional().describe("Optional description"),tool_selection_mode:F40.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:L.string().nullable().optional().describe("Optional icon URL"),status:L.enum(["active","inactive"]).optional().default("active").describe("Initial status"),metadata:L.object({instructions:L.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:L.array(L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:L.array(L.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:L.array(L.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).describe("Connections to include/exclude (can be empty for exclusion mode)")}),$14=L.object({title:L.string().min(1).max(255).optional().describe("New name"),description:L.string().nullable().optional().describe("New description (null to clear)"),tool_selection_mode:F40.optional().describe("New tool selection mode"),icon:L.string().nullable().optional().describe("New icon URL (null to clear)"),status:L.enum(["active","inactive"]).optional().describe("New status"),metadata:L.object({instructions:L.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:L.array(L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:L.array(L.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:L.array(L.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var F14=g(()=>{W14();H14()});var V40=g(()=>{Ot();Q14();F14();Q40();x3();bk()});function Mw(X){return X!==null&&X!==void 0&&"command"in X}function xk(X){if(!X||!X.startsWith("virtual://"))return null;return X.replace("virtual://","")}function gk(X){return`virtual://${X}`}var fA6,bA6,hA6,xA6,gA6,NJ,B14,D14;var ZK=g(()=>{o0();fA6=L.object({authorizationEndpoint:L.string().url(),tokenEndpoint:L.string().url(),introspectionEndpoint:L.string().url().optional(),clientId:L.string(),clientSecret:L.string().optional(),scopes:L.array(L.string()),grantType:L.enum(["authorization_code","client_credentials"])}),bA6=L.object({title:L.string().optional(),readOnlyHint:L.boolean().optional(),destructiveHint:L.boolean().optional(),idempotentHint:L.boolean().optional(),openWorldHint:L.boolean().optional()}),hA6=L.object({name:L.string(),description:L.string().optional(),inputSchema:L.record(L.string(),L.unknown()),outputSchema:L.record(L.string(),L.unknown()).optional(),annotations:bA6.optional(),_meta:L.record(L.string(),L.unknown()).optional()}),xA6=L.object({headers:L.record(L.string(),L.string()).optional()}),gA6=L.object({command:L.string().describe("Command to run (e.g., 'npx', 'node')"),args:L.array(L.string()).optional().describe("Command arguments"),cwd:L.string().optional().describe("Working directory"),envVars:L.record(L.string(),L.string()).optional().describe("Environment variables (encrypted in storage)")}),NJ=L.object({id:L.string().describe("Unique identifier for the connection"),title:L.string().describe("Human-readable name for the connection"),created_at:L.string().describe("When the connection was created"),updated_at:L.string().describe("When the connection was last updated"),created_by:L.string().describe("User ID who created the connection"),updated_by:L.string().optional().describe("User ID who last updated the connection"),organization_id:L.string().describe("Organization ID this connection belongs to"),description:L.string().nullable().describe("Description of the connection"),icon:L.string().nullable().describe("Icon URL for the connection"),app_name:L.string().nullable().describe("Associated app name"),app_id:L.string().nullable().describe("Associated app ID"),connection_type:L.enum(["HTTP","SSE","Websocket","STDIO","VIRTUAL"]).describe("Type of connection"),connection_url:L.string().nullable().describe("URL for HTTP/SSE/WebSocket connections. virtual://$id for VIRTUAL. Null for STDIO."),connection_token:L.string().nullable().describe("Authentication token (for HTTP connections)"),connection_headers:L.union([gA6,xA6]).nullable().describe("Connection parameters. HTTP: { headers }. STDIO: { command, args, cwd, envVars }"),oauth_config:fA6.nullable().describe("OAuth configuration"),configuration_state:L.record(L.string(),L.unknown()).nullable().describe("Configuration state (decrypted)"),configuration_scopes:L.array(L.string()).nullable().optional().describe("Configuration scopes"),metadata:L.record(L.string(),L.unknown()).nullable().describe("Additional metadata (includes repository info)"),tools:L.array(hA6).nullable().describe("Discovered tools from MCP"),bindings:L.array(L.string()).nullable().describe("Detected bindings"),status:L.enum(["active","inactive","error"]).describe("Current status")}),B14=NJ.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_url:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}),D14=NJ.partial()});var N14="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as O14}from"crypto";function mA6(X){if(!t3||t3.length<X)t3=Buffer.allocUnsafe(X*uA6),O14.getRandomValues(t3),UU=0;else if(UU+X>t3.length)O14.getRandomValues(t3),UU=0;UU+=X}function L14(X=21){mA6(X|=0);let Y="";for(let Q=UU-X;Q<UU;Q++)Y+=N14[t3[Q]&63];return Y}var uA6=128,t3,UU;var w14=()=>{};function zU(X){return`${X}_${L14()}`}var uk=g(()=>{w14()});function dA6(X){let Y=globalThis.DOMException;return typeof Y=="function"?new Y(X,"SyntaxError"):SyntaxError(X)}function B40(X){return X instanceof Error?"errors"in X&&Array.isArray(X.errors)?X.errors.map(B40).join(", "):("cause"in X)&&X.cause instanceof Error?`${X}: ${B40(X.cause)}`:X.message:`${X}`}function M14(X){return{type:X.type,message:X.message,code:X.code,defaultPrevented:X.defaultPrevented,cancelable:X.cancelable,timeStamp:X.timeStamp}}function pA6(){let X="document"in globalThis?globalThis.document:void 0;return X&&typeof X=="object"&&"baseURI"in X&&typeof X.baseURI=="string"?X.baseURI:void 0}var z40,T14=(X)=>{throw TypeError(X)},T40=(X,Y,Q)=>Y.has(X)||T14("Cannot "+Q),P6=(X,Y,Q)=>(T40(X,Y,"read from private field"),Q?Q.call(X):Y.get(X)),Y9=(X,Y,Q)=>Y.has(X)?T14("Cannot add the same private member more than once"):Y instanceof WeakSet?Y.add(X):Y.set(X,Q),F8=(X,Y,Q,J)=>(T40(X,Y,"write to private field"),Y.set(X,Q),Q),YW=(X,Y,Q)=>(T40(X,Y,"access private method"),Q),fY,e3,BU,mk,lk,Aw,OU,Ew,KK,DU,LU,NU,Pw,$5,D40,N40,O40,P14,L40,w40,Tw,M40,P40,wU;var A14=g(()=>{X40();z40=class z40 extends Event{constructor(X,Y){var Q,J;super(X),this.code=(Q=Y==null?void 0:Y.code)!=null?Q:void 0,this.message=(J=Y==null?void 0:Y.message)!=null?J:void 0}[Symbol.for("nodejs.util.inspect.custom")](X,Y,Q){return Q(M14(this),Y)}[Symbol.for("Deno.customInspect")](X,Y){return X(M14(this),Y)}};wU=class wU extends EventTarget{constructor(X,Y){var Q,J;super(),Y9(this,$5),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Y9(this,fY),Y9(this,e3),Y9(this,BU),Y9(this,mk),Y9(this,lk),Y9(this,Aw),Y9(this,OU),Y9(this,Ew,null),Y9(this,KK),Y9(this,DU),Y9(this,LU,null),Y9(this,NU,null),Y9(this,Pw,null),Y9(this,N40,async(G)=>{var Z;P6(this,DU).reset();let{body:W,redirected:K,status:$,headers:H}=G;if($===204){YW(this,$5,Tw).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(K?F8(this,BU,new URL(G.url)):F8(this,BU,void 0),$!==200){YW(this,$5,Tw).call(this,`Non-200 status code (${$})`,$);return}if(!(H.get("content-type")||"").startsWith("text/event-stream")){YW(this,$5,Tw).call(this,'Invalid content type, expected "text/event-stream"',$);return}if(P6(this,fY)===this.CLOSED)return;F8(this,fY,this.OPEN);let F=new Event("open");if((Z=P6(this,Pw))==null||Z.call(this,F),this.dispatchEvent(F),typeof W!="object"||!W||!("getReader"in W)){YW(this,$5,Tw).call(this,"Invalid response body, expected a web ReadableStream",$),this.close();return}let V=new TextDecoder,q=W.getReader(),z=!0;do{let{done:D,value:N}=await q.read();N&&P6(this,DU).feed(V.decode(N,{stream:!D})),D&&(z=!1,P6(this,DU).reset(),YW(this,$5,M40).call(this))}while(z)}),Y9(this,O40,(G)=>{F8(this,KK,void 0),!(G.name==="AbortError"||G.type==="aborted")&&YW(this,$5,M40).call(this,B40(G))}),Y9(this,L40,(G)=>{typeof G.id=="string"&&F8(this,Ew,G.id);let Z=new MessageEvent(G.event||"message",{data:G.data,origin:P6(this,BU)?P6(this,BU).origin:P6(this,e3).origin,lastEventId:G.id||""});P6(this,NU)&&(!G.event||G.event==="message")&&P6(this,NU).call(this,Z),this.dispatchEvent(Z)}),Y9(this,w40,(G)=>{F8(this,Aw,G)}),Y9(this,P40,()=>{F8(this,OU,void 0),P6(this,fY)===this.CONNECTING&&YW(this,$5,D40).call(this)});try{if(X instanceof URL)F8(this,e3,X);else if(typeof X=="string")F8(this,e3,new URL(X,pA6()));else throw Error("Invalid URL")}catch{throw dA6("An invalid or illegal string was specified")}F8(this,DU,_k({onEvent:P6(this,L40),onRetry:P6(this,w40)})),F8(this,fY,this.CONNECTING),F8(this,Aw,3000),F8(this,lk,(Q=Y==null?void 0:Y.fetch)!=null?Q:globalThis.fetch),F8(this,mk,(J=Y==null?void 0:Y.withCredentials)!=null?J:!1),YW(this,$5,D40).call(this)}get readyState(){return P6(this,fY)}get url(){return P6(this,e3).href}get withCredentials(){return P6(this,mk)}get onerror(){return P6(this,LU)}set onerror(X){F8(this,LU,X)}get onmessage(){return P6(this,NU)}set onmessage(X){F8(this,NU,X)}get onopen(){return P6(this,Pw)}set onopen(X){F8(this,Pw,X)}addEventListener(X,Y,Q){let J=Y;super.addEventListener(X,J,Q)}removeEventListener(X,Y,Q){let J=Y;super.removeEventListener(X,J,Q)}close(){P6(this,OU)&&clearTimeout(P6(this,OU)),P6(this,fY)!==this.CLOSED&&(P6(this,KK)&&P6(this,KK).abort(),F8(this,fY,this.CLOSED),F8(this,KK,void 0))}};fY=new WeakMap,e3=new WeakMap,BU=new WeakMap,mk=new WeakMap,lk=new WeakMap,Aw=new WeakMap,OU=new WeakMap,Ew=new WeakMap,KK=new WeakMap,DU=new WeakMap,LU=new WeakMap,NU=new WeakMap,Pw=new WeakMap,$5=new WeakSet,D40=function(){F8(this,fY,this.CONNECTING),F8(this,KK,new AbortController),P6(this,lk)(P6(this,e3),YW(this,$5,P14).call(this)).then(P6(this,N40)).catch(P6(this,O40))},N40=new WeakMap,O40=new WeakMap,P14=function(){var X;let Y={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...P6(this,Ew)?{"Last-Event-ID":P6(this,Ew)}:void 0},cache:"no-store",signal:(X=P6(this,KK))==null?void 0:X.signal};return"window"in globalThis&&(Y.credentials=this.withCredentials?"include":"same-origin"),Y},L40=new WeakMap,w40=new WeakMap,Tw=function(X,Y){var Q;P6(this,fY)!==this.CLOSED&&F8(this,fY,this.CLOSED);let J=new z40("error",{code:Y,message:X});(Q=P6(this,LU))==null||Q.call(this,J),this.dispatchEvent(J)},M40=function(X,Y){var Q;if(P6(this,fY)===this.CLOSED)return;F8(this,fY,this.CONNECTING);let J=new z40("error",{code:Y,message:X});(Q=P6(this,LU))==null||Q.call(this,J),this.dispatchEvent(J),F8(this,OU,setTimeout(P6(this,P40),P6(this,Aw)))},P40=new WeakMap,wU.CONNECTING=0,wU.OPEN=1,wU.CLOSED=2});class jw{constructor(X,Y){this._url=X,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=Y?.eventSourceInit,this._requestInit=Y?.requestInit,this._authProvider=Y?.authProvider,this._fetch=Y?.fetch,this._fetchWithInit=wk(Y?.fetch,Y?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new yY("No auth provider");let X;try{X=await XW(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(Y){throw this.onerror?.(Y),Y}if(X!=="AUTHORIZED")throw new yY;return await this._startOrAuth()}async _commonHeaders(){let X={};if(this._authProvider){let Q=await this._authProvider.tokens();if(Q)X.Authorization=`Bearer ${Q.access_token}`}if(this._protocolVersion)X["mcp-protocol-version"]=this._protocolVersion;let Y=ZU(this._requestInit?.headers);return new Headers({...X,...Y})}_startOrAuth(){let X=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((Y,Q)=>{this._eventSource=new wU(this._url.href,{...this._eventSourceInit,fetch:async(J,G)=>{let Z=await this._commonHeaders();Z.set("Accept","text/event-stream");let W=await X(J,{...G,headers:Z});if(W.status===401&&W.headers.has("www-authenticate")){let{resourceMetadataUrl:K,scope:$}=VU(W);this._resourceMetadataUrl=K,this._scope=$}return W}}),this._abortController=new AbortController,this._eventSource.onerror=(J)=>{if(J.code===401&&this._authProvider){this._authThenStart().then(Y,Q);return}let G=new E14(J.code,J.message,J);Q(G),this.onerror?.(G)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",(J)=>{let G=J;try{if(this._endpoint=new URL(G.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(Z){Q(Z),this.onerror?.(Z),this.close();return}Y()}),this._eventSource.onmessage=(J)=>{let G=J,Z;try{Z=UQ.parse(JSON.parse(G.data))}catch(W){this.onerror?.(W);return}this.onmessage?.(Z)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(X){if(!this._authProvider)throw new yY("No auth provider");if(await XW(this._authProvider,{serverUrl:this._url,authorizationCode:X,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new yY("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(X){if(!this._endpoint)throw Error("Not connected");try{let Y=await this._commonHeaders();Y.set("content-type","application/json");let Q={...this._requestInit,method:"POST",headers:Y,body:JSON.stringify(X),signal:this._abortController?.signal},J=await(this._fetch??fetch)(this._endpoint,Q);if(!J.ok){let G=await J.text().catch(()=>null);if(J.status===401&&this._authProvider){let{resourceMetadataUrl:Z,scope:W}=VU(J);if(this._resourceMetadataUrl=Z,this._scope=W,await XW(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new yY;return this.send(X)}throw Error(`Error POSTing to endpoint (HTTP ${J.status}): ${G}`)}await J.body?.cancel()}catch(Y){throw this.onerror?.(Y),Y}}setProtocolVersion(X){this._protocolVersion=X}}var E14;var A40=g(()=>{A14();zQ();s00();E14=class E14 extends Error{constructor(X,Y,Q){super(`SSE error: ${Y}`);this.code=X,this.event=Q}}});var S14=j((qP1,R14)=>{R14.exports=C14;C14.sync=nA6;var j14=U0("fs");function cA6(X,Y){var Q=Y.pathExt!==void 0?Y.pathExt:process.env.PATHEXT;if(!Q)return!0;if(Q=Q.split(";"),Q.indexOf("")!==-1)return!0;for(var J=0;J<Q.length;J++){var G=Q[J].toLowerCase();if(G&&X.substr(-G.length).toLowerCase()===G)return!0}return!1}function I14(X,Y,Q){if(!X.isSymbolicLink()&&!X.isFile())return!1;return cA6(Y,Q)}function C14(X,Y,Q){j14.stat(X,function(J,G){Q(J,J?!1:I14(G,X,Y))})}function nA6(X,Y){return I14(j14.statSync(X),X,Y)}});var f14=j((UP1,y14)=>{y14.exports=k14;k14.sync=iA6;var v14=U0("fs");function k14(X,Y,Q){v14.stat(X,function(J,G){Q(J,J?!1:_14(G,Y))})}function iA6(X,Y){return _14(v14.statSync(X),Y)}function _14(X,Y){return X.isFile()&&aA6(X,Y)}function aA6(X,Y){var{mode:Q,uid:J,gid:G}=X,Z=Y.uid!==void 0?Y.uid:process.getuid&&process.getuid(),W=Y.gid!==void 0?Y.gid:process.getgid&&process.getgid(),K=parseInt("100",8),$=parseInt("010",8),H=parseInt("001",8),F=K|$,V=Q&H||Q&$&&G===W||Q&K&&J===Z||Q&F&&Z===0;return V}});var h14=j((BP1,b14)=>{var zP1=U0("fs"),dk;if(process.platform==="win32"||global.TESTING_WINDOWS)dk=S14();else dk=f14();b14.exports=E40;E40.sync=rA6;function E40(X,Y,Q){if(typeof Y==="function")Q=Y,Y={};if(!Q){if(typeof Promise!=="function")throw TypeError("callback not provided");return new Promise(function(J,G){E40(X,Y||{},function(Z,W){if(Z)G(Z);else J(W)})})}dk(X,Y||{},function(J,G){if(J){if(J.code==="EACCES"||Y&&Y.ignoreErrors)J=null,G=!1}Q(J,G)})}function rA6(X,Y){try{return dk.sync(X,Y||{})}catch(Q){if(Y&&Y.ignoreErrors||Q.code==="EACCES")return!1;else throw Q}}});var p14=j((DP1,d14)=>{var MU=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",x14=U0("path"),oA6=MU?";":":",g14=h14(),u14=(X)=>Object.assign(Error(`not found: ${X}`),{code:"ENOENT"}),m14=(X,Y)=>{let Q=Y.colon||oA6,J=X.match(/\//)||MU&&X.match(/\\/)?[""]:[...MU?[process.cwd()]:[],...(Y.path||process.env.PATH||"").split(Q)],G=MU?Y.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",Z=MU?G.split(Q):[""];if(MU){if(X.indexOf(".")!==-1&&Z[0]!=="")Z.unshift("")}return{pathEnv:J,pathExt:Z,pathExtExe:G}},l14=(X,Y,Q)=>{if(typeof Y==="function")Q=Y,Y={};if(!Y)Y={};let{pathEnv:J,pathExt:G,pathExtExe:Z}=m14(X,Y),W=[],K=(H)=>new Promise((F,V)=>{if(H===J.length)return Y.all&&W.length?F(W):V(u14(X));let q=J[H],z=/^".*"$/.test(q)?q.slice(1,-1):q,D=x14.join(z,X),N=!z&&/^\.[\\\/]/.test(X)?X.slice(0,2)+D:D;F($(N,H,0))}),$=(H,F,V)=>new Promise((q,z)=>{if(V===G.length)return q(K(F+1));let D=G[V];g14(H+D,{pathExt:Z},(N,O)=>{if(!N&&O)if(Y.all)W.push(H+D);else return q(H+D);return q($(H,F,V+1))})});return Q?K(0).then((H)=>Q(null,H),Q):K(0)},sA6=(X,Y)=>{Y=Y||{};let{pathEnv:Q,pathExt:J,pathExtExe:G}=m14(X,Y),Z=[];for(let W=0;W<Q.length;W++){let K=Q[W],$=/^".*"$/.test(K)?K.slice(1,-1):K,H=x14.join($,X),F=!$&&/^\.[\\\/]/.test(X)?X.slice(0,2)+H:H;for(let V=0;V<J.length;V++){let q=F+J[V];try{if(g14.sync(q,{pathExt:G}))if(Y.all)Z.push(q);else return q}catch(z){}}}if(Y.all&&Z.length)return Z;if(Y.nothrow)return null;throw u14(X)};d14.exports=l14;l14.sync=sA6});var n14=j((NP1,j40)=>{var c14=(X={})=>{let Y=X.env||process.env;if((X.platform||process.platform)!=="win32")return"PATH";return Object.keys(Y).reverse().find((J)=>J.toUpperCase()==="PATH")||"Path"};j40.exports=c14;j40.exports.default=c14});var o14=j((OP1,r14)=>{var i14=U0("path"),tA6=p14(),eA6=n14();function a14(X,Y){let Q=X.options.env||process.env,J=process.cwd(),G=X.options.cwd!=null,Z=G&&process.chdir!==void 0&&!process.chdir.disabled;if(Z)try{process.chdir(X.options.cwd)}catch(K){}let W;try{W=tA6.sync(X.command,{path:Q[eA6({env:Q})],pathExt:Y?i14.delimiter:void 0})}catch(K){}finally{if(Z)process.chdir(J)}if(W)W=i14.resolve(G?X.options.cwd:"",W);return W}function XE6(X){return a14(X)||a14(X,!0)}r14.exports=XE6});var s14=j((JE6,C40)=>{var I40=/([()\][%!^"`<>&|;, *?])/g;function YE6(X){return X=X.replace(I40,"^$1"),X}function QE6(X,Y){if(X=`${X}`,X=X.replace(/(?=(\\+?)?)\1"/g,"$1$1\\\""),X=X.replace(/(?=(\\+?)?)\1$/,"$1$1"),X=`"${X}"`,X=X.replace(I40,"^$1"),Y)X=X.replace(I40,"^$1");return X}JE6.command=YE6;JE6.argument=QE6});var e14=j((LP1,t14)=>{t14.exports=/^#!(.*)/});var Y84=j((wP1,X84)=>{var ZE6=e14();X84.exports=(X="")=>{let Y=X.match(ZE6);if(!Y)return null;let[Q,J]=Y[0].replace(/#! ?/,"").split(" "),G=Q.split("/").pop();if(G==="env")return J;return J?`${G} ${J}`:G}});var J84=j((MP1,Q84)=>{var R40=U0("fs"),KE6=Y84();function $E6(X){let Q=Buffer.alloc(150),J;try{J=R40.openSync(X,"r"),R40.readSync(J,Q,0,150,0),R40.closeSync(J)}catch(G){}return KE6(Q.toString())}Q84.exports=$E6});var K84=j((PP1,Z84)=>{var HE6=U0("path"),G84=o14(),W84=s14(),FE6=J84(),VE6=process.platform==="win32",qE6=/\.(?:com|exe)$/i,UE6=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function zE6(X){X.file=G84(X);let Y=X.file&&FE6(X.file);if(Y)return X.args.unshift(X.file),X.command=Y,G84(X);return X.file}function BE6(X){if(!VE6)return X;let Y=zE6(X),Q=!qE6.test(Y);if(X.options.forceShell||Q){let J=UE6.test(Y);X.command=HE6.normalize(X.command),X.command=W84.command(X.command),X.args=X.args.map((Z)=>W84.argument(Z,J));let G=[X.command].concat(X.args).join(" ");X.args=["/d","/s","/c",`"${G}"`],X.command=process.env.comspec||"cmd.exe",X.options.windowsVerbatimArguments=!0}return X}function DE6(X,Y,Q){if(Y&&!Array.isArray(Y))Q=Y,Y=null;Y=Y?Y.slice(0):[],Q=Object.assign({},Q);let J={command:X,args:Y,options:Q,file:void 0,original:{command:X,args:Y}};return Q.shell?J:BE6(J)}Z84.exports=DE6});var F84=j((TP1,H84)=>{var S40=process.platform==="win32";function v40(X,Y){return Object.assign(Error(`${Y} ${X.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${Y} ${X.command}`,path:X.command,spawnargs:X.args})}function NE6(X,Y){if(!S40)return;let Q=X.emit;X.emit=function(J,G){if(J==="exit"){let Z=$84(G,Y);if(Z)return Q.call(X,"error",Z)}return Q.apply(X,arguments)}}function $84(X,Y){if(S40&&X===1&&!Y.file)return v40(Y.original,"spawn");return null}function OE6(X,Y){if(S40&&X===1&&!Y.file)return v40(Y.original,"spawnSync");return null}H84.exports={hookChildProcess:NE6,verifyENOENT:$84,verifyENOENTSync:OE6,notFoundError:v40}});var U84=j((AP1,PU)=>{var V84=U0("child_process"),k40=K84(),_40=F84();function q84(X,Y,Q){let J=k40(X,Y,Q),G=V84.spawn(J.command,J.args,J.options);return _40.hookChildProcess(G,J),G}function LE6(X,Y,Q){let J=k40(X,Y,Q),G=V84.spawnSync(J.command,J.args,J.options);return G.error=G.error||_40.verifyENOENTSync(G.status,J),G}PU.exports=q84;PU.exports.spawn=q84;PU.exports.sync=LE6;PU.exports._parse=k40;PU.exports._enoent=_40});class y40{append(X){this._buffer=this._buffer?Buffer.concat([this._buffer,X]):X}readMessage(){if(!this._buffer)return null;let X=this._buffer.indexOf(`
385
385
  `);if(X===-1)return null;let Y=this._buffer.toString("utf8",0,X).replace(/\r$/,"");return this._buffer=this._buffer.subarray(X+1),wE6(Y)}clear(){this._buffer=void 0}}function wE6(X){return UQ.parse(JSON.parse(X))}function z84(X){return JSON.stringify(X)+`
386
386
  `}var B84=g(()=>{zQ()});import pk from"process";import{PassThrough as ME6}from"stream";function TE6(){let X={};for(let Y of PE6){let Q=pk.env[Y];if(Q===void 0)continue;if(Q.startsWith("()"))continue;X[Y]=Q}return X}class f40{constructor(X){if(this._readBuffer=new y40,this._stderrStream=null,this._serverParams=X,X.stderr==="pipe"||X.stderr==="overlapped")this._stderrStream=new ME6}async start(){if(this._process)throw Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((X,Y)=>{if(this._process=D84.default(this._serverParams.command,this._serverParams.args??[],{env:{...TE6(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:pk.platform==="win32"&&AE6(),cwd:this._serverParams.cwd}),this._process.on("error",(Q)=>{Y(Q),this.onerror?.(Q)}),this._process.on("spawn",()=>{X()}),this._process.on("close",(Q)=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",(Q)=>{this.onerror?.(Q)}),this._process.stdout?.on("data",(Q)=>{this._readBuffer.append(Q),this.processReadBuffer()}),this._process.stdout?.on("error",(Q)=>{this.onerror?.(Q)}),this._stderrStream&&this._process.stderr)this._process.stderr.pipe(this._stderrStream)})}get stderr(){if(this._stderrStream)return this._stderrStream;return this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){while(!0)try{let X=this._readBuffer.readMessage();if(X===null)break;this.onmessage?.(X)}catch(X){this.onerror?.(X)}}async close(){if(this._process){let X=this._process;this._process=void 0;let Y=new Promise((Q)=>{X.once("close",()=>{Q()})});try{X.stdin?.end()}catch{}if(await Promise.race([Y,new Promise((Q)=>setTimeout(Q,2000).unref())]),X.exitCode===null){try{X.kill("SIGTERM")}catch{}await Promise.race([Y,new Promise((Q)=>setTimeout(Q,2000).unref())])}if(X.exitCode===null)try{X.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(X){return new Promise((Y)=>{if(!this._process?.stdin)throw Error("Not connected");let Q=z84(X);if(this._process.stdin.write(Q))Y();else this._process.stdin.once("drain",Y)})}}function AE6(){return"type"in pk}var D84,PE6;var N84=g(()=>{B84();D84=U1(U84(),1),PE6=pk.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"]});async function TU(X){switch(X.connection_type){case"STDIO":return IE6(X);case"HTTP":case"Websocket":return EE6(X);case"SSE":return jE6(X);case"VIRTUAL":return null;default:return null}}async function EE6(X){if(!X.connection_url)return console.error(`HTTP connection ${X.id} missing URL`),null;let Y=null;try{let Q={"Content-Type":"application/json"};if(X.connection_token)Q.Authorization=`Bearer ${X.connection_token}`;let J=X.connection_headers;if(J?.headers)Object.assign(Q,J.headers);let G=new qU(new URL(X.connection_url),{requestInit:{headers:Q}});Y=new GK({name:"mcp-mesh-tool-fetcher",version:"1.0.0"});let Z=new Promise((K,$)=>{setTimeout(()=>$(Error("Connection timeout")),1e4)});await Promise.race([Y.connect(G),Z]);let W=await Promise.race([Y.listTools(),Z]);if(!W.tools||W.tools.length===0)return null;return W.tools.map((K)=>({name:K.name,description:K.description??void 0,inputSchema:K.inputSchema??{},outputSchema:K.outputSchema?{...K.outputSchema,additionalProperties:!0}:void 0,annotations:K.annotations??void 0,_meta:K._meta??void 0}))}catch(Q){return console.error(`Failed to fetch tools from HTTP connection ${X.id}:`,Q),null}finally{try{if(Y&&typeof Y.close==="function")await Y.close()}catch(Q){console.warn(`Failed to close HTTP client for ${X.id}:`,Q)}}}async function jE6(X){if(!X.connection_url)return console.error(`SSE connection ${X.id} missing URL`),null;let Y=null;try{let Q={"Content-Type":"application/json"};if(X.connection_token)Q.Authorization=`Bearer ${X.connection_token}`;let J=X.connection_headers;if(J?.headers)Object.assign(Q,J.headers);let G=new jw(new URL(X.connection_url),{requestInit:{headers:Q}});Y=new GK({name:"mcp-mesh-tool-fetcher",version:"1.0.0"});let Z=new Promise((K,$)=>{setTimeout(()=>$(Error("SSE connection timeout")),15000)});await Promise.race([Y.connect(G),Z]);let W=await Promise.race([Y.listTools(),Z]);if(!W.tools||W.tools.length===0)return null;return W.tools.map((K)=>({name:K.name,description:K.description??void 0,inputSchema:K.inputSchema??{},outputSchema:K.outputSchema?{...K.outputSchema,additionalProperties:!0}:void 0,annotations:K.annotations??void 0,_meta:K._meta??void 0}))}catch(Q){return console.error(`Failed to fetch tools from SSE connection ${X.id}:`,Q),null}finally{try{await Y?.close()}catch(Q){console.warn(`Failed to close SSE client for ${X.id}:`,Q)}}}async function IE6(X){let Y=Mw(X.connection_headers)?X.connection_headers:null;if(!Y)return console.error(`STDIO connection ${X.id} missing parameters`),null;let Q=null;try{let J=new f40({command:Y.command,args:Y.args,env:Y.envVars,cwd:Y.cwd});Q=new GK({name:"mcp-mesh-tool-fetcher",version:"1.0.0"});let G=new Promise((W,K)=>{setTimeout(()=>K(Error("Tool fetch timeout")),1e4)});await Promise.race([Q.connect(J),G]);let Z=await Promise.race([Q.listTools(),G]);if(!Z.tools||Z.tools.length===0)return null;return Z.tools.map((W)=>({name:W.name,description:W.description??void 0,inputSchema:W.inputSchema??{},outputSchema:W.outputSchema??void 0,annotations:W.annotations??void 0,_meta:W._meta??void 0}))}catch(J){return console.error(`Failed to fetch tools from STDIO connection ${X.id}:`,J),null}finally{try{if(Q&&typeof Q.close==="function")await Q.close()}catch(J){console.warn(`Failed to close STDIO client for ${X.id}:`,J)}}}var ck=g(()=>{Lk();A40();N84();yk();ZK()});class b40{constructor(X){this._server=X}requestStream(X,Y,Q){return this._server.requestStream(X,Y,Q)}async getTask(X,Y){return this._server.getTask({taskId:X},Y)}async getTaskResult(X,Y,Q){return this._server.getTaskResult({taskId:X},Y,Q)}async listTasks(X,Y){return this._server.listTasks(X?{cursor:X}:void 0,Y)}async cancelTask(X,Y){return this._server.cancelTask({taskId:X},Y)}}var h40;var O84=g(()=>{be();zQ();u00();dq();h40=class h40 extends rL{constructor(X,Y){super(Y);if(this._serverInfo=X,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(nL.options.map((Q,J)=>[Q,J])),this.isMessageIgnored=(Q,J)=>{let G=this._loggingLevels.get(J);return G?this.LOG_LEVEL_SEVERITY.get(Q)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=Y?.capabilities??{},this._instructions=Y?.instructions,this._jsonSchemaValidator=Y?.jsonSchemaValidator??new Lw,this.setRequestHandler(Wv,(Q)=>this._oninitialize(Q)),this.setNotificationHandler(Zv,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(tt,async(Q,J)=>{let G=J.sessionId||J.requestInfo?.headers["mcp-session-id"]||void 0,{level:Z}=Q.params,W=nL.safeParse(Z);if(W.success)this._loggingLevels.set(G,W.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new b40(this)};return this._experimental}registerCapabilities(X){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=vv(this._capabilities,X)}setRequestHandler(X,Y){let J=jG(X)?.method;if(!J)throw Error("Schema is missing a method literal");let G;if(RY(J)){let W=J;G=W._zod?.def?.value??W.value}else{let W=J;G=W._def?.value??W.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let W=async(K,$)=>{let H=tX(iq,K);if(!H.success){let z=H.error instanceof Error?H.error.message:String(H.error);throw new G4(z4.InvalidParams,`Invalid tools/call request: ${z}`)}let{params:F}=H.data,V=await Promise.resolve(Y(K,$));if(F.task){let z=tX(a7,V);if(!z.success){let D=z.error instanceof Error?z.error.message:String(z.error);throw new G4(z4.InvalidParams,`Invalid task creation result: ${D}`)}return z.data}let q=tX(rZ,V);if(!q.success){let z=q.error instanceof Error?q.error.message:String(q.error);throw new G4(z4.InvalidParams,`Invalid tools/call result: ${z}`)}return q.data};return super.setRequestHandler(X,W)}return super.setRequestHandler(X,Y)}assertCapabilityForMethod(X){switch(X){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${X})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${X})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${X})`);break;case"ping":break}}assertNotificationCapability(X){switch(X){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${X})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${X})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${X})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${X})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${X})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(X){if(!this._capabilities)return;switch(X){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${X})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${X})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${X})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${X})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${X})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${X})`);break;case"ping":case"initialize":break}}assertTaskCapability(X){Nk(this._clientCapabilities?.tasks?.requests,X,"Client")}assertTaskHandlerCapability(X){if(!this._capabilities)return;Dk(this._capabilities.tasks?.requests,X,"Server")}async _oninitialize(X){let Y=X.params.protocolVersion;return this._clientCapabilities=X.params.capabilities,this._clientVersion=X.params.clientInfo,{protocolVersion:d3.includes(Y)?Y:iZ,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},i7)}async createMessage(X,Y){if(X.tools||X.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(X.messages.length>0){let Q=X.messages[X.messages.length-1],J=Array.isArray(Q.content)?Q.content:[Q.content],G=J.some(($)=>$.type==="tool_result"),Z=X.messages.length>1?X.messages[X.messages.length-2]:void 0,W=Z?Array.isArray(Z.content)?Z.content:[Z.content]:[],K=W.some(($)=>$.type==="tool_use");if(G){if(J.some(($)=>$.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!K)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(K){let $=new Set(W.filter((F)=>F.type==="tool_use").map((F)=>F.id)),H=new Set(J.filter((F)=>F.type==="tool_result").map((F)=>F.toolUseId));if($.size!==H.size||![...$].every((F)=>H.has(F)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(X.tools)return this.request({method:"sampling/createMessage",params:X},Xe,Y);return this.request({method:"sampling/createMessage",params:X},iL,Y)}async elicitInput(X,Y){switch(X.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let J=X;return this.request({method:"elicitation/create",params:J},aq,Y)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let J=X.mode==="form"?X:{...X,mode:"form"},G=await this.request({method:"elicitation/create",params:J},aq,Y);if(G.action==="accept"&&G.content&&J.requestedSchema)try{let W=this._jsonSchemaValidator.getValidator(J.requestedSchema)(G.content);if(!W.valid)throw new G4(z4.InvalidParams,`Elicitation response content does not match requested schema: ${W.errorMessage}`)}catch(Z){if(Z instanceof G4)throw Z;throw new G4(z4.InternalError,`Error validating elicitation response: ${Z instanceof Error?Z.message:String(Z)}`)}return G}}}createElicitationCompletionNotifier(X,Y){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:X}},Y)}async listRoots(X,Y){return this.request({method:"roots/list",params:X},Je,Y)}async sendLoggingMessage(X,Y){if(this._capabilities.logging){if(!this.isMessageIgnored(X.level,Y))return this.notification({method:"notifications/message",params:X})}}async sendResourceUpdated(X){return this.notification({method:"notifications/resources/updated",params:X})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function x40(X){return!!X&&typeof X==="object"&&w84 in X}function M84(X){return X[w84]?.complete}var w84,L84;var P84=g(()=>{w84=Symbol.for("mcp.completable");(function(X){X.Completable="McpCompletable"})(L84||(L84={}))});function RE6(X){let Y=[];if(X.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(X.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${X.length})`]};if(X.includes(" "))Y.push("Tool name contains spaces, which may cause parsing issues");if(X.includes(","))Y.push("Tool name contains commas, which may cause parsing issues");if(X.startsWith("-")||X.endsWith("-"))Y.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(X.startsWith(".")||X.endsWith("."))Y.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!CE6.test(X)){let Q=X.split("").filter((J)=>!/[A-Za-z0-9._-]/.test(J)).filter((J,G,Z)=>Z.indexOf(J)===G);return Y.push(`Tool name contains invalid characters: ${Q.map((J)=>`"${J}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:Y}}return{isValid:!0,warnings:Y}}function SE6(X,Y){if(Y.length>0){console.warn(`Tool name validation warning for "${X}":`);for(let Q of Y)console.warn(` - ${Q}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function g40(X){let Y=RE6(X);return SE6(X,Y.warnings),Y.isValid}var CE6;var T84=g(()=>{CE6=/^[A-Za-z0-9._-]{1,128}$/});class u40{constructor(X){this._mcpServer=X}registerToolTask(X,Y,Q){let J={taskSupport:"required",...Y.execution};if(J.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${X}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(X,Y.title,Y.description,Y.inputSchema,Y.outputSchema,Y.annotations,J,Y._meta,Q)}}class l40{constructor(X,Y){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new h40(X,Y)}get experimental(){if(!this._experimental)this._experimental={tasks:new u40(this)};return this._experimental}async connect(X){return await this.server.connect(X)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler($K(wv)),this.server.assertCanSetRequestHandler($K(iq)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(wv,()=>({tools:Object.entries(this._registeredTools).filter(([,X])=>X.enabled).map(([X,Y])=>{let Q={name:X,title:Y.title,description:Y.description,inputSchema:(()=>{let J=lq(Y.inputSchema);return J?ke(J,{strictUnions:!0,pipeStrategy:"input"}):vE6})(),annotations:Y.annotations,execution:Y.execution,_meta:Y._meta};if(Y.outputSchema){let J=lq(Y.outputSchema);if(J)Q.outputSchema=ke(J,{strictUnions:!0,pipeStrategy:"output"})}return Q})})),this.server.setRequestHandler(iq,async(X,Y)=>{try{let Q=this._registeredTools[X.params.name];if(!Q)throw new G4(z4.InvalidParams,`Tool ${X.params.name} not found`);if(!Q.enabled)throw new G4(z4.InvalidParams,`Tool ${X.params.name} disabled`);let J=!!X.params.task,G=Q.execution?.taskSupport,Z="createTask"in Q.handler;if((G==="required"||G==="optional")&&!Z)throw new G4(z4.InternalError,`Tool ${X.params.name} has taskSupport '${G}' but was not registered with registerToolTask`);if(G==="required"&&!J)throw new G4(z4.MethodNotFound,`Tool ${X.params.name} requires task augmentation (taskSupport: 'required')`);if(G==="optional"&&!J&&Z)return await this.handleAutomaticTaskPolling(Q,X,Y);let W=await this.validateToolInput(Q,X.params.arguments,X.params.name),K=await this.executeToolHandler(Q,W,Y);if(J)return K;return await this.validateToolOutput(Q,K,X.params.name),K}catch(Q){if(Q instanceof G4){if(Q.code===z4.UrlElicitationRequired)throw Q}return this.createToolError(Q instanceof Error?Q.message:String(Q))}}),this._toolHandlersInitialized=!0}createToolError(X){return{content:[{type:"text",text:X}],isError:!0}}async validateToolInput(X,Y,Q){if(!X.inputSchema)return;let G=lq(X.inputSchema)??X.inputSchema,Z=await tS(G,Y);if(!Z.success){let W="error"in Z?Z.error:"Unknown error",K=eS(W);throw new G4(z4.InvalidParams,`Input validation error: Invalid arguments for tool ${Q}: ${K}`)}return Z.data}async validateToolOutput(X,Y,Q){if(!X.outputSchema)return;if(!("content"in Y))return;if(Y.isError)return;if(!Y.structuredContent)throw new G4(z4.InvalidParams,`Output validation error: Tool ${Q} has an output schema but no structured content was provided`);let J=lq(X.outputSchema),G=await tS(J,Y.structuredContent);if(!G.success){let Z="error"in G?G.error:"Unknown error",W=eS(Z);throw new G4(z4.InvalidParams,`Output validation error: Invalid structured content for tool ${Q}: ${W}`)}}async executeToolHandler(X,Y,Q){let J=X.handler;if("createTask"in J){if(!Q.taskStore)throw Error("No task store provided.");let Z={...Q,taskStore:Q.taskStore};if(X.inputSchema)return await Promise.resolve(J.createTask(Y,Z));else return await Promise.resolve(J.createTask(Z))}if(X.inputSchema)return await Promise.resolve(J(Y,Q));else return await Promise.resolve(J(Q))}async handleAutomaticTaskPolling(X,Y,Q){if(!Q.taskStore)throw Error("No task store provided for task-capable tool.");let J=await this.validateToolInput(X,Y.params.arguments,Y.params.name),G=X.handler,Z={...Q,taskStore:Q.taskStore},W=J?await Promise.resolve(G.createTask(J,Z)):await Promise.resolve(G.createTask(Z)),K=W.task.taskId,$=W.task,H=$.pollInterval??5000;while($.status!=="completed"&&$.status!=="failed"&&$.status!=="cancelled"){await new Promise((V)=>setTimeout(V,H));let F=await Q.taskStore.getTask(K);if(!F)throw new G4(z4.InternalError,`Task ${K} not found during polling`);$=F}return await Q.taskStore.getTaskResult(K)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler($K(Mv)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Mv,async(X)=>{switch(X.params.ref.type){case"ref/prompt":return ws0(X),this.handlePromptCompletion(X,X.params.ref);case"ref/resource":return Ms0(X),this.handleResourceCompletion(X,X.params.ref);default:throw new G4(z4.InvalidParams,`Invalid completion reference: ${X.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(X,Y){let Q=this._registeredPrompts[Y.name];if(!Q)throw new G4(z4.InvalidParams,`Prompt ${Y.name} not found`);if(!Q.enabled)throw new G4(z4.InvalidParams,`Prompt ${Y.name} disabled`);if(!Q.argsSchema)return Iw;let G=jG(Q.argsSchema)?.[X.params.argument.name];if(!x40(G))return Iw;let Z=M84(G);if(!Z)return Iw;let W=await Z(X.params.argument.value,X.params.context);return E84(W)}async handleResourceCompletion(X,Y){let Q=Object.values(this._registeredResourceTemplates).find((Z)=>Z.resourceTemplate.uriTemplate.toString()===Y.uri);if(!Q){if(this._registeredResources[Y.uri])return Iw;throw new G4(z4.InvalidParams,`Resource template ${X.params.ref.uri} not found`)}let J=Q.resourceTemplate.completeCallback(X.params.argument.name);if(!J)return Iw;let G=await J(X.params.argument.value,X.params.context);return E84(G)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler($K(Bv)),this.server.assertCanSetRequestHandler($K(Dv)),this.server.assertCanSetRequestHandler($K(Nv)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Bv,async(X,Y)=>{let Q=Object.entries(this._registeredResources).filter(([G,Z])=>Z.enabled).map(([G,Z])=>({uri:G,name:Z.name,...Z.metadata})),J=[];for(let G of Object.values(this._registeredResourceTemplates)){if(!G.resourceTemplate.listCallback)continue;let Z=await G.resourceTemplate.listCallback(Y);for(let W of Z.resources)J.push({...G.metadata,...W})}return{resources:[...Q,...J]}}),this.server.setRequestHandler(Dv,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([Y,Q])=>({name:Y,uriTemplate:Q.resourceTemplate.uriTemplate.toString(),...Q.metadata}))}}),this.server.setRequestHandler(Nv,async(X,Y)=>{let Q=new URL(X.params.uri),J=this._registeredResources[Q.toString()];if(J){if(!J.enabled)throw new G4(z4.InvalidParams,`Resource ${Q} disabled`);return J.readCallback(Q,Y)}for(let G of Object.values(this._registeredResourceTemplates)){let Z=G.resourceTemplate.uriTemplate.match(Q.toString());if(Z)return G.readCallback(Q,Z,Y)}throw new G4(z4.InvalidParams,`Resource ${Q} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler($K(Ov)),this.server.assertCanSetRequestHandler($K(Lv)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ov,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,X])=>X.enabled).map(([X,Y])=>{return{name:X,title:Y.title,description:Y.description,arguments:Y.argsSchema?_E6(Y.argsSchema):void 0}})})),this.server.setRequestHandler(Lv,async(X,Y)=>{let Q=this._registeredPrompts[X.params.name];if(!Q)throw new G4(z4.InvalidParams,`Prompt ${X.params.name} not found`);if(!Q.enabled)throw new G4(z4.InvalidParams,`Prompt ${X.params.name} disabled`);if(Q.argsSchema){let J=lq(Q.argsSchema),G=await tS(J,X.params.arguments);if(!G.success){let K="error"in G?G.error:"Unknown error",$=eS(K);throw new G4(z4.InvalidParams,`Invalid arguments for prompt ${X.params.name}: ${$}`)}let Z=G.data,W=Q.callback;return await Promise.resolve(W(Z,Y))}else{let J=Q.callback;return await Promise.resolve(J(Y))}}),this._promptHandlersInitialized=!0}resource(X,Y,...Q){let J;if(typeof Q[0]==="object")J=Q.shift();let G=Q[0];if(typeof Y==="string"){if(this._registeredResources[Y])throw Error(`Resource ${Y} is already registered`);let Z=this._createRegisteredResource(X,void 0,Y,J,G);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),Z}else{if(this._registeredResourceTemplates[X])throw Error(`Resource template ${X} is already registered`);let Z=this._createRegisteredResourceTemplate(X,void 0,Y,J,G);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),Z}}registerResource(X,Y,Q,J){if(typeof Y==="string"){if(this._registeredResources[Y])throw Error(`Resource ${Y} is already registered`);let G=this._createRegisteredResource(X,Q.title,Y,Q,J);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),G}else{if(this._registeredResourceTemplates[X])throw Error(`Resource template ${X} is already registered`);let G=this._createRegisteredResourceTemplate(X,Q.title,Y,Q,J);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),G}}_createRegisteredResource(X,Y,Q,J,G){let Z={name:X,title:Y,metadata:J,readCallback:G,enabled:!0,disable:()=>Z.update({enabled:!1}),enable:()=>Z.update({enabled:!0}),remove:()=>Z.update({uri:null}),update:(W)=>{if(typeof W.uri<"u"&&W.uri!==Q){if(delete this._registeredResources[Q],W.uri)this._registeredResources[W.uri]=Z}if(typeof W.name<"u")Z.name=W.name;if(typeof W.title<"u")Z.title=W.title;if(typeof W.metadata<"u")Z.metadata=W.metadata;if(typeof W.callback<"u")Z.readCallback=W.callback;if(typeof W.enabled<"u")Z.enabled=W.enabled;this.sendResourceListChanged()}};return this._registeredResources[Q]=Z,Z}_createRegisteredResourceTemplate(X,Y,Q,J,G){let Z={resourceTemplate:Q,title:Y,metadata:J,readCallback:G,enabled:!0,disable:()=>Z.update({enabled:!1}),enable:()=>Z.update({enabled:!0}),remove:()=>Z.update({name:null}),update:($)=>{if(typeof $.name<"u"&&$.name!==X){if(delete this._registeredResourceTemplates[X],$.name)this._registeredResourceTemplates[$.name]=Z}if(typeof $.title<"u")Z.title=$.title;if(typeof $.template<"u")Z.resourceTemplate=$.template;if(typeof $.metadata<"u")Z.metadata=$.metadata;if(typeof $.callback<"u")Z.readCallback=$.callback;if(typeof $.enabled<"u")Z.enabled=$.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[X]=Z;let W=Q.uriTemplate.variableNames;if(Array.isArray(W)&&W.some(($)=>!!Q.completeCallback($)))this.setCompletionRequestHandler();return Z}_createRegisteredPrompt(X,Y,Q,J,G){let Z={title:Y,description:Q,argsSchema:J===void 0?void 0:l3(J),callback:G,enabled:!0,disable:()=>Z.update({enabled:!1}),enable:()=>Z.update({enabled:!0}),remove:()=>Z.update({name:null}),update:(W)=>{if(typeof W.name<"u"&&W.name!==X){if(delete this._registeredPrompts[X],W.name)this._registeredPrompts[W.name]=Z}if(typeof W.title<"u")Z.title=W.title;if(typeof W.description<"u")Z.description=W.description;if(typeof W.argsSchema<"u")Z.argsSchema=l3(W.argsSchema);if(typeof W.callback<"u")Z.callback=W.callback;if(typeof W.enabled<"u")Z.enabled=W.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[X]=Z,J){if(Object.values(J).some((K)=>{let $=K instanceof y9?K._def?.innerType:K;return x40($)}))this.setCompletionRequestHandler()}return Z}_createRegisteredTool(X,Y,Q,J,G,Z,W,K,$){g40(X);let H={title:Y,description:Q,inputSchema:A84(J),outputSchema:A84(G),annotations:Z,execution:W,_meta:K,handler:$,enabled:!0,disable:()=>H.update({enabled:!1}),enable:()=>H.update({enabled:!0}),remove:()=>H.update({name:null}),update:(F)=>{if(typeof F.name<"u"&&F.name!==X){if(typeof F.name==="string")g40(F.name);if(delete this._registeredTools[X],F.name)this._registeredTools[F.name]=H}if(typeof F.title<"u")H.title=F.title;if(typeof F.description<"u")H.description=F.description;if(typeof F.paramsSchema<"u")H.inputSchema=l3(F.paramsSchema);if(typeof F.outputSchema<"u")H.outputSchema=l3(F.outputSchema);if(typeof F.callback<"u")H.handler=F.callback;if(typeof F.annotations<"u")H.annotations=F.annotations;if(typeof F._meta<"u")H._meta=F._meta;if(typeof F.enabled<"u")H.enabled=F.enabled;this.sendToolListChanged()}};return this._registeredTools[X]=H,this.setToolRequestHandlers(),this.sendToolListChanged(),H}tool(X,...Y){if(this._registeredTools[X])throw Error(`Tool ${X} is already registered`);let Q,J,G,Z;if(typeof Y[0]==="string")Q=Y.shift();if(Y.length>1){let K=Y[0];if(m40(K)){if(J=Y.shift(),Y.length>1&&typeof Y[0]==="object"&&Y[0]!==null&&!m40(Y[0]))Z=Y.shift()}else if(typeof K==="object"&&K!==null)Z=Y.shift()}let W=Y[0];return this._createRegisteredTool(X,void 0,Q,J,G,Z,{taskSupport:"forbidden"},void 0,W)}registerTool(X,Y,Q){if(this._registeredTools[X])throw Error(`Tool ${X} is already registered`);let{title:J,description:G,inputSchema:Z,outputSchema:W,annotations:K,_meta:$}=Y;return this._createRegisteredTool(X,J,G,Z,W,K,{taskSupport:"forbidden"},$,Q)}prompt(X,...Y){if(this._registeredPrompts[X])throw Error(`Prompt ${X} is already registered`);let Q;if(typeof Y[0]==="string")Q=Y.shift();let J;if(Y.length>1)J=Y.shift();let G=Y[0],Z=this._createRegisteredPrompt(X,void 0,Q,J,G);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),Z}registerPrompt(X,Y,Q){if(this._registeredPrompts[X])throw Error(`Prompt ${X} is already registered`);let{title:J,description:G,argsSchema:Z}=Y,W=this._createRegisteredPrompt(X,J,G,Z,Q);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),W}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(X,Y){return this.server.sendLoggingMessage(X,Y)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}function j84(X){return X!==null&&typeof X==="object"&&"parse"in X&&typeof X.parse==="function"&&"safeParse"in X&&typeof X.safeParse==="function"}function kE6(X){return"_def"in X||"_zod"in X||j84(X)}function m40(X){if(typeof X!=="object"||X===null)return!1;if(kE6(X))return!1;if(Object.keys(X).length===0)return!0;return Object.values(X).some(j84)}function A84(X){if(!X)return;if(m40(X))return l3(X);return X}function _E6(X){let Y=jG(X);if(!Y)return[];return Object.entries(Y).map(([Q,J])=>{let G=Qs0(J),Z=Js0(J);return{name:Q,description:G,required:!Z}})}function $K(X){let Q=jG(X)?.method;if(!Q)throw Error("Schema is missing a method literal");let J=Xv(Q);if(typeof J==="string")return J;throw Error("Schema method literal must be a string")}function E84(X){return{completion:{values:X.slice(0,100),total:X.length,hasMore:X.length>100}}}var vE6,Iw;var I84=g(()=>{O84();dq();fe();zQ();P84();T84();o0();vE6={type:"object",properties:{}};Iw={completion:{values:[],hasMore:!1}}});class d40{constructor(X={}){this._started=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=X.sessionIdGenerator,this._enableJsonResponse=X.enableJsonResponse??!1,this._eventStore=X.eventStore,this._onsessioninitialized=X.onsessioninitialized,this._onsessionclosed=X.onsessionclosed,this._allowedHosts=X.allowedHosts,this._allowedOrigins=X.allowedOrigins,this._enableDnsRebindingProtection=X.enableDnsRebindingProtection??!1,this._retryInterval=X.retryInterval}async start(){if(this._started)throw Error("Transport already started");this._started=!0}createJsonErrorResponse(X,Y,Q,J){let G={code:Y,message:Q};if(J?.data!==void 0)G.data=J.data;return new Response(JSON.stringify({jsonrpc:"2.0",error:G,id:null}),{status:X,headers:{"Content-Type":"application/json",...J?.headers}})}validateRequestHeaders(X){if(!this._enableDnsRebindingProtection)return;if(this._allowedHosts&&this._allowedHosts.length>0){let Y=X.headers.get("host");if(!Y||!this._allowedHosts.includes(Y)){let Q=`Invalid Host header: ${Y}`;return this.onerror?.(Error(Q)),this.createJsonErrorResponse(403,-32000,Q)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let Y=X.headers.get("origin");if(Y&&!this._allowedOrigins.includes(Y)){let Q=`Invalid Origin header: ${Y}`;return this.onerror?.(Error(Q)),this.createJsonErrorResponse(403,-32000,Q)}}return}async handleRequest(X,Y){let Q=this.validateRequestHeaders(X);if(Q)return Q;switch(X.method){case"POST":return this.handlePostRequest(X,Y);case"GET":return this.handleGetRequest(X);case"DELETE":return this.handleDeleteRequest(X);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(X,Y,Q,J){if(!this._eventStore)return;if(J<"2025-11-25")return;let G=await this._eventStore.storeEvent(Q,{}),Z=`id: ${G}
387
387
  data:
@@ -406,7 +406,7 @@ ${Y.stack}`;return Q}try{let G=JSON.stringify(Y,null,2);if(G!=="{}"&&G.length<10
406
406
  Stack trace:
407
407
  ${Y.stack}`;return G}}catch{}if(typeof Y.toString==="function")try{let G=Y.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Y);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof X==="string")return X;if(typeof X==="number"||typeof X==="boolean")return String(X);if(typeof X==="function")return`[Function: ${X.name||"anon"}]`;if(typeof X==="symbol")return X.toString();if(typeof X==="bigint")return X.toString();try{return String(X)}catch{return"Unknown value (could not convert to string)"}}function IU(X,Y){switch(typeof Y){case"string":return X.newString(Y);case"number":return X.newNumber(Y);case"boolean":return Y?X.true:X.false;case"undefined":return X.undefined;case"object":{if(Y===null)return X.null;if(Array.isArray(Y)){let J=X.newArray();return Y.forEach((G,Z)=>{let W=IU(X,G);try{X.setProp(J,String(Z),W)}finally{W.dispose?.()}}),J}let Q=X.newObject();for(let[J,G]of Object.entries(Y)){let Z=IU(X,G);try{X.setProp(Q,J,Z)}finally{Z.dispose?.()}}return Q}case"function":{let Q=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return X.newFunction(Q,(...G)=>{try{let Z=G.map((K)=>X.dump(K)),W=Y(...Z);if(W&&typeof W.then==="function"){let K=X.newPromise();return W.then(($)=>{try{let H=IU(X,$);K.resolve(H),H.dispose(),X.runtime.executePendingJobs()}catch(H){let F=jU(H),V=X.newString(`Promise resolution error: ${F}`);K.reject(V),V.dispose(),X.runtime.executePendingJobs()}}).catch(($)=>{let H=jU($),F=X.newString(`Promise rejection: ${H}`);K.reject(F),F.dispose(),X.runtime.executePendingJobs()}),K.handle}return IU(X,W)}catch(Z){let W=jU(Z);return X.newString(`HostFunctionError: ${W}`)}finally{G.forEach((Z)=>Z.dispose())}})}case"bigint":return X.newString(Y.toString());case"symbol":return X.newString(Y.toString());default:try{return X.newString(String(Y))}catch{return X.undefined}}}var C94=()=>{};function S94(X){let Y=X.runtime.executePendingJobs(100);try{if("unwrap"in Y&&typeof Y.unwrap==="function")Y.unwrap()}finally{if("dispose"in Y&&typeof Y.dispose==="function")Y.dispose()}}async function R94(X,Y,Q){let J=Date.now(),G=X.resolvePromise(Y);while(!0){S94(X);let Z=await Promise.race([G,aE6(0).then(()=>null)]);if(Z!==null)return Z;if(Date.now()-J>Q)throw Error(`Timed out after ${Q}ms while awaiting a QuickJS promise`)}}async function U60({tools:X,code:Y,timeoutMs:Q}){let W=[];try{let J=await j94({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=$_(W,J.newContext({interruptAfterMs:Q}),0);const Z=$_(W,e84(G),0);try{let F=G.evalCode(Y,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=IU(G,X);G.setProp(G.global,"tools",q);let z=G.runtime.hasPendingJob()?G.unwrapResult(await R94(G,V,Q)):V;if(z!==V)V.dispose();let D=G.getProp(z,"default"),N=G.typeof(D);if(N!=="function")return{error:`Code must export default a function (tools). Got ${N}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:Z.logs};let O=G.callFunction(D,G.undefined,q),w=G.unwrapResult(O),E=await R94(G,w,Q),C=G.unwrapResult(E);if(G.runtime.hasPendingJob())S94(G);return{returnValue:G.dump(C),consoleLogs:Z.logs}}catch(F){return console.log(F),{error:jU(F),consoleLogs:Z.logs}}}catch(K){var $=K,H=1}finally{V10(W,$,H)}}var aE6=(X)=>new Promise((Y)=>setTimeout(Y,X));var v94=g(()=>{I94();C94()});var k94=g(()=>{v94()});async function rE6(X,Y){let Q;if(X.tool_selection_mode==="exclusion"){let G=(await Y.storage.connections.list(X.organization_id)).filter((W)=>W.status==="active"),Z=new Map;for(let W of X.connections)Z.set(W.connection_id,{selectedTools:W.selected_tools,selectedResources:W.selected_resources,selectedPrompts:W.selected_prompts});Q=[];for(let W of G){let K=Z.get(W.id);if(K===void 0)Q.push({connection:W,selectedTools:null,selectedResources:null,selectedPrompts:null});else if((K.selectedTools===null||K.selectedTools.length===0)&&(K.selectedResources===null||K.selectedResources.length===0)&&(K.selectedPrompts===null||K.selectedPrompts.length===0));else Q.push({connection:W,selectedTools:K.selectedTools,selectedResources:K.selectedResources,selectedPrompts:K.selectedPrompts})}}else{let J=X.connections.map((Z)=>Z.connection_id),G=[];for(let Z of J){let W=await Y.storage.connections.findById(Z);if(W&&W.status==="active")G.push(W)}Q=G.map((Z)=>{let W=X.connections.find((K)=>K.connection_id===Z.id);return{connection:Z,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}return Q}async function _94(X,Y){return(await Y.storage.connections.list(X)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function oE6(X,Y,Q){let J=await ik.create(X,Q),G=await J.mapSettled(async(F,V)=>{try{let z=(await F.proxy.client.listTools()).tools;if(Y==="exclusion"){if(F.selectedTools&&F.selectedTools.length>0){let D=new Set(F.selectedTools);z=z.filter((N)=>!D.has(N.name))}}else if(F.selectedTools&&F.selectedTools.length>0){let D=new Set(F.selectedTools);z=z.filter((N)=>D.has(N.name))}return{connectionId:V,connectionTitle:F.connection.title,tools:z}}catch(q){return console.error(`[code-execution] Failed to list tools for connection ${V}:`,q),null}}),Z=new Set,W=[],K=new Map,$=new Set;for(let F of G){if(F.status!=="fulfilled"||!F.value)continue;let{connectionId:V,connectionTitle:q,tools:z}=F.value;$.add(q);for(let D of z){if(Z.has(D.name))continue;Z.add(D.name),W.push({...D,_meta:{connectionId:V,connectionTitle:q}}),K.set(D.name,{connectionId:V,originalName:D.name})}}return{tools:W,callTool:async(F,V)=>{let q=K.get(F);if(!q)return{content:[{type:"text",text:`Tool not found: ${F}`}],isError:!0};let z=J.get(q.connectionId);if(!z)return{content:[{type:"text",text:`Connection not found for tool: ${F}`}],isError:!0};return await z.proxy.client.callTool({name:q.originalName,arguments:V})},categories:Array.from($).sort()}}async function CU(X){let Y=j4(X),Q,J="inclusion";if(X.connectionId){let G=await X.storage.virtualMcps.findById(X.connectionId);if(G)Q=await rE6(G,X),J=G.tool_selection_mode;else Q=await _94(Y.id,X)}else Q=await _94(Y.id,X);return oE6(Q,J,X)}function sE6(X){return X.toLowerCase().split(/[\s_\-./]+/).filter((Y)=>Y.length>=2)}function tE6(X,Y){let Q=0,J=Y.name.toLowerCase(),G=(Y.description??"").toLowerCase(),Z=Y._meta.connectionTitle.toLowerCase();for(let W of X){if(J===W)Q+=10;else if(J.includes(W))Q+=3;if(G.includes(W))Q+=2;if(Z.includes(W))Q+=1}return Q}function y94(X,Y,Q){let J=sE6(X);if(J.length===0)return Y.slice(0,Q);return Y.map((G)=>({tool:G,score:tE6(J,G)})).filter((G)=>G.score>0).sort((G,Z)=>Z.score-G.score).slice(0,Q).map((G)=>G.tool)}function f94(X,Y){let Q=new Map(Y.map((G)=>[G.name,G]));return{tools:X.map((G)=>Q.get(G)).filter((G)=>G!==void 0).map((G)=>({name:G.name,description:G.description,connection:G._meta.connectionTitle,inputSchema:G.inputSchema,outputSchema:G.outputSchema})),notFound:X.filter((G)=>!Q.has(G))}}async function b94(X,Y,Q){let J=Object.fromEntries(Y.tools.map((G)=>[G.name,async(Z)=>Y.callTool(G.name,Z??{})]));return U60({code:X,tools:J,timeoutMs:Q})}var sk=g(()=>{k94()});var z60;var h94=g(()=>{s4();Cw();sk();z60=r0({name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling CODE_EXECUTION_DESCRIBE_TOOLS for detailed schemas.",inputSchema:i84,outputSchema:a84,handler:async(X,Y)=>{H4(Y),j4(Y),await Y.access.check();let Q=await CU(Y),J=y94(X.query,Q.tools,X.limit);return{query:X.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta.connectionTitle})),totalAvailable:Q.tools.length}}})});var B60;var x94=g(()=>{s4();Cw();sk();B60=r0({name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after CODE_EXECUTION_SEARCH_TOOLS to get full input/output schemas before executing code.",inputSchema:r84,outputSchema:o84,handler:async(X,Y)=>{H4(Y),j4(Y),await Y.access.check();let Q=await CU(Y);return f94(X.tools,Q.tools)}})});var D60;var g94=g(()=>{s4();Cw();sk();D60=r0({name:"CODE_EXECUTION_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use CODE_EXECUTION_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',inputSchema:s84,outputSchema:t84,handler:async(X,Y)=>{H4(Y),j4(Y),await Y.access.check();let Q=await CU(Y);return await b94(X.code,Q,X.timeoutMs)}})});var u94=g(()=>{h94();x94();g94();Cw()});var Xj6,Yj6,N60;var m94=g(()=>{V40();o0();s4();ck();ZK();Xj6=L.object({data:B14.describe("Data for the new connection (id is auto-generated if not provided)")}),Yj6=L.object({item:NJ.describe("The created connection entity")}),N60=r0({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:Xj6,outputSchema:Yj6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(Y);if(!J)throw Error("User ID required to create connection");let G={...X.data,organization_id:Q.id,created_by:J};if(G.connection_type==="VIRTUAL"){let $=xk(G.connection_url);if(!$)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let H=await Y.storage.virtualMcps.findById($);if(!H)throw Error(`Virtual MCP not found: ${$}`);if(H.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=gk($)}let Z=await TU({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),W=Z?.length?Z:null,K=await Y.storage.connections.create({...G,tools:W});return await Y.eventBus.publish(Q.id,s3.SELF(Q.id),{type:"connection.created",data:K}),{item:K}}})});function Sw(X,Y){if(X===Y)return!0;if(X==null||Y==null)return X===Y;if(typeof X!==typeof Y)return!1;if(Array.isArray(X)&&Array.isArray(Y)){if(X.length!==Y.length)return!1;return X.every((Q,J)=>Sw(Q,Y[J]))}if(typeof X==="object"&&typeof Y==="object"){let Q=Object.keys(X),J=Object.keys(Y);if(Q.length!==J.length)return!1;return Q.every((G)=>J.includes(G)&&Sw(X[G],Y[G]))}return!1}function Aj6(){return(X)=>{if(!Array.isArray(X))return!0;let Y=[];return X.every((Q)=>{if(Y.some((G)=>Sw(Q,G)))return!1;return Y.push(Q),!0})}}function tk(X,Y){return X.safeParse(Y).success}function XX(X){if(typeof X==="boolean")return X?L.any():L.never();let Y={};for(let G of xj6)G.apply(Y,X);let Q=[];if(Y.string!==!1)Q.push(Y.string||L.string());if(Y.number!==!1)Q.push(Y.number||L.number());if(Y.boolean!==!1)Q.push(Y.boolean||L.boolean());if(Y.null!==!1)Q.push(Y.null||L.null());if(Y.array!==!1)Q.push(Y.array||L.array(L.any()));if(Y.tuple!==!1&&Y.tuple!==void 0)Q.push(Y.tuple);if(Y.object!==!1)if(Y.object)Q.push(Y.object);else{let G=L.custom((Z)=>{return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)},"Must be an object, not an array");Q.push(G)}if(Y.file!==!1&&Y.file!==void 0)Q.push(Y.file);let J;if(Q.length===0)J=L.never();else if(Q.length===1)J=Q[0];else if(!Object.keys(X).some((Z)=>Z!=="$schema"&&Z!=="title"&&Z!=="description"))J=L.any();else J=L.union(Q);for(let G of gj6)J=G.apply(J,X);return J}var Qj6=class{apply(X,Y){if(!Y.type)return;let Q=Array.isArray(Y.type)?Y.type:[Y.type],J=new Set(Q);if(!J.has("string"))X.string=!1;if(!J.has("number")&&!J.has("integer"))X.number=!1;if(!J.has("boolean"))X.boolean=!1;if(!J.has("null"))X.null=!1;if(!J.has("array"))X.array=!1;if(!J.has("object"))X.object=!1;if(J.has("integer")&&X.number!==!1){let G=X.number||L.number();if(G instanceof L.ZodNumber)X.number=G.int()}}},Jj6=class{apply(X,Y){if(Y.const===void 0)return;let Q=Y.const;if(X.string=!1,X.number=!1,X.boolean=!1,X.null=!1,X.array=!1,X.object=!1,typeof Q==="string")X.string=L.literal(Q);else if(typeof Q==="number")X.number=L.literal(Q);else if(typeof Q==="boolean")X.boolean=L.literal(Q);else if(Q===null)X.null=L.null();else if(Array.isArray(Q))X.array=void 0;else if(typeof Q==="object")X.object=void 0}},Gj6=class{apply(X,Y){if(!Y.enum)return;if(Y.enum.length===0){if(!Y.type)X.string=!1,X.number=!1,X.boolean=!1,X.null=!1,X.array=!1,X.object=!1;return}let Q={string:Y.enum.filter((J)=>typeof J==="string"),number:Y.enum.filter((J)=>typeof J==="number"),boolean:Y.enum.filter((J)=>typeof J==="boolean"),null:Y.enum.filter((J)=>J===null),array:Y.enum.filter((J)=>Array.isArray(J)),object:Y.enum.filter((J)=>typeof J==="object"&&J!==null&&!Array.isArray(J))};X.string=this.createTypeSchema(Q.string,"string"),X.number=this.createTypeSchema(Q.number,"number"),X.boolean=this.createTypeSchema(Q.boolean,"boolean"),X.null=Q.null.length>0?L.null():!1,X.array=Q.array.length>0?void 0:!1,X.object=Q.object.length>0?void 0:!1}createTypeSchema(X,Y){if(X.length===0)return!1;if(X.length===1)return L.literal(X[0]);if(Y==="string")return L.enum(X);if(Y==="number"){let[Q,J,...G]=X;return L.union([L.literal(Q),L.literal(J),...G.map((Z)=>L.literal(Z))])}if(Y==="boolean")return L.union([L.literal(!0),L.literal(!1)]);return!1}},Wj6=class{apply(X,Y){let Q=Y;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let J=L.file();if(Q.minLength!==void 0)J=J.min(Q.minLength);if(Q.maxLength!==void 0)J=J.max(Q.maxLength);if(Q.contentMediaType!==void 0)J=J.mime(Q.contentMediaType);X.file=J,X.string=!1}}},Zj6=class{apply(X,Y){let Q=Y;if(Y.type===void 0&&(Q.minLength!==void 0||Q.maxLength!==void 0||Q.pattern!==void 0)){if(X.string===void 0)X.string=L.string()}}},Kj6=class{apply(X,Y){let Q=Y;if(Q.minLength===void 0)return;if(X.string!==!1){let J=X.string||L.string();if(J instanceof L.ZodString)X.string=J.refine((G)=>{return Array.from(G).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},$j6=class{apply(X,Y){let Q=Y;if(Q.maxLength===void 0)return;if(X.string!==!1){let J=X.string||L.string();if(J instanceof L.ZodString)X.string=J.refine((G)=>{return Array.from(G).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},Hj6=class{apply(X,Y){let Q=Y;if(!Q.pattern)return;if(X.string!==!1){let J=X.string||L.string();if(J instanceof L.ZodString){let G=new RegExp(Q.pattern);X.string=J.regex(G)}}}},Fj6=class{apply(X,Y){let Q=Y;if(Q.minimum===void 0)return;if(X.number!==!1){let J=X.number||L.number();if(J instanceof L.ZodNumber)X.number=J.min(Q.minimum)}}},Vj6=class{apply(X,Y){let Q=Y;if(Q.maximum===void 0)return;if(X.number!==!1){let J=X.number||L.number();if(J instanceof L.ZodNumber)X.number=J.max(Q.maximum)}}},qj6=class{apply(X,Y){let Q=Y;if(Q.exclusiveMinimum===void 0)return;if(X.number!==!1){let J=X.number||L.number();if(J instanceof L.ZodNumber)if(typeof Q.exclusiveMinimum==="number")X.number=J.gt(Q.exclusiveMinimum);else X.number=!1}}},Uj6=class{apply(X,Y){let Q=Y;if(Q.exclusiveMaximum===void 0)return;if(X.number!==!1){let J=X.number||L.number();if(J instanceof L.ZodNumber)if(typeof Q.exclusiveMaximum==="number")X.number=J.lt(Q.exclusiveMaximum);else X.number=!1}}},zj6=class{apply(X,Y){let Q=Y;if(Q.multipleOf===void 0)return;if(X.number!==!1){let J=X.number||L.number();if(J instanceof L.ZodNumber)X.number=J.refine((G)=>{if(Q.multipleOf===0)return!1;let Z=G/Q.multipleOf,W=Math.round(Z),K=Math.min(Math.abs(G)*Number.EPSILON*10,Math.abs(Q.multipleOf)*Number.EPSILON*10);return Math.abs(Z-W)<=K/Math.abs(Q.multipleOf)},{message:`Must be a multiple of ${Q.multipleOf}`})}}},Bj6=class{apply(X,Y){let Q=Y;if(Y.type===void 0&&(Q.minItems!==void 0||Q.maxItems!==void 0||Q.items!==void 0||Q.prefixItems!==void 0)){if(X.array===void 0)X.array=L.array(L.any())}}},Dj6=class{apply(X,Y){let Q=Y;if(Q.minItems===void 0)return;if(X.array!==!1)X.array=(X.array||L.array(L.any())).min(Q.minItems)}},Nj6=class{apply(X,Y){let Q=Y;if(Q.maxItems===void 0)return;if(X.array!==!1)X.array=(X.array||L.array(L.any())).max(Q.maxItems)}},Oj6=class{apply(X,Y){let Q=Y;if(X.array===!1)return;if(Array.isArray(Q.items))X.array=X.array||L.array(L.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let J=XX(Q.items),G=L.array(J);if(X.array&&X.array instanceof L.ZodArray){let Z=X.array._def;if(Z.checks)Z.checks.forEach((W)=>{if(W._zod&&W._zod.def){let K=W._zod.def;if(K.check==="min_length"&&K.minimum!==void 0)G=G.min(K.minimum);else if(K.check==="max_length"&&K.maximum!==void 0)G=G.max(K.maximum)}})}X.array=G}else if(typeof Q.items==="boolean"&&Q.items===!1)if(!Q.prefixItems)X.array=L.array(L.any()).max(0);else X.array=X.array||L.array(L.any());else if(typeof Q.items==="boolean"&&Q.items===!0)X.array=X.array||L.array(L.any());else if(Q.prefixItems)X.array=X.array||L.array(L.any())}},Lj6=class{apply(X,Y){if(Y.type!=="array")return;let Q=Y;if(!Array.isArray(Q.items))return;if(X.array===!1)return;let J=Q.items.map((Z)=>XX(Z)),G;if(J.length===0)G=L.tuple([]);else G=L.tuple(J);if(Q.minItems!==void 0&&Q.minItems>J.length)G=!1;if(Q.maxItems!==void 0&&Q.maxItems<J.length)G=!1;X.tuple=G,X.array=!1}},wj6=class{apply(X,Y){let Q=Y;if(X.object===!1)return;if(Q.properties||Q.required||Q.additionalProperties!==void 0)X.object=X.object||L.object({}).passthrough()}},Mj6=class{apply(X,Y){let Q=Y;if(Y.type===void 0&&(Q.maxProperties!==void 0||Q.minProperties!==void 0)){if(X.object===void 0)X.object=L.object({}).passthrough()}}},Pj6=class{apply(X,Y){let Q=Y;if(Q.maxProperties===void 0)return;if(X.object!==!1){let J=X.object||L.object({}).passthrough();X.object=J.refine((G)=>Object.keys(G).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},Tj6=class{apply(X,Y){let Q=Y;if(Q.minProperties===void 0)return;if(X.object!==!1){let J=X.object||L.object({}).passthrough();X.object=J.refine((G)=>Object.keys(G).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},Ej6=class{apply(X,Y){if(!Y.not)return X;let Q=XX(Y.not);return X.refine((J)=>!tk(Q,J),{message:"Value must not match the 'not' schema"})}},jj6=class{apply(X,Y){if(Y.uniqueItems!==!0)return X;return X.refine(Aj6(),{message:"Array items must be unique"})}},Ij6=class{apply(X,Y){if(!Y.allOf||Y.allOf.length===0)return X;return Y.allOf.map((J)=>XX(J)).reduce((J,G)=>L.intersection(J,G),X)}},Cj6=class{apply(X,Y){if(!Y.anyOf||Y.anyOf.length===0)return X;let Q=Y.anyOf.length===1?XX(Y.anyOf[0]):L.union([XX(Y.anyOf[0]),XX(Y.anyOf[1]),...Y.anyOf.slice(2).map((J)=>XX(J))]);return L.intersection(X,Q)}},Rj6=class{apply(X,Y){if(!Y.oneOf||Y.oneOf.length===0)return X;let Q=Y.oneOf.map((J)=>XX(J));return X.refine((J)=>{let G=0;for(let Z of Q)if(Z.safeParse(J).success){if(G++,G>1)return!1}return G===1},{message:"Value must match exactly one of the oneOf schemas"})}},Sj6=class{apply(X,Y){let Q=Y;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((Z)=>XX(Z));return X.refine((Z)=>{if(!Array.isArray(Z))return!0;for(let W=0;W<Math.min(Z.length,G.length);W++)if(!tk(G[W],Z[W]))return!1;if(Z.length>G.length){if(typeof Q.items==="boolean"&&Q.items===!1)return!1;else if(Q.items&&typeof Q.items==="object"&&!Array.isArray(Q.items)){let W=XX(Q.items);for(let K=G.length;K<Z.length;K++)if(!tk(W,Z[K]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return X}},vj6=class{apply(X,Y){let Q=Y;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return X;if(X instanceof L.ZodObject||X instanceof L.ZodRecord){let J={};if(Q.properties){for(let[G,Z]of Object.entries(Q.properties))if(Z!==void 0)J[G]=XX(Z)}if(Q.required&&Array.isArray(Q.required)){let G=new Set(Q.required);for(let Z of Object.keys(J))if(!G.has(Z))J[Z]=J[Z].optional()}else for(let G of Object.keys(J))J[G]=J[G].optional();if(Q.additionalProperties===!1)return L.object(J);else return L.object(J).passthrough()}return X.refine((J)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return!0;if(Q.properties){for(let[G,Z]of Object.entries(Q.properties))if(Z!==void 0){if(Object.getOwnPropertyDescriptor(J,G)!==void 0){if(!XX(Z).safeParse(J[G]).success)return!1}}}if(Q.required&&Array.isArray(Q.required)){for(let G of Q.required)if(Object.getOwnPropertyDescriptor(J,G)===void 0)return!1}if(Q.additionalProperties===!1&&Q.properties){let G=new Set(Object.keys(Q.properties));for(let Z in J)if(!G.has(Z))return!1}return!0},{message:"Object constraints validation failed"})}},kj6=class{apply(X,Y){if(!Y.enum||Y.enum.length===0)return X;let Q=Y.enum.filter((J)=>Array.isArray(J)||typeof J==="object"&&J!==null);if(Q.length===0)return X;return X.refine((J)=>{if(typeof J!=="object"||J===null)return!0;return Q.some((G)=>Sw(J,G))},{message:"Value must match one of the enum values"})}},_j6=class{apply(X,Y){if(Y.const===void 0)return X;let Q=Y.const;if(typeof Q!=="object"||Q===null)return X;return X.refine((J)=>Sw(J,Q),{message:"Value must equal the const value"})}},yj6=class{apply(X,Y){if(Y.description)X=X.describe(Y.description);return X}},fj6=class{apply(X,Y){var Q;let J=Y;if(!((Q=J.required)==null?void 0:Q.includes("__proto__"))||Y.type!==void 0)return X;return L.any().refine((G)=>this.validateRequired(G,J.required),{message:"Missing required properties"})}validateRequired(X,Y){if(typeof X!=="object"||X===null||Array.isArray(X))return!0;return Y.every((Q)=>Object.prototype.hasOwnProperty.call(X,Q))}},bj6=class{apply(X,Y){var Q;let J=Y;if(J.contains===void 0)return X;let G=XX(J.contains),Z=(Q=J.minContains)!=null?Q:1,W=J.maxContains;return X.refine((K)=>{if(!Array.isArray(K))return!0;let $=0;for(let H of K)if(tk(G,H))$++;if($<Z)return!1;if(W!==void 0&&$>W)return!1;return!0},{message:"Array must contain required items matching the schema"})}},hj6=class{apply(X,Y){let{default:Q}=Y;if(Q===void 0)return X;if(!X.safeParse(Q).success)return X;return X.default(Q)}},xj6,gj6;var l94=g(()=>{O9();O9();O9();O9();O9();O9();O9();O9();O9();O9();O9();O9();O9();O9();xj6=[new Jj6,new Gj6,new Qj6,new Wj6,new Zj6,new Bj6,new Mj6,new Kj6,new $j6,new Hj6,new Fj6,new Vj6,new qj6,new Uj6,new zj6,new Lj6,new Dj6,new Nj6,new Oj6,new Pj6,new Tj6,new wj6],gj6=[new fj6,new kj6,new _j6,new Ij6,new Cj6,new Rj6,new Sj6,new vj6,new bj6,new Ej6,new jj6,new hj6,new yj6]});class O60{constructor(X){this._url=X}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((X,Y)=>{this._socket=new WebSocket(this._url,uj6),this._socket.onerror=(Q)=>{let J="error"in Q?Q.error:Error(`WebSocket error: ${JSON.stringify(Q)}`);Y(J),this.onerror?.(J)},this._socket.onopen=()=>{X()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(Q)=>{let J;try{J=UQ.parse(JSON.parse(Q.data))}catch(G){this.onerror?.(G);return}this.onmessage?.(J)}})}async close(){this._socket?.close()}send(X){return new Promise((Y,Q)=>{if(!this._socket){Q(Error("Not connected"));return}this._socket?.send(JSON.stringify(X)),Y()})}}var uj6="mcp";var d94=g(()=>{zQ()});function mj6(X){let Y=X;if(!Y||typeof Y!=="object"||!("method"in Y))return null;switch(Y.method){case"initialize":{let Q=Y?.params?.protocolVersion;if(!Q)return null;return{type:"emit",message:{result:{protocolVersion:Q,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:Y.jsonrpc??"2.0",id:Y.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var L60;var p94=g(()=>{yk();L60=class L60 extends qU{constructor(X,Y){super(X,Y)}send(X,Y){let Q=mj6(X);if(Q?.type==="emit")return this.onmessage?.(Q.message),Promise.resolve();if(Q?.type==="suppress")return Promise.resolve();return super.send(X,Y)}}});var c94,n94=async(X,Y,Q)=>{let J=lj6(X.connection,Y,Q);if(!J)throw Error("Unknown MCP connection type");let G=new c94({name:X?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(Z,W)=>{if(X.connection.type!=="HTTP")throw Error("HTTP connection required");let K=new Headers(Q);if(!K.has("Authorization"))K.set("Authorization",`Bearer ${X.connection.token}`);for(let[F,V]of Object.entries(X.connection.headers??{}))K.set(F,V);let $=new URL(X.connection.url),H=$.pathname.replace(/\/+$/,"")||"/";return $.pathname=`${H}/call-tool/${encodeURIComponent(Z)}`,fetch($.href,{method:"POST",redirect:"manual",body:JSON.stringify(W),headers:K})}}},lj6=(X,Y,Q)=>{if(X.type==="Websocket")return new O60(new URL(X.url));if(X.type!=="SSE"&&X.type!=="HTTP")return null;let G={...X.token?{authorization:`Bearer ${X.token}`}:{},...Q??{},..."headers"in X?X.headers||{}:{}};if(X.type==="SSE"){let Z={requestInit:{headers:G,signal:Y}};if(X.token)Z.eventSourceInit={fetch:(W,K)=>{return fetch(W,{...K,headers:{...G,Accept:"text/event-stream"},signal:Y})}};return new jw(new URL(X.url),Z)}return new L60(new URL(X.url),{requestInit:{headers:G,signal:Y,credentials:"include"}})};var i94=g(()=>{Lk();A40();d94();zQ();p94();c94=class c94 extends GK{constructor(X,Y){super(X,Y)}async listTools(X,Y){return await this.request({method:"tools/list",params:X},cL,Y)}}});function r94(X){let Y=(Q)=>{if("connection"in X)return n94({connection:X.connection},void 0,Q);return X.client};return new Proxy({},{get(Q,J){if(J==="toJSON")return null;if(typeof J!=="string")throw Error("Name must be a string");if(J==="listTools")return K;async function G($,H=J){let F=X?.debugId?.(),V=F?{"x-trace-debug-id":F}:void 0,{client:q,callStreamableTool:z}=await Y(V);if(X?.streamable?.[String(H)])return z(String(H),$);let{structuredContent:D,isError:N,content:O}=await q.callTool({name:String(H),arguments:$});if(N){let w=O?.[0]?.text,E=typeof w==="string"?dj6(w):null,C=E?.code&&typeof X?.getErrorByStatusCode==="function"?X.getErrorByStatusCode(E.code,E.message,E.traceId):null;if(C)throw C;throw Error(`Tool ${String(H)} returned an error: ${JSON.stringify(D??O)}`)}return D}async function Z(){let{client:$}=await Y(),{tools:H}=await $.listTools();return H}async function W(){if(!("connection"in X))return Z();let $=X.connection,H=JSON.stringify($);try{if(!ek.has(H))ek.set(H,Z());return await ek.get(H)}catch(F){console.error("Failed to list tools",F),ek.delete(H);return}}async function K(){return(await W()??[]).map((H)=>a94(H,G))}return G.asTool=async()=>{let H=(await W()??[]).find((F)=>F.name===J);if(!H)throw Error(`Tool ${J} not found`);return a94(H,G)},G}})}var dj6=(X)=>{try{return JSON.parse(X)}catch{return X}},ek,a94=(X,Y)=>{return{...X,id:X.name,inputSchema:X.inputSchema?XX(X.inputSchema):void 0,outputSchema:X.outputSchema?XX(X.outputSchema):void 0,execute:(Q)=>{return Y(Q.context,X.name)}}};var o94=g(()=>{l94();i94();ek=new Map});function X_(X){return r94(X)}var _j1;var s94=g(()=>{o94();_j1=new Proxy({},{get(X,Y){if(Y==="toJSON")return null;if(Y==="forConnection")return(Q)=>X_({connection:Q});return global[Y]}})});function Y_(X){return{isImplementedBy:(Y)=>{for(let Q of X){let J=typeof Q.name==="string"?new RegExp(`^${Q.name}$`):Q.name,G=Y.find((Z)=>J.test(Z.name));if(!G&&Q.opt)continue;if(!G)return!1}return!0}}}var JH=(X)=>{return{...Y_(X),forClient:(Y)=>{return X_({client:Y,streamable:X.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(Y)=>{return X_({connection:Y,streamable:X.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var vw=g(()=>{s94()});var w60,xj1;var t94=g(()=>{LL();w60=U1(OL(),1),xj1=w60.createContext(null)});function WH(X){return L.object({items:L.array(X).describe("Array of collection items"),totalCount:L.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:L.boolean().optional().describe("Whether there are more items available")})}function _w(X){return L.object({item:X.nullable().describe("The retrieved item, or null if not found")})}function nj6(X){return L.object({data:X.partial().describe("Data for the new entity (id may be auto-generated)")})}function ij6(X){return L.object({item:X.describe("The created entity with generated id")})}function aj6(X){return L.object({id:L.string().describe("ID of the entity to update"),data:X.partial().describe("Partial entity data to update")})}function rj6(X){return L.object({item:X.describe("The updated entity")})}function fw(X){return L.object({item:X.describe("The deleted entity")})}function SU(X,Y,Q){let J=X.toUpperCase(),G=Q?.readOnly??!1,Z=[{name:`COLLECTION_${J}_LIST`,inputSchema:GH,outputSchema:WH(Y)},{name:`COLLECTION_${J}_GET`,inputSchema:kw,outputSchema:_w(Y)}];if(!G)Z.push({name:`COLLECTION_${J}_CREATE`,inputSchema:nj6(Y),outputSchema:ij6(Y),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:aj6(Y),outputSchema:rj6(Y),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:yw,outputSchema:fw(Y),opt:!0});return Z}var RU,pj6,e94,cj6,GH,kw,yw;var F5=g(()=>{o0();RU=L.object({id:L.string().describe("Unique identifier for the entity"),title:L.string().describe("Human-readable title for the entity"),description:L.string().nullish().describe("Description of the entity"),created_at:L.string().datetime(),updated_at:L.string().datetime(),created_by:L.string().optional(),updated_by:L.string().optional()}),pj6=L.object({field:L.array(L.string()),operator:L.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:L.unknown()}),e94=L.lazy(()=>L.union([pj6,L.object({operator:L.enum(["and","or","not"]),conditions:L.array(e94)})])),cj6=L.object({field:L.array(L.string()),direction:L.enum(["asc","desc"]),nulls:L.enum(["first","last"]).optional()}),GH=L.object({where:e94.optional().describe("Filter expression"),orderBy:L.array(cj6).optional().describe("Sort expressions"),limit:L.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:L.number().int().min(0).optional().describe("Number of items to skip")});kw=L.object({id:L.string().describe("ID of the entity to retrieve")});yw=L.object({id:L.string().describe("ID of the entity to delete")})});var oj6,XX4,cj1;var YX4=g(()=>{o0();F5();oj6=L.object({id:L.string(),name:L.string(),description:L.string().optional(),inputSchema:L.record(L.string(),L.unknown()),outputSchema:L.record(L.string(),L.unknown()).optional()}),XX4=RU.extend({_meta:L.object({"io.decocms":L.object({id:L.string(),verified:L.boolean(),scopeName:L.string(),appName:L.string(),friendlyName:L.string().nullable().optional(),metadata:L.record(L.string(),L.unknown()).nullable().optional(),publishedAt:L.string().datetime().optional(),updatedAt:L.string().datetime().optional(),tools:L.array(oj6).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:L.object({$schema:L.string().optional(),_meta:L.record(L.string(),L.unknown()).optional(),name:L.string().describe("The server name (scope/app)"),title:L.string().optional().describe("User-friendly title"),description:L.string().optional().describe("Server description"),icons:L.array(L.object({src:L.string(),mimeType:L.string().optional(),sizes:L.array(L.string()).optional(),theme:L.enum(["light","dark"]).optional()})).optional(),remotes:L.array(L.object({type:L.enum(["http","stdio","sse"]),url:L.string().optional(),headers:L.array(L.unknown()).optional()})).optional(),packages:L.array(L.unknown()).optional(),repository:L.object({url:L.string(),source:L.string().optional(),subfolder:L.string().optional()}).optional(),version:L.string().optional(),websiteUrl:L.string().optional()})}),cj1=SU("registry_app",XX4,{readOnly:!0})});var QX4,JX4,GX4,WX4,ZX4,sj6;var KX4=g(()=>{o0();vw();QX4=L.object({specversion:L.literal("1.0").describe("CloudEvents specification version"),id:L.string().describe("Unique identifier for this event (UUID recommended)"),source:L.string().describe("Connection ID of the event publisher"),type:L.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:L.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:L.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:L.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:L.string().url().optional().describe("URI to the schema for the data attribute"),data:L.unknown().optional().describe("Event payload (any JSON value)")}),JX4=L.object({events:L.array(QX4).min(1).describe("Batch of CloudEvents to process")}),GX4=L.object({success:L.boolean().optional().describe("Whether this event was processed successfully"),error:L.string().optional().describe("Error message for this event"),retryAfter:L.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),WX4=L.object({success:L.boolean().optional().describe("Batch success - applies to events not in results"),error:L.string().optional().describe("Batch error message - applies to events not in results"),processedCount:L.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:L.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:L.record(L.string(),GX4).optional().describe("Per-event results keyed by event ID")}),ZX4=[{name:"ON_EVENTS",inputSchema:JX4,outputSchema:WX4}],sj6=JH(ZX4)});var bw,hw,xw,gw,$X4,HX4,uw,mw,lw,dw,pw,cw,nw,iw,FX4,tj6;var VX4=g(()=>{o0();vw();bw=L.object({type:L.string().min(1).max(255).describe("Event type identifier"),subject:L.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:L.unknown().optional().describe("Event payload"),deliverAt:L.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:L.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),hw=L.object({id:L.string().describe("Unique event ID"),type:L.string().describe("Event type"),source:L.string().describe("Source connection ID"),time:L.string().describe("Event timestamp")}),xw=L.object({eventType:L.string().min(1).max(255).describe("Event type to subscribe to"),publisher:L.string().optional().describe("Filter events by publisher connection ID"),filter:L.string().max(1000).optional().describe("JSONPath filter expression on event data")}),gw=L.object({subscription:L.object({id:L.string().describe("Subscription ID"),connectionId:L.string().describe("Subscriber connection ID"),eventType:L.string().describe("Event type pattern"),publisher:L.string().nullable().describe("Publisher connection filter"),filter:L.string().nullable().describe("JSONPath filter expression"),enabled:L.boolean().describe("Whether subscription is enabled"),createdAt:L.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:L.string().datetime().describe("Updated timestamp (ISO 8601)")})}),$X4=L.object({eventType:L.string().min(1).max(255).describe("Event type to subscribe to"),publisher:L.string().optional().describe("Filter events by publisher connection ID"),filter:L.string().max(1000).optional().describe("JSONPath filter expression on event data")}),HX4=L.object({id:L.string().describe("Subscription ID"),connectionId:L.string().describe("Subscriber connection ID"),eventType:L.string().describe("Event type pattern"),publisher:L.string().nullable().describe("Publisher connection filter"),filter:L.string().nullable().describe("JSONPath filter expression"),enabled:L.boolean().describe("Whether subscription is enabled"),createdAt:L.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:L.string().datetime().describe("Updated timestamp (ISO 8601)")}),uw=L.object({subscriptions:L.array($X4).describe("Desired subscriptions - system will create/update/delete to match")}),mw=L.object({created:L.number().int().min(0).describe("Number of subscriptions created"),updated:L.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:L.number().int().min(0).describe("Number of subscriptions removed"),unchanged:L.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:L.array(HX4).describe("Current subscriptions after sync")}),lw=L.object({subscriptionId:L.string().describe("Subscription ID to remove")}),dw=L.object({success:L.boolean().describe("Whether unsubscribe was successful"),subscriptionId:L.string().describe("Subscription ID that was removed")}),pw=L.object({eventId:L.string().describe("Event ID to cancel")}),cw=L.object({success:L.boolean().describe("Whether cancellation was successful"),eventId:L.string().describe("Event ID that was cancelled")}),nw=L.object({eventId:L.string().describe("Event ID to acknowledge")}),iw=L.object({success:L.boolean().describe("Whether ACK was successful"),eventId:L.string().describe("Event ID that was acknowledged")}),FX4=[{name:"EVENT_PUBLISH",inputSchema:bw,outputSchema:hw},{name:"EVENT_SUBSCRIBE",inputSchema:xw,outputSchema:gw},{name:"EVENT_UNSUBSCRIBE",inputSchema:lw,outputSchema:dw},{name:"EVENT_CANCEL",inputSchema:pw,outputSchema:cw},{name:"EVENT_ACK",inputSchema:nw,outputSchema:iw},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:uw,outputSchema:mw}],tj6=JH(FX4)});var XI1,YI1,QI1,JI1,GI1,WI1,ZI1,KI1,$I1,HI1,FI1,VI1;var qX4=g(()=>{o0();XI1=L.object({prefix:L.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:L.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:L.string().optional().describe("Token for pagination from previous response"),delimiter:L.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),YI1=L.object({objects:L.array(L.object({key:L.string().describe("Object key/path"),size:L.number().describe("Object size in bytes"),lastModified:L.string().describe("Last modified timestamp"),etag:L.string().describe("Entity tag for the object")})),nextContinuationToken:L.string().optional().describe("Token for fetching next page of results"),isTruncated:L.boolean().describe("Whether there are more results available"),commonPrefixes:L.array(L.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),QI1=L.object({key:L.string().describe("Object key/path to get metadata for")}),JI1=L.object({contentType:L.string().optional().describe("MIME type of the object"),contentLength:L.number().describe("Size of the object in bytes"),lastModified:L.string().describe("Last modified timestamp"),etag:L.string().describe("Entity tag for the object"),metadata:L.record(L.string(),L.string()).optional().describe("Custom metadata key-value pairs")}),GI1=L.object({key:L.string().describe("Object key/path to generate URL for"),expiresIn:L.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),WI1=L.object({url:L.string().describe("Presigned URL for downloading the object"),expiresIn:L.number().describe("Expiration time in seconds that was used")}),ZI1=L.object({key:L.string().describe("Object key/path for the upload"),expiresIn:L.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:L.string().optional().describe("MIME type for the object being uploaded")}),KI1=L.object({url:L.string().describe("Presigned URL for uploading the object"),expiresIn:L.number().describe("Expiration time in seconds that was used")}),$I1=L.object({key:L.string().describe("Object key/path to delete")}),HI1=L.object({success:L.boolean().describe("Whether the deletion was successful"),key:L.string().describe("The key that was deleted")}),FI1=L.object({keys:L.array(L.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),VI1=L.object({deleted:L.array(L.string()).describe("Array of successfully deleted keys"),errors:L.array(L.object({key:L.string(),message:L.string()})).describe("Array of errors for failed deletions")})});var M60=g(()=>{vw();t94();YX4();KX4();VX4();qX4()});var ej6,XI6,UX4;var zX4=g(()=>{o0();F5();ej6=RU.extend({avatar:L.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:L.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:L.string().describe("Virtual MCP ID to use for this assistant"),model:L.object({id:L.string().describe("Model ID"),connectionId:L.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),XI6=SU("assistant",ej6),UX4=[...XI6]});var aw,JW,DX4,YI6,QI6,NX4,JI6,GI6,WI6,ZI6,KI6,$I6,OX4,HI6,FI6,VI6,qI6,UI6,zI6,BI6,DI6,NI6,OI6,vI1,LI6,kI1,BX4,wI6,MI6,P60,_I1;var LX4=g(()=>{o0();vw();F5();aw=L.lazy(()=>L.union([L.null(),L.string(),L.number(),L.boolean(),L.record(L.string(),aw),L.array(aw)])),JW=L.record(L.string(),L.record(L.string(),aw)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),DX4=L.object({type:L.literal("text"),text:L.string().describe("The text content"),providerOptions:JW}),YI6=L.object({type:L.literal("text"),text:L.string().describe("The text content"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata")}),QI6=L.string().describe("File data as URL string"),NX4=L.object({type:L.literal("file"),filename:L.string().optional().describe("Optional filename of the file"),data:QI6,mediaType:L.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:JW}),JI6=L.object({type:L.literal("file"),mediaType:L.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:L.string().describe("Generated file data as base64 encoded string")}),GI6=L.object({type:L.literal("reasoning"),text:L.string().describe("The reasoning text"),providerOptions:JW}),WI6=L.object({type:L.literal("reasoning"),text:L.string().describe("The reasoning text"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata")}),ZI6=L.object({type:L.literal("tool-call"),toolCallId:L.string().describe("ID of the tool call, used to match with tool result"),toolName:L.string().describe("Name of the tool being called"),input:L.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:L.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:JW}),KI6=L.object({type:L.literal("tool-call"),toolCallId:L.string().describe("ID of the tool call"),toolName:L.string().describe("Name of the tool being called"),input:L.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:L.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata")}),$I6=L.union([L.object({type:L.literal("text"),value:L.string()}),L.object({type:L.literal("json"),value:aw}),L.object({type:L.literal("error-text"),value:L.string()}),L.object({type:L.literal("error-json"),value:aw}),L.object({type:L.literal("content"),value:L.array(L.union([L.object({type:L.literal("text"),text:L.string().describe("Text content")}),L.object({type:L.literal("media"),data:L.string().describe("Base-64 encoded media data"),mediaType:L.string().describe("IANA media type")})]))})]),OX4=L.object({type:L.literal("tool-result"),toolCallId:L.string().describe("ID of the tool call that this result is associated with"),toolName:L.string().describe("Name of the tool that generated this result"),output:$I6.describe("Result of the tool call"),result:L.unknown().describe("Unknown result of the tool call"),providerOptions:JW}),HI6=L.object({type:L.literal("tool-result"),toolCallId:L.string().describe("ID of the tool call that this result is associated with"),toolName:L.string().describe("Name of the tool that generated this result"),result:L.any().describe("Result of the tool call (JSON-serializable)"),isError:L.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:L.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata")}),FI6=L.union([L.object({type:L.literal("source"),sourceType:L.literal("url"),id:L.string().describe("The ID of the source"),url:L.string().describe("The URL of the source"),title:L.string().optional().describe("The title of the source"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata")}),L.object({type:L.literal("source"),sourceType:L.literal("document"),id:L.string().describe("The ID of the source"),mediaType:L.string().describe("IANA media type of the document (e.g., application/pdf)"),title:L.string().describe("The title of the document"),filename:L.string().optional().describe("Optional filename of the document"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata")})]),VI6=L.object({role:L.literal("system"),content:L.string().describe("System message content"),providerOptions:JW}),qI6=L.object({role:L.literal("user"),content:L.array(L.union([DX4,NX4])).describe("User message content parts (text or file)"),providerOptions:JW}),UI6=L.object({role:L.literal("assistant"),content:L.array(L.union([DX4,NX4,GI6,ZI6,OX4])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:JW}),zI6=L.object({role:L.literal("tool"),content:L.array(OX4).describe("Tool message content (tool results)"),providerOptions:JW}),BI6=L.union([VI6,qI6,UI6,zI6]),DI6=L.array(BI6).describe("A list of messages forming the prompt"),NI6=L.object({prompt:DI6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:L.number().optional().describe("Maximum number of tokens to generate"),temperature:L.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:L.number().optional().describe("Nucleus sampling parameter"),topK:L.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:L.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:L.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:L.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:L.array(L.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:L.union([L.object({type:L.literal("text")}),L.object({type:L.literal("json"),schema:L.any().optional().describe("JSON schema that the generated output should conform to"),name:L.string().optional().describe("Name of output that should be generated"),description:L.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:L.array(L.any()).optional().describe("The tools that are available for the model"),toolChoice:L.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:L.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:L.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:L.any().optional().describe("Additional provider-specific options")}),OI6=L.object({content:L.array(L.union([YI6,JI6,WI6,KI6,HI6,FI6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:L.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:L.looseObject({inputTokens:L.number().optional(),outputTokens:L.number().optional(),totalTokens:L.number().optional(),reasoningTokens:L.number().optional()}).describe("Usage information for the language model call"),providerMetadata:L.any().optional().describe("Additional provider-specific metadata"),request:L.object({body:L.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:L.object({id:L.string().optional().describe("ID for the generated response"),timestamp:L.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:L.string().optional().describe("The ID of the response model that was used"),headers:L.record(L.string(),L.string()).optional().describe("Response headers"),body:L.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:L.array(L.any()).describe("Warnings for the call, e.g. unsupported settings")}),vI1=L.object({stream:L.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:L.object({body:L.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:L.object({headers:L.record(L.string(),L.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),LI6=L.object({supportedUrls:L.record(L.string(),L.array(L.string())).describe("Supported URL patterns by media type for the provider")}),kI1=L.object({modelId:L.string().describe("The ID of the model"),logo:L.string().nullable(),description:L.string().nullable(),capabilities:L.array(L.string()),limits:L.object({contextWindow:L.number(),maxOutputTokens:L.number()}).nullable(),costs:L.object({input:L.number(),output:L.number()}).nullable(),provider:L.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),BX4=L.object({modelId:L.string().describe("The ID of the model"),callOptions:NI6}),wI6=RU.extend({logo:L.string().nullable(),description:L.string().nullable(),capabilities:L.array(L.string()),limits:L.object({contextWindow:L.number(),maxOutputTokens:L.number()}).nullable(),costs:L.object({input:L.number(),output:L.number()}).nullable(),provider:L.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),MI6=SU("llm",wI6,{readOnly:!0}),P60=[{name:"LLM_METADATA",inputSchema:L.object({modelId:L.string().describe("The ID of the model")}),outputSchema:LI6},{name:"LLM_DO_STREAM",inputSchema:BX4,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:BX4,outputSchema:OI6},...MI6],_I1=JH(P60)});function TI6(X){let Y=[],Q=0;while(Q<X.length){let J=X[Q];if(J==="%")Y.push(".*");else if(J==="_")Y.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Y.push("\\"+J);else Y.push(J);Q++}return Y.join("")}function FK(X){return typeof X==="string"||typeof X==="number"}function Q_(X,Y){if("conditions"in Y){let{operator:K,conditions:$}=Y;switch(K){case"and":return $.every((H)=>Q_(X,H));case"or":return $.some((H)=>Q_(X,H));case"not":return!$.every((H)=>Q_(X,H));default:return!0}}let{field:Q,operator:J,value:G}=Y,Z=Q.join("."),W=T60(X,Z);switch(J){case"eq":return W===G;case"gt":return FK(W)&&FK(G)&&W>G;case"gte":return FK(W)&&FK(G)&&W>=G;case"lt":return FK(W)&&FK(G)&&W<G;case"lte":return FK(W)&&FK(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let K=TI6(G);return new RegExp(`^${K}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function T60(X,Y){let Q=Y.split("."),J=X;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function AI6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let Z=G.field.join("."),W=T60(Q,Z),K=T60(J,Z),$=0;if(W==null&&K==null)continue;if(W==null)$=G.nulls==="first"?-1:1;else if(K==null)$=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof K==="string")$=W.localeCompare(K);else if(typeof W==="number"&&typeof K==="number")$=W-K;else $=String(W).localeCompare(String(K));if($!==0)return G.direction==="desc"?-$:$}return 0})}var PI6,EI6,jI6,A60;var wX4=g(()=>{M60();zX4();F5();LX4();o0();s4();ZK();PI6={LLM:P60,ASSISTANTS:UX4};EI6=GH.extend({binding:L.union([L.object({}).passthrough(),L.string()]).optional()}),jI6=WH(NJ),A60=r0({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:EI6,outputSchema:jI6,handler:async(X,Y)=>{await Y.access.check();let Q=j4(Y),J=X.binding?typeof X.binding==="string"?(()=>{let z=PI6[X.binding.toUpperCase()];if(!z)throw Error(`Unknown binding: ${X.binding}`);return z})():X.binding:void 0,G=J?Y_(J):void 0,W=(await Y.storage.connections.list(Q.id)).filter((z)=>z.connection_type!=="VIRTUAL"),K=G?await Promise.all(W.map(async(z)=>{if(!z.tools||z.tools.length===0)return null;return G.isImplementedBy(z.tools.map((N)=>({name:N.name,inputSchema:N.inputSchema,outputSchema:N.outputSchema})))?z:null})).then((z)=>z.filter((D)=>D!==null)):W;if(X.where)K=K.filter((z)=>Q_(z,X.where));if(X.orderBy&&X.orderBy.length>0)K=AI6(K,X.orderBy);let $=K.length,H=X.offset??0,F=X.limit??100,V=K.slice(H,H+F),q=H+F<$;return{items:V,totalCount:$,hasMore:q}}})});var II6,E60;var MX4=g(()=>{F5();s4();ZK();II6=_w(NJ),E60=r0({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:kw,outputSchema:II6,handler:async(X,Y)=>{let Q=j4(Y);await Y.access.check();let J=await Y.storage.connections.findById(X.id);if(!J||J.organization_id!==Q.id)return{item:null};return{item:J}}})});var J_=(X,Y)=>{if(Y===null||Y===void 0)return;let Q=X.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Y;for(let G of Q){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function PX4(X){let Y=X.split("::");if(Y.length!==2||!Y[0]||!Y[1])throw Error(`Invalid scope format: ${X}. Expected format: "KEY::SCOPE"`);return Y}function CI6(X){let Y=X.split("::");if(Y.length!==2||!Y[0]||!Y[1])return null;return Y}function RI6(X){if(typeof X==="object"&&X!==null&&"value"in X){let Y=X.value;if(typeof Y==="string")return Y}return null}function SI6(X,Y){let Q={};if(!X||!Y)return Q;for(let J of Y){if(J==="*"){Q["*"]=["*"];continue}let G=CI6(J);if(!G)continue;let[Z,W]=G,K=J_(Z,X),$=RI6(K);if($){if(!Q[$])Q[$]=[];Q[$].push(W)}}return Q}function TX4(X,Y){let Q=SI6(X,Y);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var AX4=()=>{};class j60{db;vault;constructor(X,Y){this.db=X;this.vault=Y}async get(X){let Y=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",X).executeTakeFirst();if(!Y)return null;return this.decryptToken(Y)}async upsert(X){let Y=new Date().toISOString(),Q=await this.vault.encrypt(X.accessToken),J=X.refreshToken?await this.vault.encrypt(X.refreshToken):null,G=X.clientSecret?await this.vault.encrypt(X.clientSecret):null;return await this.db.transaction().execute(async(Z)=>{let W=await Z.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",X.connectionId).executeTakeFirst();if(W)return await Z.updateTable("downstream_tokens").set({accessToken:Q,refreshToken:J,scope:X.scope,expiresAt:X.expiresAt?.toISOString()??null,clientId:X.clientId,clientSecret:G,tokenEndpoint:X.tokenEndpoint,updatedAt:Y}).where("id","=",W.id).execute(),{id:W.id,connectionId:X.connectionId,accessToken:X.accessToken,refreshToken:X.refreshToken,scope:X.scope,expiresAt:X.expiresAt,createdAt:W.createdAt,updatedAt:Y,clientId:X.clientId,clientSecret:X.clientSecret,tokenEndpoint:X.tokenEndpoint};let K=zU("dtok");return await Z.insertInto("downstream_tokens").values({id:K,connectionId:X.connectionId,accessToken:Q,refreshToken:J,scope:X.scope,expiresAt:X.expiresAt?.toISOString()??null,clientId:X.clientId,clientSecret:G,tokenEndpoint:X.tokenEndpoint,createdAt:Y,updatedAt:Y}).execute(),{id:K,connectionId:X.connectionId,accessToken:X.accessToken,refreshToken:X.refreshToken,scope:X.scope,expiresAt:X.expiresAt,createdAt:Y,updatedAt:Y,clientId:X.clientId,clientSecret:X.clientSecret,tokenEndpoint:X.tokenEndpoint}})}async delete(X){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",X).execute()}isExpired(X,Y=0){if(!X.expiresAt)return!1;let J=(X.expiresAt instanceof Date?X.expiresAt:new Date(X.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Y<Date.now()}async decryptToken(X){let Y=await this.vault.decrypt(X.accessToken),Q=X.refreshToken?await this.vault.decrypt(X.refreshToken):null,J=X.clientSecret?await this.vault.decrypt(X.clientSecret):null;return{id:X.id,connectionId:X.connectionId,accessToken:Y,refreshToken:Q,scope:X.scope,expiresAt:X.expiresAt,createdAt:X.createdAt,updatedAt:X.updatedAt,clientId:X.clientId,clientSecret:J,tokenEndpoint:X.tokenEndpoint}}}var EX4=g(()=>{uk()});async function _I6(X,Y,Q,J){for(let Z of Y){if(Z==="*")continue;let[W]=PX4(Z),K=J_(W,X);if(K===void 0||K===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let G=TX4(X,Y);for(let Z of G){if(Z.endsWith("_self"))continue;let W=await J.storage.connections.findById(Z);if(!W||W.organization_id!==Q)throw Error(`Referenced connection not found: ${Z}`);try{await J.access.check(Z)}catch(K){throw Error(`Access denied to referenced connection: ${Z}. ${K.message}`)}}}var vI6,kI6,I60;var jX4=g(()=>{AX4();EX4();o0();s4();ck();ZK();vI6=L.object({id:L.string().describe("ID of the connection to update"),data:D14.describe("Partial connection data to update")}),kI6=L.object({item:NJ.describe("The updated connection entity")});I60=r0({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:vI6,outputSchema:kI6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);if(await Y.access.check(),!E8(Y))throw Error("User ID required to update connection");let{id:G,data:Z}=X,W=await Y.storage.connections.findById(G);if(!W||W.organization_id!==Q.id)throw Error("Connection not found in organization");let K=Z.connection_type??W.connection_type,$=Z.connection_url??W.connection_url;if(K==="VIRTUAL"){let O=xk($);if(!O)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let w=await Y.storage.virtualMcps.findById(O);if(!w)throw Error(`Virtual MCP not found: ${O}`);if(w.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");$=gk(O)}let H=Z.configuration_state??W.configuration_state,F=Z.configuration_scopes??W.configuration_scopes??[];if(Z.configuration_state!==void 0||Z.configuration_scopes!==void 0){if(Z.configuration_state!==void 0)H=Z.configuration_state;else if(H===null)H={};if(Z.configuration_scopes!==void 0)F=Z.configuration_scopes??[];if(F.length>0&&H)await _I6(H,F,Q.id,Y)}let V=Z.connection_token??W.connection_token;if(!V)try{let w=await new j60(Y.db,Y.vault).get(G);if(w?.accessToken)V=w.accessToken}catch{}let q=await TU({id:W.id,title:Z.title??W.title,connection_type:K,connection_url:$,connection_token:V,connection_headers:Z.connection_headers??W.connection_headers}).catch(()=>null),z=q?.length?q:null,D={...Z,connection_url:$,tools:z,configuration_state:H,configuration_scopes:F},N=await Y.storage.connections.update(G,D);if((Z.configuration_state!==void 0||Z.configuration_scopes!==void 0)&&H&&F.length>0)try{await(await Y.createMCPProxy(G)).client.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:H,scopes:F}})}catch(O){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",O)}return{item:N}}})});var C60;var IX4=g(()=>{F5();s4();ZK();C60=r0({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:yw,outputSchema:fw(NJ),handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=await Y.storage.connections.findById(X.id);if(!J)throw Error(`Connection not found: ${X.id}`);if(J.organization_id!==Q.id)throw Error("Connection not found in organization");return await Y.storage.connections.delete(X.id),{item:J}}})});var R60;var CX4=g(()=>{o0();s4();R60=r0({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:L.object({id:L.string()}),outputSchema:L.object({id:L.string(),healthy:L.boolean(),latencyMs:L.number()}),handler:async(X,Y)=>{let Q=j4(Y);await Y.access.check();let J=await Y.storage.connections.findById(X.id);if(!J||J.organization_id!==Q.id)throw Error("Connection not found");let G=await Y.storage.connections.testConnection(X.id);return{id:X.id,...G}}})});var RX4=g(()=>{m94();wX4();MX4();jX4();IX4();CX4()});import{sql as p6}from"kysely";function SX4(X){if(X===null||X===void 0)return"NULL";if(typeof X==="number")return String(X);if(typeof X==="boolean")return X?"TRUE":"FALSE";if(typeof X==="string")return`'${X.replace(/'/g,"''")}'`;if(X instanceof Date)return`'${X.toISOString()}'`;return`'${JSON.stringify(X).replace(/'/g,"''")}'`}function bI6(X,Y){let Q=X;for(let G=Y.length;G>=1;G--){let Z=`$${G}`;if(Q.includes(Z))Q=Q.replaceAll(Z,SX4(Y[G-1]))}let J=[];for(let G=0;G<Q.length;G++)if(Q[G]==="?")J.push(G);for(let G=Math.min(J.length,Y.length)-1;G>=0;G--){let Z=J[G],W=SX4(Y[G]);Q=Q.slice(0,Z)+W+Q.slice(Z+1)}return Q}function vX4(X){return X.replace(/-/g,"_")}function xI6(X){return`app_${vX4(X)}`}function gI6(X){return`app_role_${vX4(X)}`}function uI6(X){if(X instanceof Error){let Y=X.message.toLowerCase(),Q=X.code;return Q==="3F000"||Q==="42704"||Y.includes("schema")&&Y.includes("does not exist")||Y.includes("role")&&Y.includes("does not exist")}return!1}async function mI6(X,Y,Q){if(await p6`CREATE SCHEMA IF NOT EXISTS ${p6.id(Y)}`.execute(X),!(await p6`
408
408
  SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${Q}) as exists
409
- `.execute(X)).rows[0]?.exists)await p6`CREATE ROLE ${p6.id(Q)} NOLOGIN`.execute(X);await p6`GRANT ${p6.id(Q)} TO CURRENT_USER`.execute(X),await p6`GRANT USAGE, CREATE ON SCHEMA ${p6.id(Y)} TO ${p6.id(Q)}`.execute(X),await p6`GRANT ALL ON ALL TABLES IN SCHEMA ${p6.id(Y)} TO ${p6.id(Q)}`.execute(X),await p6`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${p6.id(Y)} TO ${p6.id(Q)}`.execute(X),await p6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${p6.id(Y)} GRANT ALL ON TABLES TO ${p6.id(Q)}`.execute(X),await p6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${p6.id(Y)} GRANT ALL ON SEQUENCES TO ${p6.id(Q)}`.execute(X),await p6`REVOKE ALL ON SCHEMA public FROM ${p6.id(Q)}`.execute(X)}async function lI6(X,Y,Q,J){try{return await X.transaction().execute(async(G)=>{return await p6`SET LOCAL ROLE ${p6.id(Q)}`.execute(G),await p6`SET LOCAL search_path TO ${p6.id(Y)}`.execute(G),await p6.raw(J).execute(G)})}catch(G){if(uI6(G))return await mI6(X,Y,Q),await X.transaction().execute(async(Z)=>{return await p6`SET LOCAL ROLE ${p6.id(Q)}`.execute(Z),await p6`SET LOCAL search_path TO ${p6.id(Y)}`.execute(Z),await p6.raw(J).execute(Z)});throw G}}var fI6,hI6,kX4;var _X4=g(()=>{o0();s4();fI6=L.object({results:L.array(L.unknown()).optional(),success:L.boolean().optional()});hI6=L.object({sql:L.string().describe("The SQL query to run"),params:L.array(L.any()).describe("The parameters to pass to the SQL query").optional()});kX4=r0({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:hI6,outputSchema:L.object({result:L.array(fI6)}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=bI6(X.sql,X.params||[]);if(!Y.connectionId)throw Error("Connection context required for database access");let J=xI6(Y.connectionId),G=gI6(Y.connectionId);return{result:[{results:(await lI6(Y.db,J,G,Q)).rows,success:!0}]}}})});var yX4,pI6,fX4;var GW=g(()=>{o0();M60();yX4=L.object({connectionId:L.string().optional().describe("Filter subscriptions by connection ID (optional)")}),pI6=L.object({id:L.string().describe("Subscription ID"),connectionId:L.string().describe("Subscriber connection ID"),eventType:L.string().describe("Event type pattern"),publisher:L.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:L.string().nullable().describe("JSONPath filter expression"),enabled:L.boolean().describe("Whether subscription is enabled"),createdAt:L.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:L.string().datetime().describe("Updated timestamp (ISO 8601)")}),fX4=L.object({subscriptions:L.array(pI6).describe("List of subscriptions")})});var S60;var bX4=g(()=>{s4();GW();S60=r0({name:"EVENT_PUBLISH",description:"Publish an event to the event bus. Supports immediate, scheduled (deliverAt), and recurring (cron) delivery. The source is automatically set to the caller's connection ID.",inputSchema:bw,outputSchema:hw,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await Y.eventBus.publish(Q.id,J,{type:X.type,subject:X.subject,data:X.data,deliverAt:X.deliverAt,cron:X.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var v60;var hX4=g(()=>{s4();GW();v60=r0({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:xw,outputSchema:gw,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await Y.eventBus.subscribe(Q.id,{connectionId:J,eventType:X.eventType,publisher:X.publisher,filter:X.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var k60;var xX4=g(()=>{s4();GW();k60=r0({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:lw,outputSchema:dw,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await Y.eventBus.getSubscription(Q.id,X.subscriptionId);if(!G)throw Error(`Subscription not found: ${X.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await Y.eventBus.unsubscribe(Q.id,X.subscriptionId)).success,subscriptionId:X.subscriptionId}}})});var _60;var gX4=g(()=>{s4();GW();_60=r0({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:pw,outputSchema:cw,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await Y.eventBus.getEvent(Q.id,X.eventId))throw Error(`Event not found: ${X.eventId}`);if(!(await Y.eventBus.cancelEvent(Q.id,X.eventId,J)).success)throw Error("Failed to cancel event. Either the event is already completed/failed, or you are not the publisher.");return{success:!0,eventId:X.eventId}}})});var y60;var uX4=g(()=>{s4();GW();y60=r0({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:nw,outputSchema:iw,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await Y.eventBus.ackEvent(Q.id,X.eventId,J)).success)throw Error("Failed to acknowledge event. Either the event was not found, already delivered, or you are not a subscriber.");return{success:!0,eventId:X.eventId}}})});var f60;var mX4=g(()=>{s4();GW();f60=r0({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:yX4,outputSchema:fX4,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);return await Y.access.check(),{subscriptions:(await Y.eventBus.listSubscriptions(Q.id,X.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}))}}})});var b60;var lX4=g(()=>{s4();GW();b60=r0({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:uw,outputSchema:mw,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await Y.eventBus.syncSubscriptions(Q.id,{connectionId:J,subscriptions:X.subscriptions});return{created:G.created,updated:G.updated,deleted:G.deleted,unchanged:G.unchanged,subscriptions:G.subscriptions.map((Z)=>({id:Z.id,connectionId:Z.connectionId,eventType:Z.eventType,publisher:Z.publisher,filter:Z.filter,enabled:Z.enabled,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt,updatedAt:Z.updatedAt instanceof Date?Z.updatedAt.toISOString():Z.updatedAt}))}}})});var dX4=g(()=>{bX4();hX4();xX4();gX4();uX4();mX4();lX4();GW()});var h60,nI6,vG,pX4,cX4;var vU=g(()=>{o0();h60=L.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),nI6=L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:L.array(L.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:L.array(L.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),vG=L.object({id:L.string().describe("Unique identifier for the virtual MCP"),title:L.string().describe("Human-readable name for the virtual MCP"),description:L.string().nullable().describe("Description of the virtual MCP"),icon:L.string().nullable().optional().describe("Icon URL for the virtual MCP"),created_at:L.string().describe("When the virtual MCP was created"),updated_at:L.string().describe("When the virtual MCP was last updated"),created_by:L.string().describe("User ID who created the virtual MCP"),updated_by:L.string().optional().describe("User ID who last updated the virtual MCP"),organization_id:L.string().describe("Organization ID this virtual MCP belongs to"),tool_selection_mode:h60.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:L.enum(["active","inactive"]).describe("Current status"),connections:L.array(nI6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),pX4=L.object({title:L.string().min(1).max(255).describe("Name for the virtual MCP"),description:L.string().nullable().optional().describe("Optional description"),tool_selection_mode:h60.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:L.string().nullable().optional().describe("Optional icon URL"),status:L.enum(["active","inactive"]).optional().default("active").describe("Initial status"),connections:L.array(L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:L.array(L.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:L.array(L.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).describe("Connections to include/exclude (can be empty for exclusion mode)")}),cX4=L.object({title:L.string().min(1).max(255).optional().describe("New name"),description:L.string().nullable().optional().describe("New description (null to clear)"),tool_selection_mode:h60.optional().describe("New tool selection mode"),icon:L.string().nullable().optional().describe("New icon URL (null to clear)"),status:L.enum(["active","inactive"]).optional().describe("New status"),connections:L.array(L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:L.array(L.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:L.array(L.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var iI6,aI6,x60;var nX4=g(()=>{o0();s4();vU();iI6=L.object({data:pX4.describe("Data for the new virtual MCP")}),aI6=L.object({item:vG.describe("The created virtual MCP entity")}),x60=r0({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new MCP virtual MCP in the organization",inputSchema:iI6,outputSchema:aI6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(Y);if(!J)throw Error("User ID required to create virtual MCP");return{item:await Y.storage.virtualMcps.create(Q.id,J,X.data)}}})});function rI6(X){let Y=[],Q=0;while(Q<X.length){let J=X[Q];if(J==="%")Y.push(".*");else if(J==="_")Y.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Y.push("\\"+J);else Y.push(J);Q++}return Y.join("")}function VK(X){return typeof X==="string"||typeof X==="number"}function g60(X,Y){let Q=Y.split("."),J=X;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function oI6(X,Y){return X.connections.some((Q)=>Q.connection_id===Y)}function G_(X,Y){if("conditions"in Y){let{operator:K,conditions:$}=Y;switch(K){case"and":return $.every((H)=>G_(X,H));case"or":return $.some((H)=>G_(X,H));case"not":return!$.every((H)=>G_(X,H));default:return!0}}let{field:Q,operator:J,value:G}=Y,Z=Q.join(".");if(Z==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return oI6(X,G)}let W=g60(X,Z);switch(J){case"eq":return W===G;case"gt":return VK(W)&&VK(G)&&W>G;case"gte":return VK(W)&&VK(G)&&W>=G;case"lt":return VK(W)&&VK(G)&&W<G;case"lte":return VK(W)&&VK(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let K=rI6(G);return new RegExp(`^${K}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function sI6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let Z=G.field.join("."),W=g60(Q,Z),K=g60(J,Z),$=0;if(W==null&&K==null)continue;if(W==null)$=G.nulls==="first"?-1:1;else if(K==null)$=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof K==="string")$=W.localeCompare(K);else if(typeof W==="number"&&typeof K==="number")$=W-K;else $=String(W).localeCompare(String(K));if($!==0)return G.direction==="desc"?-$:$}return 0})}var tI6,eI6,u60;var iX4=g(()=>{F5();s4();vU();tI6=GH,eI6=WH(vG),u60=r0({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",inputSchema:tI6,outputSchema:eI6,handler:async(X,Y)=>{await Y.access.check();let Q=j4(Y),J=X.where&&!("conditions"in X.where)&&X.where.field.join(".")==="connection_id"&&X.where.operator==="eq"&&typeof X.where.value==="string"?X.where.value:void 0,Z=J?await Y.storage.virtualMcps.listByConnectionId(Q.id,J):await Y.storage.virtualMcps.list(Q.id);if(X.where)Z=Z.filter((V)=>G_(V,X.where));if(X.orderBy&&X.orderBy.length>0)Z=sI6(Z,X.orderBy);let W=Z.length,K=X.offset??0,$=X.limit??100,H=Z.slice(K,K+$),F=K+$<W;return{items:H,totalCount:W,hasMore:F}}})});var XC6,YC6,m60;var aX4=g(()=>{o0();s4();vU();XC6=L.object({id:L.string().describe("ID of the virtual MCP to retrieve")}),YC6=L.object({item:vG.nullable().describe("The retrieved virtual MCP, or null if not found")}),m60=r0({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",inputSchema:XC6,outputSchema:YC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=await Y.storage.virtualMcps.findById(X.id);if(J&&J.organization_id!==Q.id)return{item:null};if(!J)return{item:null};return{item:J}}})});var QC6,JC6,l60;var rX4=g(()=>{o0();s4();vU();QC6=L.object({id:L.string().describe("ID of the virtual MCP to update"),data:cX4.describe("Partial virtual MCP data to update")}),JC6=L.object({item:vG.describe("The updated virtual MCP entity")}),l60=r0({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",inputSchema:QC6,outputSchema:JC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(Y);if(!J)throw Error("User ID required to update virtual MCP");let G=await Y.storage.virtualMcps.findById(X.id);if(!G)throw Error(`Virtual MCP not found: ${X.id}`);if(G.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${X.id}`);return{item:await Y.storage.virtualMcps.update(X.id,J,X.data)}}})});var GC6,WC6,d60;var oX4=g(()=>{o0();s4();vU();GC6=L.object({id:L.string().describe("ID of the virtual MCP to delete")}),WC6=L.object({item:vG.describe("The deleted virtual MCP entity")}),d60=r0({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",inputSchema:GC6,outputSchema:WC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=await Y.storage.virtualMcps.findById(X.id);if(!J)throw Error(`Virtual MCP not found: ${X.id}`);if(J.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${X.id}`);return await Y.storage.virtualMcps.delete(X.id),{item:J}}})});var sX4=g(()=>{nX4();iX4();aX4();rX4();oX4()});var KC6,p60;var tX4=g(()=>{s4();o0();KC6=L.object({id:L.string().optional().describe("Unique log identifier"),organizationId:L.string().describe("Organization ID"),connectionId:L.string().describe("Connection ID"),connectionTitle:L.string().describe("Connection display name"),toolName:L.string().describe("Name of the tool that was called"),input:L.record(L.string(),L.unknown()).describe("Redacted tool input"),output:L.record(L.string(),L.unknown()).describe("Redacted tool output"),isError:L.boolean().describe("Whether the call resulted in an error"),errorMessage:L.string().nullish().describe("Error message if applicable"),durationMs:L.number().describe("Call duration in milliseconds"),timestamp:L.string().describe("ISO 8601 timestamp of the call"),userId:L.string().nullish().describe("User who triggered the call"),requestId:L.string().describe("Unique request identifier"),userAgent:L.string().nullish().describe("Client identifier (x-mesh-client header)"),virtualMcpId:L.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:L.record(L.string(),L.string()).nullish().describe("Custom key-value metadata attached to the log")}),p60=r0({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:L.object({connectionId:L.string().optional().describe("Filter by connection ID"),virtualMcpId:L.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:L.string().optional().describe("Filter by tool name"),isError:L.boolean().optional().describe("Filter by error status"),startDate:L.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:L.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:L.number().default(100).describe("Maximum number of results"),offset:L.number().default(0).describe("Offset for pagination"),properties:L.record(L.string(),L.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:L.array(L.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:L.record(L.string(),L.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)")}),outputSchema:L.object({logs:L.array(KC6).describe("Array of monitoring logs"),total:L.number().describe("Total number of logs matching filters"),offset:L.number().describe("Current offset for pagination"),limit:L.number().describe("Current limit for pagination")}),handler:async(X,Y)=>{let Q=j4(Y),G=X.properties||X.propertyKeys||X.propertyPatterns?{properties:X.properties,propertyKeys:X.propertyKeys,propertyPatterns:X.propertyPatterns}:void 0,Z={organizationId:Q.id,connectionId:X.connectionId,virtualMcpId:X.virtualMcpId,toolName:X.toolName,isError:X.isError,startDate:X.startDate?new Date(X.startDate):void 0,endDate:X.endDate?new Date(X.endDate):void 0,limit:X.limit,offset:X.offset,propertyFilters:G},W=await Y.storage.monitoring.query(Z);return{logs:W.logs.map((K)=>({...K,timestamp:K.timestamp instanceof Date?K.timestamp.toISOString():K.timestamp})),total:W.total,offset:X.offset,limit:X.limit}}})});var c60;var eX4=g(()=>{s4();o0();c60=r0({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:L.object({startDate:L.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:L.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:L.object({totalCalls:L.number().describe("Total number of tool calls"),errorRate:L.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:L.number().describe("Average call duration in milliseconds"),errorRatePercent:L.string().describe("Error rate as a percentage string")}),handler:async(X,Y)=>{let J={organizationId:j4(Y).id,startDate:X.startDate?new Date(X.startDate):void 0,endDate:X.endDate?new Date(X.endDate):void 0},G=await Y.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var XY4=g(()=>{tX4();eX4()});var n60;var YY4=g(()=>{o0();s4();n60=r0({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:L.object({slug:L.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:L.string().min(1).max(255),description:L.string().optional()}),outputSchema:L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),members:L.array(L.any()).optional()}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=E8(Y);if(!Q)throw Error("User ID required to create organization");let J=await Y.boundAuth.organization.create({name:X.name,slug:X.slug,metadata:X.description?{description:X.description}:void 0,userId:Q});if(!J)throw Error("Failed to create organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var i60;var QY4=g(()=>{o0();s4();i60=r0({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:L.object({userId:L.string().optional()}),outputSchema:L.object({organizations:L.array(L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=E8(Y),J=X.userId||Q;if(!J)throw Error("User ID required to list organizations");return{organizations:(await Y.boundAuth.organization.list(J)).map((Z)=>({...Z,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt}))}}})});var a60;var JY4=g(()=>{o0();s4();a60=r0({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:L.object({}),outputSchema:L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),members:L.array(L.any()).optional(),invitations:L.array(L.any()).optional()}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=await Y.boundAuth.organization.get();if(!Q)throw Error("No active organization found");let J=new Date,G=Q.invitations?.filter((Z)=>new Date(Z.expiresAt)>J);return{...Q,invitations:G,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt}}})});var r60;var GY4=g(()=>{o0();s4();r60=r0({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:L.object({id:L.string(),slug:L.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:L.string().min(1).max(255).optional(),description:L.string().optional()}),outputSchema:L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q={};if(X.name)Q.name=X.name;if(X.slug)Q.slug=X.slug;if(X.description)Q.metadata={description:X.description};let J=await Y.boundAuth.organization.update({organizationId:X.id,data:Q});if(!J)throw Error("Failed to update organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var o60;var WY4=g(()=>{o0();s4();o60=r0({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:L.object({id:L.string()}),outputSchema:L.object({success:L.boolean(),id:L.string()}),handler:async(X,Y)=>{return H4(Y),await Y.access.check(),await Y.boundAuth.organization.delete(X.id),{success:!0,id:X.id}}})});var rw;var s60=g(()=>{o0();rw=L.object({title:L.string(),url:L.string(),icon:L.string()})});var t60;var ZY4=g(()=>{o0();s4();s60();t60=r0({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:L.object({}),outputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(rw).nullable().optional(),enabled_plugins:L.array(L.string()).nullable().optional(),createdAt:L.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:L.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.storage.organizationSettings.get(Q);if(!J)return{organizationId:Q};return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var e60;var KY4=g(()=>{o0();s4();s60();e60=r0({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(rw).optional(),enabled_plugins:L.array(L.string()).optional()}),outputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(rw).nullable().optional(),enabled_plugins:L.array(L.string()).nullable().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),updatedAt:L.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{if(H4(Y),await Y.access.check(),Y.organization&&Y.organization.id!==X.organizationId)throw Error("Cannot update settings for a different organization");let Q=await Y.storage.organizationSettings.upsert(X.organizationId,{sidebar_items:X.sidebar_items,enabled_plugins:X.enabled_plugins});return{...Q,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,updatedAt:Q.updatedAt instanceof Date?Q.updatedAt.toISOString():Q.updatedAt}}})});var X10;var $Y4=g(()=>{o0();s4();X10=r0({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:L.object({organizationId:L.string().optional(),userId:L.string(),role:L.array(L.string())}),outputSchema:L.object({id:L.string(),organizationId:L.string(),userId:L.string(),role:L.union([L.string(),L.array(L.string())]),createdAt:L.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.addMember({organizationId:Q,userId:X.userId,role:X.role});if(!J)throw Error("Failed to add member");return{...J,role:J.role,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var Y10;var HY4=g(()=>{o0();s4();Y10=r0({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:L.object({organizationId:L.string().optional(),memberIdOrEmail:L.string()}),outputSchema:L.object({success:L.boolean(),memberIdOrEmail:L.string()}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");return await Y.boundAuth.organization.removeMember({organizationId:Q,memberIdOrEmail:X.memberIdOrEmail}),{success:!0,memberIdOrEmail:X.memberIdOrEmail}}})});var Q10;var FY4=g(()=>{o0();s4();Q10=r0({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:L.object({limit:L.number().optional(),offset:L.number().optional()}),outputSchema:L.object({members:L.array(L.object({id:L.string(),organizationId:L.string(),userId:L.string(),role:L.string(),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),user:L.object({id:L.string(),name:L.string(),email:L.string(),image:L.string().optional()}).optional()}))}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.listMembers({organizationId:Q,limit:X.limit,offset:X.offset});return{members:(Array.isArray(J)?J:[]).map((Z)=>({...Z,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt}))}}})});var J10;var VY4=g(()=>{o0();s4();J10=r0({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:L.object({organizationId:L.string().optional(),memberId:L.string(),role:L.array(L.string())}),outputSchema:L.object({id:L.string(),organizationId:L.string(),userId:L.string(),role:L.union([L.literal("admin"),L.literal("member"),L.literal("owner")]),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),user:L.object({email:L.string(),name:L.string(),image:L.string().optional()})}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.updateMemberRole({organizationId:Q,memberId:X.memberId,role:X.role});if(!J)throw Error("Failed to update member role");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var qY4=g(()=>{YY4();QY4();JY4();GY4();WY4();ZY4();KY4();$Y4();HY4();FY4();VY4()});var UY4,kG,zY4,BY4;var ZH=g(()=>{o0();UY4=L.object({id:L.string().describe("Unique message ID"),threadId:L.string().describe("ID of the parent thread"),metadata:L.unknown().optional().describe("Optional message metadata"),parts:L.array(L.record(L.string(),L.unknown())).describe("Message content parts (AI SDK UIMessagePart format)"),role:L.enum(["user","assistant","system"]).describe("Message role"),createdAt:L.string().datetime().describe("Timestamp of creation"),updatedAt:L.string().datetime().describe("Timestamp of last update")}),kG=L.object({id:L.string().describe("Unique thread ID"),organizationId:L.string().describe("Organization this thread belongs to"),title:L.string().describe("Thread title"),description:L.string().nullable().describe("Thread description"),createdAt:L.string().datetime().describe("Timestamp of creation"),updatedAt:L.string().datetime().describe("Timestamp of last update"),hidden:L.boolean().optional().describe("Whether the thread is hidden"),createdBy:L.string().describe("User ID who created the thread"),updatedBy:L.string().nullable().describe("User ID who last updated the thread")}),zY4=L.object({id:L.string().optional().describe("Optional custom ID for the thread"),title:L.string().describe("Thread title"),description:L.string().nullish().describe("Thread description")}),BY4=L.object({title:L.string().optional().describe("New thread title"),description:L.string().nullish().describe("New thread description"),hidden:L.boolean().optional().describe("Whether the thread is hidden")})});var FC6,VC6,G10;var DY4=g(()=>{o0();s4();ZH();uk();FC6=L.object({data:zY4.describe("Data for the new thread (id is auto-generated if not provided)")}),VC6=L.object({item:kG.describe("The created thread entity")}),G10=r0({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",inputSchema:FC6,outputSchema:VC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(Y);if(!J)throw Error("User ID required to create thread");let G=X.data.id??zU("thrd"),Z=await Y.storage.threads.create({id:G,organizationId:Q.id,title:X.data.title,description:X.data.description,createdBy:J});return{item:{...Z,hidden:Z.hidden??!1}}}})});var qC6,UC6,W10;var NY4=g(()=>{F5();s4();ZH();o0();qC6=GH.extend({where:L.object({created_by:L.string().optional()}).optional()}),UC6=WH(kG),W10=r0({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",inputSchema:qC6,outputSchema:UC6,handler:async(X,Y)=>{await Y.access.check();let Q=Y.auth.user?.id;if(!Q)throw Error("User ID required to list threads");let J=j4(Y),G=X.offset??0,Z=X.limit??100,{threads:W,total:K}=await Y.storage.threads.list(J.id,Q,{limit:Z,offset:G}),$=G+Z<K;return{items:W.map((H)=>({...H,hidden:H.hidden??!1})),totalCount:K,hasMore:$}}})});var zC6,Z10;var OY4=g(()=>{F5();s4();ZH();zC6=_w(kG),Z10=r0({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",inputSchema:kw,outputSchema:zC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=await Y.storage.threads.get(X.id);if(!J||J.organizationId!==Q.id)return{item:null};return{item:{...J,hidden:J.hidden??!1}}}})});var BC6,DC6,K10;var LY4=g(()=>{o0();s4();ZH();BC6=L.object({id:L.string().describe("ID of the thread to update"),data:BY4.describe("Partial thread data to update")}),DC6=L.object({item:kG.describe("The updated thread entity")}),K10=r0({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",inputSchema:BC6,outputSchema:DC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(Y);if(!J)throw Error("User ID required to update thread");let{id:G,data:Z}=X,W=await Y.storage.threads.get(G);if(!W||W.organizationId!==Q.id)throw Error("Thread not found in organization");let K=await Y.storage.threads.update(G,{title:Z.title,description:Z.description,hidden:Z.hidden,updatedBy:J});return{item:{...K,hidden:K.hidden??!1}}}})});var $10;var wY4=g(()=>{F5();s4();ZH();$10=r0({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",inputSchema:yw,outputSchema:fw(kG),handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=await Y.storage.threads.get(X.id);if(!J)throw Error(`Thread not found: ${X.id}`);if(J.organizationId!==Q.id)throw Error(`Thread not found: ${X.id}`);return await Y.storage.threads.delete(X.id),{item:{...J,hidden:J.hidden??!1}}}})});var NC6,OC6,H10;var MY4=g(()=>{o0();s4();ZH();NC6=L.object({threadId:L.string().describe("ID of the thread to list messages for"),limit:L.number().optional().describe("Maximum number of messages to return"),offset:L.number().optional().describe("Number of messages to skip")}),OC6=L.object({items:L.array(UY4).describe("List of thread messages"),totalCount:L.number().describe("Total number of messages in the thread"),hasMore:L.boolean().describe("Whether there are more messages available")}),H10=r0({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",inputSchema:NC6,outputSchema:OC6,handler:async(X,Y)=>{let Q=j4(Y);await Y.access.check();let J=await Y.storage.threads.get(X.threadId);if(!J||J.organizationId!==Q.id)throw Error("Thread not found in organization");let G=X.offset??0,Z=X.limit??100,{messages:W,total:K}=await Y.storage.threads.listMessages(X.threadId,{limit:Z,offset:G}),$=G+Z<K;return{items:W,totalCount:K,hasMore:$}}})});var PY4=g(()=>{DY4();NY4();OY4();LY4();wY4();MY4()});var wC6,MC6,F10;var TY4=g(()=>{o0();s4();wC6=L.object({id:L.string().min(1)}),MC6=L.object({user:L.object({id:L.string(),name:L.string(),email:L.string(),image:L.string().nullable()}).nullable()}),F10=r0({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:wC6,outputSchema:MC6,handler:async(X,Y)=>{await Y.access.check(),H4(Y);let Q=E8(Y);if(!Q)throw Error("Authentication required");let J=await Y.storage.users.findById(X.id,Q);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var AY4=g(()=>{TY4()});var jY4={};h4(jY4,{managementMCP:()=>TC6,ALL_TOOLS:()=>EY4});var EY4,TC6=(X)=>{let Y=EY4.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,outputSchema:J.outputSchema,handler:async(G)=>{return X.access.setToolName(J.name),await J.execute(G,X)}}));return v84({name:"mcp-mesh-management",version:"1.0.0"}).withTools(Y).build()};var IY4=g(()=>{k84();n84();u94();RX4();_X4();dX4();sX4();XY4();qY4();PY4();AY4();EY4=[n60,i60,a60,r60,o60,t60,e60,X10,Y10,Q10,J10,N60,A60,E60,I60,C60,R60,x60,u60,m60,l60,d60,kX4,p60,c60,c40,i40,a40,n40,S60,v60,k60,_60,y60,f60,b60,F10,z60,B60,D60,G10,W10,Z10,K10,$10,H10]});g_();import{Migrator as bY4}from"kysely";var k10={benchmark:()=>Promise.resolve().then(() => (v10(),S10)).then((X)=>X.seed)};async function _10(X,Y){let Q=k10[Y];if(!Q)throw Error(`Unknown seed: ${Y}. Available: ${Object.keys(k10).join(", ")}`);let J=await Q();console.log(`\uD83C\uDF31 Running seed: ${Y}`);let G=await J(X);return console.log(`\u2705 Seed "${Y}" completed`),G}_G();NQ();_G();NQ();FX();H9();var z8=(X,Y="ms")=>{return new Date(Date.now()+(Y==="sec"?X*1000:X))},YE=new WeakMap;function HQ0(X,Y){let Q=Y.fields,J={};for(let G in X){let Z=Q[G];if(!Z){J[G]=X[G];continue}if(Z.returned===!1)continue;J[G]=X[G]}return J}function QE(X,Y){if(!YE.has(X))YE.set(X,new Map);let Q=YE.get(X);if(Q.has(Y))return Q.get(Y);let J={...Y==="user"?X.user?.additionalFields:{},...Y==="session"?X.session?.additionalFields:{}};for(let G of X.plugins||[])if(G.schema&&G.schema[Y])J={...J,...G.schema[Y].fields};return YE.get(X).set(Y,J),J}function F9(X,Y){return{...HQ0(Y,{fields:QE(X,"user")}),id:Y.id}}function j5(X,Y){return HQ0(Y,{fields:QE(X,"session")})}function zg(X,Y){let Q=Y.action||"create",J=Y.fields,G=Object.assign(Object.create(null),null);for(let Z in J){if(Z in X){if(J[Z].input===!1){if(J[Z].defaultValue!==void 0){if(Q!=="update"){G[Z]=J[Z].defaultValue;continue}}if(X[Z])throw new c("BAD_REQUEST",{message:`${Z} is not allowed to be set`});continue}if(J[Z].validator?.input&&X[Z]!==void 0){G[Z]=J[Z].validator.input["~standard"].validate(X[Z]);continue}if(J[Z].transform?.input&&X[Z]!==void 0){G[Z]=J[Z].transform?.input(X[Z]);continue}G[Z]=X[Z];continue}if(J[Z].defaultValue!==void 0&&Q==="create"){if(typeof J[Z].defaultValue==="function"){G[Z]=J[Z].defaultValue();continue}G[Z]=J[Z].defaultValue;continue}if(J[Z].required&&Q==="create")throw new c("BAD_REQUEST",{message:`${Z} is required`})}return G}function JE(X,Y={},Q){return zg(Y,{fields:QE(X,"user"),action:Q})}function Bg(X,Y){return zg(Y,{fields:QE(X,"session")})}function SX(X,Y){if(!Y)return X;for(let Q in Y){let J=Y[Q]?.modelName;if(J)X[Q].modelName=J;for(let G in X[Q].fields){let Z=Y[Q]?.fields?.[G];if(!Z)continue;X[Q].fields[G].fieldName=Z}}return X}HY();o0();var RW4="127.0.0.1";function fW(X,Y){if(Y.advanced?.ipAddress?.disableIpTracking)return null;if(iG()||JF())return RW4;let Q="headers"in X?X.headers:X,J=Y.advanced?.ipAddress?.ipAddressHeaders||["x-forwarded-for"];for(let G of J){let Z="get"in Q?Q.get(G):Q[G];if(typeof Z==="string"){let W=Z.split(",")[0].trim();if(SW4(W))return W}}return null}function SW4(X){if(cK().safeParse(X).success)return!0;if(nK().safeParse(X).success)return!0;return!1}VX();P5();HY();j8();import{sql as C5}from"kysely";async function zQ0(X,Y){let Q;if(!X.database){let J=xY(X),G=Object.keys(J).reduce((W,K)=>{return W[K]=[],W},{}),{memoryAdapter:Z}=await Promise.resolve().then(() => (UQ0(),qQ0));Q=Z(G)(X)}else if(typeof X.database==="function")Q=X.database(X);else Q=await Y(X);if(!Q.transaction)v4.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),Q.transaction=async(J)=>{return J(Q)};return Q}async function Mg(X){return zQ0(X,async(Y)=>{let{createKyselyAdapter:Q}=await Promise.resolve().then(() => (wg(),Lg)),{kysely:J,databaseType:G,transaction:Z}=await Q(Y);if(!J)throw new T4("Failed to initialize database adapter");let{kyselyAdapter:W}=await Promise.resolve().then(() => (wg(),Lg));return W(J,{type:G||"sqlite",debugLogs:Y.database&&"debugLogs"in Y.database?Y.database.debugLogs:!1,transaction:Z})(Y)})}function BQ0(X,Y){let Q=Y.hooks;async function J($,H,F){let V=await gY(),q=$;for(let N of Q||[]){let O=N[H]?.create?.before;if(O){let w=await O(q,V);if(w===!1)return null;if(typeof w==="object"&&"data"in w)q={...q,...w.data}}}let z=F?await F.fn(q):null,D=!F||F.executeMainFn?await(await K1(X)).create({model:H,data:q,forceAllowId:!0}):z;for(let N of Q||[]){let O=N[H]?.create?.after;if(O)await O(D,V)}return D}async function G($,H,F,V){let q=await gY(),z=$;for(let O of Q||[]){let w=O[F]?.update?.before;if(w){let E=await w($,q);if(E===!1)return null;if(typeof E==="object"&&"data"in E)z={...z,...E.data}}}let D=V?await V.fn(z):null,N=!V||V.executeMainFn?await(await K1(X)).update({model:F,update:z,where:H}):D;for(let O of Q||[]){let w=O[F]?.update?.after;if(w)await w(N,q)}return N}async function Z($,H,F,V){let q=await gY(),z=$;for(let O of Q||[]){let w=O[F]?.update?.before;if(w){let E=await w($,q);if(E===!1)return null;if(typeof E==="object"&&"data"in E)z={...z,...E.data}}}let D=V?await V.fn(z):null,N=!V||V.executeMainFn?await(await K1(X)).updateMany({model:F,update:z,where:H}):D;for(let O of Q||[]){let w=O[F]?.update?.after;if(w)await w(N,q)}return N}async function W($,H,F){let V=await gY(),q=null;try{q=(await(await K1(X)).findMany({model:H,where:$,limit:1}))[0]||null}catch(N){}if(q)for(let N of Q||[]){let O=N[H]?.delete?.before;if(O){if(await O(q,V)===!1)return null}}let z=F?await F.fn($):null,D=!F||F.executeMainFn?await(await K1(X)).delete({model:H,where:$}):z;if(q)for(let N of Q||[]){let O=N[H]?.delete?.after;if(O)await O(q,V)}return D}async function K($,H,F){let V=await gY(),q=[];try{q=await(await K1(X)).findMany({model:H,where:$})}catch(N){}for(let N of q)for(let O of Q||[]){let w=O[H]?.delete?.before;if(w){if(await w(N,V)===!1)return null}}let z=F?await F.fn($):null,D=!F||F.executeMainFn?await(await K1(X)).deleteMany({model:H,where:$}):z;for(let N of q)for(let O of Q||[]){let w=O[H]?.delete?.after;if(w)await w(N,V)}return D}return{createWithHooks:J,updateWithHooks:G,updateManyWithHooks:Z,deleteWithHooks:W,deleteManyWithHooks:K}}var FE=(X,Y)=>{let{logger:Q,options:J}=Y,G=J.secondaryStorage,Z=J.session?.expiresIn||604800,{createWithHooks:W,updateWithHooks:K,updateManyWithHooks:$,deleteWithHooks:H,deleteManyWithHooks:F}=BQ0(X,Y);async function V(q){if(!G)return;let z=await G.get(`active-sessions-${q.id}`);if(!z)return;let D=Date.now(),N=(D1(z)||[]).filter((O)=>O.expiresAt>D);await Promise.all(N.map(async({token:O})=>{let w=await G.get(O);if(!w)return;let E=D1(w);if(!E)return;let C=Math.max(Math.floor(new Date(E.session.expiresAt).getTime()-D)/1000,0);await G.set(O,JSON.stringify({session:E.session,user:q}),Math.floor(C))}))}return{createOAuthUser:async(q,z)=>{return Wz(X,async()=>{let D=await W({createdAt:new Date,updatedAt:new Date,...q},"user",void 0);return{user:D,account:await W({...z,userId:D.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}})},createUser:async(q)=>{return await W({createdAt:new Date,updatedAt:new Date,...q,email:q.email?.toLowerCase()},"user",void 0)},createAccount:async(q)=>{return await W({createdAt:new Date,updatedAt:new Date,...q},"account",void 0)},listSessions:async(q)=>{if(G){let z=await G.get(`active-sessions-${q}`);if(!z)return[];let D=D1(z)||[],N=Date.now(),O=D.filter((E)=>E.expiresAt>N),w=[];for(let E of O){let C=await G.get(E.token);if(C){let A=D1(C);if(!A)return[];let T=j5(Y.options,{...A.session,expiresAt:new Date(A.session.expiresAt)});w.push(T)}}return w}return await(await K1(X)).findMany({model:"session",where:[{field:"userId",value:q}]})},listUsers:async(q,z,D,N)=>{return await(await K1(X)).findMany({model:"user",limit:q,offset:z,sortBy:D,where:N})},countTotalUsers:async(q)=>{let z=await(await K1(X)).count({model:"user",where:q});if(typeof z==="string")return parseInt(z);return z},deleteUser:async(q)=>{if(G)await G.delete(`active-sessions-${q}`);if(!G||J.session?.storeSessionInDatabase)await F([{field:"userId",value:q}],"session",void 0);await F([{field:"userId",value:q}],"account",void 0),await H([{field:"id",value:q}],"user",void 0)},createSession:async(q,z,D,N)=>{let O=await gY().catch(()=>null),w=O?.headers||O?.request?.headers,{id:E,...C}=D||{},A=Bg(O?.context.options??J,{}),T={ipAddress:O?.request||O?.headers?fW(O?.request||O?.headers,O?.context.options)||"":"",userAgent:w?.get("user-agent")||"",...C,expiresAt:z?z8(86400,"sec"):z8(Z,"sec"),userId:q,token:g8(32),createdAt:new Date,updatedAt:new Date,...A,...N?C:{}};return await W(T,"session",G?{fn:async(I)=>{let R=await G.get(`active-sessions-${q}`),v=[],_=Date.now();if(R)v=D1(R)||[],v=v.filter((m)=>m.expiresAt>_);let y=v.sort((m,t)=>m.expiresAt-t.expiresAt),f=y.at(-1)?.expiresAt;if(y.push({token:T.token,expiresAt:T.expiresAt.getTime()}),!f||f<T.expiresAt.getTime())f=T.expiresAt.getTime();let a=Math.max(Math.floor((f-_)/1000),0);if(a>0)await G.set(`active-sessions-${q}`,JSON.stringify(y),a);let x=await X.findOne({model:"user",where:[{field:"id",value:q}]}),k=Math.max(Math.floor((T.expiresAt.getTime()-_)/1000),0);if(k>0)await G.set(T.token,JSON.stringify({session:I,user:x}),k);return I},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},findSession:async(q)=>{if(G){let O=await G.get(q);if(!O&&!J.session?.storeSessionInDatabase)return null;if(O){let w=D1(O);if(!w)return null;return{session:j5(Y.options,{...w.session,expiresAt:new Date(w.session.expiresAt),createdAt:new Date(w.session.createdAt),updatedAt:new Date(w.session.updatedAt)}),user:F9(Y.options,{...w.user,createdAt:new Date(w.user.createdAt),updatedAt:new Date(w.user.updatedAt)})}}}let z=await(await K1(X)).findOne({model:"session",where:[{value:q,field:"token"}],join:{user:!0}});if(!z)return null;let{user:D,...N}=z;if(!D)return null;return{session:j5(Y.options,N),user:F9(Y.options,D)}},findSessions:async(q)=>{if(G){let D=[];for(let N of q){let O=await G.get(N);if(O){let w=D1(O);if(!w)return[];let E={session:{...w.session,expiresAt:new Date(w.session.expiresAt)},user:{...w.user,createdAt:new Date(w.user.createdAt),updatedAt:new Date(w.user.updatedAt)}};D.push(E)}}return D}let z=await(await K1(X)).findMany({model:"session",where:[{field:"token",value:q,operator:"in"}],join:{user:!0}});if(!z.length)return[];if(z.some((D)=>!D.user))return[];return z.map((D)=>{let{user:N,...O}=D;return{session:O,user:N}})},updateSession:async(q,z)=>{return await K(z,[{field:"token",value:q}],"session",G?{async fn(D){let N=await G.get(q),O=null;if(N){let w=D1(N);if(!w)return null;return O={...w.session,...D},O}else return null},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},deleteSession:async(q)=>{if(G){let z=await G.get(q);if(z){let{session:D}=D1(z)??{};if(!D){Q.error("Session not found in secondary storage");return}let N=D.userId,O=await G.get(`active-sessions-${N}`);if(O){let w=D1(O)||[],E=Date.now(),C=w.filter((T)=>T.expiresAt>E&&T.token!==q),A=C.sort((T,I)=>T.expiresAt-I.expiresAt).at(-1)?.expiresAt;if(C.length>0&&A&&A>Date.now())await G.set(`active-sessions-${N}`,JSON.stringify(C),Math.floor((A-E)/1000));else await G.delete(`active-sessions-${N}`)}else Q.error("Active sessions list not found in secondary storage")}if(await G.delete(q),!J.session?.storeSessionInDatabase||Y.options.session?.preserveSessionInDatabase)return}await(await K1(X)).delete({model:"session",where:[{field:"token",value:q}]})},deleteAccounts:async(q)=>{await F([{field:"userId",value:q}],"account",void 0)},deleteAccount:async(q)=>{await H([{field:"id",value:q}],"account",void 0)},deleteSessions:async(q)=>{if(G){if(typeof q==="string"){let z=await G.get(`active-sessions-${q}`),D=z?D1(z):[];if(!D)return;for(let N of D)await G.delete(N.token)}else for(let z of q)if(await G.get(z))await G.delete(z);if(!J.session?.storeSessionInDatabase||Y.options.session?.preserveSessionInDatabase)return}await F([{field:Array.isArray(q)?"token":"userId",value:q,operator:Array.isArray(q)?"in":void 0}],"session",void 0)},findOAuthUser:async(q,z,D)=>{let N=await(await K1(X)).findMany({model:"account",where:[{value:z,field:"accountId"}],join:{user:!0}}).then((O)=>{return O.find((w)=>w.providerId===D)});if(N)if(N.user)return{user:N.user,accounts:[N]};else{let O=await(await K1(X)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}]});if(O)return{user:O,accounts:[N]};return null}else{let O=await(await K1(X)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}]});if(O)return{user:O,accounts:await(await K1(X)).findMany({model:"account",where:[{value:O.id,field:"userId"}]})||[]};else return null}},findUserByEmail:async(q,z)=>{let D=await(await K1(X)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}],join:{...z?.includeAccounts?{account:!0}:{}}});if(!D)return null;let{account:N,...O}=D;return{user:O,accounts:N??[]}},findUserById:async(q)=>{if(!q)return null;return await(await K1(X)).findOne({model:"user",where:[{field:"id",value:q}]})},linkAccount:async(q)=>{return await W({createdAt:new Date,updatedAt:new Date,...q},"account",void 0)},updateUser:async(q,z)=>{let D=await K(z,[{field:"id",value:q}],"user",void 0);return await V(D),await V(D),D},updateUserByEmail:async(q,z)=>{let D=await K(z,[{field:"email",value:q.toLowerCase()}],"user",void 0);return await V(D),await V(D),D},updatePassword:async(q,z)=>{await $({password:z},[{field:"userId",value:q},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async(q)=>{return await(await K1(X)).findMany({model:"account",where:[{field:"userId",value:q}]})},findAccount:async(q)=>{return await(await K1(X)).findOne({model:"account",where:[{field:"accountId",value:q}]})},findAccountByProviderId:async(q,z)=>{return await(await K1(X)).findOne({model:"account",where:[{field:"accountId",value:q},{field:"providerId",value:z}]})},findAccountByUserId:async(q)=>{return await(await K1(X)).findMany({model:"account",where:[{field:"userId",value:q}]})},updateAccount:async(q,z)=>{return await K(z,[{field:"id",value:q}],"account",void 0)},createVerificationValue:async(q)=>{return await W({createdAt:new Date,updatedAt:new Date,...q},"verification",void 0)},findVerificationValue:async(q)=>{let z=await(await K1(X)).findMany({model:"verification",where:[{field:"identifier",value:q}],sortBy:{field:"createdAt",direction:"desc"},limit:1});if(!J.verification?.disableCleanup)await(await K1(X)).deleteMany({model:"verification",where:[{field:"expiresAt",value:new Date,operator:"lt"}]});return z[0]},deleteVerificationValue:async(q)=>{await(await K1(X)).delete({model:"verification",where:[{field:"id",value:q}]})},deleteVerificationByIdentifier:async(q)=>{await(await K1(X)).delete({model:"verification",where:[{field:"identifier",value:q}]})},updateVerificationValue:async(q,z)=>{return await K(z,[{field:"id",value:q}],"verification",void 0)}}};function DQ0(X){let Y=xY(X),Q={};for(let J in Y){let G=Y[J],Z=G.fields,W={};if(Object.entries(Z).forEach(([K,$])=>{if(W[$.fieldName||K]=$,$.references){let H=Y[$.references.model];if(H)W[$.fieldName||K].references={...$.references,model:H.modelName,field:$.references.field}}}),Q[G.modelName]){Q[G.modelName].fields={...Q[G.modelName].fields,...W};continue}Q[G.modelName]={fields:W,order:G.order||1/0}}return Q}var bW4={postgres:{string:["character varying","varchar","text","uuid"],number:["int4","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamptz","timestamp","date"],json:["json","jsonb"]},mysql:{string:["varchar","text","uuid"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean","tinyint"],date:["timestamp","datetime","date"],json:["json"]},sqlite:{string:["TEXT"],number:["INTEGER","REAL"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"],json:["TEXT"]},mssql:{string:["varchar","nvarchar","uniqueidentifier"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","smallint"],date:["datetime2","date","datetime"],json:["varchar","nvarchar"]}};function NQ0(X,Y,Q){function J(Z){return Z.toLowerCase().split("(")[0].trim()}if(Y==="string[]"||Y==="number[]")return X.toLowerCase().includes("json");let G=bW4[Q];return(Array.isArray(Y)?G.string.map((Z)=>Z.toLowerCase()):G[Y].map((Z)=>Z.toLowerCase())).includes(J(X))}async function hW4(X){try{let Y=await C5`SHOW search_path`.execute(X);if(Y.rows[0]?.search_path)return Y.rows[0].search_path.split(",").map((Q)=>Q.trim()).map((Q)=>Q.replace(/^["']|["']$/g,"")).filter((Q)=>!Q.startsWith("$"))[0]||"public"}catch(Y){}return"public"}async function hB(X){let Y=DQ0(X),Q=WF(X.logger),{kysely:J,databaseType:G}=await QM(X);if(!G)Q.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),G="sqlite";if(!J)Q.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1);let Z="public";if(G==="postgres"){Z=await hW4(J),Q.debug(`PostgreSQL migration: Using schema '${Z}' (from search_path)`);try{if(!(await C5`
409
+ `.execute(X)).rows[0]?.exists)await p6`CREATE ROLE ${p6.id(Q)} NOLOGIN`.execute(X);await p6`GRANT ${p6.id(Q)} TO CURRENT_USER`.execute(X),await p6`GRANT USAGE, CREATE ON SCHEMA ${p6.id(Y)} TO ${p6.id(Q)}`.execute(X),await p6`GRANT ALL ON ALL TABLES IN SCHEMA ${p6.id(Y)} TO ${p6.id(Q)}`.execute(X),await p6`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${p6.id(Y)} TO ${p6.id(Q)}`.execute(X),await p6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${p6.id(Y)} GRANT ALL ON TABLES TO ${p6.id(Q)}`.execute(X),await p6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${p6.id(Y)} GRANT ALL ON SEQUENCES TO ${p6.id(Q)}`.execute(X),await p6`REVOKE ALL ON SCHEMA public FROM ${p6.id(Q)}`.execute(X)}async function lI6(X,Y,Q,J){try{return await X.transaction().execute(async(G)=>{return await p6`SET LOCAL ROLE ${p6.id(Q)}`.execute(G),await p6`SET LOCAL search_path TO ${p6.id(Y)}`.execute(G),await p6.raw(J).execute(G)})}catch(G){if(uI6(G))return await mI6(X,Y,Q),await X.transaction().execute(async(Z)=>{return await p6`SET LOCAL ROLE ${p6.id(Q)}`.execute(Z),await p6`SET LOCAL search_path TO ${p6.id(Y)}`.execute(Z),await p6.raw(J).execute(Z)});throw G}}var fI6,hI6,kX4;var _X4=g(()=>{o0();s4();fI6=L.object({results:L.array(L.unknown()).optional(),success:L.boolean().optional()});hI6=L.object({sql:L.string().describe("The SQL query to run"),params:L.array(L.any()).describe("The parameters to pass to the SQL query").optional()});kX4=r0({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:hI6,outputSchema:L.object({result:L.array(fI6)}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=bI6(X.sql,X.params||[]);if(!Y.connectionId)throw Error("Connection context required for database access");let J=xI6(Y.connectionId),G=gI6(Y.connectionId);return{result:[{results:(await lI6(Y.db,J,G,Q)).rows,success:!0}]}}})});var yX4,pI6,fX4;var GW=g(()=>{o0();M60();yX4=L.object({connectionId:L.string().optional().describe("Filter subscriptions by connection ID (optional)")}),pI6=L.object({id:L.string().describe("Subscription ID"),connectionId:L.string().describe("Subscriber connection ID"),eventType:L.string().describe("Event type pattern"),publisher:L.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:L.string().nullable().describe("JSONPath filter expression"),enabled:L.boolean().describe("Whether subscription is enabled"),createdAt:L.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:L.string().datetime().describe("Updated timestamp (ISO 8601)")}),fX4=L.object({subscriptions:L.array(pI6).describe("List of subscriptions")})});var S60;var bX4=g(()=>{s4();GW();S60=r0({name:"EVENT_PUBLISH",description:"Publish an event to the event bus. Supports immediate, scheduled (deliverAt), and recurring (cron) delivery. The source is automatically set to the caller's connection ID.",inputSchema:bw,outputSchema:hw,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await Y.eventBus.publish(Q.id,J,{type:X.type,subject:X.subject,data:X.data,deliverAt:X.deliverAt,cron:X.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var v60;var hX4=g(()=>{s4();GW();v60=r0({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:xw,outputSchema:gw,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await Y.eventBus.subscribe(Q.id,{connectionId:J,eventType:X.eventType,publisher:X.publisher,filter:X.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var k60;var xX4=g(()=>{s4();GW();k60=r0({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:lw,outputSchema:dw,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await Y.eventBus.getSubscription(Q.id,X.subscriptionId);if(!G)throw Error(`Subscription not found: ${X.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await Y.eventBus.unsubscribe(Q.id,X.subscriptionId)).success,subscriptionId:X.subscriptionId}}})});var _60;var gX4=g(()=>{s4();GW();_60=r0({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:pw,outputSchema:cw,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await Y.eventBus.getEvent(Q.id,X.eventId))throw Error(`Event not found: ${X.eventId}`);if(!(await Y.eventBus.cancelEvent(Q.id,X.eventId,J)).success)throw Error("Failed to cancel event. Either the event is already completed/failed, or you are not the publisher.");return{success:!0,eventId:X.eventId}}})});var y60;var uX4=g(()=>{s4();GW();y60=r0({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:nw,outputSchema:iw,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await Y.eventBus.ackEvent(Q.id,X.eventId,J)).success)throw Error("Failed to acknowledge event. Either the event was not found, already delivered, or you are not a subscriber.");return{success:!0,eventId:X.eventId}}})});var f60;var mX4=g(()=>{s4();GW();f60=r0({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:yX4,outputSchema:fX4,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);return await Y.access.check(),{subscriptions:(await Y.eventBus.listSubscriptions(Q.id,X.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}))}}})});var b60;var lX4=g(()=>{s4();GW();b60=r0({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:uw,outputSchema:mw,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await Y.eventBus.syncSubscriptions(Q.id,{connectionId:J,subscriptions:X.subscriptions});return{created:G.created,updated:G.updated,deleted:G.deleted,unchanged:G.unchanged,subscriptions:G.subscriptions.map((Z)=>({id:Z.id,connectionId:Z.connectionId,eventType:Z.eventType,publisher:Z.publisher,filter:Z.filter,enabled:Z.enabled,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt,updatedAt:Z.updatedAt instanceof Date?Z.updatedAt.toISOString():Z.updatedAt}))}}})});var dX4=g(()=>{bX4();hX4();xX4();gX4();uX4();mX4();lX4();GW()});var h60,nI6,vG,pX4,cX4;var vU=g(()=>{o0();h60=L.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),nI6=L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:L.array(L.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:L.array(L.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),vG=L.object({id:L.string().describe("Unique identifier for the virtual MCP"),title:L.string().describe("Human-readable name for the virtual MCP"),description:L.string().nullable().describe("Description of the virtual MCP"),icon:L.string().nullable().optional().describe("Icon URL for the virtual MCP"),created_at:L.string().describe("When the virtual MCP was created"),updated_at:L.string().describe("When the virtual MCP was last updated"),created_by:L.string().describe("User ID who created the virtual MCP"),updated_by:L.string().optional().describe("User ID who last updated the virtual MCP"),organization_id:L.string().describe("Organization ID this virtual MCP belongs to"),tool_selection_mode:h60.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:L.enum(["active","inactive"]).describe("Current status"),metadata:L.object({instructions:L.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:L.array(nI6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),pX4=L.object({title:L.string().min(1).max(255).describe("Name for the virtual MCP"),description:L.string().nullable().optional().describe("Optional description"),tool_selection_mode:h60.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:L.string().nullable().optional().describe("Optional icon URL"),status:L.enum(["active","inactive"]).optional().default("active").describe("Initial status"),metadata:L.object({instructions:L.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:L.array(L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:L.array(L.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:L.array(L.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).describe("Connections to include/exclude (can be empty for exclusion mode)")}),cX4=L.object({title:L.string().min(1).max(255).optional().describe("New name"),description:L.string().nullable().optional().describe("New description (null to clear)"),tool_selection_mode:h60.optional().describe("New tool selection mode"),icon:L.string().nullable().optional().describe("New icon URL (null to clear)"),status:L.enum(["active","inactive"]).optional().describe("New status"),metadata:L.object({instructions:L.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:L.array(L.object({connection_id:L.string().describe("Connection ID"),selected_tools:L.array(L.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:L.array(L.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:L.array(L.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var iI6,aI6,x60;var nX4=g(()=>{o0();s4();vU();iI6=L.object({data:pX4.describe("Data for the new virtual MCP")}),aI6=L.object({item:vG.describe("The created virtual MCP entity")}),x60=r0({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new MCP virtual MCP in the organization",inputSchema:iI6,outputSchema:aI6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(Y);if(!J)throw Error("User ID required to create virtual MCP");return{item:await Y.storage.virtualMcps.create(Q.id,J,X.data)}}})});function rI6(X){let Y=[],Q=0;while(Q<X.length){let J=X[Q];if(J==="%")Y.push(".*");else if(J==="_")Y.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Y.push("\\"+J);else Y.push(J);Q++}return Y.join("")}function VK(X){return typeof X==="string"||typeof X==="number"}function g60(X,Y){let Q=Y.split("."),J=X;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function oI6(X,Y){return X.connections.some((Q)=>Q.connection_id===Y)}function G_(X,Y){if("conditions"in Y){let{operator:K,conditions:$}=Y;switch(K){case"and":return $.every((H)=>G_(X,H));case"or":return $.some((H)=>G_(X,H));case"not":return!$.every((H)=>G_(X,H));default:return!0}}let{field:Q,operator:J,value:G}=Y,Z=Q.join(".");if(Z==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return oI6(X,G)}let W=g60(X,Z);switch(J){case"eq":return W===G;case"gt":return VK(W)&&VK(G)&&W>G;case"gte":return VK(W)&&VK(G)&&W>=G;case"lt":return VK(W)&&VK(G)&&W<G;case"lte":return VK(W)&&VK(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let K=rI6(G);return new RegExp(`^${K}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function sI6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let Z=G.field.join("."),W=g60(Q,Z),K=g60(J,Z),$=0;if(W==null&&K==null)continue;if(W==null)$=G.nulls==="first"?-1:1;else if(K==null)$=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof K==="string")$=W.localeCompare(K);else if(typeof W==="number"&&typeof K==="number")$=W-K;else $=String(W).localeCompare(String(K));if($!==0)return G.direction==="desc"?-$:$}return 0})}var tI6,eI6,u60;var iX4=g(()=>{F5();s4();vU();tI6=GH,eI6=WH(vG),u60=r0({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",inputSchema:tI6,outputSchema:eI6,handler:async(X,Y)=>{await Y.access.check();let Q=j4(Y),J=X.where&&!("conditions"in X.where)&&X.where.field.join(".")==="connection_id"&&X.where.operator==="eq"&&typeof X.where.value==="string"?X.where.value:void 0,Z=J?await Y.storage.virtualMcps.listByConnectionId(Q.id,J):await Y.storage.virtualMcps.list(Q.id);if(X.where)Z=Z.filter((V)=>G_(V,X.where));if(X.orderBy&&X.orderBy.length>0)Z=sI6(Z,X.orderBy);let W=Z.length,K=X.offset??0,$=X.limit??100,H=Z.slice(K,K+$),F=K+$<W;return{items:H,totalCount:W,hasMore:F}}})});var XC6,YC6,m60;var aX4=g(()=>{o0();s4();vU();XC6=L.object({id:L.string().describe("ID of the virtual MCP to retrieve")}),YC6=L.object({item:vG.nullable().describe("The retrieved virtual MCP, or null if not found")}),m60=r0({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",inputSchema:XC6,outputSchema:YC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=await Y.storage.virtualMcps.findById(X.id);if(J&&J.organization_id!==Q.id)return{item:null};if(!J)return{item:null};return{item:J}}})});var QC6,JC6,l60;var rX4=g(()=>{o0();s4();vU();QC6=L.object({id:L.string().describe("ID of the virtual MCP to update"),data:cX4.describe("Partial virtual MCP data to update")}),JC6=L.object({item:vG.describe("The updated virtual MCP entity")}),l60=r0({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",inputSchema:QC6,outputSchema:JC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(Y);if(!J)throw Error("User ID required to update virtual MCP");let G=await Y.storage.virtualMcps.findById(X.id);if(!G)throw Error(`Virtual MCP not found: ${X.id}`);if(G.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${X.id}`);return{item:await Y.storage.virtualMcps.update(X.id,J,X.data)}}})});var GC6,WC6,d60;var oX4=g(()=>{o0();s4();vU();GC6=L.object({id:L.string().describe("ID of the virtual MCP to delete")}),WC6=L.object({item:vG.describe("The deleted virtual MCP entity")}),d60=r0({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",inputSchema:GC6,outputSchema:WC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=await Y.storage.virtualMcps.findById(X.id);if(!J)throw Error(`Virtual MCP not found: ${X.id}`);if(J.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${X.id}`);return await Y.storage.virtualMcps.delete(X.id),{item:J}}})});var sX4=g(()=>{nX4();iX4();aX4();rX4();oX4()});var KC6,p60;var tX4=g(()=>{s4();o0();KC6=L.object({id:L.string().optional().describe("Unique log identifier"),organizationId:L.string().describe("Organization ID"),connectionId:L.string().describe("Connection ID"),connectionTitle:L.string().describe("Connection display name"),toolName:L.string().describe("Name of the tool that was called"),input:L.record(L.string(),L.unknown()).describe("Redacted tool input"),output:L.record(L.string(),L.unknown()).describe("Redacted tool output"),isError:L.boolean().describe("Whether the call resulted in an error"),errorMessage:L.string().nullish().describe("Error message if applicable"),durationMs:L.number().describe("Call duration in milliseconds"),timestamp:L.string().describe("ISO 8601 timestamp of the call"),userId:L.string().nullish().describe("User who triggered the call"),requestId:L.string().describe("Unique request identifier"),userAgent:L.string().nullish().describe("Client identifier (x-mesh-client header)"),virtualMcpId:L.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:L.record(L.string(),L.string()).nullish().describe("Custom key-value metadata attached to the log")}),p60=r0({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:L.object({connectionId:L.string().optional().describe("Filter by connection ID"),virtualMcpId:L.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:L.string().optional().describe("Filter by tool name"),isError:L.boolean().optional().describe("Filter by error status"),startDate:L.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:L.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:L.number().default(100).describe("Maximum number of results"),offset:L.number().default(0).describe("Offset for pagination"),properties:L.record(L.string(),L.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:L.array(L.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:L.record(L.string(),L.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)")}),outputSchema:L.object({logs:L.array(KC6).describe("Array of monitoring logs"),total:L.number().describe("Total number of logs matching filters"),offset:L.number().describe("Current offset for pagination"),limit:L.number().describe("Current limit for pagination")}),handler:async(X,Y)=>{let Q=j4(Y),G=X.properties||X.propertyKeys||X.propertyPatterns?{properties:X.properties,propertyKeys:X.propertyKeys,propertyPatterns:X.propertyPatterns}:void 0,Z={organizationId:Q.id,connectionId:X.connectionId,virtualMcpId:X.virtualMcpId,toolName:X.toolName,isError:X.isError,startDate:X.startDate?new Date(X.startDate):void 0,endDate:X.endDate?new Date(X.endDate):void 0,limit:X.limit,offset:X.offset,propertyFilters:G},W=await Y.storage.monitoring.query(Z);return{logs:W.logs.map((K)=>({...K,timestamp:K.timestamp instanceof Date?K.timestamp.toISOString():K.timestamp})),total:W.total,offset:X.offset,limit:X.limit}}})});var c60;var eX4=g(()=>{s4();o0();c60=r0({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:L.object({startDate:L.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:L.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:L.object({totalCalls:L.number().describe("Total number of tool calls"),errorRate:L.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:L.number().describe("Average call duration in milliseconds"),errorRatePercent:L.string().describe("Error rate as a percentage string")}),handler:async(X,Y)=>{let J={organizationId:j4(Y).id,startDate:X.startDate?new Date(X.startDate):void 0,endDate:X.endDate?new Date(X.endDate):void 0},G=await Y.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var XY4=g(()=>{tX4();eX4()});var n60;var YY4=g(()=>{o0();s4();n60=r0({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:L.object({slug:L.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:L.string().min(1).max(255),description:L.string().optional()}),outputSchema:L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),members:L.array(L.any()).optional()}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=E8(Y);if(!Q)throw Error("User ID required to create organization");let J=await Y.boundAuth.organization.create({name:X.name,slug:X.slug,metadata:X.description?{description:X.description}:void 0,userId:Q});if(!J)throw Error("Failed to create organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var i60;var QY4=g(()=>{o0();s4();i60=r0({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:L.object({userId:L.string().optional()}),outputSchema:L.object({organizations:L.array(L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=E8(Y),J=X.userId||Q;if(!J)throw Error("User ID required to list organizations");return{organizations:(await Y.boundAuth.organization.list(J)).map((Z)=>({...Z,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt}))}}})});var a60;var JY4=g(()=>{o0();s4();a60=r0({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:L.object({}),outputSchema:L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),members:L.array(L.any()).optional(),invitations:L.array(L.any()).optional()}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=await Y.boundAuth.organization.get();if(!Q)throw Error("No active organization found");let J=new Date,G=Q.invitations?.filter((Z)=>new Date(Z.expiresAt)>J);return{...Q,invitations:G,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt}}})});var r60;var GY4=g(()=>{o0();s4();r60=r0({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:L.object({id:L.string(),slug:L.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:L.string().min(1).max(255).optional(),description:L.string().optional()}),outputSchema:L.object({id:L.string(),name:L.string(),slug:L.string(),logo:L.string().nullable().optional(),metadata:L.any().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q={};if(X.name)Q.name=X.name;if(X.slug)Q.slug=X.slug;if(X.description)Q.metadata={description:X.description};let J=await Y.boundAuth.organization.update({organizationId:X.id,data:Q});if(!J)throw Error("Failed to update organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var o60;var WY4=g(()=>{o0();s4();o60=r0({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:L.object({id:L.string()}),outputSchema:L.object({success:L.boolean(),id:L.string()}),handler:async(X,Y)=>{return H4(Y),await Y.access.check(),await Y.boundAuth.organization.delete(X.id),{success:!0,id:X.id}}})});var rw;var s60=g(()=>{o0();rw=L.object({title:L.string(),url:L.string(),icon:L.string()})});var t60;var ZY4=g(()=>{o0();s4();s60();t60=r0({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:L.object({}),outputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(rw).nullable().optional(),enabled_plugins:L.array(L.string()).nullable().optional(),createdAt:L.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:L.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.storage.organizationSettings.get(Q);if(!J)return{organizationId:Q};return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var e60;var KY4=g(()=>{o0();s4();s60();e60=r0({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(rw).optional(),enabled_plugins:L.array(L.string()).optional()}),outputSchema:L.object({organizationId:L.string(),sidebar_items:L.array(rw).nullable().optional(),enabled_plugins:L.array(L.string()).nullable().optional(),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),updatedAt:L.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{if(H4(Y),await Y.access.check(),Y.organization&&Y.organization.id!==X.organizationId)throw Error("Cannot update settings for a different organization");let Q=await Y.storage.organizationSettings.upsert(X.organizationId,{sidebar_items:X.sidebar_items,enabled_plugins:X.enabled_plugins});return{...Q,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,updatedAt:Q.updatedAt instanceof Date?Q.updatedAt.toISOString():Q.updatedAt}}})});var X10;var $Y4=g(()=>{o0();s4();X10=r0({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:L.object({organizationId:L.string().optional(),userId:L.string(),role:L.array(L.string())}),outputSchema:L.object({id:L.string(),organizationId:L.string(),userId:L.string(),role:L.union([L.string(),L.array(L.string())]),createdAt:L.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.addMember({organizationId:Q,userId:X.userId,role:X.role});if(!J)throw Error("Failed to add member");return{...J,role:J.role,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var Y10;var HY4=g(()=>{o0();s4();Y10=r0({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:L.object({organizationId:L.string().optional(),memberIdOrEmail:L.string()}),outputSchema:L.object({success:L.boolean(),memberIdOrEmail:L.string()}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");return await Y.boundAuth.organization.removeMember({organizationId:Q,memberIdOrEmail:X.memberIdOrEmail}),{success:!0,memberIdOrEmail:X.memberIdOrEmail}}})});var Q10;var FY4=g(()=>{o0();s4();Q10=r0({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:L.object({limit:L.number().optional(),offset:L.number().optional()}),outputSchema:L.object({members:L.array(L.object({id:L.string(),organizationId:L.string(),userId:L.string(),role:L.string(),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),user:L.object({id:L.string(),name:L.string(),email:L.string(),image:L.string().optional()}).optional()}))}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.listMembers({organizationId:Q,limit:X.limit,offset:X.offset});return{members:(Array.isArray(J)?J:[]).map((Z)=>({...Z,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt}))}}})});var J10;var VY4=g(()=>{o0();s4();J10=r0({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:L.object({organizationId:L.string().optional(),memberId:L.string(),role:L.array(L.string())}),outputSchema:L.object({id:L.string(),organizationId:L.string(),userId:L.string(),role:L.union([L.literal("admin"),L.literal("member"),L.literal("owner")]),createdAt:L.string().datetime().describe("ISO 8601 timestamp"),user:L.object({email:L.string(),name:L.string(),image:L.string().optional()})}),handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.updateMemberRole({organizationId:Q,memberId:X.memberId,role:X.role});if(!J)throw Error("Failed to update member role");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var qY4=g(()=>{YY4();QY4();JY4();GY4();WY4();ZY4();KY4();$Y4();HY4();FY4();VY4()});var UY4,kG,zY4,BY4;var ZH=g(()=>{o0();UY4=L.object({id:L.string().describe("Unique message ID"),threadId:L.string().describe("ID of the parent thread"),metadata:L.unknown().optional().describe("Optional message metadata"),parts:L.array(L.record(L.string(),L.unknown())).describe("Message content parts (AI SDK UIMessagePart format)"),role:L.enum(["user","assistant","system"]).describe("Message role"),createdAt:L.string().datetime().describe("Timestamp of creation"),updatedAt:L.string().datetime().describe("Timestamp of last update")}),kG=L.object({id:L.string().describe("Unique thread ID"),organizationId:L.string().describe("Organization this thread belongs to"),title:L.string().describe("Thread title"),description:L.string().nullable().describe("Thread description"),createdAt:L.string().datetime().describe("Timestamp of creation"),updatedAt:L.string().datetime().describe("Timestamp of last update"),hidden:L.boolean().optional().describe("Whether the thread is hidden"),createdBy:L.string().describe("User ID who created the thread"),updatedBy:L.string().nullable().describe("User ID who last updated the thread")}),zY4=L.object({id:L.string().optional().describe("Optional custom ID for the thread"),title:L.string().describe("Thread title"),description:L.string().nullish().describe("Thread description")}),BY4=L.object({title:L.string().optional().describe("New thread title"),description:L.string().nullish().describe("New thread description"),hidden:L.boolean().optional().describe("Whether the thread is hidden")})});var FC6,VC6,G10;var DY4=g(()=>{o0();s4();ZH();uk();FC6=L.object({data:zY4.describe("Data for the new thread (id is auto-generated if not provided)")}),VC6=L.object({item:kG.describe("The created thread entity")}),G10=r0({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",inputSchema:FC6,outputSchema:VC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(Y);if(!J)throw Error("User ID required to create thread");let G=X.data.id??zU("thrd"),Z=await Y.storage.threads.create({id:G,organizationId:Q.id,title:X.data.title,description:X.data.description,createdBy:J});return{item:{...Z,hidden:Z.hidden??!1}}}})});var qC6,UC6,W10;var NY4=g(()=>{F5();s4();ZH();o0();qC6=GH.extend({where:L.object({created_by:L.string().optional()}).optional()}),UC6=WH(kG),W10=r0({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",inputSchema:qC6,outputSchema:UC6,handler:async(X,Y)=>{await Y.access.check();let Q=Y.auth.user?.id;if(!Q)throw Error("User ID required to list threads");let J=j4(Y),G=X.offset??0,Z=X.limit??100,{threads:W,total:K}=await Y.storage.threads.list(J.id,Q,{limit:Z,offset:G}),$=G+Z<K;return{items:W.map((H)=>({...H,hidden:H.hidden??!1})),totalCount:K,hasMore:$}}})});var zC6,Z10;var OY4=g(()=>{F5();s4();ZH();zC6=_w(kG),Z10=r0({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",inputSchema:kw,outputSchema:zC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=await Y.storage.threads.get(X.id);if(!J||J.organizationId!==Q.id)return{item:null};return{item:{...J,hidden:J.hidden??!1}}}})});var BC6,DC6,K10;var LY4=g(()=>{o0();s4();ZH();BC6=L.object({id:L.string().describe("ID of the thread to update"),data:BY4.describe("Partial thread data to update")}),DC6=L.object({item:kG.describe("The updated thread entity")}),K10=r0({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",inputSchema:BC6,outputSchema:DC6,handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=E8(Y);if(!J)throw Error("User ID required to update thread");let{id:G,data:Z}=X,W=await Y.storage.threads.get(G);if(!W||W.organizationId!==Q.id)throw Error("Thread not found in organization");let K=await Y.storage.threads.update(G,{title:Z.title,description:Z.description,hidden:Z.hidden,updatedBy:J});return{item:{...K,hidden:K.hidden??!1}}}})});var $10;var wY4=g(()=>{F5();s4();ZH();$10=r0({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",inputSchema:yw,outputSchema:fw(kG),handler:async(X,Y)=>{H4(Y);let Q=j4(Y);await Y.access.check();let J=await Y.storage.threads.get(X.id);if(!J)throw Error(`Thread not found: ${X.id}`);if(J.organizationId!==Q.id)throw Error(`Thread not found: ${X.id}`);return await Y.storage.threads.delete(X.id),{item:{...J,hidden:J.hidden??!1}}}})});var NC6,OC6,H10;var MY4=g(()=>{o0();s4();ZH();NC6=L.object({threadId:L.string().describe("ID of the thread to list messages for"),limit:L.number().optional().describe("Maximum number of messages to return"),offset:L.number().optional().describe("Number of messages to skip")}),OC6=L.object({items:L.array(UY4).describe("List of thread messages"),totalCount:L.number().describe("Total number of messages in the thread"),hasMore:L.boolean().describe("Whether there are more messages available")}),H10=r0({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",inputSchema:NC6,outputSchema:OC6,handler:async(X,Y)=>{let Q=j4(Y);await Y.access.check();let J=await Y.storage.threads.get(X.threadId);if(!J||J.organizationId!==Q.id)throw Error("Thread not found in organization");let G=X.offset??0,Z=X.limit??100,{messages:W,total:K}=await Y.storage.threads.listMessages(X.threadId,{limit:Z,offset:G}),$=G+Z<K;return{items:W,totalCount:K,hasMore:$}}})});var PY4=g(()=>{DY4();NY4();OY4();LY4();wY4();MY4()});var wC6,MC6,F10;var TY4=g(()=>{o0();s4();wC6=L.object({id:L.string().min(1)}),MC6=L.object({user:L.object({id:L.string(),name:L.string(),email:L.string(),image:L.string().nullable()}).nullable()}),F10=r0({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:wC6,outputSchema:MC6,handler:async(X,Y)=>{await Y.access.check(),H4(Y);let Q=E8(Y);if(!Q)throw Error("Authentication required");let J=await Y.storage.users.findById(X.id,Q);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var AY4=g(()=>{TY4()});var jY4={};h4(jY4,{managementMCP:()=>TC6,ALL_TOOLS:()=>EY4});var EY4,TC6=(X)=>{let Y=EY4.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,outputSchema:J.outputSchema,handler:async(G)=>{return X.access.setToolName(J.name),await J.execute(G,X)}}));return v84({name:"mcp-mesh-management",version:"1.0.0"}).withTools(Y).build()};var IY4=g(()=>{k84();n84();u94();RX4();_X4();dX4();sX4();XY4();qY4();PY4();AY4();EY4=[n60,i60,a60,r60,o60,t60,e60,X10,Y10,Q10,J10,N60,A60,E60,I60,C60,R60,x60,u60,m60,l60,d60,kX4,p60,c60,c40,i40,a40,n40,S60,v60,k60,_60,y60,f60,b60,F10,z60,B60,D60,G10,W10,Z10,K10,$10,H10]});g_();import{Migrator as bY4}from"kysely";var k10={benchmark:()=>Promise.resolve().then(() => (v10(),S10)).then((X)=>X.seed)};async function _10(X,Y){let Q=k10[Y];if(!Q)throw Error(`Unknown seed: ${Y}. Available: ${Object.keys(k10).join(", ")}`);let J=await Q();console.log(`\uD83C\uDF31 Running seed: ${Y}`);let G=await J(X);return console.log(`\u2705 Seed "${Y}" completed`),G}_G();NQ();_G();NQ();FX();H9();var z8=(X,Y="ms")=>{return new Date(Date.now()+(Y==="sec"?X*1000:X))},YE=new WeakMap;function HQ0(X,Y){let Q=Y.fields,J={};for(let G in X){let Z=Q[G];if(!Z){J[G]=X[G];continue}if(Z.returned===!1)continue;J[G]=X[G]}return J}function QE(X,Y){if(!YE.has(X))YE.set(X,new Map);let Q=YE.get(X);if(Q.has(Y))return Q.get(Y);let J={...Y==="user"?X.user?.additionalFields:{},...Y==="session"?X.session?.additionalFields:{}};for(let G of X.plugins||[])if(G.schema&&G.schema[Y])J={...J,...G.schema[Y].fields};return YE.get(X).set(Y,J),J}function F9(X,Y){return{...HQ0(Y,{fields:QE(X,"user")}),id:Y.id}}function j5(X,Y){return HQ0(Y,{fields:QE(X,"session")})}function zg(X,Y){let Q=Y.action||"create",J=Y.fields,G=Object.assign(Object.create(null),null);for(let Z in J){if(Z in X){if(J[Z].input===!1){if(J[Z].defaultValue!==void 0){if(Q!=="update"){G[Z]=J[Z].defaultValue;continue}}if(X[Z])throw new c("BAD_REQUEST",{message:`${Z} is not allowed to be set`});continue}if(J[Z].validator?.input&&X[Z]!==void 0){G[Z]=J[Z].validator.input["~standard"].validate(X[Z]);continue}if(J[Z].transform?.input&&X[Z]!==void 0){G[Z]=J[Z].transform?.input(X[Z]);continue}G[Z]=X[Z];continue}if(J[Z].defaultValue!==void 0&&Q==="create"){if(typeof J[Z].defaultValue==="function"){G[Z]=J[Z].defaultValue();continue}G[Z]=J[Z].defaultValue;continue}if(J[Z].required&&Q==="create")throw new c("BAD_REQUEST",{message:`${Z} is required`})}return G}function JE(X,Y={},Q){return zg(Y,{fields:QE(X,"user"),action:Q})}function Bg(X,Y){return zg(Y,{fields:QE(X,"session")})}function SX(X,Y){if(!Y)return X;for(let Q in Y){let J=Y[Q]?.modelName;if(J)X[Q].modelName=J;for(let G in X[Q].fields){let Z=Y[Q]?.fields?.[G];if(!Z)continue;X[Q].fields[G].fieldName=Z}}return X}HY();o0();var RW4="127.0.0.1";function fW(X,Y){if(Y.advanced?.ipAddress?.disableIpTracking)return null;if(iG()||JF())return RW4;let Q="headers"in X?X.headers:X,J=Y.advanced?.ipAddress?.ipAddressHeaders||["x-forwarded-for"];for(let G of J){let Z="get"in Q?Q.get(G):Q[G];if(typeof Z==="string"){let W=Z.split(",")[0].trim();if(SW4(W))return W}}return null}function SW4(X){if(cK().safeParse(X).success)return!0;if(nK().safeParse(X).success)return!0;return!1}VX();P5();HY();j8();import{sql as C5}from"kysely";async function zQ0(X,Y){let Q;if(!X.database){let J=xY(X),G=Object.keys(J).reduce((W,K)=>{return W[K]=[],W},{}),{memoryAdapter:Z}=await Promise.resolve().then(() => (UQ0(),qQ0));Q=Z(G)(X)}else if(typeof X.database==="function")Q=X.database(X);else Q=await Y(X);if(!Q.transaction)v4.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),Q.transaction=async(J)=>{return J(Q)};return Q}async function Mg(X){return zQ0(X,async(Y)=>{let{createKyselyAdapter:Q}=await Promise.resolve().then(() => (wg(),Lg)),{kysely:J,databaseType:G,transaction:Z}=await Q(Y);if(!J)throw new T4("Failed to initialize database adapter");let{kyselyAdapter:W}=await Promise.resolve().then(() => (wg(),Lg));return W(J,{type:G||"sqlite",debugLogs:Y.database&&"debugLogs"in Y.database?Y.database.debugLogs:!1,transaction:Z})(Y)})}function BQ0(X,Y){let Q=Y.hooks;async function J($,H,F){let V=await gY(),q=$;for(let N of Q||[]){let O=N[H]?.create?.before;if(O){let w=await O(q,V);if(w===!1)return null;if(typeof w==="object"&&"data"in w)q={...q,...w.data}}}let z=F?await F.fn(q):null,D=!F||F.executeMainFn?await(await K1(X)).create({model:H,data:q,forceAllowId:!0}):z;for(let N of Q||[]){let O=N[H]?.create?.after;if(O)await O(D,V)}return D}async function G($,H,F,V){let q=await gY(),z=$;for(let O of Q||[]){let w=O[F]?.update?.before;if(w){let E=await w($,q);if(E===!1)return null;if(typeof E==="object"&&"data"in E)z={...z,...E.data}}}let D=V?await V.fn(z):null,N=!V||V.executeMainFn?await(await K1(X)).update({model:F,update:z,where:H}):D;for(let O of Q||[]){let w=O[F]?.update?.after;if(w)await w(N,q)}return N}async function Z($,H,F,V){let q=await gY(),z=$;for(let O of Q||[]){let w=O[F]?.update?.before;if(w){let E=await w($,q);if(E===!1)return null;if(typeof E==="object"&&"data"in E)z={...z,...E.data}}}let D=V?await V.fn(z):null,N=!V||V.executeMainFn?await(await K1(X)).updateMany({model:F,update:z,where:H}):D;for(let O of Q||[]){let w=O[F]?.update?.after;if(w)await w(N,q)}return N}async function W($,H,F){let V=await gY(),q=null;try{q=(await(await K1(X)).findMany({model:H,where:$,limit:1}))[0]||null}catch(N){}if(q)for(let N of Q||[]){let O=N[H]?.delete?.before;if(O){if(await O(q,V)===!1)return null}}let z=F?await F.fn($):null,D=!F||F.executeMainFn?await(await K1(X)).delete({model:H,where:$}):z;if(q)for(let N of Q||[]){let O=N[H]?.delete?.after;if(O)await O(q,V)}return D}async function K($,H,F){let V=await gY(),q=[];try{q=await(await K1(X)).findMany({model:H,where:$})}catch(N){}for(let N of q)for(let O of Q||[]){let w=O[H]?.delete?.before;if(w){if(await w(N,V)===!1)return null}}let z=F?await F.fn($):null,D=!F||F.executeMainFn?await(await K1(X)).deleteMany({model:H,where:$}):z;for(let N of q)for(let O of Q||[]){let w=O[H]?.delete?.after;if(w)await w(N,V)}return D}return{createWithHooks:J,updateWithHooks:G,updateManyWithHooks:Z,deleteWithHooks:W,deleteManyWithHooks:K}}var FE=(X,Y)=>{let{logger:Q,options:J}=Y,G=J.secondaryStorage,Z=J.session?.expiresIn||604800,{createWithHooks:W,updateWithHooks:K,updateManyWithHooks:$,deleteWithHooks:H,deleteManyWithHooks:F}=BQ0(X,Y);async function V(q){if(!G)return;let z=await G.get(`active-sessions-${q.id}`);if(!z)return;let D=Date.now(),N=(D1(z)||[]).filter((O)=>O.expiresAt>D);await Promise.all(N.map(async({token:O})=>{let w=await G.get(O);if(!w)return;let E=D1(w);if(!E)return;let C=Math.max(Math.floor(new Date(E.session.expiresAt).getTime()-D)/1000,0);await G.set(O,JSON.stringify({session:E.session,user:q}),Math.floor(C))}))}return{createOAuthUser:async(q,z)=>{return Wz(X,async()=>{let D=await W({createdAt:new Date,updatedAt:new Date,...q},"user",void 0);return{user:D,account:await W({...z,userId:D.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}})},createUser:async(q)=>{return await W({createdAt:new Date,updatedAt:new Date,...q,email:q.email?.toLowerCase()},"user",void 0)},createAccount:async(q)=>{return await W({createdAt:new Date,updatedAt:new Date,...q},"account",void 0)},listSessions:async(q)=>{if(G){let z=await G.get(`active-sessions-${q}`);if(!z)return[];let D=D1(z)||[],N=Date.now(),O=D.filter((E)=>E.expiresAt>N),w=[];for(let E of O){let C=await G.get(E.token);if(C){let A=D1(C);if(!A)return[];let T=j5(Y.options,{...A.session,expiresAt:new Date(A.session.expiresAt)});w.push(T)}}return w}return await(await K1(X)).findMany({model:"session",where:[{field:"userId",value:q}]})},listUsers:async(q,z,D,N)=>{return await(await K1(X)).findMany({model:"user",limit:q,offset:z,sortBy:D,where:N})},countTotalUsers:async(q)=>{let z=await(await K1(X)).count({model:"user",where:q});if(typeof z==="string")return parseInt(z);return z},deleteUser:async(q)=>{if(G)await G.delete(`active-sessions-${q}`);if(!G||J.session?.storeSessionInDatabase)await F([{field:"userId",value:q}],"session",void 0);await F([{field:"userId",value:q}],"account",void 0),await H([{field:"id",value:q}],"user",void 0)},createSession:async(q,z,D,N)=>{let O=await gY().catch(()=>null),w=O?.headers||O?.request?.headers,{id:E,...C}=D||{},A=Bg(O?.context.options??J,{}),T={ipAddress:O?.request||O?.headers?fW(O?.request||O?.headers,O?.context.options)||"":"",userAgent:w?.get("user-agent")||"",...C,expiresAt:z?z8(86400,"sec"):z8(Z,"sec"),userId:q,token:g8(32),createdAt:new Date,updatedAt:new Date,...A,...N?C:{}};return await W(T,"session",G?{fn:async(I)=>{let R=await G.get(`active-sessions-${q}`),v=[],_=Date.now();if(R)v=D1(R)||[],v=v.filter((m)=>m.expiresAt>_);let y=v.sort((m,t)=>m.expiresAt-t.expiresAt),f=y.at(-1)?.expiresAt;if(y.push({token:T.token,expiresAt:T.expiresAt.getTime()}),!f||f<T.expiresAt.getTime())f=T.expiresAt.getTime();let a=Math.max(Math.floor((f-_)/1000),0);if(a>0)await G.set(`active-sessions-${q}`,JSON.stringify(y),a);let x=await X.findOne({model:"user",where:[{field:"id",value:q}]}),k=Math.max(Math.floor((T.expiresAt.getTime()-_)/1000),0);if(k>0)await G.set(T.token,JSON.stringify({session:I,user:x}),k);return I},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},findSession:async(q)=>{if(G){let O=await G.get(q);if(!O&&!J.session?.storeSessionInDatabase)return null;if(O){let w=D1(O);if(!w)return null;return{session:j5(Y.options,{...w.session,expiresAt:new Date(w.session.expiresAt),createdAt:new Date(w.session.createdAt),updatedAt:new Date(w.session.updatedAt)}),user:F9(Y.options,{...w.user,createdAt:new Date(w.user.createdAt),updatedAt:new Date(w.user.updatedAt)})}}}let z=await(await K1(X)).findOne({model:"session",where:[{value:q,field:"token"}],join:{user:!0}});if(!z)return null;let{user:D,...N}=z;if(!D)return null;return{session:j5(Y.options,N),user:F9(Y.options,D)}},findSessions:async(q)=>{if(G){let D=[];for(let N of q){let O=await G.get(N);if(O){let w=D1(O);if(!w)return[];let E={session:{...w.session,expiresAt:new Date(w.session.expiresAt)},user:{...w.user,createdAt:new Date(w.user.createdAt),updatedAt:new Date(w.user.updatedAt)}};D.push(E)}}return D}let z=await(await K1(X)).findMany({model:"session",where:[{field:"token",value:q,operator:"in"}],join:{user:!0}});if(!z.length)return[];if(z.some((D)=>!D.user))return[];return z.map((D)=>{let{user:N,...O}=D;return{session:O,user:N}})},updateSession:async(q,z)=>{return await K(z,[{field:"token",value:q}],"session",G?{async fn(D){let N=await G.get(q),O=null;if(N){let w=D1(N);if(!w)return null;return O={...w.session,...D},O}else return null},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},deleteSession:async(q)=>{if(G){let z=await G.get(q);if(z){let{session:D}=D1(z)??{};if(!D){Q.error("Session not found in secondary storage");return}let N=D.userId,O=await G.get(`active-sessions-${N}`);if(O){let w=D1(O)||[],E=Date.now(),C=w.filter((T)=>T.expiresAt>E&&T.token!==q),A=C.sort((T,I)=>T.expiresAt-I.expiresAt).at(-1)?.expiresAt;if(C.length>0&&A&&A>Date.now())await G.set(`active-sessions-${N}`,JSON.stringify(C),Math.floor((A-E)/1000));else await G.delete(`active-sessions-${N}`)}else Q.error("Active sessions list not found in secondary storage")}if(await G.delete(q),!J.session?.storeSessionInDatabase||Y.options.session?.preserveSessionInDatabase)return}await(await K1(X)).delete({model:"session",where:[{field:"token",value:q}]})},deleteAccounts:async(q)=>{await F([{field:"userId",value:q}],"account",void 0)},deleteAccount:async(q)=>{await H([{field:"id",value:q}],"account",void 0)},deleteSessions:async(q)=>{if(G){if(typeof q==="string"){let z=await G.get(`active-sessions-${q}`),D=z?D1(z):[];if(!D)return;for(let N of D)await G.delete(N.token)}else for(let z of q)if(await G.get(z))await G.delete(z);if(!J.session?.storeSessionInDatabase||Y.options.session?.preserveSessionInDatabase)return}await F([{field:Array.isArray(q)?"token":"userId",value:q,operator:Array.isArray(q)?"in":void 0}],"session",void 0)},findOAuthUser:async(q,z,D)=>{let N=await(await K1(X)).findMany({model:"account",where:[{value:z,field:"accountId"}],join:{user:!0}}).then((O)=>{return O.find((w)=>w.providerId===D)});if(N)if(N.user)return{user:N.user,accounts:[N]};else{let O=await(await K1(X)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}]});if(O)return{user:O,accounts:[N]};return null}else{let O=await(await K1(X)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}]});if(O)return{user:O,accounts:await(await K1(X)).findMany({model:"account",where:[{value:O.id,field:"userId"}]})||[]};else return null}},findUserByEmail:async(q,z)=>{let D=await(await K1(X)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}],join:{...z?.includeAccounts?{account:!0}:{}}});if(!D)return null;let{account:N,...O}=D;return{user:O,accounts:N??[]}},findUserById:async(q)=>{if(!q)return null;return await(await K1(X)).findOne({model:"user",where:[{field:"id",value:q}]})},linkAccount:async(q)=>{return await W({createdAt:new Date,updatedAt:new Date,...q},"account",void 0)},updateUser:async(q,z)=>{let D=await K(z,[{field:"id",value:q}],"user",void 0);return await V(D),await V(D),D},updateUserByEmail:async(q,z)=>{let D=await K(z,[{field:"email",value:q.toLowerCase()}],"user",void 0);return await V(D),await V(D),D},updatePassword:async(q,z)=>{await $({password:z},[{field:"userId",value:q},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async(q)=>{return await(await K1(X)).findMany({model:"account",where:[{field:"userId",value:q}]})},findAccount:async(q)=>{return await(await K1(X)).findOne({model:"account",where:[{field:"accountId",value:q}]})},findAccountByProviderId:async(q,z)=>{return await(await K1(X)).findOne({model:"account",where:[{field:"accountId",value:q},{field:"providerId",value:z}]})},findAccountByUserId:async(q)=>{return await(await K1(X)).findMany({model:"account",where:[{field:"userId",value:q}]})},updateAccount:async(q,z)=>{return await K(z,[{field:"id",value:q}],"account",void 0)},createVerificationValue:async(q)=>{return await W({createdAt:new Date,updatedAt:new Date,...q},"verification",void 0)},findVerificationValue:async(q)=>{let z=await(await K1(X)).findMany({model:"verification",where:[{field:"identifier",value:q}],sortBy:{field:"createdAt",direction:"desc"},limit:1});if(!J.verification?.disableCleanup)await(await K1(X)).deleteMany({model:"verification",where:[{field:"expiresAt",value:new Date,operator:"lt"}]});return z[0]},deleteVerificationValue:async(q)=>{await(await K1(X)).delete({model:"verification",where:[{field:"id",value:q}]})},deleteVerificationByIdentifier:async(q)=>{await(await K1(X)).delete({model:"verification",where:[{field:"identifier",value:q}]})},updateVerificationValue:async(q,z)=>{return await K(z,[{field:"id",value:q}],"verification",void 0)}}};function DQ0(X){let Y=xY(X),Q={};for(let J in Y){let G=Y[J],Z=G.fields,W={};if(Object.entries(Z).forEach(([K,$])=>{if(W[$.fieldName||K]=$,$.references){let H=Y[$.references.model];if(H)W[$.fieldName||K].references={...$.references,model:H.modelName,field:$.references.field}}}),Q[G.modelName]){Q[G.modelName].fields={...Q[G.modelName].fields,...W};continue}Q[G.modelName]={fields:W,order:G.order||1/0}}return Q}var bW4={postgres:{string:["character varying","varchar","text","uuid"],number:["int4","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamptz","timestamp","date"],json:["json","jsonb"]},mysql:{string:["varchar","text","uuid"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean","tinyint"],date:["timestamp","datetime","date"],json:["json"]},sqlite:{string:["TEXT"],number:["INTEGER","REAL"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"],json:["TEXT"]},mssql:{string:["varchar","nvarchar","uniqueidentifier"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","smallint"],date:["datetime2","date","datetime"],json:["varchar","nvarchar"]}};function NQ0(X,Y,Q){function J(Z){return Z.toLowerCase().split("(")[0].trim()}if(Y==="string[]"||Y==="number[]")return X.toLowerCase().includes("json");let G=bW4[Q];return(Array.isArray(Y)?G.string.map((Z)=>Z.toLowerCase()):G[Y].map((Z)=>Z.toLowerCase())).includes(J(X))}async function hW4(X){try{let Y=await C5`SHOW search_path`.execute(X);if(Y.rows[0]?.search_path)return Y.rows[0].search_path.split(",").map((Q)=>Q.trim()).map((Q)=>Q.replace(/^["']|["']$/g,"")).filter((Q)=>!Q.startsWith("$"))[0]||"public"}catch(Y){}return"public"}async function hB(X){let Y=DQ0(X),Q=WF(X.logger),{kysely:J,databaseType:G}=await QM(X);if(!G)Q.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),G="sqlite";if(!J)Q.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1);let Z="public";if(G==="postgres"){Z=await hW4(J),Q.debug(`PostgreSQL migration: Using schema '${Z}' (from search_path)`);try{if(!(await C5`
410
410
  SELECT schema_name
411
411
  FROM information_schema.schemata
412
412
  WHERE schema_name = ${Z}