@decocms/mesh 2.90.0 → 2.91.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.
- package/dist/client/assets/{AlertCircle-C7tRYAkQ.js → AlertCircle-D3uMaIep.js} +1 -1
- package/dist/client/assets/{AlertOctagon-D28THNQG.js → AlertOctagon-D8xrBki-.js} +1 -1
- package/dist/client/assets/{ArrowLeft-ClBGgo4l.js → ArrowLeft-BjqYsLvO.js} +1 -1
- package/dist/client/assets/{ArrowUp-BpGy_9ab.js → ArrowUp-BZmoIrId.js} +1 -1
- package/dist/client/assets/{Check-BlM4FeFk.js → Check-BezMXh3m.js} +1 -1
- package/dist/client/assets/{CheckCircle-D3DqVSof.js → CheckCircle-BJs6jTra.js} +1 -1
- package/dist/client/assets/{CheckDone01-BfRwhIAp.js → CheckDone01-B8_tfP98.js} +1 -1
- package/dist/client/assets/{ChevronDown-n5N_Lrv1.js → ChevronDown-Cvn22peU.js} +1 -1
- package/dist/client/assets/{ChevronRight-lgE9DrmA.js → ChevronRight-CTxl6bgR.js} +1 -1
- package/dist/client/assets/{Clock-3uBZYEa5.js → Clock-0kD4NxnQ.js} +1 -1
- package/dist/client/assets/{Code01-cW71Rk7W.js → Code01-BQDW5YjG.js} +1 -1
- package/dist/client/assets/{Copy01-DXqcDIlB.js → Copy01---hH64QW.js} +1 -1
- package/dist/client/assets/{Dataflow03-BjBcE8LM.js → Dataflow03-Ewf19tYQ.js} +1 -1
- package/dist/client/assets/{DotsHorizontal-RsDeFGvO.js → DotsHorizontal-KHWDbLx3.js} +1 -1
- package/dist/client/assets/{DotsVertical-Co7jTcE3.js → DotsVertical-CMwmj3Es.js} +1 -1
- package/dist/client/assets/{Download01-Bmf0yTxv.js → Download01-D2v6tnjT.js} +1 -1
- package/dist/client/assets/{Edit01-N_wE51Ji.js → Edit01-DLX_Q0on.js} +1 -1
- package/dist/client/assets/{Eye-Cjx3gmL-.js → Eye-DRhYa9c6.js} +1 -1
- package/dist/client/assets/{File02-B0_YpZ9K.js → File02-CJp6EwHF.js} +1 -1
- package/dist/client/assets/{File06-D5WlkKz7.js → File06-DVtDhdE5.js} +1 -1
- package/dist/client/assets/{FilterLines-ByV6YQqf.js → FilterLines-BcYSGfMN.js} +1 -1
- package/dist/client/assets/{Grid01-g5UbnnWY.js → Grid01-CgGHrqe5.js} +1 -1
- package/dist/client/assets/{Home02-6R9rPjal.js → Home02-uUB8Atfq.js} +1 -1
- package/dist/client/assets/{Image01-BoBW5lkf.js → Image01-C2cIbm7r.js} +1 -1
- package/dist/client/assets/{Inbox01-V2c_v8Vp.js → Inbox01-De5dzagw.js} +1 -1
- package/dist/client/assets/{InfoCircle-DbRe7m5X.js → InfoCircle-CWs-zdhv.js} +1 -1
- package/dist/client/assets/{LinkExternal01-B46QCd1_.js → LinkExternal01-7UvZi8_7.js} +1 -1
- package/dist/client/assets/{List-CnnFCaa_.js → List-B1anaj6z.js} +1 -1
- package/dist/client/assets/{Loading01-Ccnn8_nz.js → Loading01-CLaVZz2q.js} +1 -1
- package/dist/client/assets/{Lock01-CVg2TqaU.js → Lock01-DQZtigfQ.js} +1 -1
- package/dist/client/assets/{Pin01-CF5MBNG_.js → Pin01-DbMTghLG.js} +1 -1
- package/dist/client/assets/{Play-C_QZtdLh.js → Play-DifJQu9t.js} +1 -1
- package/dist/client/assets/{Plus-CvcYPEKD.js → Plus-BSoD06T5.js} +1 -1
- package/dist/client/assets/{RefreshCcw01-BhE8Z0sx.js → RefreshCcw01-vEyX2U13.js} +1 -1
- package/dist/client/assets/{SearchMd-B9p0bq1M.js → SearchMd-C3imEkj_.js} +1 -1
- package/dist/client/assets/{Settings01-BhBPpX3P.js → Settings01-D8Z_Og0d.js} +1 -1
- package/dist/client/assets/{Settings02-C75jbNRo.js → Settings02-DgNG_ojd.js} +1 -1
- package/dist/client/assets/{Share07-CA-_juFF.js → Share07-hI7-H_19.js} +1 -1
- package/dist/client/assets/{Terminal-D42HfJTr.js → Terminal-DY1lkBQp.js} +1 -1
- package/dist/client/assets/{Tool01-KjU2GsJW.js → Tool01-0C3r9eV1.js} +1 -1
- package/dist/client/assets/{Trash01-D_mSmFpX.js → Trash01-DMOrN3jw.js} +1 -1
- package/dist/client/assets/{Upload01-CYF85wnV.js → Upload01-BexbsGa1.js} +1 -1
- package/dist/client/assets/{Users03-DnAc5DRq.js → Users03-BwVADaNJ.js} +1 -1
- package/dist/client/assets/{X-CTTAOdP5.js → X-Bl4EbJn_.js} +1 -1
- package/dist/client/assets/{XClose-BDwJzgQF.js → XClose-9BHLBZyJ.js} +1 -1
- package/dist/client/assets/{agent-connections-preview-WthQDsUW.js → agent-connections-preview-bfNWF9f4.js} +1 -1
- package/dist/client/assets/{agent-detail-BqH9cJNR.js → agent-detail-C0LVwYuk.js} +1 -1
- package/dist/client/assets/{agents-BKnANQQN.js → agents-Da7CoTZX.js} +1 -1
- package/dist/client/assets/{alert-dialog-BJDYLAWS.js → alert-dialog-COW9KsrJ.js} +1 -1
- package/dist/client/assets/{auth-catchall-CuG4SMT1.js → auth-catchall-Cx74TIV5.js} +1 -1
- package/dist/client/assets/{avatar-hfcMVnoj.js → avatar-B3_biBMx.js} +1 -1
- package/dist/client/assets/{badge-CIAJTYZ7.js → badge-BdBlFaz2.js} +1 -1
- package/dist/client/assets/{binder--fFRikp7.js → binder-C_nJEmPU.js} +1 -1
- package/dist/client/assets/{breadcrumb-D1rwM2Yk.js → breadcrumb-CFvRp0LA.js} +1 -1
- package/dist/client/assets/{button-BnN5ws1J.js → button-DjRH1lB9.js} +1 -1
- package/dist/client/assets/{card-BX6VrB48.js → card-Crky3Dgs.js} +1 -1
- package/dist/client/assets/{checkbox-DOeM5BVC.js → checkbox-Buxpr0H5.js} +1 -1
- package/dist/client/assets/{circle-alert-CanUFwMg.js → circle-alert-B1x_VZv1.js} +1 -1
- package/dist/client/assets/{collection-detail-BfT9tQOH.js → collection-detail-hSjhUQb2.js} +1 -1
- package/dist/client/assets/{collection-search-Bg9cWleV.js → collection-search-Bznozec1.js} +1 -1
- package/dist/client/assets/{collection-tab-CMls2aRz.js → collection-tab-ETUYU_1h.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-IH3SFlYc.js → collection-table-wrapper-vIBxhjD_.js} +1 -1
- package/dist/client/assets/{collection-tabs-HtJ4lBOg.js → collection-tabs-Bsw5t_Dk.js} +1 -1
- package/dist/client/assets/{command-DKX4YOs7.js → command-BAunXmp4.js} +1 -1
- package/dist/client/assets/{connect-CScXrMiF.js → connect-r9AFxBWi.js} +1 -1
- package/dist/client/assets/{connection-card-8FtaUNQo.js → connection-card-BDRzJeyM.js} +1 -1
- package/dist/client/assets/{connection-detail-Bth-DhCL.js → connection-detail-BdzqkQsY.js} +1 -1
- package/dist/client/assets/{connections-CdtHndVF.js → connections-Ba704Ay2.js} +1 -1
- package/dist/client/assets/constants-B-3MHVrP.js +1 -0
- package/dist/client/assets/{constants-C28hHydK.js → constants-BbV5_Gvn.js} +1 -1
- package/dist/client/assets/{create-organization-dialog-ACj0lCMg.js → create-organization-dialog-CjDiPAzO.js} +1 -1
- package/dist/client/assets/{create-project-dialog-CG1IAO6H.js → create-project-dialog-BdjSvU61.js} +1 -1
- package/dist/client/assets/{dialog-DeXMCOEf.js → dialog-Ci90OZB_.js} +1 -1
- package/dist/client/assets/{dropdown-menu-DPxrC0cn.js → dropdown-menu-D0d6DveS.js} +1 -1
- package/dist/client/assets/{dynamic-plugin-layout-RLjAjaM3.js → dynamic-plugin-layout-Cde8Zw72.js} +1 -1
- package/dist/client/assets/{empty-state-DXwHwR9N.js → empty-state-B1u2cnEd.js} +1 -1
- package/dist/client/assets/{empty-state-C7dCfthv.js → empty-state-Db26F2g6.js} +1 -1
- package/dist/client/assets/{env-vars-editor-CLkN05wk.js → env-vars-editor-CCksRmt4.js} +1 -1
- package/dist/client/assets/{error-boundary-D93CFTiZ.js → error-boundary-DAtnvYEv.js} +1 -1
- package/dist/client/assets/{extract-connection-data-BXN_EDIw.js → extract-connection-data-C1ap4UAi.js} +1 -1
- package/dist/client/assets/{file-browser-BS2NyUbN.js → file-browser-vsIHIoyy.js} +2 -2
- package/dist/client/assets/{form-BCLb-UZ8.js → form-DwpSVrp-.js} +1 -1
- package/dist/client/assets/{grid-view-ooajsBAE.js → grid-view-B0rAMSSu.js} +1 -1
- package/dist/client/assets/{home-DxR7zQcl.js → home-BvOOt5Jz.js} +1 -1
- package/dist/client/assets/{index-sPSrSvLX.js → index-B6v49bFc.js} +1 -1
- package/dist/client/assets/{index-COa_SM9b.js → index-BWt7IZ6Z.js} +1 -1
- package/dist/client/assets/{index-Ddnu0nh3.js → index-Bs-0nDVT.js} +1 -1
- package/dist/client/assets/{index-CIh8Wxq9.js → index-C0Cm9UFB.js} +1 -1
- package/dist/client/assets/{index-BKKW7mU3.js → index-CGRyA9w8.js} +2 -2
- package/dist/client/assets/{index-BeRVkHG-.js → index-CnWGXAB7.js} +1 -1
- package/dist/client/assets/{index-Yaa_q04V.js → index-DA6l4j1R.js} +1 -1
- package/dist/client/assets/{index-Cm60R_4-.js → index-DF5Pmq_t.js} +1 -1
- package/dist/client/assets/{index-DH-kjK80.js → index-DirGeY-G.js} +1 -1
- package/dist/client/assets/{infiniteQueryObserver-C--Cp687.js → infiniteQueryObserver-Bz2qGnnL.js} +1 -1
- package/dist/client/assets/{input-U8YSaKi9.js → input-BN8tWROr.js} +1 -1
- package/dist/client/assets/{integration-icon-CAACzZ59.js → integration-icon-C_JseQQS.js} +1 -1
- package/dist/client/assets/{label-DSCjug1q.js → label-DgY9ov9i.js} +1 -1
- package/dist/client/assets/{layout-D93kgkkB.js → layout-CBw836gt.js} +1 -1
- package/dist/client/assets/{localstorage-keys-B_Uu7Ngj.js → localstorage-keys-nexyeweP.js} +1 -1
- package/dist/client/assets/{login-mt0PAQTm.js → login-CiVf3zef.js} +1 -1
- package/dist/client/assets/{mcp-oauth-BmANfNMA.js → mcp-oauth-B6wyAMx4.js} +1 -1
- package/dist/client/assets/{mcp-server-card-DOw4tptS.js → mcp-server-card-OYdKEPTN.js} +1 -1
- package/dist/client/assets/{mcp-server-detail-HN9d-4zv.js → mcp-server-detail-CuJRzZD8.js} +2 -2
- package/dist/client/assets/{members-o9UHewte.js → members-DkeJcxqi.js} +1 -1
- package/dist/client/assets/{monitoring-DeMCxpp8.js → monitoring-egwPLjp0.js} +1 -1
- package/dist/client/assets/{oauth-callback-OXPIh8UO.js → oauth-callback-CiwqJVg6.js} +1 -1
- package/dist/client/assets/{page-D8ANTJRr.js → page-BmoxBndy.js} +1 -1
- package/dist/client/assets/{page-D1jCMFVy.js → page-YgKzJWRP.js} +1 -1
- package/dist/client/assets/{plugin-empty-state-CseSTXo8.js → plugin-empty-state-Bm8j6Yah.js} +1 -1
- package/dist/client/assets/{plugin-empty-state-BztjA2Hv.js → plugin-empty-state-Cg6QQuTW.js} +1 -1
- package/dist/client/assets/{plugin-header-CYOR-GLV.js → plugin-header-BiBPfNm9.js} +1 -1
- package/dist/client/assets/{plugin-header-CJXqQw-8.js → plugin-header-Za0zOP8_.js} +1 -1
- package/dist/client/assets/{popover-Z8clS3LN.js → popover-DBISvNt-.js} +1 -1
- package/dist/client/assets/{project-layout-CToIFtP6.js → project-layout-wSllqfdZ.js} +1 -1
- package/dist/client/assets/{project-settings-BjPBm7hi.js → project-settings-B34SlsnE.js} +1 -1
- package/dist/client/assets/{projects-list-B8b521eA.js → projects-list-KQgHFl7X.js} +1 -1
- package/dist/client/assets/{registry-utils-CCgmzWkr.js → registry-utils-D9WTBcQy.js} +1 -1
- package/dist/client/assets/{resizable-CcAX-qs1.js → resizable-J8Aer48-.js} +1 -1
- package/dist/client/assets/{scroll-area-F4PB57Kk.js → scroll-area-DMcUXGPI.js} +1 -1
- package/dist/client/assets/{select-CPhIWiJc.js → select-CMUKnHD5.js} +1 -1
- package/dist/client/assets/{shell-layout-D9dQPkQK.js → shell-layout-CSqxCJ3A.js} +3 -3
- package/dist/client/assets/{spinner-BJo9JKPd.js → spinner-BWmTCne_.js} +1 -1
- package/dist/client/assets/{store-invite-BEQkmcfX.js → store-invite-DQVzahJ1.js} +1 -1
- package/dist/client/assets/{switch-C7RggtH3.js → switch-C-ipB4wM.js} +1 -1
- package/dist/client/assets/{table-GcQdAqoi.js → table-CTqJjnnx.js} +1 -1
- package/dist/client/assets/{tasks-B82Xf5C5.js → tasks-DQVfyRle.js} +1 -1
- package/dist/client/assets/{textarea-DWFHG2PH.js → textarea-BqR62h0i.js} +1 -1
- package/dist/client/assets/{tools-list-BziYrhBQ.js → tools-list-1sYuTCQT.js} +1 -1
- package/dist/client/assets/{topbar-portal-DGJkq20l.js → topbar-portal-uY9HhOr1.js} +1 -1
- package/dist/client/assets/{typewriter-title-BBGN8eX7.js → typewriter-title-rlX4QtWe.js} +1 -1
- package/dist/client/assets/{use-binding-C4vpH74C.js → use-binding-CBFm-KJH.js} +1 -1
- package/dist/client/assets/{use-connection-BWi2Db6r.js → use-connection-TBbvY88o.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-CccQ7wjf.js → use-create-virtual-mcp-DkEEEEVB.js} +1 -1
- package/dist/client/assets/{use-deco-chat-open-B9pKJybL.js → use-deco-chat-open-B3MDOzNO.js} +1 -1
- package/dist/client/assets/{use-install-from-registry-CNEIPsot.js → use-install-from-registry-CanzeI6m.js} +1 -1
- package/dist/client/assets/{use-list-state-D5f0NwUO.js → use-list-state-CB60FBzS.js} +1 -1
- package/dist/client/assets/{use-llm-DYhOWhPI.js → use-llm-D5XtsGft.js} +1 -1
- package/dist/client/assets/{use-mcp-prompts-CH0-e-U1.js → use-mcp-prompts-DdiPSE2K.js} +1 -1
- package/dist/client/assets/{use-mcp-tools-Yi0eODm2.js → use-mcp-tools-DreUeH6b.js} +1 -1
- package/dist/client/assets/{use-mobile-mUe1k1NH.js → use-mobile-C8iqPQJB.js} +1 -1
- package/dist/client/assets/{use-organization-settings-ZMMNYlgW.js → use-organization-settings-BjgTdt4t.js} +1 -1
- package/dist/client/assets/{use-project-C8eld6R6.js → use-project-kGpYxwPL.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-C7qHxpwx.js → use-virtual-mcp-C7Kk1mBJ.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-XNPJlDVU.js +1 -0
- package/dist/client/assets/{useMutation-Bmfdf_Yk.js → useMutation-Bm-DrAfF.js} +1 -1
- package/dist/client/assets/useQuery-DM_qidpz.js +1 -0
- package/dist/client/assets/{view-mode-toggle-BseoteE9.js → view-mode-toggle-a-_OzLvE.js} +1 -1
- package/dist/client/assets/{workflow-DK9VwlEt.js → workflow-Q7ys8Pux.js} +1 -1
- package/dist/client/index.html +1 -1
- package/dist/server/cli.js +1 -1
- package/dist/server/migrate.js +1 -1
- package/dist/server/server.js +1 -1
- package/package.json +1 -1
- package/dist/client/assets/constants-9Txgq7Bp.js +0 -1
- package/dist/client/assets/useInfiniteQuery-B1egfGHi.js +0 -1
- package/dist/client/assets/useQuery-DoLjDGJT.js +0 -1
package/dist/server/server.js
CHANGED
|
@@ -1200,7 +1200,7 @@ ${Y.stack}`;return Q}if(typeof Y==="object"&&Y!==null){let Q=Y,X="";if(typeof Q.
|
|
|
1200
1200
|
${Q.stack}`;return X}try{let G=JSON.stringify(Q,null,2);if(G!=="{}"&&G.length<1000){if(typeof Q.stack==="string"&&Q.stack&&Q.stack.length<2000)return`${G}
|
|
1201
1201
|
|
|
1202
1202
|
Stack trace:
|
|
1203
|
-
${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Q);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function HN(Y,Q){switch(typeof Q){case"string":return Y.newString(Q);case"number":return Y.newNumber(Q);case"boolean":return Q?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(Q===null)return Y.null;if(Array.isArray(Q)){let J=Y.newArray();return Q.forEach((G,K)=>{let W=HN(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let X=Y.newObject();for(let[J,G]of Object.entries(Q)){let K=HN(Y,G);try{Y.setProp(X,J,K)}finally{K.dispose?.()}}return X}case"function":{let X=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(X,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=Q(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let F=HN(Y,H);Z.resolve(F),F.dispose()}catch(F){let $=KN(F),V=Y.newString(`Promise resolution error: ${$}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let F=KN(H),$=Y.newString(`Promise rejection: ${F}`);Z.reject($),$.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return HN(Y,W)}catch(K){let W=KN(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(Q.toString());case"symbol":return Y.newString(Q.toString());default:try{return Y.newString(String(Q))}catch{return Y.undefined}}}var yE0=()=>{};function bE0(Y){let Q=Y.runtime.executePendingJobs(100);try{if("unwrap"in Q&&typeof Q.unwrap==="function")Q.unwrap()}finally{if("dispose"in Q&&typeof Q.dispose==="function")Q.dispose()}}async function fE0(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){bE0(Y);let K=await Promise.race([G,yF4(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>X)throw Error(`Timed out after ${X}ms while awaiting a QuickJS promise`)}}async function oC({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=lR(W,await kE0({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=lR(W,J.newContext({interruptAfterMs:X}),0);const K=lR(W,IE0(G),0);try{let $=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult($),q=HN(G,Y);G.setProp(G.global,"tools",q);let z=G.runtime.hasPendingJob()?G.unwrapResult(await fE0(G,V,X)):V;if(z!==V)V.dispose();let U=G.getProp(z,"default"),D=G.typeof(U);if(D!=="function")return U.dispose(),z.dispose(),q.dispose(),{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let M=G.callFunction(U,G.undefined,q);q.dispose(),U.dispose(),z.dispose();let w=G.unwrapResult(M),R=await fE0(G,w,X);w.dispose();let P=G.unwrapResult(R);if(G.runtime.hasPendingJob())bE0(G);let T=G.dump(P);return P.dispose(),{returnValue:T,consoleLogs:K.logs}}catch($){return console.log($),{error:KN($),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{TF1(W,H,F)}}var yF4=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var hE0=k(()=>{_E0();yE0()});var gK1=k(()=>{hE0()});async function fF4(Y,Q){let X=Y.connections.map((K)=>K.connection_id),J=[];for(let K of X){let W=await Q.storage.connections.findById(K);if(W&&W.status==="active")J.push(W)}return J.map((K)=>{let W=Y.connections.find((Z)=>Z.connection_id===K.id);return{connection:K,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}async function xE0(Y,Q){return(await Q.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function bF4(Y,Q){let X=new Map;for(let q of Y)X.set(q.connection.id,q);let J=Y.map((q)=>q.connection),G=new Map,K=await Promise.allSettled(J.map(async(q)=>{try{let z=await Q.createMCPProxy(q);return{connection:q,proxy:z}}catch(z){return console.warn(`[code-execution] Failed to create proxy for connection ${q.id}:`,z),null}}));for(let q of K)if(q.status==="fulfilled"&&q.value)G.set(q.value.connection.id,q.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([q,z])=>{try{let D=(await z.proxy.listTools()).tools,M=X.get(q);if(M?.selectedTools&&M.selectedTools.length>0){let w=new Set(M.selectedTools);D=D.filter((R)=>w.has(R.name))}return{connectionId:q,connectionTitle:z.connection.title,tools:D}}catch(U){return console.error(`[code-execution] Failed to list tools for connection ${q}:`,U),null}})),Z=new Set,H=[],F=new Map;for(let q of W){if(q.status!=="fulfilled"||!q.value)continue;let{connectionId:z,connectionTitle:U,tools:D}=q.value;for(let M of D){if(Z.has(M.name))continue;Z.add(M.name),H.push({...M,_meta:{connectionId:z,connectionTitle:U}}),F.set(M.name,z)}}let $=async(q,z)=>{let U=F.get(q);if(!U)return{content:[{type:"text",text:`Tool not found: ${q}`}],isError:!0};let D=G.get(U);if(!D)return{content:[{type:"text",text:`Connection not found for tool: ${q}`}],isError:!0};return await D.proxy.callTool({name:q,arguments:z})},V=[];for(let[,q]of G)V.push(q.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:$}}async function FN(Y){let Q=A0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await fF4(J,Y);else X=await xE0(Q.id,Y)}else X=await xE0(Q.id,Y);return bF4(X,Y)}function hF4(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function xF4(Y,Q){let X=0,J=Q.name.toLowerCase(),G=(Q.description??"").toLowerCase(),K=(Q._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)X+=10;else if(J.includes(W))X+=3;if(G.includes(W))X+=2;if(K.includes(W))X+=1}return X}function kl(Y,Q,X){let J=hF4(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:xF4(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function _l(Y,Q){let X=new Map(Q.map((G)=>[G.name,G]));return{tools:Y.map((G)=>X.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:Y.filter((G)=>!X.has(G))}}async function yl(Y,Q,X){let J=Object.fromEntries(Q.tools.map((G)=>[G.name,async(K)=>Q.callTool(G.name,K??{})]));return oC({code:Y,tools:J,timeoutMs:X})}function sC(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function H$(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function w3(Y){let Q=new Set(gF4);return Y.filter((X)=>!Q.has(X.name))}var gF4;var xB=k(()=>{gK1();gF4=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var uK1;var gE0=k(()=>{c0();rC();xB();uK1=l1({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:AE0,outputSchema:PE0,handler:async(Y,Q)=>{a1(Q),A0(Q),await Q.access.check();let X=await FN(Q),J=kl(Y.query,X.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:X.tools.length}}})});var mK1;var uE0=k(()=>{c0();rC();xB();mK1=l1({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:EE0,outputSchema:TE0,handler:async(Y,Q)=>{a1(Q),A0(Q),await Q.access.check();let X=await FN(Q);return _l(Y.tools,X.tools)}})});var lK1;var mE0=k(()=>{c0();rC();xB();lK1=l1({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:CE0,outputSchema:RE0,handler:async(Y,Q)=>{a1(Q),A0(Q),await Q.access.check();let X=await FN(Q);return await yl(Y.code,X,Y.timeoutMs)}})});var lE0=k(()=>{gE0();uE0();mE0();rC()});var mF4,lF4,dK1;var dE0=k(()=>{UY();d1();c0();Tm();G3();mF4=B.object({data:z2.describe("Data for the new connection (id is auto-generated if not provided)")}),lF4=B.object({item:EQ.describe("The created connection entity")}),dK1=l1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:mF4,outputSchema:lF4,handler:async(Y,Q)=>{a1(Q);let X=A0(Q);await Q.access.check();let J=O9(Q);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:X.id,created_by:J};if(G.connection_type==="VIRTUAL"){let H=$q(G.connection_url);if(!H)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await Q.storage.virtualMcps.findById(H);if(!F)throw Error(`Virtual MCP not found: ${H}`);if(F.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=Vq(H)}let K=await xL({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=K?.length?K:null,Z=await Q.storage.connections.create({...G,tools:W});return await Q.eventBus.publish(X.id,PQ.SELF(X.id),{type:"connection.created",data:Z}),{item:Z}}})});var dF4,pE0,kj8;var cE0=k(()=>{d1();wJ();dF4=B.object({id:B.string(),name:B.string(),description:B.string().optional(),inputSchema:B.record(B.string(),B.unknown()),outputSchema:B.record(B.string(),B.unknown()).optional()}),pE0=NZ.extend({_meta:B.object({"io.decocms":B.object({id:B.string(),verified:B.boolean(),scopeName:B.string(),appName:B.string(),friendlyName:B.string().nullable().optional(),metadata:B.record(B.string(),B.unknown()).nullable().optional(),publishedAt:B.string().datetime().optional(),updatedAt:B.string().datetime().optional(),tools:B.array(dF4).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:B.object({$schema:B.string().optional(),_meta:B.record(B.string(),B.unknown()).optional(),name:B.string().describe("The server name (scope/app)"),title:B.string().optional().describe("User-friendly title"),description:B.string().optional().describe("Server description"),icons:B.array(B.object({src:B.string(),mimeType:B.string().optional(),sizes:B.array(B.string()).optional(),theme:B.enum(["light","dark"]).optional()})).optional(),remotes:B.array(B.object({type:B.enum(["http","stdio","sse"]),url:B.string().optional(),headers:B.array(B.unknown()).optional()})).optional(),packages:B.array(B.unknown()).optional(),repository:B.object({url:B.string(),source:B.string().optional(),subfolder:B.string().optional()}).optional(),version:B.string().optional(),websiteUrl:B.string().optional()})}),kj8=MZ("registry_app",pE0,{readOnly:!0})});var nE0,iE0,aE0,rE0,oE0,pK1;var sE0=k(()=>{d1();gL();nE0=B.object({specversion:B.literal("1.0").describe("CloudEvents specification version"),id:B.string().describe("Unique identifier for this event (UUID recommended)"),source:B.string().describe("Connection ID of the event publisher"),type:B.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:B.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:B.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:B.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:B.string().url().optional().describe("URI to the schema for the data attribute"),data:B.unknown().optional().describe("Event payload (any JSON value)")}),iE0=B.object({events:B.array(nE0).min(1).describe("Batch of CloudEvents to process")}),aE0=B.object({success:B.boolean().optional().describe("Whether this event was processed successfully"),error:B.string().optional().describe("Error message for this event"),retryAfter:B.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),rE0=B.object({success:B.boolean().optional().describe("Batch success - applies to events not in results"),error:B.string().optional().describe("Batch error message - applies to events not in results"),processedCount:B.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:B.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:B.record(B.string(),aE0).optional().describe("Per-event results keyed by event ID")}),oE0=[{name:"ON_EVENTS",inputSchema:iE0,outputSchema:rE0}],pK1=K3(oE0)});var tC,eC,YR,QR,tE0,eE0,XR,JR,GR,WR,ZR,KR,HR,FR,YT0,pF4;var QT0=k(()=>{d1();gL();tC=B.object({type:B.string().min(1).max(255).describe("Event type identifier"),subject:B.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:B.unknown().optional().describe("Event payload"),deliverAt:B.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:B.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),eC=B.object({id:B.string().describe("Unique event ID"),type:B.string().describe("Event type"),source:B.string().describe("Source connection ID"),time:B.string().describe("Event timestamp")}),YR=B.object({eventType:B.string().min(1).max(255).describe("Event type to subscribe to"),publisher:B.string().optional().describe("Filter events by publisher connection ID"),filter:B.string().max(1000).optional().describe("JSONPath filter expression on event data")}),QR=B.object({subscription:B.object({id:B.string().describe("Subscription ID"),connectionId:B.string().describe("Subscriber connection ID"),eventType:B.string().describe("Event type pattern"),publisher:B.string().nullable().describe("Publisher connection filter"),filter:B.string().nullable().describe("JSONPath filter expression"),enabled:B.boolean().describe("Whether subscription is enabled"),createdAt:B.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:B.string().datetime().describe("Updated timestamp (ISO 8601)")})}),tE0=B.object({eventType:B.string().min(1).max(255).describe("Event type to subscribe to"),publisher:B.string().optional().describe("Filter events by publisher connection ID"),filter:B.string().max(1000).optional().describe("JSONPath filter expression on event data")}),eE0=B.object({id:B.string().describe("Subscription ID"),connectionId:B.string().describe("Subscriber connection ID"),eventType:B.string().describe("Event type pattern"),publisher:B.string().nullable().describe("Publisher connection filter"),filter:B.string().nullable().describe("JSONPath filter expression"),enabled:B.boolean().describe("Whether subscription is enabled"),createdAt:B.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:B.string().datetime().describe("Updated timestamp (ISO 8601)")}),XR=B.object({subscriptions:B.array(tE0).describe("Desired subscriptions - system will create/update/delete to match")}),JR=B.object({created:B.number().int().min(0).describe("Number of subscriptions created"),updated:B.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:B.number().int().min(0).describe("Number of subscriptions removed"),unchanged:B.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:B.array(eE0).describe("Current subscriptions after sync")}),GR=B.object({subscriptionId:B.string().describe("Subscription ID to remove")}),WR=B.object({success:B.boolean().describe("Whether unsubscribe was successful"),subscriptionId:B.string().describe("Subscription ID that was removed")}),ZR=B.object({eventId:B.string().describe("Event ID to cancel")}),KR=B.object({success:B.boolean().describe("Whether cancellation was successful"),eventId:B.string().describe("Event ID that was cancelled")}),HR=B.object({eventId:B.string().describe("Event ID to acknowledge")}),FR=B.object({success:B.boolean().describe("Whether ACK was successful"),eventId:B.string().describe("Event ID that was acknowledged")}),YT0=[{name:"EVENT_PUBLISH",inputSchema:tC,outputSchema:eC},{name:"EVENT_SUBSCRIBE",inputSchema:YR,outputSchema:QR},{name:"EVENT_UNSUBSCRIBE",inputSchema:GR,outputSchema:WR},{name:"EVENT_CANCEL",inputSchema:ZR,outputSchema:KR},{name:"EVENT_ACK",inputSchema:HR,outputSchema:FR},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:XR,outputSchema:JR}],pF4=K3(YT0)});var cF4,nF4,iF4,aF4,rF4,oF4,sF4,tF4,eF4,Y$4,Q$4,X$4,$R;var fl=k(()=>{d1();cF4=B.object({prefix:B.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:B.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:B.string().optional().describe("Token for pagination from previous response"),delimiter:B.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),nF4=B.object({objects:B.array(B.object({key:B.string().describe("Object key/path"),size:B.number().describe("Object size in bytes"),lastModified:B.string().describe("Last modified timestamp"),etag:B.string().describe("Entity tag for the object")})),nextContinuationToken:B.string().optional().describe("Token for fetching next page of results"),isTruncated:B.boolean().describe("Whether there are more results available"),commonPrefixes:B.array(B.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),iF4=B.object({key:B.string().describe("Object key/path to get metadata for")}),aF4=B.object({contentType:B.string().optional().describe("MIME type of the object"),contentLength:B.number().describe("Size of the object in bytes"),lastModified:B.string().describe("Last modified timestamp"),etag:B.string().describe("Entity tag for the object"),metadata:B.record(B.string(),B.string()).optional().describe("Custom metadata key-value pairs")}),rF4=B.object({key:B.string().describe("Object key/path to generate URL for"),expiresIn:B.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),oF4=B.object({url:B.string().describe("Presigned URL for downloading the object"),expiresIn:B.number().describe("Expiration time in seconds that was used")}),sF4=B.object({key:B.string().describe("Object key/path for the upload"),expiresIn:B.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:B.string().optional().describe("MIME type for the object being uploaded")}),tF4=B.object({url:B.string().describe("Presigned URL for uploading the object"),expiresIn:B.number().describe("Expiration time in seconds that was used")}),eF4=B.object({key:B.string().describe("Object key/path to delete")}),Y$4=B.object({success:B.boolean().describe("Whether the deletion was successful"),key:B.string().describe("The key that was deleted")}),Q$4=B.object({keys:B.array(B.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),X$4=B.object({deleted:B.array(B.string()).describe("Array of successfully deleted keys"),errors:B.array(B.object({key:B.string(),message:B.string()})).describe("Array of errors for failed deletions")}),$R=[{name:"LIST_OBJECTS",inputSchema:cF4,outputSchema:nF4},{name:"GET_OBJECT_METADATA",inputSchema:iF4,outputSchema:aF4},{name:"GET_PRESIGNED_URL",inputSchema:rF4,outputSchema:oF4},{name:"PUT_PRESIGNED_URL",inputSchema:sF4,outputSchema:tF4},{name:"DELETE_OBJECT",inputSchema:eF4,outputSchema:Y$4},{name:"DELETE_OBJECTS",inputSchema:Q$4,outputSchema:X$4}]});var bl=k(()=>{gL();cE0();sE0();QT0();fl();uL()});var J$4,G$4,XT0;var JT0=k(()=>{d1();wJ();J$4=NZ.extend({avatar:B.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:B.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:B.string().describe("Virtual MCP ID to use for this assistant"),model:B.object({id:B.string().describe("Model ID"),connectionId:B.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),G$4=MZ("assistant",J$4),XT0=[...G$4]});var VR,A3,WT0,W$4,Z$4,ZT0,K$4,H$4,F$4,$$4,V$4,q$4,KT0,B$4,z$4,U$4,D$4,O$4,L$4,N$4,M$4,w$4,A$4,JS8,P$4,GS8,GT0,E$4,T$4,cK1,qR;var hl=k(()=>{d1();gL();wJ();VR=B.lazy(()=>B.union([B.null(),B.string(),B.number(),B.boolean(),B.record(B.string(),VR),B.array(VR)])),A3=B.record(B.string(),B.record(B.string(),VR)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),WT0=B.object({type:B.literal("text"),text:B.string().describe("The text content"),providerOptions:A3}),W$4=B.object({type:B.literal("text"),text:B.string().describe("The text content"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),Z$4=B.string().describe("File data as URL string"),ZT0=B.object({type:B.literal("file"),filename:B.string().optional().describe("Optional filename of the file"),data:Z$4,mediaType:B.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:A3}),K$4=B.object({type:B.literal("file"),mediaType:B.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:B.string().describe("Generated file data as base64 encoded string")}),H$4=B.object({type:B.literal("reasoning"),text:B.string().describe("The reasoning text"),providerOptions:A3}),F$4=B.object({type:B.literal("reasoning"),text:B.string().describe("The reasoning text"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),$$4=B.object({type:B.literal("tool-call"),toolCallId:B.string().describe("ID of the tool call, used to match with tool result"),toolName:B.string().describe("Name of the tool being called"),input:B.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:B.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:A3}),V$4=B.object({type:B.literal("tool-call"),toolCallId:B.string().describe("ID of the tool call"),toolName:B.string().describe("Name of the tool being called"),input:B.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:B.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),q$4=B.union([B.object({type:B.literal("text"),value:B.string()}),B.object({type:B.literal("json"),value:VR}),B.object({type:B.literal("error-text"),value:B.string()}),B.object({type:B.literal("error-json"),value:VR}),B.object({type:B.literal("content"),value:B.array(B.union([B.object({type:B.literal("text"),text:B.string().describe("Text content")}),B.object({type:B.literal("media"),data:B.string().describe("Base-64 encoded media data"),mediaType:B.string().describe("IANA media type")})]))})]),KT0=B.object({type:B.literal("tool-result"),toolCallId:B.string().describe("ID of the tool call that this result is associated with"),toolName:B.string().describe("Name of the tool that generated this result"),output:q$4.describe("Result of the tool call"),result:B.unknown().describe("Unknown result of the tool call"),providerOptions:A3}),B$4=B.object({type:B.literal("tool-result"),toolCallId:B.string().describe("ID of the tool call that this result is associated with"),toolName:B.string().describe("Name of the tool that generated this result"),result:B.any().describe("Result of the tool call (JSON-serializable)"),isError:B.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:B.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),z$4=B.union([B.object({type:B.literal("source"),sourceType:B.literal("url"),id:B.string().describe("The ID of the source"),url:B.string().describe("The URL of the source"),title:B.string().optional().describe("The title of the source"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),B.object({type:B.literal("source"),sourceType:B.literal("document"),id:B.string().describe("The ID of the source"),mediaType:B.string().describe("IANA media type of the document (e.g., application/pdf)"),title:B.string().describe("The title of the document"),filename:B.string().optional().describe("Optional filename of the document"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")})]),U$4=B.object({role:B.literal("system"),content:B.string().describe("System message content"),providerOptions:A3}),D$4=B.object({role:B.literal("user"),content:B.array(B.union([WT0,ZT0])).describe("User message content parts (text or file)"),providerOptions:A3}),O$4=B.object({role:B.literal("assistant"),content:B.array(B.union([WT0,ZT0,H$4,$$4,KT0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:A3}),L$4=B.object({role:B.literal("tool"),content:B.array(KT0).describe("Tool message content (tool results)"),providerOptions:A3}),N$4=B.union([U$4,D$4,O$4,L$4]),M$4=B.array(N$4).describe("A list of messages forming the prompt"),w$4=B.object({prompt:M$4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:B.number().optional().describe("Maximum number of tokens to generate"),temperature:B.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:B.number().optional().describe("Nucleus sampling parameter"),topK:B.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:B.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:B.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:B.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:B.array(B.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:B.union([B.object({type:B.literal("text")}),B.object({type:B.literal("json"),schema:B.any().optional().describe("JSON schema that the generated output should conform to"),name:B.string().optional().describe("Name of output that should be generated"),description:B.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:B.array(B.any()).optional().describe("The tools that are available for the model"),toolChoice:B.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:B.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:B.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:B.any().optional().describe("Additional provider-specific options")}),A$4=B.object({content:B.array(B.union([W$4,K$4,F$4,V$4,B$4,z$4])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:B.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:B.looseObject({inputTokens:B.number().optional(),outputTokens:B.number().optional(),totalTokens:B.number().optional(),reasoningTokens:B.number().optional()}).describe("Usage information for the language model call"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata"),request:B.object({body:B.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:B.object({id:B.string().optional().describe("ID for the generated response"),timestamp:B.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:B.string().optional().describe("The ID of the response model that was used"),headers:B.record(B.string(),B.string()).optional().describe("Response headers"),body:B.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:B.array(B.any()).describe("Warnings for the call, e.g. unsupported settings")}),JS8=B.object({stream:B.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:B.object({body:B.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:B.object({headers:B.record(B.string(),B.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),P$4=B.object({supportedUrls:B.record(B.string(),B.array(B.string())).describe("Supported URL patterns by media type for the provider")}),GS8=B.object({modelId:B.string().describe("The ID of the model"),logo:B.string().nullable(),description:B.string().nullable(),capabilities:B.array(B.string()),limits:B.object({contextWindow:B.number(),maxOutputTokens:B.number()}).nullable(),costs:B.object({input:B.number(),output:B.number()}).nullable(),provider:B.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),GT0=B.object({modelId:B.string().describe("The ID of the model"),callOptions:w$4}),E$4=NZ.extend({logo:B.string().nullable(),description:B.string().nullable(),capabilities:B.array(B.string()),limits:B.object({contextWindow:B.number(),maxOutputTokens:B.number()}).nullable(),costs:B.object({input:B.number(),output:B.number()}).nullable(),provider:B.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),T$4=MZ("llm",E$4,{readOnly:!0}),cK1=[{name:"LLM_METADATA",inputSchema:B.object({modelId:B.string().describe("The ID of the model")}),outputSchema:P$4},{name:"LLM_DO_STREAM",inputSchema:GT0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:GT0,outputSchema:A$4},...T$4],qR=K3(cK1)});function $N(){return!1}function xl(Y,Q){return Y===PQ.DEV_ASSETS(Q)}function VN(Y,Q){let X=Z91(Q,Y),J=new Date().toISOString();return{id:X.id??PQ.DEV_ASSETS(Y),title:X.title,description:X.description??null,icon:X.icon??null,app_name:X.app_name??null,app_id:X.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:X.connection_type,connection_url:X.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata??null,tools:C$4,bindings:["OBJECT_STORAGE"],status:"active"}}var C$4;var gl=k(()=>{fl();UY();d1();C$4=$R.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:B.toJSONSchema(Y.inputSchema),outputSchema:B.toJSONSchema(Y.outputSchema)}))});function I$4(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function F$(Y){return typeof Y==="string"||typeof Y==="number"}function ul(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every((F)=>ul(Y,F));case"or":return H.some((F)=>ul(Y,F));case"not":return!H.every((F)=>ul(Y,F));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=nK1(Y,K);switch(J){case"eq":return W===G;case"gt":return F$(W)&&F$(G)&&W>G;case"gte":return F$(W)&&F$(G)&&W>=G;case"lt":return F$(W)&&F$(G)&&W<G;case"lte":return F$(W)&&F$(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 Z=I$4(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function nK1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function j$4(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=nK1(X,K),Z=nK1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var R$4,S$4,v$4,iK1;var HT0=k(()=>{bl();JT0();wJ();hl();fl();UY();d1();c0();gl();G3();R$4={LLM:cK1,ASSISTANTS:XT0,OBJECT_STORAGE:$R};S$4=H3.extend({binding:B.union([B.object({}).passthrough(),B.string()]).optional(),include_virtual:B.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),v$4=F3(EQ),iK1=l1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:S$4,outputSchema:v$4,handler:async(Y,Q)=>{await Q.access.check();let X=A0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let q=R$4[Y.binding.toUpperCase()];if(!q)throw Error(`Unknown binding: ${Y.binding}`);return q})():Y.binding:void 0,G=J?km(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if($N()){let q=NJ(),z=PQ.DEV_ASSETS(X.id);if(!K.some((U)=>U.id===z)){let U=VN(X.id,q);K.unshift(U)}}let W=G?await Promise.all(K.map(async(q)=>{if(!q.tools||q.tools.length===0)return null;return G.isImplementedBy(q.tools.map((U)=>({name:U.name,inputSchema:U.inputSchema,outputSchema:U.outputSchema})))?q:null})).then((q)=>q.filter((z)=>z!==null)):K;if(Y.where)W=W.filter((q)=>ul(q,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=j$4(W,Y.orderBy);let Z=W.length,H=Y.offset??0,F=Y.limit??100,$=W.slice(H,H+F),V=H+F<Z;return{items:$,totalCount:Z,hasMore:V}}})});var k$4,aK1;var FT0=k(()=>{wJ();c0();gl();G3();k$4=DC(EQ),aK1=l1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:UC,outputSchema:k$4,handler:async(Y,Q)=>{let X=A0(Q);if(await Q.access.check(),$N()&&xl(Y.id,X.id))return{item:VN(X.id,NJ())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var ml=(Y,Q)=>{if(Q===null||Q===void 0)return;let X=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Q;for(let G of X){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function $T0(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return Q}function _$4(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function y$4(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function rK1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=_$4(J);if(!G)continue;let[K,W]=G,Z=ml(K,Y),H=y$4(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function VT0(Y,Q){let X=rK1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var oK1=()=>{};import{randomBytes as f$4}from"crypto";function qT0(){if(BR)return BR;let Y=process.env.MESH_JWT_SECRET??s9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)BR=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),BR=new Uint8Array(f$4(32));return BR}async function BT0(Y,Q="5m"){let X=qT0();return await new jX(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}async function zT0(Y){try{let Q=qT0(),{payload:X}=await a8(Y,Q);return X}catch{return}}var BR=null;var sK1=k(()=>{FJ();zR()});async function UT0(Y){if(!Y.refreshToken)return{success:!1,error:"No refresh token available"};if(!Y.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Y.clientId)return{success:!1,error:"No client ID available"};try{let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)Q.set("client_secret",Y.clientSecret);if(Y.scope)Q.set("scope",Y.scope);let X=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let G=await X.text();console.error(`[TokenRefresh] Failed to refresh token: ${X.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${X.status}`}}catch{return{success:!1,error:`Token refresh failed: ${X.status}`}}}let J=await X.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Q){return console.error("[TokenRefresh] Error refreshing token:",Q),{success:!1,error:Q instanceof Error?Q.message:"Token refresh failed"}}}class P3{db;vault;constructor(Y,Q){this.db=Y;this.vault=Q}async get(Y){let Q=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!Q)return null;return this.decryptToken(Q)}async upsert(Y){let Q=new Date().toISOString(),X=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:Q}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=D8("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:Q,updatedAt:Q}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Q,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,Q=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Q<Date.now()}async decryptToken(Y){let Q=await this.vault.decrypt(Y.accessToken),X=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:Q,refreshToken:X,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var ll=k(()=>{_7()});async function UR(Y,Q,X){let J=Y.id,G=rK1(Y.configuration_state,Y.configuration_scopes),K=Q.auth.user?.id??Q.auth.apiKey?.userId??(X?Y.created_by:void 0),[W,Z]=K?await BT0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:process.env.MESH_URL??Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((z)=>[z,null]).catch((z)=>[null,z]):[null,Error("User ID required to issue configuration token")];if(Z)console.error("Failed to issue configuration token:",W);let H=Q.auth.user?.connectionId,F={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},$=null,V=new P3(Q.db,Q.vault),q=await V.get(J);if(q){let z=!!q.refreshToken&&!!q.tokenEndpoint;if(V.isExpired(q,z?300000:0))if(z){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let D=await UT0(q);if(D.success&&D.accessToken)await V.upsert({connectionId:J,accessToken:D.accessToken,refreshToken:D.refreshToken??q.refreshToken,scope:D.scope??q.scope,expiresAt:D.expiresIn?new Date(Date.now()+D.expiresIn*1000):null,clientId:q.clientId,clientSecret:q.clientSecret,tokenEndpoint:q.tokenEndpoint}),$=D.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${D.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else $=q.accessToken}if(!$&&Y.connection_token)$=Y.connection_token;if($)F.Authorization=`Bearer ${$}`;if(W)F["x-mesh-token"]=W;return F}var tK1=k(()=>{oK1();sK1();ll()});function dl(){let Y=new Map;function Q(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;console.log(`[ClientPool] Creating new client for ${G}`);let W=new DX({name:`outbound-client-${G}`,version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});W.onclose=()=>{Y.delete(G)};let Z=W.connect(J,{timeout:30000}).then(()=>W).catch((H)=>{throw Y.delete(G),H});return Y.set(G,Z),Z}return Object.assign(Q,{[Symbol.asyncDispose]:async()=>{let J=[];for(let[G,K]of Y)J.push(K.then((W)=>W.close()).catch((W)=>console.error(`[ClientPool] Error closing client ${G}:`,W)));await Promise.all(J),Y.clear()}})}var eK1=k(()=>{Hq()});function DT0(Y){let Q=new HC({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),X=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return Q.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${X}]\x1B[0m`)}),Q}var OT0=k(()=>{TW1()});class DR{innerTransport;constructor(Y){this.innerTransport=Y}async start(){return this.innerTransport.onmessage=(Y)=>{this.handleIncomingMessage(Y)},this.innerTransport.onerror=(Y)=>{this.onerror?.(Y)},this.innerTransport.onclose=()=>{this.onclose?.()},this.innerTransport.start()}async send(Y){return this.handleOutgoingMessage(Y)}async close(){return this.innerTransport.close()}async handleOutgoingMessage(Y){return this.innerTransport.send(Y)}handleIncomingMessage(Y){this.onmessage?.(Y)}isRequest(Y){return"method"in Y&&Y.method!==void 0}isResponse(Y){return"result"in Y||"error"in Y&&!("method"in Y)}onmessage;onerror;onclose}function OR(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var LT0="mcp.mesh";var NT0,Y31,E3;var LR=k(()=>{NT0=class NT0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};Y31=class Y31 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};E3=class E3{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,Q,X,J,G,K="self",W){this.userId=Q;this.toolName=X;this.boundAuth=J;this.role=G;this.connectionId=K;this.getToolMeta=W}[Symbol.dispose](){this._granted=!1}setToolName(Y){this.toolName=Y}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Y){if(this._granted)return;if(this.toolName?.startsWith("MESH_PUBLIC_")){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new NT0("Authentication required. Please provide a valid OAuth token or API key.")}let Q=Y.length>0?Y:this.toolName?[this.toolName]:[];if(Q.length===0)throw new Y31("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new Y31(`Access denied to: ${Q.join(", ")}`)}async checkResource(Y){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Q={};if(this.connectionId)Q[this.connectionId]=[Y];return this.boundAuth.hasPermission(Q)}async isToolPublic(){if(this.toolName?.startsWith("MESH_PUBLIC_"))return!0;if(!this.getToolMeta)return!1;try{let Y=await this.getToolMeta();if(!Y)return!1;let X=Y[LT0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var b$4="mcp.mesh",qN;var MT0=k(()=>{LR();qN=class qN extends DR{options;cachedToolsMap=null;constructor(Y,Q){super(Y);this.options=Q;if(Q.connection.tools)this.cachedToolsMap=new Map(Q.connection.tools.map((X)=>[X.name,X]))}async handleOutgoingMessage(Y){if(!this.isRequest(Y))return this.innerTransport.send(Y);let Q=Y;if(Q.method==="tools/call")await this.authorizeToolCall(Q),this.stripMetaFromArguments(Q);return this.innerTransport.send(Y)}async authorizeToolCall(Y){if(this.options.superUser)return;let X=Y.params.name,{ctx:J,connection:G}=this.options;if(this.isPublicTool(X))return;if(!J.auth.user?.id&&!J.auth.apiKey?.id)throw Error("Authentication required. Please provide a valid OAuth token or API key.");let K=async()=>{return this.cachedToolsMap?.get(X)?._meta};await new E3(J.authInstance,J.auth.user?.id??J.auth.apiKey?.userId,X,J.boundAuth,J.auth.user?.role,G.id,K).check(X)}isPublicTool(Y){if(Y.startsWith("MESH_PUBLIC_"))return!0;if(!this.cachedToolsMap)return!1;let Q=this.cachedToolsMap.get(Y);if(!Q?._meta)return!1;return Q._meta[b$4]?.public_tool===!0}stripMetaFromArguments(Y){let Q=Y.params;if(Q.arguments&&"_meta"in Q.arguments){let{_meta:X,...J}=Q.arguments;Q.arguments=J}}}});function AT0(Y){if(!Y.isError)return;let Q=Y.content;if(!Array.isArray(Q))return;for(let X of Q)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function X31(Y){if(!Y)return;let Q=Y._meta;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let X=Q.properties;if(!X||typeof X!=="object"||Array.isArray(X))return;let J={};for(let[G,K]of Object.entries(X))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function J31(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function G31(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let Q=Y,X=Q.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return Q}return{value:Y}}async function h$4(Y,Q){let X=Y.body;if(!X)return{text:"",truncated:!1};let J=X.getReader(),G=new TextDecoder,K=!1,W=0,Z=[];try{while(!0){let{value:H,done:F}=await J.read();if(F)break;if(H){if(W+=H.byteLength,W>Q){K=!0;let $=Q-(W-H.byteLength);if($>0)Z.push(G.decode(H.slice(0,$),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}async function Q31(Y){let{ctx:Q,enabled:X}=Y,J=Y.organizationId??Q.organization?.id;if(!X||!J)return;if(LK(Y.connectionId))return;let G=X31(Y.request.params.arguments),K=J31(Q.metadata.properties,G),W=Q.auth.user?.id||Q.auth.apiKey?.userId;if(W)try{let Z=await Q.storage.tags.getUserTagsInOrg(W,J);if(Z.length>0){let H=Z.map((F)=>F.name).join(",");K={...K,user_tags:H}}}catch{}await Q.storage.monitoring.log({organizationId:J,connectionId:Y.connectionId,connectionTitle:Y.connectionTitle,toolName:Y.request.params.name,input:Y.request.params.arguments??{},output:Y.output,isError:Y.isError,errorMessage:Y.errorMessage,durationMs:Y.durationMs,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:Y.virtualMcpId,properties:K})}function PT0(Y){let{ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K}=Y;return async(W,Z)=>{let H=Date.now();try{let F=await Z(),$=Q.organization?.id;if(X&&$){let V=F.clone();(async()=>{try{let{text:q,truncated:z}=await h$4(V,wT0),U=Date.now()-H,D=V.headers.get("content-type")??"",M=q;if(D.includes("application/json"))try{M=q.length?JSON.parse(q):null}catch{M=q}let w=F.status>=400,R=w&&M&&typeof M==="object"&&"error"in M?M.error:void 0,P=typeof R==="string"&&R?R:w&&typeof M==="string"&&M.trim()?M.slice(0,500):w?`HTTP ${F.status} ${F.statusText}`.trim():z?`Response body truncated to ${wT0} bytes`:void 0;await Q31({ctx:Q,enabled:X,organizationId:$,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:G31(M),isError:w,errorMessage:P,durationMs:U})}catch(q){let z=Date.now()-H;await Q31({ctx:Q,enabled:X,organizationId:$,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${q.message}`,durationMs:z})}})()}return F}catch(F){let $=F,V=Date.now()-H;throw await Q31({ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:$.message,durationMs:V}),F}}}var wT0=262144;var W31=k(()=>{UY()});var BN;var ET0=k(()=>{cT();W31();BN=class BN extends DR{options;inflightRequests=new Map;constructor(Y,Q){super(Y);this.options=Q}async handleOutgoingMessage(Y){if(this.isRequest(Y)){let Q=Y;this.onRequestStart(Q)}return this.innerTransport.send(Y)}handleIncomingMessage(Y){if(this.isResponse(Y)){let Q=Y;this.onResponseEnd(Q)}this.onmessage?.(Y)}onRequestStart(Y){let{ctx:Q,connectionId:X}=this.options,J,G;if(Y.method==="tools/call"&&Y.params){let W=Y.params;J=W.name,G=W.arguments}let K;if(Y.method==="tools/call"&&J)K=Q.tracer.startSpan("mcp.proxy.callTool",{attributes:{"connection.id":X,"tool.name":J,"request.id":Q.metadata.requestId,"jsonrpc.id":Y.id,"jsonrpc.method":Y.method}});if(Y.id!==null&&Y.id!==void 0)this.inflightRequests.set(Y.id,{startTime:Date.now(),method:Y.method,toolName:J,toolArguments:G,span:K})}onResponseEnd(Y){if(Y.id===null||Y.id===void 0)return;let Q=this.inflightRequests.get(Y.id);if(!Q)return;let{ctx:X,connectionId:J}=this.options,{startTime:G,method:K,toolName:W,toolArguments:Z,span:H}=Q,F=Date.now()-G;if(this.inflightRequests.delete(Y.id),K!=="tools/call"||!W)return;let $="error"in Y,V=$?Y.error:Y.result,q=$?{content:[{type:"text",text:Y.error?.message||"Unknown error"}],isError:!0}:V;if(X.meter.createHistogram("connection.proxy.duration").record(F,{"connection.id":J,"tool.name":W,status:$?"error":"success"}),$)X.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":J,"tool.name":W,error:Y.error?.message});else X.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":J,"tool.name":W,status:"success"});if(H){if($&&Y.error)H.recordException(Error(Y.error.message)),H.setAttributes({error:!0,"error.code":Y.error.code,"error.message":Y.error.message});H.end()}this.logToDatabase({toolName:W,toolArguments:Z,result:q,duration:F,isError:Boolean($)})}async logToDatabase(Y){let{ctx:Q,connectionId:X,connectionTitle:J,virtualMcpId:G}=this.options,{toolName:K,toolArguments:W,result:Z,duration:H,isError:F}=Y;if(!Qm().enabled)return;let V=Q.organization?.id;if(!V)return;let q=AT0(Z),z=G31(Z),U=X31(W),D=J31(Q.metadata.properties,U);try{await Q.storage.monitoring.log({organizationId:V,connectionId:X,connectionTitle:J,toolName:K,input:W??{},output:z,isError:F,errorMessage:q,durationMs:H,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:G,properties:D})}catch(M){console.error("[MonitoringTransport] Failed to log to database:",M)}}async close(){for(let Y of this.inflightRequests.values())if(Y.span)Y.span.setAttributes({"transport.closed":!0}),Y.span.end();return this.inflightRequests.clear(),super.close()}}});var TT0=k(()=>{MT0();ET0()});async function CT0(Y,Q,X=!1){let J=Y.id,G=Q.connectionId&&Q.connectionId!==J?Q.connectionId:void 0;switch(Y.connection_type){case"STDIO":{if(process.env.UNSAFE_ALLOW_STDIO_TRANSPORT!=="true")throw Error("STDIO connections are disabled in production. Set UNSAFE_ALLOW_STDIO_TRANSPORT=true to enable.");let K=Y.connection_headers;if(!_W(K))throw Error("STDIO connection missing parameters");let W=DT0({id:J,name:Y.title,command:K.command,args:K.args,env:K.envVars,cwd:K.cwd});return W=OR(W,(Z)=>new qN(Z,{ctx:Q,connection:Y,superUser:X}),(Z)=>new BN(Z,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),x$4(W,J)}case"HTTP":case"Websocket":{if(!Y.connection_url)throw Error(`${Y.connection_type} connection missing URL`);let K=await UR(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new rH(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=OR(Z,(H)=>new qN(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new BN(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}case"SSE":{if(!Y.connection_url)throw Error("SSE connection missing URL");let K=await UR(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new EB(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=OR(Z,(H)=>new qN(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new BN(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}var x$4;var RT0=k(()=>{G3();Am();B2();tK1();eK1();OT0();TT0();x$4=dl()});function $$(Y){if(!Y?._meta)return!1;return typeof Y._meta["mcp.mesh"]?.["tool.fn"]==="string"}function ST0(Y){return Y._meta["mcp.mesh"]["tool.fn"]}function NR(Y,Q,X,J){return{id:Y,name:Q.name,description:Q.description,inputSchema:Q.inputSchema,outputSchema:Q.outputSchema,annotations:Q.annotations,code:Q._meta["mcp.mesh"]["tool.fn"],connection_dependencies:Q._meta.connectionDependencies??[],created_at:X,updated_at:J}}var Z31,wv8,TZ,IT0,jT0;var T3=k(()=>{d1();Z31=B.object({title:B.string().optional(),readOnlyHint:B.boolean().optional(),destructiveHint:B.boolean().optional(),idempotentHint:B.boolean().optional(),openWorldHint:B.boolean().optional()}),wv8=B.object({"tool.fn":B.string().describe("JavaScript ES module code that exports a default async function")}),TZ=B.object({id:B.string().describe("Unique identifier for the virtual tool (auto-generated)"),name:B.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:B.string().optional().describe("Human-readable description of what the tool does"),inputSchema:B.record(B.string(),B.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:B.record(B.string(),B.unknown()).optional().describe("JSON Schema defining the tool's output (optional)"),annotations:Z31.optional().describe("MCP tool annotations"),code:B.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:B.array(B.string()).describe("Connection IDs that this tool depends on (specified by the creator)"),created_at:B.string().describe("When the virtual tool was created"),updated_at:B.string().describe("When the virtual tool was last updated")}),IT0=B.object({name:B.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:B.string().optional().describe("Human-readable description"),inputSchema:B.record(B.string(),B.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:B.record(B.string(),B.unknown()).optional().describe("JSON Schema for output"),annotations:Z31.optional().describe("MCP tool annotations"),code:B.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:B.array(B.string()).optional().describe("Connection IDs that this tool depends on. Creates indirect aggregations to prevent deletion of referenced connections.")}),jT0=B.object({name:B.string().min(1).max(255).optional().describe("New tool name"),description:B.string().nullable().optional().describe("New description (null to clear)"),inputSchema:B.record(B.string(),B.unknown()).optional().describe("New input schema"),outputSchema:B.record(B.string(),B.unknown()).nullable().optional().describe("New output schema (null to clear)"),annotations:Z31.nullable().optional().describe("New annotations (null to clear)"),code:B.string().optional().describe("New JavaScript code"),connection_dependencies:B.array(B.string()).optional().describe("Connection IDs that this tool depends on. Replaces existing dependencies if provided.")})});function gB(Y){return(Q)=>{if(Q instanceof w0&&Q.code===C0.MethodNotFound)return Y;throw Q}}var K31=k(()=>{zY()});class vT0{factory;promise=null;constructor(Y){this.factory=Y}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Y,Q){return this.getOrCreatePromise().then(Y,Q)}catch(Y){return this.getOrCreatePromise().catch(Y)}finally(Y){return this.getOrCreatePromise().finally(Y)}}function uB(Y){return new vT0(Y)}async function g$4(Y,Q,X=!1){let J=await Promise.all(Y.map(async(G)=>{try{let K=await aQ(G,Q,X);return[G.id,K]}catch(K){return console.warn(`[aggregator] Failed to create client for connection ${G.id}:`,K),null}}));return new Map(J.filter((G)=>!!G))}async function kT0(Y){let Q=[];for(let[,X]of Y)Q.push(X.close().catch(()=>{}));await Promise.all(Q)}var zN;var H31=k(()=>{UN();K31();Hq();gK1();T3();zN=class zN extends DX{options;ctx;_cachedTools;_cachedResources;_cachedPrompts;_clients;_connections;_selectionMap;constructor(Y,Q){super({name:"virtual-mcp-passthrough",version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});this.options=Y;this.ctx=Q;this._selectionMap=new Map;for(let X of Y.virtualMcp.connections)this._selectionMap.set(X.connection_id,X);this._connections=new Map;for(let X of Y.connections)this._connections.set(X.id,X);this._clients=uB(()=>g$4(this.options.connections,this.ctx,this.options.superUser)),this._cachedTools=uB(()=>this.loadToolsCache()),this._cachedResources=uB(()=>this.loadCache("resources")),this._cachedPrompts=uB(()=>this.loadCache("prompts"))}async loadToolsCache(){let Y=await this._clients,Q=await Promise.all(Array.from(Y.entries()).map(async([W,Z])=>{try{let H=await Z.listTools().then(($)=>$.tools),F=this._selectionMap.get(W);if(F?.selected_tools?.length){let $=new Set(F.selected_tools);H=H.filter((V)=>$.has(V.name))}return{connectionId:W,data:H}}catch(H){return console.error(`[PassthroughClient] Failed to load tools for connection ${W}:`,H),null}})),X=[],J=new Map,G=new Map,K=this.options.virtualTools??[];for(let W of K){if(J.has(W.name))continue;let Z={name:W.name,description:W.description,inputSchema:W.inputSchema,outputSchema:W.outputSchema,annotations:W.annotations,_meta:{connectionId:this.options.virtualMcp.id??"__VIRTUAL__",connectionTitle:this.options.virtualMcp.title}};X.push(Z),J.set(W.name,"__VIRTUAL__"),G.set(W.name,W)}for(let W of Q){if(!W)continue;let{connectionId:Z,data:H}=W,$=this._connections.get(Z)?.title??"";for(let V of H){let q=V.name;if(J.has(q))continue;let z={...V,_meta:{connectionId:Z,connectionTitle:$,...V?._meta}};X.push(z),J.set(q,Z)}}return{data:X,mappings:J,virtualTools:G}}async loadCache(Y){let Q=await this._clients,X=await Promise.all(Array.from(Q.entries()).map(async([K,W])=>{try{let Z=Y==="resources"?await W.listResources().catch(gB({resources:[]})).then(($)=>$.resources):await W.listPrompts().catch(gB({prompts:[]})).then(($)=>$.prompts),H=this._selectionMap.get(K),F=Y==="resources"?"selected_resources":"selected_prompts";if(H?.[F]?.length){let $=new Set(H[F]);return{connectionId:K,data:Z.filter((V)=>$.has(V.name))}}return{connectionId:K,data:Z}}catch(Z){return console.error(`[PassthroughClient] Failed to load cache for connection ${K}:`,Z),null}})),J=[],G=new Map;for(let K of X){if(!K)continue;let{connectionId:W,data:Z}=K,F=this._connections.get(W)?.title??"";for(let $ of Z){let V=$.name??$.uri;if(G.has(V))continue;let q={...$,_meta:{connectionId:W,connectionTitle:F,...$?._meta}};J.push(q),G.set(V,W)}}return{data:J,mappings:G}}async listTools(){return{tools:(await this._cachedTools).data}}async callTool(Y){let[Q,X]=await Promise.all([this._cachedTools,this._clients]),J=Q.mappings.get(Y.name);if(!J)return{content:[{type:"text",text:`Tool not found: ${Y.name}`}],isError:!0};if(J==="__VIRTUAL__")return this.executeVirtualTool(Y.name,Y.arguments??{},Q,X);let G=X.get(J);if(!G)return{content:[{type:"text",text:`Connection not found for tool: ${Y.name}`}],isError:!0};return await G.callTool({name:Y.name,arguments:Y.arguments??{}})}async executeVirtualTool(Y,Q,X,J){let G=X.virtualTools.get(Y);if(!G)return{content:[{type:"text",text:`Virtual tool not found: ${Y}`}],isError:!0};let K=ST0(G),W={};for(let[Z,H]of X.mappings){if(H==="__VIRTUAL__")continue;let F=J.get(H);if(!F)continue;W[Z]=async($)=>{let V=await F.callTool({name:Z,arguments:$}),q=V.content;if(q?.[0]?.type==="text"&&q[0].text)try{return JSON.parse(q[0].text)}catch{return q[0].text}return V}}try{let H=`
|
|
1203
|
+
${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Q);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function HN(Y,Q){switch(typeof Q){case"string":return Y.newString(Q);case"number":return Y.newNumber(Q);case"boolean":return Q?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(Q===null)return Y.null;if(Array.isArray(Q)){let J=Y.newArray();return Q.forEach((G,K)=>{let W=HN(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let X=Y.newObject();for(let[J,G]of Object.entries(Q)){let K=HN(Y,G);try{Y.setProp(X,J,K)}finally{K.dispose?.()}}return X}case"function":{let X=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(X,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=Q(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let F=HN(Y,H);Z.resolve(F),F.dispose()}catch(F){let $=KN(F),V=Y.newString(`Promise resolution error: ${$}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let F=KN(H),$=Y.newString(`Promise rejection: ${F}`);Z.reject($),$.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return HN(Y,W)}catch(K){let W=KN(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(Q.toString());case"symbol":return Y.newString(Q.toString());default:try{return Y.newString(String(Q))}catch{return Y.undefined}}}var yE0=()=>{};function bE0(Y){let Q=Y.runtime.executePendingJobs(100);try{if("unwrap"in Q&&typeof Q.unwrap==="function")Q.unwrap()}finally{if("dispose"in Q&&typeof Q.dispose==="function")Q.dispose()}}async function fE0(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){bE0(Y);let K=await Promise.race([G,yF4(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>X)throw Error(`Timed out after ${X}ms while awaiting a QuickJS promise`)}}async function oC({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=lR(W,await kE0({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=lR(W,J.newContext({interruptAfterMs:X}),0);const K=lR(W,IE0(G),0);try{let $=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult($),q=HN(G,Y);G.setProp(G.global,"tools",q);let z=G.runtime.hasPendingJob()?G.unwrapResult(await fE0(G,V,X)):V;if(z!==V)V.dispose();let U=G.getProp(z,"default"),D=G.typeof(U);if(D!=="function")return U.dispose(),z.dispose(),q.dispose(),{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let M=G.callFunction(U,G.undefined,q);q.dispose(),U.dispose(),z.dispose();let w=G.unwrapResult(M),R=await fE0(G,w,X);w.dispose();let P=G.unwrapResult(R);if(G.runtime.hasPendingJob())bE0(G);let T=G.dump(P);return P.dispose(),{returnValue:T,consoleLogs:K.logs}}catch($){return console.log($),{error:KN($),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{TF1(W,H,F)}}var yF4=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var hE0=k(()=>{_E0();yE0()});var gK1=k(()=>{hE0()});async function fF4(Y,Q){let X=Y.connections.map((K)=>K.connection_id),J=[];for(let K of X){let W=await Q.storage.connections.findById(K);if(W&&W.status==="active")J.push(W)}return J.map((K)=>{let W=Y.connections.find((Z)=>Z.connection_id===K.id);return{connection:K,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}async function xE0(Y,Q){return(await Q.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function bF4(Y,Q){let X=new Map;for(let q of Y)X.set(q.connection.id,q);let J=Y.map((q)=>q.connection),G=new Map,K=await Promise.allSettled(J.map(async(q)=>{try{let z=await Q.createMCPProxy(q);return{connection:q,proxy:z}}catch(z){return console.warn(`[code-execution] Failed to create proxy for connection ${q.id}:`,z),null}}));for(let q of K)if(q.status==="fulfilled"&&q.value)G.set(q.value.connection.id,q.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([q,z])=>{try{let D=(await z.proxy.listTools()).tools,M=X.get(q);if(M?.selectedTools&&M.selectedTools.length>0){let w=new Set(M.selectedTools);D=D.filter((R)=>w.has(R.name))}return{connectionId:q,connectionTitle:z.connection.title,tools:D}}catch(U){return console.error(`[code-execution] Failed to list tools for connection ${q}:`,U),null}})),Z=new Set,H=[],F=new Map;for(let q of W){if(q.status!=="fulfilled"||!q.value)continue;let{connectionId:z,connectionTitle:U,tools:D}=q.value;for(let M of D){if(Z.has(M.name))continue;Z.add(M.name),H.push({...M,_meta:{connectionId:z,connectionTitle:U}}),F.set(M.name,z)}}let $=async(q,z)=>{let U=F.get(q);if(!U)return{content:[{type:"text",text:`Tool not found: ${q}`}],isError:!0};let D=G.get(U);if(!D)return{content:[{type:"text",text:`Connection not found for tool: ${q}`}],isError:!0};return await D.proxy.callTool({name:q,arguments:z})},V=[];for(let[,q]of G)V.push(q.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:$}}async function FN(Y){let Q=A0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await fF4(J,Y);else X=await xE0(Q.id,Y)}else X=await xE0(Q.id,Y);return bF4(X,Y)}function hF4(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function xF4(Y,Q){let X=0,J=Q.name.toLowerCase(),G=(Q.description??"").toLowerCase(),K=(Q._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)X+=10;else if(J.includes(W))X+=3;if(G.includes(W))X+=2;if(K.includes(W))X+=1}return X}function kl(Y,Q,X){let J=hF4(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:xF4(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function _l(Y,Q){let X=new Map(Q.map((G)=>[G.name,G]));return{tools:Y.map((G)=>X.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:Y.filter((G)=>!X.has(G))}}async function yl(Y,Q,X){let J=Object.fromEntries(Q.tools.map((G)=>[G.name,async(K)=>{let W=await Q.callTool(G.name,K??{});if(W.structuredContent&&typeof W.structuredContent==="object")return W.structuredContent;let Z=W.content;if(Z?.[0]?.type==="text"&&Z[0].text)try{return JSON.parse(Z[0].text)}catch{return Z[0].text}return W}]));return oC({code:Y,tools:J,timeoutMs:X})}function sC(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function H$(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function w3(Y){let Q=new Set(gF4);return Y.filter((X)=>!Q.has(X.name))}var gF4;var xB=k(()=>{gK1();gF4=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var uK1;var gE0=k(()=>{c0();rC();xB();uK1=l1({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:AE0,outputSchema:PE0,handler:async(Y,Q)=>{a1(Q),A0(Q),await Q.access.check();let X=await FN(Q),J=kl(Y.query,X.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:X.tools.length}}})});var mK1;var uE0=k(()=>{c0();rC();xB();mK1=l1({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:EE0,outputSchema:TE0,handler:async(Y,Q)=>{a1(Q),A0(Q),await Q.access.check();let X=await FN(Q);return _l(Y.tools,X.tools)}})});var lK1;var mE0=k(()=>{c0();rC();xB();lK1=l1({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:CE0,outputSchema:RE0,handler:async(Y,Q)=>{a1(Q),A0(Q),await Q.access.check();let X=await FN(Q);return await yl(Y.code,X,Y.timeoutMs)}})});var lE0=k(()=>{gE0();uE0();mE0();rC()});var mF4,lF4,dK1;var dE0=k(()=>{UY();d1();c0();Tm();G3();mF4=B.object({data:z2.describe("Data for the new connection (id is auto-generated if not provided)")}),lF4=B.object({item:EQ.describe("The created connection entity")}),dK1=l1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:mF4,outputSchema:lF4,handler:async(Y,Q)=>{a1(Q);let X=A0(Q);await Q.access.check();let J=O9(Q);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:X.id,created_by:J};if(G.connection_type==="VIRTUAL"){let H=$q(G.connection_url);if(!H)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await Q.storage.virtualMcps.findById(H);if(!F)throw Error(`Virtual MCP not found: ${H}`);if(F.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=Vq(H)}let K=await xL({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=K?.length?K:null,Z=await Q.storage.connections.create({...G,tools:W});return await Q.eventBus.publish(X.id,PQ.SELF(X.id),{type:"connection.created",data:Z}),{item:Z}}})});var dF4,pE0,kj8;var cE0=k(()=>{d1();wJ();dF4=B.object({id:B.string(),name:B.string(),description:B.string().optional(),inputSchema:B.record(B.string(),B.unknown()),outputSchema:B.record(B.string(),B.unknown()).optional()}),pE0=NZ.extend({_meta:B.object({"io.decocms":B.object({id:B.string(),verified:B.boolean(),scopeName:B.string(),appName:B.string(),friendlyName:B.string().nullable().optional(),metadata:B.record(B.string(),B.unknown()).nullable().optional(),publishedAt:B.string().datetime().optional(),updatedAt:B.string().datetime().optional(),tools:B.array(dF4).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:B.object({$schema:B.string().optional(),_meta:B.record(B.string(),B.unknown()).optional(),name:B.string().describe("The server name (scope/app)"),title:B.string().optional().describe("User-friendly title"),description:B.string().optional().describe("Server description"),icons:B.array(B.object({src:B.string(),mimeType:B.string().optional(),sizes:B.array(B.string()).optional(),theme:B.enum(["light","dark"]).optional()})).optional(),remotes:B.array(B.object({type:B.enum(["http","stdio","sse"]),url:B.string().optional(),headers:B.array(B.unknown()).optional()})).optional(),packages:B.array(B.unknown()).optional(),repository:B.object({url:B.string(),source:B.string().optional(),subfolder:B.string().optional()}).optional(),version:B.string().optional(),websiteUrl:B.string().optional()})}),kj8=MZ("registry_app",pE0,{readOnly:!0})});var nE0,iE0,aE0,rE0,oE0,pK1;var sE0=k(()=>{d1();gL();nE0=B.object({specversion:B.literal("1.0").describe("CloudEvents specification version"),id:B.string().describe("Unique identifier for this event (UUID recommended)"),source:B.string().describe("Connection ID of the event publisher"),type:B.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:B.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:B.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:B.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:B.string().url().optional().describe("URI to the schema for the data attribute"),data:B.unknown().optional().describe("Event payload (any JSON value)")}),iE0=B.object({events:B.array(nE0).min(1).describe("Batch of CloudEvents to process")}),aE0=B.object({success:B.boolean().optional().describe("Whether this event was processed successfully"),error:B.string().optional().describe("Error message for this event"),retryAfter:B.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),rE0=B.object({success:B.boolean().optional().describe("Batch success - applies to events not in results"),error:B.string().optional().describe("Batch error message - applies to events not in results"),processedCount:B.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:B.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:B.record(B.string(),aE0).optional().describe("Per-event results keyed by event ID")}),oE0=[{name:"ON_EVENTS",inputSchema:iE0,outputSchema:rE0}],pK1=K3(oE0)});var tC,eC,YR,QR,tE0,eE0,XR,JR,GR,WR,ZR,KR,HR,FR,YT0,pF4;var QT0=k(()=>{d1();gL();tC=B.object({type:B.string().min(1).max(255).describe("Event type identifier"),subject:B.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:B.unknown().optional().describe("Event payload"),deliverAt:B.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:B.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),eC=B.object({id:B.string().describe("Unique event ID"),type:B.string().describe("Event type"),source:B.string().describe("Source connection ID"),time:B.string().describe("Event timestamp")}),YR=B.object({eventType:B.string().min(1).max(255).describe("Event type to subscribe to"),publisher:B.string().optional().describe("Filter events by publisher connection ID"),filter:B.string().max(1000).optional().describe("JSONPath filter expression on event data")}),QR=B.object({subscription:B.object({id:B.string().describe("Subscription ID"),connectionId:B.string().describe("Subscriber connection ID"),eventType:B.string().describe("Event type pattern"),publisher:B.string().nullable().describe("Publisher connection filter"),filter:B.string().nullable().describe("JSONPath filter expression"),enabled:B.boolean().describe("Whether subscription is enabled"),createdAt:B.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:B.string().datetime().describe("Updated timestamp (ISO 8601)")})}),tE0=B.object({eventType:B.string().min(1).max(255).describe("Event type to subscribe to"),publisher:B.string().optional().describe("Filter events by publisher connection ID"),filter:B.string().max(1000).optional().describe("JSONPath filter expression on event data")}),eE0=B.object({id:B.string().describe("Subscription ID"),connectionId:B.string().describe("Subscriber connection ID"),eventType:B.string().describe("Event type pattern"),publisher:B.string().nullable().describe("Publisher connection filter"),filter:B.string().nullable().describe("JSONPath filter expression"),enabled:B.boolean().describe("Whether subscription is enabled"),createdAt:B.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:B.string().datetime().describe("Updated timestamp (ISO 8601)")}),XR=B.object({subscriptions:B.array(tE0).describe("Desired subscriptions - system will create/update/delete to match")}),JR=B.object({created:B.number().int().min(0).describe("Number of subscriptions created"),updated:B.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:B.number().int().min(0).describe("Number of subscriptions removed"),unchanged:B.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:B.array(eE0).describe("Current subscriptions after sync")}),GR=B.object({subscriptionId:B.string().describe("Subscription ID to remove")}),WR=B.object({success:B.boolean().describe("Whether unsubscribe was successful"),subscriptionId:B.string().describe("Subscription ID that was removed")}),ZR=B.object({eventId:B.string().describe("Event ID to cancel")}),KR=B.object({success:B.boolean().describe("Whether cancellation was successful"),eventId:B.string().describe("Event ID that was cancelled")}),HR=B.object({eventId:B.string().describe("Event ID to acknowledge")}),FR=B.object({success:B.boolean().describe("Whether ACK was successful"),eventId:B.string().describe("Event ID that was acknowledged")}),YT0=[{name:"EVENT_PUBLISH",inputSchema:tC,outputSchema:eC},{name:"EVENT_SUBSCRIBE",inputSchema:YR,outputSchema:QR},{name:"EVENT_UNSUBSCRIBE",inputSchema:GR,outputSchema:WR},{name:"EVENT_CANCEL",inputSchema:ZR,outputSchema:KR},{name:"EVENT_ACK",inputSchema:HR,outputSchema:FR},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:XR,outputSchema:JR}],pF4=K3(YT0)});var cF4,nF4,iF4,aF4,rF4,oF4,sF4,tF4,eF4,Y$4,Q$4,X$4,$R;var fl=k(()=>{d1();cF4=B.object({prefix:B.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:B.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:B.string().optional().describe("Token for pagination from previous response"),delimiter:B.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),nF4=B.object({objects:B.array(B.object({key:B.string().describe("Object key/path"),size:B.number().describe("Object size in bytes"),lastModified:B.string().describe("Last modified timestamp"),etag:B.string().describe("Entity tag for the object")})),nextContinuationToken:B.string().optional().describe("Token for fetching next page of results"),isTruncated:B.boolean().describe("Whether there are more results available"),commonPrefixes:B.array(B.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),iF4=B.object({key:B.string().describe("Object key/path to get metadata for")}),aF4=B.object({contentType:B.string().optional().describe("MIME type of the object"),contentLength:B.number().describe("Size of the object in bytes"),lastModified:B.string().describe("Last modified timestamp"),etag:B.string().describe("Entity tag for the object"),metadata:B.record(B.string(),B.string()).optional().describe("Custom metadata key-value pairs")}),rF4=B.object({key:B.string().describe("Object key/path to generate URL for"),expiresIn:B.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),oF4=B.object({url:B.string().describe("Presigned URL for downloading the object"),expiresIn:B.number().describe("Expiration time in seconds that was used")}),sF4=B.object({key:B.string().describe("Object key/path for the upload"),expiresIn:B.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:B.string().optional().describe("MIME type for the object being uploaded")}),tF4=B.object({url:B.string().describe("Presigned URL for uploading the object"),expiresIn:B.number().describe("Expiration time in seconds that was used")}),eF4=B.object({key:B.string().describe("Object key/path to delete")}),Y$4=B.object({success:B.boolean().describe("Whether the deletion was successful"),key:B.string().describe("The key that was deleted")}),Q$4=B.object({keys:B.array(B.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),X$4=B.object({deleted:B.array(B.string()).describe("Array of successfully deleted keys"),errors:B.array(B.object({key:B.string(),message:B.string()})).describe("Array of errors for failed deletions")}),$R=[{name:"LIST_OBJECTS",inputSchema:cF4,outputSchema:nF4},{name:"GET_OBJECT_METADATA",inputSchema:iF4,outputSchema:aF4},{name:"GET_PRESIGNED_URL",inputSchema:rF4,outputSchema:oF4},{name:"PUT_PRESIGNED_URL",inputSchema:sF4,outputSchema:tF4},{name:"DELETE_OBJECT",inputSchema:eF4,outputSchema:Y$4},{name:"DELETE_OBJECTS",inputSchema:Q$4,outputSchema:X$4}]});var bl=k(()=>{gL();cE0();sE0();QT0();fl();uL()});var J$4,G$4,XT0;var JT0=k(()=>{d1();wJ();J$4=NZ.extend({avatar:B.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:B.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:B.string().describe("Virtual MCP ID to use for this assistant"),model:B.object({id:B.string().describe("Model ID"),connectionId:B.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),G$4=MZ("assistant",J$4),XT0=[...G$4]});var VR,A3,WT0,W$4,Z$4,ZT0,K$4,H$4,F$4,$$4,V$4,q$4,KT0,B$4,z$4,U$4,D$4,O$4,L$4,N$4,M$4,w$4,A$4,JS8,P$4,GS8,GT0,E$4,T$4,cK1,qR;var hl=k(()=>{d1();gL();wJ();VR=B.lazy(()=>B.union([B.null(),B.string(),B.number(),B.boolean(),B.record(B.string(),VR),B.array(VR)])),A3=B.record(B.string(),B.record(B.string(),VR)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),WT0=B.object({type:B.literal("text"),text:B.string().describe("The text content"),providerOptions:A3}),W$4=B.object({type:B.literal("text"),text:B.string().describe("The text content"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),Z$4=B.string().describe("File data as URL string"),ZT0=B.object({type:B.literal("file"),filename:B.string().optional().describe("Optional filename of the file"),data:Z$4,mediaType:B.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:A3}),K$4=B.object({type:B.literal("file"),mediaType:B.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:B.string().describe("Generated file data as base64 encoded string")}),H$4=B.object({type:B.literal("reasoning"),text:B.string().describe("The reasoning text"),providerOptions:A3}),F$4=B.object({type:B.literal("reasoning"),text:B.string().describe("The reasoning text"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),$$4=B.object({type:B.literal("tool-call"),toolCallId:B.string().describe("ID of the tool call, used to match with tool result"),toolName:B.string().describe("Name of the tool being called"),input:B.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:B.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:A3}),V$4=B.object({type:B.literal("tool-call"),toolCallId:B.string().describe("ID of the tool call"),toolName:B.string().describe("Name of the tool being called"),input:B.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:B.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),q$4=B.union([B.object({type:B.literal("text"),value:B.string()}),B.object({type:B.literal("json"),value:VR}),B.object({type:B.literal("error-text"),value:B.string()}),B.object({type:B.literal("error-json"),value:VR}),B.object({type:B.literal("content"),value:B.array(B.union([B.object({type:B.literal("text"),text:B.string().describe("Text content")}),B.object({type:B.literal("media"),data:B.string().describe("Base-64 encoded media data"),mediaType:B.string().describe("IANA media type")})]))})]),KT0=B.object({type:B.literal("tool-result"),toolCallId:B.string().describe("ID of the tool call that this result is associated with"),toolName:B.string().describe("Name of the tool that generated this result"),output:q$4.describe("Result of the tool call"),result:B.unknown().describe("Unknown result of the tool call"),providerOptions:A3}),B$4=B.object({type:B.literal("tool-result"),toolCallId:B.string().describe("ID of the tool call that this result is associated with"),toolName:B.string().describe("Name of the tool that generated this result"),result:B.any().describe("Result of the tool call (JSON-serializable)"),isError:B.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:B.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),z$4=B.union([B.object({type:B.literal("source"),sourceType:B.literal("url"),id:B.string().describe("The ID of the source"),url:B.string().describe("The URL of the source"),title:B.string().optional().describe("The title of the source"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),B.object({type:B.literal("source"),sourceType:B.literal("document"),id:B.string().describe("The ID of the source"),mediaType:B.string().describe("IANA media type of the document (e.g., application/pdf)"),title:B.string().describe("The title of the document"),filename:B.string().optional().describe("Optional filename of the document"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")})]),U$4=B.object({role:B.literal("system"),content:B.string().describe("System message content"),providerOptions:A3}),D$4=B.object({role:B.literal("user"),content:B.array(B.union([WT0,ZT0])).describe("User message content parts (text or file)"),providerOptions:A3}),O$4=B.object({role:B.literal("assistant"),content:B.array(B.union([WT0,ZT0,H$4,$$4,KT0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:A3}),L$4=B.object({role:B.literal("tool"),content:B.array(KT0).describe("Tool message content (tool results)"),providerOptions:A3}),N$4=B.union([U$4,D$4,O$4,L$4]),M$4=B.array(N$4).describe("A list of messages forming the prompt"),w$4=B.object({prompt:M$4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:B.number().optional().describe("Maximum number of tokens to generate"),temperature:B.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:B.number().optional().describe("Nucleus sampling parameter"),topK:B.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:B.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:B.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:B.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:B.array(B.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:B.union([B.object({type:B.literal("text")}),B.object({type:B.literal("json"),schema:B.any().optional().describe("JSON schema that the generated output should conform to"),name:B.string().optional().describe("Name of output that should be generated"),description:B.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:B.array(B.any()).optional().describe("The tools that are available for the model"),toolChoice:B.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:B.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:B.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:B.any().optional().describe("Additional provider-specific options")}),A$4=B.object({content:B.array(B.union([W$4,K$4,F$4,V$4,B$4,z$4])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:B.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:B.looseObject({inputTokens:B.number().optional(),outputTokens:B.number().optional(),totalTokens:B.number().optional(),reasoningTokens:B.number().optional()}).describe("Usage information for the language model call"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata"),request:B.object({body:B.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:B.object({id:B.string().optional().describe("ID for the generated response"),timestamp:B.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:B.string().optional().describe("The ID of the response model that was used"),headers:B.record(B.string(),B.string()).optional().describe("Response headers"),body:B.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:B.array(B.any()).describe("Warnings for the call, e.g. unsupported settings")}),JS8=B.object({stream:B.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:B.object({body:B.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:B.object({headers:B.record(B.string(),B.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),P$4=B.object({supportedUrls:B.record(B.string(),B.array(B.string())).describe("Supported URL patterns by media type for the provider")}),GS8=B.object({modelId:B.string().describe("The ID of the model"),logo:B.string().nullable(),description:B.string().nullable(),capabilities:B.array(B.string()),limits:B.object({contextWindow:B.number(),maxOutputTokens:B.number()}).nullable(),costs:B.object({input:B.number(),output:B.number()}).nullable(),provider:B.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),GT0=B.object({modelId:B.string().describe("The ID of the model"),callOptions:w$4}),E$4=NZ.extend({logo:B.string().nullable(),description:B.string().nullable(),capabilities:B.array(B.string()),limits:B.object({contextWindow:B.number(),maxOutputTokens:B.number()}).nullable(),costs:B.object({input:B.number(),output:B.number()}).nullable(),provider:B.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),T$4=MZ("llm",E$4,{readOnly:!0}),cK1=[{name:"LLM_METADATA",inputSchema:B.object({modelId:B.string().describe("The ID of the model")}),outputSchema:P$4},{name:"LLM_DO_STREAM",inputSchema:GT0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:GT0,outputSchema:A$4},...T$4],qR=K3(cK1)});function $N(){return!1}function xl(Y,Q){return Y===PQ.DEV_ASSETS(Q)}function VN(Y,Q){let X=Z91(Q,Y),J=new Date().toISOString();return{id:X.id??PQ.DEV_ASSETS(Y),title:X.title,description:X.description??null,icon:X.icon??null,app_name:X.app_name??null,app_id:X.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:X.connection_type,connection_url:X.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata??null,tools:C$4,bindings:["OBJECT_STORAGE"],status:"active"}}var C$4;var gl=k(()=>{fl();UY();d1();C$4=$R.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:B.toJSONSchema(Y.inputSchema),outputSchema:B.toJSONSchema(Y.outputSchema)}))});function I$4(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function F$(Y){return typeof Y==="string"||typeof Y==="number"}function ul(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every((F)=>ul(Y,F));case"or":return H.some((F)=>ul(Y,F));case"not":return!H.every((F)=>ul(Y,F));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=nK1(Y,K);switch(J){case"eq":return W===G;case"gt":return F$(W)&&F$(G)&&W>G;case"gte":return F$(W)&&F$(G)&&W>=G;case"lt":return F$(W)&&F$(G)&&W<G;case"lte":return F$(W)&&F$(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 Z=I$4(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function nK1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function j$4(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=nK1(X,K),Z=nK1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var R$4,S$4,v$4,iK1;var HT0=k(()=>{bl();JT0();wJ();hl();fl();UY();d1();c0();gl();G3();R$4={LLM:cK1,ASSISTANTS:XT0,OBJECT_STORAGE:$R};S$4=H3.extend({binding:B.union([B.object({}).passthrough(),B.string()]).optional(),include_virtual:B.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),v$4=F3(EQ),iK1=l1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:S$4,outputSchema:v$4,handler:async(Y,Q)=>{await Q.access.check();let X=A0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let q=R$4[Y.binding.toUpperCase()];if(!q)throw Error(`Unknown binding: ${Y.binding}`);return q})():Y.binding:void 0,G=J?km(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if($N()){let q=NJ(),z=PQ.DEV_ASSETS(X.id);if(!K.some((U)=>U.id===z)){let U=VN(X.id,q);K.unshift(U)}}let W=G?await Promise.all(K.map(async(q)=>{if(!q.tools||q.tools.length===0)return null;return G.isImplementedBy(q.tools.map((U)=>({name:U.name,inputSchema:U.inputSchema,outputSchema:U.outputSchema})))?q:null})).then((q)=>q.filter((z)=>z!==null)):K;if(Y.where)W=W.filter((q)=>ul(q,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=j$4(W,Y.orderBy);let Z=W.length,H=Y.offset??0,F=Y.limit??100,$=W.slice(H,H+F),V=H+F<Z;return{items:$,totalCount:Z,hasMore:V}}})});var k$4,aK1;var FT0=k(()=>{wJ();c0();gl();G3();k$4=DC(EQ),aK1=l1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:UC,outputSchema:k$4,handler:async(Y,Q)=>{let X=A0(Q);if(await Q.access.check(),$N()&&xl(Y.id,X.id))return{item:VN(X.id,NJ())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var ml=(Y,Q)=>{if(Q===null||Q===void 0)return;let X=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Q;for(let G of X){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function $T0(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return Q}function _$4(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function y$4(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function rK1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=_$4(J);if(!G)continue;let[K,W]=G,Z=ml(K,Y),H=y$4(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function VT0(Y,Q){let X=rK1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var oK1=()=>{};import{randomBytes as f$4}from"crypto";function qT0(){if(BR)return BR;let Y=process.env.MESH_JWT_SECRET??s9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)BR=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),BR=new Uint8Array(f$4(32));return BR}async function BT0(Y,Q="5m"){let X=qT0();return await new jX(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}async function zT0(Y){try{let Q=qT0(),{payload:X}=await a8(Y,Q);return X}catch{return}}var BR=null;var sK1=k(()=>{FJ();zR()});async function UT0(Y){if(!Y.refreshToken)return{success:!1,error:"No refresh token available"};if(!Y.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Y.clientId)return{success:!1,error:"No client ID available"};try{let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)Q.set("client_secret",Y.clientSecret);if(Y.scope)Q.set("scope",Y.scope);let X=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let G=await X.text();console.error(`[TokenRefresh] Failed to refresh token: ${X.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${X.status}`}}catch{return{success:!1,error:`Token refresh failed: ${X.status}`}}}let J=await X.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Q){return console.error("[TokenRefresh] Error refreshing token:",Q),{success:!1,error:Q instanceof Error?Q.message:"Token refresh failed"}}}class P3{db;vault;constructor(Y,Q){this.db=Y;this.vault=Q}async get(Y){let Q=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!Q)return null;return this.decryptToken(Q)}async upsert(Y){let Q=new Date().toISOString(),X=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:Q}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=D8("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:Q,updatedAt:Q}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Q,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,Q=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Q<Date.now()}async decryptToken(Y){let Q=await this.vault.decrypt(Y.accessToken),X=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:Q,refreshToken:X,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var ll=k(()=>{_7()});async function UR(Y,Q,X){let J=Y.id,G=rK1(Y.configuration_state,Y.configuration_scopes),K=Q.auth.user?.id??Q.auth.apiKey?.userId??(X?Y.created_by:void 0),[W,Z]=K?await BT0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:process.env.MESH_URL??Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((z)=>[z,null]).catch((z)=>[null,z]):[null,Error("User ID required to issue configuration token")];if(Z)console.error("Failed to issue configuration token:",W);let H=Q.auth.user?.connectionId,F={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},$=null,V=new P3(Q.db,Q.vault),q=await V.get(J);if(q){let z=!!q.refreshToken&&!!q.tokenEndpoint;if(V.isExpired(q,z?300000:0))if(z){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let D=await UT0(q);if(D.success&&D.accessToken)await V.upsert({connectionId:J,accessToken:D.accessToken,refreshToken:D.refreshToken??q.refreshToken,scope:D.scope??q.scope,expiresAt:D.expiresIn?new Date(Date.now()+D.expiresIn*1000):null,clientId:q.clientId,clientSecret:q.clientSecret,tokenEndpoint:q.tokenEndpoint}),$=D.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${D.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else $=q.accessToken}if(!$&&Y.connection_token)$=Y.connection_token;if($)F.Authorization=`Bearer ${$}`;if(W)F["x-mesh-token"]=W;return F}var tK1=k(()=>{oK1();sK1();ll()});function dl(){let Y=new Map;function Q(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;console.log(`[ClientPool] Creating new client for ${G}`);let W=new DX({name:`outbound-client-${G}`,version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});W.onclose=()=>{Y.delete(G)};let Z=W.connect(J,{timeout:30000}).then(()=>W).catch((H)=>{throw Y.delete(G),H});return Y.set(G,Z),Z}return Object.assign(Q,{[Symbol.asyncDispose]:async()=>{let J=[];for(let[G,K]of Y)J.push(K.then((W)=>W.close()).catch((W)=>console.error(`[ClientPool] Error closing client ${G}:`,W)));await Promise.all(J),Y.clear()}})}var eK1=k(()=>{Hq()});function DT0(Y){let Q=new HC({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),X=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return Q.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${X}]\x1B[0m`)}),Q}var OT0=k(()=>{TW1()});class DR{innerTransport;constructor(Y){this.innerTransport=Y}async start(){return this.innerTransport.onmessage=(Y)=>{this.handleIncomingMessage(Y)},this.innerTransport.onerror=(Y)=>{this.onerror?.(Y)},this.innerTransport.onclose=()=>{this.onclose?.()},this.innerTransport.start()}async send(Y){return this.handleOutgoingMessage(Y)}async close(){return this.innerTransport.close()}async handleOutgoingMessage(Y){return this.innerTransport.send(Y)}handleIncomingMessage(Y){this.onmessage?.(Y)}isRequest(Y){return"method"in Y&&Y.method!==void 0}isResponse(Y){return"result"in Y||"error"in Y&&!("method"in Y)}onmessage;onerror;onclose}function OR(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var LT0="mcp.mesh";var NT0,Y31,E3;var LR=k(()=>{NT0=class NT0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};Y31=class Y31 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};E3=class E3{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,Q,X,J,G,K="self",W){this.userId=Q;this.toolName=X;this.boundAuth=J;this.role=G;this.connectionId=K;this.getToolMeta=W}[Symbol.dispose](){this._granted=!1}setToolName(Y){this.toolName=Y}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Y){if(this._granted)return;if(this.toolName?.startsWith("MESH_PUBLIC_")){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new NT0("Authentication required. Please provide a valid OAuth token or API key.")}let Q=Y.length>0?Y:this.toolName?[this.toolName]:[];if(Q.length===0)throw new Y31("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new Y31(`Access denied to: ${Q.join(", ")}`)}async checkResource(Y){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Q={};if(this.connectionId)Q[this.connectionId]=[Y];return this.boundAuth.hasPermission(Q)}async isToolPublic(){if(this.toolName?.startsWith("MESH_PUBLIC_"))return!0;if(!this.getToolMeta)return!1;try{let Y=await this.getToolMeta();if(!Y)return!1;let X=Y[LT0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var b$4="mcp.mesh",qN;var MT0=k(()=>{LR();qN=class qN extends DR{options;cachedToolsMap=null;constructor(Y,Q){super(Y);this.options=Q;if(Q.connection.tools)this.cachedToolsMap=new Map(Q.connection.tools.map((X)=>[X.name,X]))}async handleOutgoingMessage(Y){if(!this.isRequest(Y))return this.innerTransport.send(Y);let Q=Y;if(Q.method==="tools/call")await this.authorizeToolCall(Q),this.stripMetaFromArguments(Q);return this.innerTransport.send(Y)}async authorizeToolCall(Y){if(this.options.superUser)return;let X=Y.params.name,{ctx:J,connection:G}=this.options;if(this.isPublicTool(X))return;if(!J.auth.user?.id&&!J.auth.apiKey?.id)throw Error("Authentication required. Please provide a valid OAuth token or API key.");let K=async()=>{return this.cachedToolsMap?.get(X)?._meta};await new E3(J.authInstance,J.auth.user?.id??J.auth.apiKey?.userId,X,J.boundAuth,J.auth.user?.role,G.id,K).check(X)}isPublicTool(Y){if(Y.startsWith("MESH_PUBLIC_"))return!0;if(!this.cachedToolsMap)return!1;let Q=this.cachedToolsMap.get(Y);if(!Q?._meta)return!1;return Q._meta[b$4]?.public_tool===!0}stripMetaFromArguments(Y){let Q=Y.params;if(Q.arguments&&"_meta"in Q.arguments){let{_meta:X,...J}=Q.arguments;Q.arguments=J}}}});function AT0(Y){if(!Y.isError)return;let Q=Y.content;if(!Array.isArray(Q))return;for(let X of Q)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function X31(Y){if(!Y)return;let Q=Y._meta;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let X=Q.properties;if(!X||typeof X!=="object"||Array.isArray(X))return;let J={};for(let[G,K]of Object.entries(X))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function J31(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function G31(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let Q=Y,X=Q.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return Q}return{value:Y}}async function h$4(Y,Q){let X=Y.body;if(!X)return{text:"",truncated:!1};let J=X.getReader(),G=new TextDecoder,K=!1,W=0,Z=[];try{while(!0){let{value:H,done:F}=await J.read();if(F)break;if(H){if(W+=H.byteLength,W>Q){K=!0;let $=Q-(W-H.byteLength);if($>0)Z.push(G.decode(H.slice(0,$),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}async function Q31(Y){let{ctx:Q,enabled:X}=Y,J=Y.organizationId??Q.organization?.id;if(!X||!J)return;if(LK(Y.connectionId))return;let G=X31(Y.request.params.arguments),K=J31(Q.metadata.properties,G),W=Q.auth.user?.id||Q.auth.apiKey?.userId;if(W)try{let Z=await Q.storage.tags.getUserTagsInOrg(W,J);if(Z.length>0){let H=Z.map((F)=>F.name).join(",");K={...K,user_tags:H}}}catch{}await Q.storage.monitoring.log({organizationId:J,connectionId:Y.connectionId,connectionTitle:Y.connectionTitle,toolName:Y.request.params.name,input:Y.request.params.arguments??{},output:Y.output,isError:Y.isError,errorMessage:Y.errorMessage,durationMs:Y.durationMs,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:Y.virtualMcpId,properties:K})}function PT0(Y){let{ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K}=Y;return async(W,Z)=>{let H=Date.now();try{let F=await Z(),$=Q.organization?.id;if(X&&$){let V=F.clone();(async()=>{try{let{text:q,truncated:z}=await h$4(V,wT0),U=Date.now()-H,D=V.headers.get("content-type")??"",M=q;if(D.includes("application/json"))try{M=q.length?JSON.parse(q):null}catch{M=q}let w=F.status>=400,R=w&&M&&typeof M==="object"&&"error"in M?M.error:void 0,P=typeof R==="string"&&R?R:w&&typeof M==="string"&&M.trim()?M.slice(0,500):w?`HTTP ${F.status} ${F.statusText}`.trim():z?`Response body truncated to ${wT0} bytes`:void 0;await Q31({ctx:Q,enabled:X,organizationId:$,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:G31(M),isError:w,errorMessage:P,durationMs:U})}catch(q){let z=Date.now()-H;await Q31({ctx:Q,enabled:X,organizationId:$,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${q.message}`,durationMs:z})}})()}return F}catch(F){let $=F,V=Date.now()-H;throw await Q31({ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:$.message,durationMs:V}),F}}}var wT0=262144;var W31=k(()=>{UY()});var BN;var ET0=k(()=>{cT();W31();BN=class BN extends DR{options;inflightRequests=new Map;constructor(Y,Q){super(Y);this.options=Q}async handleOutgoingMessage(Y){if(this.isRequest(Y)){let Q=Y;this.onRequestStart(Q)}return this.innerTransport.send(Y)}handleIncomingMessage(Y){if(this.isResponse(Y)){let Q=Y;this.onResponseEnd(Q)}this.onmessage?.(Y)}onRequestStart(Y){let{ctx:Q,connectionId:X}=this.options,J,G;if(Y.method==="tools/call"&&Y.params){let W=Y.params;J=W.name,G=W.arguments}let K;if(Y.method==="tools/call"&&J)K=Q.tracer.startSpan("mcp.proxy.callTool",{attributes:{"connection.id":X,"tool.name":J,"request.id":Q.metadata.requestId,"jsonrpc.id":Y.id,"jsonrpc.method":Y.method}});if(Y.id!==null&&Y.id!==void 0)this.inflightRequests.set(Y.id,{startTime:Date.now(),method:Y.method,toolName:J,toolArguments:G,span:K})}onResponseEnd(Y){if(Y.id===null||Y.id===void 0)return;let Q=this.inflightRequests.get(Y.id);if(!Q)return;let{ctx:X,connectionId:J}=this.options,{startTime:G,method:K,toolName:W,toolArguments:Z,span:H}=Q,F=Date.now()-G;if(this.inflightRequests.delete(Y.id),K!=="tools/call"||!W)return;let $="error"in Y,V=$?Y.error:Y.result,q=$?{content:[{type:"text",text:Y.error?.message||"Unknown error"}],isError:!0}:V;if(X.meter.createHistogram("connection.proxy.duration").record(F,{"connection.id":J,"tool.name":W,status:$?"error":"success"}),$)X.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":J,"tool.name":W,error:Y.error?.message});else X.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":J,"tool.name":W,status:"success"});if(H){if($&&Y.error)H.recordException(Error(Y.error.message)),H.setAttributes({error:!0,"error.code":Y.error.code,"error.message":Y.error.message});H.end()}this.logToDatabase({toolName:W,toolArguments:Z,result:q,duration:F,isError:Boolean($)})}async logToDatabase(Y){let{ctx:Q,connectionId:X,connectionTitle:J,virtualMcpId:G}=this.options,{toolName:K,toolArguments:W,result:Z,duration:H,isError:F}=Y;if(!Qm().enabled)return;let V=Q.organization?.id;if(!V)return;let q=AT0(Z),z=G31(Z),U=X31(W),D=J31(Q.metadata.properties,U);try{await Q.storage.monitoring.log({organizationId:V,connectionId:X,connectionTitle:J,toolName:K,input:W??{},output:z,isError:F,errorMessage:q,durationMs:H,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:G,properties:D})}catch(M){console.error("[MonitoringTransport] Failed to log to database:",M)}}async close(){for(let Y of this.inflightRequests.values())if(Y.span)Y.span.setAttributes({"transport.closed":!0}),Y.span.end();return this.inflightRequests.clear(),super.close()}}});var TT0=k(()=>{MT0();ET0()});async function CT0(Y,Q,X=!1){let J=Y.id,G=Q.connectionId&&Q.connectionId!==J?Q.connectionId:void 0;switch(Y.connection_type){case"STDIO":{if(process.env.UNSAFE_ALLOW_STDIO_TRANSPORT!=="true")throw Error("STDIO connections are disabled in production. Set UNSAFE_ALLOW_STDIO_TRANSPORT=true to enable.");let K=Y.connection_headers;if(!_W(K))throw Error("STDIO connection missing parameters");let W=DT0({id:J,name:Y.title,command:K.command,args:K.args,env:K.envVars,cwd:K.cwd});return W=OR(W,(Z)=>new qN(Z,{ctx:Q,connection:Y,superUser:X}),(Z)=>new BN(Z,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),x$4(W,J)}case"HTTP":case"Websocket":{if(!Y.connection_url)throw Error(`${Y.connection_type} connection missing URL`);let K=await UR(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new rH(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=OR(Z,(H)=>new qN(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new BN(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}case"SSE":{if(!Y.connection_url)throw Error("SSE connection missing URL");let K=await UR(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new EB(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=OR(Z,(H)=>new qN(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new BN(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}var x$4;var RT0=k(()=>{G3();Am();B2();tK1();eK1();OT0();TT0();x$4=dl()});function $$(Y){if(!Y?._meta)return!1;return typeof Y._meta["mcp.mesh"]?.["tool.fn"]==="string"}function ST0(Y){return Y._meta["mcp.mesh"]["tool.fn"]}function NR(Y,Q,X,J){return{id:Y,name:Q.name,description:Q.description,inputSchema:Q.inputSchema,outputSchema:Q.outputSchema,annotations:Q.annotations,code:Q._meta["mcp.mesh"]["tool.fn"],connection_dependencies:Q._meta.connectionDependencies??[],created_at:X,updated_at:J}}var Z31,wv8,TZ,IT0,jT0;var T3=k(()=>{d1();Z31=B.object({title:B.string().optional(),readOnlyHint:B.boolean().optional(),destructiveHint:B.boolean().optional(),idempotentHint:B.boolean().optional(),openWorldHint:B.boolean().optional()}),wv8=B.object({"tool.fn":B.string().describe("JavaScript ES module code that exports a default async function")}),TZ=B.object({id:B.string().describe("Unique identifier for the virtual tool (auto-generated)"),name:B.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:B.string().optional().describe("Human-readable description of what the tool does"),inputSchema:B.record(B.string(),B.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:B.record(B.string(),B.unknown()).optional().describe("JSON Schema defining the tool's output (optional)"),annotations:Z31.optional().describe("MCP tool annotations"),code:B.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:B.array(B.string()).describe("Connection IDs that this tool depends on (specified by the creator)"),created_at:B.string().describe("When the virtual tool was created"),updated_at:B.string().describe("When the virtual tool was last updated")}),IT0=B.object({name:B.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:B.string().optional().describe("Human-readable description"),inputSchema:B.record(B.string(),B.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:B.record(B.string(),B.unknown()).optional().describe("JSON Schema for output"),annotations:Z31.optional().describe("MCP tool annotations"),code:B.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:B.array(B.string()).optional().describe("Connection IDs that this tool depends on. Creates indirect aggregations to prevent deletion of referenced connections.")}),jT0=B.object({name:B.string().min(1).max(255).optional().describe("New tool name"),description:B.string().nullable().optional().describe("New description (null to clear)"),inputSchema:B.record(B.string(),B.unknown()).optional().describe("New input schema"),outputSchema:B.record(B.string(),B.unknown()).nullable().optional().describe("New output schema (null to clear)"),annotations:Z31.nullable().optional().describe("New annotations (null to clear)"),code:B.string().optional().describe("New JavaScript code"),connection_dependencies:B.array(B.string()).optional().describe("Connection IDs that this tool depends on. Replaces existing dependencies if provided.")})});function gB(Y){return(Q)=>{if(Q instanceof w0&&Q.code===C0.MethodNotFound)return Y;throw Q}}var K31=k(()=>{zY()});class vT0{factory;promise=null;constructor(Y){this.factory=Y}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Y,Q){return this.getOrCreatePromise().then(Y,Q)}catch(Y){return this.getOrCreatePromise().catch(Y)}finally(Y){return this.getOrCreatePromise().finally(Y)}}function uB(Y){return new vT0(Y)}async function g$4(Y,Q,X=!1){let J=await Promise.all(Y.map(async(G)=>{try{let K=await aQ(G,Q,X);return[G.id,K]}catch(K){return console.warn(`[aggregator] Failed to create client for connection ${G.id}:`,K),null}}));return new Map(J.filter((G)=>!!G))}async function kT0(Y){let Q=[];for(let[,X]of Y)Q.push(X.close().catch(()=>{}));await Promise.all(Q)}var zN;var H31=k(()=>{UN();K31();Hq();gK1();T3();zN=class zN extends DX{options;ctx;_cachedTools;_cachedResources;_cachedPrompts;_clients;_connections;_selectionMap;constructor(Y,Q){super({name:"virtual-mcp-passthrough",version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});this.options=Y;this.ctx=Q;this._selectionMap=new Map;for(let X of Y.virtualMcp.connections)this._selectionMap.set(X.connection_id,X);this._connections=new Map;for(let X of Y.connections)this._connections.set(X.id,X);this._clients=uB(()=>g$4(this.options.connections,this.ctx,this.options.superUser)),this._cachedTools=uB(()=>this.loadToolsCache()),this._cachedResources=uB(()=>this.loadCache("resources")),this._cachedPrompts=uB(()=>this.loadCache("prompts"))}async loadToolsCache(){let Y=await this._clients,Q=await Promise.all(Array.from(Y.entries()).map(async([W,Z])=>{try{let H=await Z.listTools().then(($)=>$.tools),F=this._selectionMap.get(W);if(F?.selected_tools?.length){let $=new Set(F.selected_tools);H=H.filter((V)=>$.has(V.name))}return{connectionId:W,data:H}}catch(H){return console.error(`[PassthroughClient] Failed to load tools for connection ${W}:`,H),null}})),X=[],J=new Map,G=new Map,K=this.options.virtualTools??[];for(let W of K){if(J.has(W.name))continue;let Z={name:W.name,description:W.description,inputSchema:W.inputSchema,outputSchema:W.outputSchema,annotations:W.annotations,_meta:{connectionId:this.options.virtualMcp.id??"__VIRTUAL__",connectionTitle:this.options.virtualMcp.title}};X.push(Z),J.set(W.name,"__VIRTUAL__"),G.set(W.name,W)}for(let W of Q){if(!W)continue;let{connectionId:Z,data:H}=W,$=this._connections.get(Z)?.title??"";for(let V of H){let q=V.name;if(J.has(q))continue;let z={...V,_meta:{connectionId:Z,connectionTitle:$,...V?._meta}};X.push(z),J.set(q,Z)}}return{data:X,mappings:J,virtualTools:G}}async loadCache(Y){let Q=await this._clients,X=await Promise.all(Array.from(Q.entries()).map(async([K,W])=>{try{let Z=Y==="resources"?await W.listResources().catch(gB({resources:[]})).then(($)=>$.resources):await W.listPrompts().catch(gB({prompts:[]})).then(($)=>$.prompts),H=this._selectionMap.get(K),F=Y==="resources"?"selected_resources":"selected_prompts";if(H?.[F]?.length){let $=new Set(H[F]);return{connectionId:K,data:Z.filter((V)=>$.has(V.name))}}return{connectionId:K,data:Z}}catch(Z){return console.error(`[PassthroughClient] Failed to load cache for connection ${K}:`,Z),null}})),J=[],G=new Map;for(let K of X){if(!K)continue;let{connectionId:W,data:Z}=K,F=this._connections.get(W)?.title??"";for(let $ of Z){let V=$.name??$.uri;if(G.has(V))continue;let q={...$,_meta:{connectionId:W,connectionTitle:F,...$?._meta}};J.push(q),G.set(V,W)}}return{data:J,mappings:G}}async listTools(){return{tools:(await this._cachedTools).data}}async callTool(Y){let[Q,X]=await Promise.all([this._cachedTools,this._clients]),J=Q.mappings.get(Y.name);if(!J)return{content:[{type:"text",text:`Tool not found: ${Y.name}`}],isError:!0};if(J==="__VIRTUAL__")return this.executeVirtualTool(Y.name,Y.arguments??{},Q,X);let G=X.get(J);if(!G)return{content:[{type:"text",text:`Connection not found for tool: ${Y.name}`}],isError:!0};return await G.callTool({name:Y.name,arguments:Y.arguments??{}})}async executeVirtualTool(Y,Q,X,J){let G=X.virtualTools.get(Y);if(!G)return{content:[{type:"text",text:`Virtual tool not found: ${Y}`}],isError:!0};let K=ST0(G),W={};for(let[Z,H]of X.mappings){if(H==="__VIRTUAL__")continue;let F=J.get(H);if(!F)continue;W[Z]=async($)=>{let V=await F.callTool({name:Z,arguments:$});if(V.structuredContent&&typeof V.structuredContent==="object")return V.structuredContent;let q=V.content;if(q?.[0]?.type==="text"&&q[0].text)try{return JSON.parse(q[0].text)}catch{return q[0].text}return V}}try{let H=`
|
|
1204
1204
|
const __virtualToolFn = ${K.replace(/^\s*export\s+default\s+/,"").trim()};
|
|
1205
1205
|
export default async (tools) => {
|
|
1206
1206
|
const args = ${JSON.stringify(Q)};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{M as t,Q as a}from"./index-BKKW7mU3.js";const e=t(a,{target:"draft-7"});export{e as B};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{I as u}from"./infiniteQueryObserver-C--Cp687.js";import{a5 as i}from"./index-BKKW7mU3.js";function t(e,r){return i(e,u,r)}export{t as u};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a5 as u,a8 as s}from"./index-BKKW7mU3.js";function o(e,r){return u(e,s,r)}export{o as u};
|