@decocms/mesh 2.125.3 → 2.127.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-CAn1onHH.js → AlertCircle-DJ052zqS.js} +1 -1
- package/dist/client/assets/{AlertOctagon-ChcnKW7P.js → AlertOctagon-DCNCOxEl.js} +1 -1
- package/dist/client/assets/{AlertTriangle-Suhq71Ba.js → AlertTriangle-MQM19F_y.js} +1 -1
- package/dist/client/assets/{ArrowDown-BQn3fvf7.js → ArrowDown-Bn9Nw2BD.js} +1 -1
- package/dist/client/assets/{ArrowLeft-DkojAdWe.js → ArrowLeft-BSPqreiE.js} +1 -1
- package/dist/client/assets/{ArrowUp-CCTJ8tar.js → ArrowUp-BLFAP4Oh.js} +1 -1
- package/dist/client/assets/{Check-2BTd1528.js → Check-BXz-Aa3Y.js} +1 -1
- package/dist/client/assets/{CheckCircle-DUsP9qJl.js → CheckCircle-DmsV77x1.js} +1 -1
- package/dist/client/assets/{CheckDone01-Bs5yfbwu.js → CheckDone01-CQuFbmYi.js} +1 -1
- package/dist/client/assets/{CheckVerified02-D9LvEg4-.js → CheckVerified02-C2uVr9FW.js} +1 -1
- package/dist/client/assets/{ChevronDown-BK0Z-3ss.js → ChevronDown-CEb48ZDu.js} +1 -1
- package/dist/client/assets/{ChevronRight-CpFHeZ-k.js → ChevronRight-CQS5xbc3.js} +1 -1
- package/dist/client/assets/{Clock-DWLl74MU.js → Clock-X1ZnQ0e8.js} +1 -1
- package/dist/client/assets/{Code01-D7rt1C5k.js → Code01-CVF-mmmz.js} +1 -1
- package/dist/client/assets/{Container-Dkua_wx6.js → Container-D3N8SS-J.js} +1 -1
- package/dist/client/assets/{Copy01-CWD2XYkN.js → Copy01-CFXdI8SF.js} +1 -1
- package/dist/client/assets/{Dataflow03-dIUcYa_e.js → Dataflow03-BvFbR-2p.js} +1 -1
- package/dist/client/assets/{DotsHorizontal-R03fSXLm.js → DotsHorizontal-BlKZUIAr.js} +1 -1
- package/dist/client/assets/{DotsVertical-nJGFqnIJ.js → DotsVertical-CJJQe-sw.js} +1 -1
- package/dist/client/assets/{Download01-w53nljTi.js → Download01-BuGXWPUb.js} +1 -1
- package/dist/client/assets/{Edit01-Een9NeGa.js → Edit01-vxAH-tv6.js} +1 -1
- package/dist/client/assets/{Eye-cRMKwlob.js → Eye-Cqy0OQfO.js} +1 -1
- package/dist/client/assets/{File02-BiHbI-Bs.js → File02-CYWnFy5E.js} +1 -1
- package/dist/client/assets/{File06-DK6hozGp.js → File06-p-mGMfLu.js} +1 -1
- package/dist/client/assets/{FilterLines-DcFfiBYv.js → FilterLines-B-D6srZC.js} +1 -1
- package/dist/client/assets/{Globe01-zBSU4RrG.js → Globe01-Di6WS1d0.js} +1 -1
- package/dist/client/assets/{Globe02-BzI-D3XF.js → Globe02-CL5aTFno.js} +1 -1
- package/dist/client/assets/{Grid01-DtWTP079.js → Grid01-BGPoEeik.js} +1 -1
- package/dist/client/assets/{Hash02-B_cIkiva.js → Hash02-BWg3CKrn.js} +1 -1
- package/dist/client/assets/{Home02-B0J9-6Fj.js → Home02-Atzompjz.js} +1 -1
- package/dist/client/assets/{Image01-DuLPJrbP.js → Image01-B-9nWGvT.js} +1 -1
- package/dist/client/assets/{Inbox01-DkeOZ2C_.js → Inbox01-CWbCHIve.js} +1 -1
- package/dist/client/assets/{InfoCircle-v_Zi3ix-.js → InfoCircle-BxNpDB4f.js} +1 -1
- package/dist/client/assets/{Key01-FdWHEw6c.js → Key01-BBHw8-AF.js} +1 -1
- package/dist/client/assets/{LinkExternal01-BvWelMzx.js → LinkExternal01-BH7m2QmL.js} +1 -1
- package/dist/client/assets/{List-D1SXIq-Q.js → List-DZq_3WJK.js} +1 -1
- package/dist/client/assets/{Loading01-BntQXW3R.js → Loading01-Bm0RmGTq.js} +1 -1
- package/dist/client/assets/{Lock01-Ca25inpJ.js → Lock01-BY0MGONc.js} +1 -1
- package/dist/client/assets/{Pin01-D5SNXGno.js → Pin01-BQxfi8aj.js} +1 -1
- package/dist/client/assets/{Play-Dv6XoPC1.js → Play-CGUn4LDu.js} +1 -1
- package/dist/client/assets/{Plus-BpJ1F9ED.js → Plus-CfD4U7h2.js} +1 -1
- package/dist/client/assets/{RefreshCcw01-C6HpBrM2.js → RefreshCcw01-ClQUpEVA.js} +1 -1
- package/dist/client/assets/{RefreshCw01-BLvlqjIJ.js → RefreshCw01-DsYl6Nso.js} +1 -1
- package/dist/client/assets/{Rows03-Bw2KmPLF.js → Rows03-BmDCzA2B.js} +1 -1
- package/dist/client/assets/{Save01-C7Op6P3G.js → Save01-CVm8Nhi5.js} +1 -1
- package/dist/client/assets/{SearchMd-B22BWSrE.js → SearchMd-rBeGYVN8.js} +1 -1
- package/dist/client/assets/{Settings01-39eYdV1s.js → Settings01-BCU61Dg3.js} +1 -1
- package/dist/client/assets/{Shield01-D5vtlDrS.js → Shield01-D73wrcGm.js} +1 -1
- package/dist/client/assets/{Terminal-jwgZ8meH.js → Terminal-B7IR3GOF.js} +1 -1
- package/dist/client/assets/Tool01-D4p-h1gd.js +1 -0
- package/dist/client/assets/{Trash01-NHvYJiOw.js → Trash01-CNjhe6V_.js} +1 -1
- package/dist/client/assets/{Upload01-B7z0chWz.js → Upload01-KtFgXqwG.js} +1 -1
- package/dist/client/assets/{Users03-CfBv5uVc.js → Users03-DNxW_fja.js} +1 -1
- package/dist/client/assets/{X-nbY3n5YX.js → X-OID4YrAs.js} +1 -1
- package/dist/client/assets/{XCircle-CdrNrzcr.js → XCircle-LfPUm5IL.js} +1 -1
- package/dist/client/assets/{XClose-DHV8bqGR.js → XClose-CVjVP425.js} +1 -1
- package/dist/client/assets/{agent-connections-preview-D2nPeCg-.js → agent-connections-preview-BPhKy-Id.js} +1 -1
- package/dist/client/assets/agent-detail-HyuxH4Ve.js +2 -0
- package/dist/client/assets/agents-Bc9eRkDe.js +1 -0
- package/dist/client/assets/{alert-dialog-DIblcPQC.js → alert-dialog-9GjsXnzK.js} +1 -1
- package/dist/client/assets/{auth-catchall-lueUuNUs.js → auth-catchall-Bsy9nmf9.js} +1 -1
- package/dist/client/assets/{avatar-DAde4Coq.js → avatar-D7LZZNPu.js} +1 -1
- package/dist/client/assets/{badge-EvnzqGBM.js → badge-CQ9R9pkG.js} +1 -1
- package/dist/client/assets/{binder-DtqSnmtn.js → binder-BRFblyKj.js} +1 -1
- package/dist/client/assets/{breadcrumb-Dit0z7A7.js → breadcrumb-_jAneXHm.js} +1 -1
- package/dist/client/assets/{button-DDY6hri1.js → button-BjJbLzI1.js} +1 -1
- package/dist/client/assets/{card-CHcjH7V4.js → card-BiNPXwY7.js} +1 -1
- package/dist/client/assets/{chart-BEZIHLHA.js → chart-Cye540qd.js} +5 -5
- package/dist/client/assets/{checkbox-_pZquTsv.js → checkbox-ClNyXMEe.js} +1 -1
- package/dist/client/assets/{circle-alert-8my-DdYx.js → circle-alert-BwBTOPt2.js} +1 -1
- package/dist/client/assets/collection-detail-CgUzsg7m.js +26 -0
- package/dist/client/assets/collection-search-D9lLlfmK.js +1 -0
- package/dist/client/assets/collection-tab-CK-Q89lj.js +1 -0
- package/dist/client/assets/collection-table-wrapper-HJznMrYU.js +1 -0
- package/dist/client/assets/{collection-tabs-CMMj9apF.js → collection-tabs-D0BDRIQH.js} +1 -1
- package/dist/client/assets/{command-D0lPyqX9.js → command-CmCm6EpS.js} +1 -1
- package/dist/client/assets/{connect-jPJQySxH.js → connect-D_vBcyxr.js} +1 -1
- package/dist/client/assets/{connection-card-C36z_Zfo.js → connection-card-O78FPkKW.js} +1 -1
- package/dist/client/assets/connection-detail-CqECx5w9.js +1 -0
- package/dist/client/assets/connections-DcBskx9Y.js +1 -0
- package/dist/client/assets/{constants-BWuwqVaf.js → constants-Bz_J8k2h.js} +1 -1
- package/dist/client/assets/constants-CQfW12Qo.js +1 -0
- package/dist/client/assets/{context-BoqYBHof.js → context-DPw3JrfP.js} +1 -1
- package/dist/client/assets/{create-organization-dialog-DZ-29KA3.js → create-organization-dialog-ChDwEIL0.js} +1 -1
- package/dist/client/assets/{create-project-dialog-5JWgj7o1.js → create-project-dialog-D_pqfYAD.js} +1 -1
- package/dist/client/assets/{deco-constants-Lndb0_Fi.js → deco-constants-CGrimklY.js} +1 -1
- package/dist/client/assets/{dialog-AmArt43J.js → dialog-CsS26GNP.js} +1 -1
- package/dist/client/assets/{dropdown-menu-CMr4pVGd.js → dropdown-menu-Bx6HZEO6.js} +1 -1
- package/dist/client/assets/{dynamic-plugin-layout-B-RWLbim.js → dynamic-plugin-layout-ChDoP95P.js} +1 -1
- package/dist/client/assets/editable-thread-title-DG8vSbP7.js +16 -0
- package/dist/client/assets/{empty-state-BxqfhnZC.js → empty-state-BIKMZA4A.js} +1 -1
- package/dist/client/assets/{env-vars-editor-CeWJLU0d.js → env-vars-editor-Bu4z6L63.js} +1 -1
- package/dist/client/assets/{error-boundary-BbdoNwwk.js → error-boundary-BOjL_3iE.js} +1 -1
- package/dist/client/assets/{extract-connection-data-FghvIcuN.js → extract-connection-data-9qHOXLXC.js} +1 -1
- package/dist/client/assets/{file-browser-BRNDEG3O.js → file-browser-DlsvWnR4.js} +2 -2
- package/dist/client/assets/{form-Bsyh-cQj.js → form-BcYKMkAo.js} +1 -1
- package/dist/client/assets/{grid-view-BjxbyS3V.js → grid-view-DKE_LwVv.js} +1 -1
- package/dist/client/assets/{home-BqlHZV0D.js → home-CfX1o6Ev.js} +1 -1
- package/dist/client/assets/index-B7FUMscm.css +1 -0
- package/dist/client/assets/{index-ClGhCbA0.js → index-BFnklquP.js} +72 -62
- package/dist/client/assets/{index-IwkUYudi.js → index-BqwppNxk.js} +1 -1
- package/dist/client/assets/{index-CMIePc8v.js → index-CKXRhh0t.js} +37 -37
- package/dist/client/assets/{index-7GX9Z2_E.js → index-DbG6jisP.js} +1 -1
- package/dist/client/assets/{index-BwsTCLNe.js → index-Ds78Hq48.js} +1 -1
- package/dist/client/assets/index-LVMAuFW8.js +1 -0
- package/dist/client/assets/{index-_qbzL5MU.js → index-kQL4iCgd.js} +1 -1
- package/dist/client/assets/{index-Ck8tqNHK.js → index-lC9RbQEq.js} +1 -1
- package/dist/client/assets/{index-MmPZuevW.js → index-nl6bR4T8.js} +1 -1
- package/dist/client/assets/{infiniteQueryObserver-DuAdiH0n.js → infiniteQueryObserver-C_YVCa9u.js} +1 -1
- package/dist/client/assets/{input-Je9XV62u.js → input-BPPp7fkV.js} +1 -1
- package/dist/client/assets/{integration-icon-DeiJ75EP.js → integration-icon-CaUI1jG_.js} +1 -1
- package/dist/client/assets/{label-Ct-IE-k2.js → label-Ce-8MeXM.js} +1 -1
- package/dist/client/assets/{layout-BWtcS0Q2.js → layout-B_vm2aCi.js} +1 -1
- package/dist/client/assets/{localstorage-keys-B-4HWrAO.js → localstorage-keys-D7-2hl7K.js} +1 -1
- package/dist/client/assets/{login-swb3IsCw.js → login-BZjy-JZF.js} +1 -1
- package/dist/client/assets/{markdown-BshJmJUr.js → markdown-CL_nEHz6.js} +1 -1
- package/dist/client/assets/mcp-oauth-6gipdrl8.js +1 -0
- package/dist/client/assets/{mcp-server-card-DJ-C7iNn.js → mcp-server-card-k65UbfnQ.js} +1 -1
- package/dist/client/assets/mcp-server-detail-DOi3A41L.js +2 -0
- package/dist/client/assets/members-DyXednFN.js +3 -0
- package/dist/client/assets/{monitoring-Dkzs8zLr.js → monitoring-CbDWX7qw.js} +2 -2
- package/dist/client/assets/{monitoring-dashboard-edit-6Jd7ItfF.js → monitoring-dashboard-edit-Xu9WaY0f.js} +1 -1
- package/dist/client/assets/{monitoring-dashboard-view-NmZHmCWV.js → monitoring-dashboard-view-BnJZoOh6.js} +1 -1
- package/dist/client/assets/{oauth-callback-hu62EGGB.js → oauth-callback-CLQrXT_i.js} +1 -1
- package/dist/client/assets/page-NSWxyYqB.js +1 -0
- package/dist/client/assets/page-tLMAT584.js +1 -0
- package/dist/client/assets/{plugin-empty-state-BfDH4uPn.js → plugin-empty-state-D5Ff5dMm.js} +1 -1
- package/dist/client/assets/{plugin-empty-state-DRRVQKmb.js → plugin-empty-state-WLlCNcH0.js} +1 -1
- package/dist/client/assets/{plugin-header-BPNBXPjM.js → plugin-header-DBNmWz2Z.js} +1 -1
- package/dist/client/assets/{plugin-header-8kNYjC6n.js → plugin-header-D_CX7196.js} +1 -1
- package/dist/client/assets/{popover-CdPr2kUy.js → popover-Dz4mFPzW.js} +1 -1
- package/dist/client/assets/{project-layout-bgteQ5fY.js → project-layout-L7FdQtTW.js} +1 -1
- package/dist/client/assets/projects-list-DFLeaqhB.js +1 -0
- package/dist/client/assets/{ranking-layout-BxRgmZtS.js → ranking-layout-CLhL84_g.js} +1 -1
- package/dist/client/assets/{readme-viewer-ym80L_hw.js → readme-viewer-BAJaQnye.js} +1 -1
- package/dist/client/assets/{registry-layout-C8Ew4flr.js → registry-layout-CLL316VY.js} +1 -1
- package/dist/client/assets/{registry-utils-DBAgugDf.js → registry-utils-C_nLhlWN.js} +1 -1
- package/dist/client/assets/{reports-layout-BoIJWhiW.js → reports-layout-DnfAta3q.js} +2 -2
- package/dist/client/assets/{reset-password-DY5mUItc.js → reset-password-Cpx9ZUFt.js} +1 -1
- package/dist/client/assets/{resizable-8m39GKGn.js → resizable-TMJNEC5w.js} +1 -1
- package/dist/client/assets/{save-actions-DnxE-Bzm.js → save-actions-BYQZP6Sr.js} +1 -1
- package/dist/client/assets/{scroll-area-C-RNU2ZC.js → scroll-area-D6nBfX1Y.js} +4 -4
- package/dist/client/assets/{select-B9AjxT2Q.js → select-CwR5iwKr.js} +1 -1
- package/dist/client/assets/shell-layout-BnW-yUkb.js +3 -0
- package/dist/client/assets/{skeleton-BAWgWTH6.js → skeleton-DzMO4E_x.js} +1 -1
- package/dist/client/assets/{spinner-C5H8EOvR.js → spinner-B4HBT9r3.js} +1 -1
- package/dist/client/assets/{store-invite-BSP87zro.js → store-invite-DR-2VUII.js} +1 -1
- package/dist/client/assets/{switch-Bnxx_fFZ.js → switch-DkAfY5Xp.js} +1 -1
- package/dist/client/assets/{table-Bt31_DyV.js → table-BDxbk9kk.js} +1 -1
- package/dist/client/assets/tasks-JeX1dzU3.js +1 -0
- package/dist/client/assets/{textarea-Dfcf9iVI.js → textarea-C7R7dq5L.js} +1 -1
- package/dist/client/assets/{time-range-picker-VoxMdMGw.js → time-range-picker-CPtVWgsO.js} +1 -1
- package/dist/client/assets/{toggle-group-BYr6H2N2.js → toggle-group-BsC04HU0.js} +1 -1
- package/dist/client/assets/tools-list-C1FJexpR.js +1 -0
- package/dist/client/assets/{tooltip-Kun6OEqc.js → tooltip-C-TvyUPP.js} +1 -1
- package/dist/client/assets/{topbar-portal-BYkDxjeH.js → topbar-portal-BlsIm0Za.js} +1 -1
- package/dist/client/assets/types-DWiNuJXJ.js +155 -0
- package/dist/client/assets/{use-binding-Bt6opM01.js → use-binding-DtOyQ6H-.js} +1 -1
- package/dist/client/assets/{use-connection-CZeLlUDa.js → use-connection-CU1wdNM8.js} +1 -1
- package/dist/client/assets/{use-copy-BLt7-cw9.js → use-copy-C-xyAEAK.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-BWbRPuCZ.js → use-create-virtual-mcp-CdmTVIKM.js} +1 -1
- package/dist/client/assets/use-deco-chat-open-yra_c3Dw.js +1 -0
- package/dist/client/assets/{use-install-from-registry-BsUBgwfp.js → use-install-from-registry-Dpg6ludv.js} +1 -1
- package/dist/client/assets/{use-list-state-B_n0GZwG.js → use-list-state-DEj8YIwi.js} +1 -1
- package/dist/client/assets/{use-llm-CBsUcVLv.js → use-llm-Bjuj_MKF.js} +1 -1
- package/dist/client/assets/use-mcp-prompts-C2SxEfwc.js +1 -0
- package/dist/client/assets/{use-mcp-tools-BED8kPD7.js → use-mcp-tools-aLeNmzej.js} +1 -1
- package/dist/client/assets/{use-mobile-DLzBblnh.js → use-mobile-B6wwiLld.js} +1 -1
- package/dist/client/assets/{use-organization-settings-BTKBql6r.js → use-organization-settings-DdF3cHOT.js} +1 -1
- package/dist/client/assets/{use-project-Dgs5h9hm.js → use-project-Bmqhspht.js} +1 -1
- package/dist/client/assets/{use-settings-modal-CL7KNbwO.js → use-settings-modal-BQGLflyF.js} +1 -1
- package/dist/client/assets/{use-view-mode-Cm6MlS0B.js → use-view-mode-D5ZS-ZdB.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-chylq6BL.js → use-virtual-mcp-DqbEku8h.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-DgzNofe0.js +1 -0
- package/dist/client/assets/{useMutation-CTU78J7M.js → useMutation-D2jNlXyR.js} +1 -1
- package/dist/client/assets/useQuery-6KDecjjg.js +1 -0
- package/dist/client/assets/useSuspenseInfiniteQuery-B2-Ew4j-.js +1 -0
- package/dist/client/assets/workflow-DJP52hJ3.js +1 -0
- package/dist/client/index.html +2 -2
- package/dist/server/cli.js +5 -5
- package/dist/server/migrate.js +2 -2
- package/dist/server/server.js +5 -5
- package/package.json +2 -1
- package/dist/client/assets/agent-detail-CAAcyNFf.js +0 -2
- package/dist/client/assets/agents-IxYsoQkx.js +0 -1
- package/dist/client/assets/collection-detail-BPjVfY9E.js +0 -26
- package/dist/client/assets/collection-search-BhyeAK8D.js +0 -1
- package/dist/client/assets/collection-tab-DYRZjIfR.js +0 -1
- package/dist/client/assets/collection-table-wrapper-DF0r5l64.js +0 -1
- package/dist/client/assets/connection-detail-D4fpJvP6.js +0 -1
- package/dist/client/assets/connections-Dd7R3YoP.js +0 -1
- package/dist/client/assets/constants-alL-orOw.js +0 -1
- package/dist/client/assets/empty-state-CUU2GnRG.js +0 -1
- package/dist/client/assets/index-D1eaSCBW.css +0 -1
- package/dist/client/assets/index-DFjHyz2s.js +0 -1
- package/dist/client/assets/mcp-oauth-DtHeHoWJ.js +0 -1
- package/dist/client/assets/mcp-server-detail-Du1aBWwk.js +0 -2
- package/dist/client/assets/members-BLWGtvj7.js +0 -3
- package/dist/client/assets/page-C-wJ53x_.js +0 -1
- package/dist/client/assets/page-Y1SYGnRN.js +0 -1
- package/dist/client/assets/projects-list-DngofdiO.js +0 -1
- package/dist/client/assets/shell-layout-DY2c6Efx.js +0 -3
- package/dist/client/assets/tasks-OIFCJv2K.js +0 -1
- package/dist/client/assets/tools-list-CMPsf87L.js +0 -1
- package/dist/client/assets/typewriter-title-ir44iZyu.js +0 -16
- package/dist/client/assets/use-deco-chat-open-DqF5WsjN.js +0 -1
- package/dist/client/assets/use-mcp-prompts-CTAKOvKB.js +0 -1
- package/dist/client/assets/useInfiniteQuery-B4zFsz_-.js +0 -1
- package/dist/client/assets/useQuery-CL8s1AaN.js +0 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-CnNOZleg.js +0 -1
- package/dist/client/assets/view-mode-toggle-lRAyyRMm.js +0 -1
- package/dist/client/assets/workflow-CH4Jfjr7.js +0 -1
package/dist/server/migrate.js
CHANGED
|
@@ -1467,7 +1467,7 @@ ${Y.stack}`;return Q}if(typeof Y==="object"&&Y!==null){let Q=Y,X="";if(typeof Q.
|
|
|
1467
1467
|
${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}
|
|
1468
1468
|
|
|
1469
1469
|
Stack trace:
|
|
1470
|
-
${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 $=bN(F),V=Y.newString(`Promise resolution error: ${$}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let F=bN(H),$=Y.newString(`Promise rejection: ${F}`);Z.reject($),$.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return hN(Y,W)}catch(K){let W=bN(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 ty0=()=>{};function Yf0(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 ey0(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){Yf0(Y);let K=await Promise.race([G,s24(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 sR({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=qI(W,await oy0({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=qI(W,J.newContext({interruptAfterMs:X}),0);const K=qI(W,ny0(G),0);try{let $=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult($),B=hN(G,Y);G.setProp(G.global,"tools",B);let U=G.runtime.hasPendingJob()?G.unwrapResult(await ey0(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),O=G.typeof(z);if(O!=="function")return z.dispose(),U.dispose(),B.dispose(),{error:`Code must export default a function (tools). Got ${O}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let M=G.callFunction(z,G.undefined,B);B.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(M),P=await ey0(G,w,X);w.dispose();let j=G.unwrapResult(P);if(G.runtime.hasPendingJob())Yf0(G);let C=G.dump(j);return j.dispose(),{returnValue:C,consoleLogs:K.logs}}catch($){return console.log($),{error:bN($),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{lV1(W,H,F)}}var s24=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var Qf0=S(()=>{sy0();ty0()});var W$1=S(()=>{Qf0()});async function t24(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 Xf0(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 e24(Y,Q){let X=new Map;for(let B of Y)X.set(B.connection.id,B);let J=Y.map((B)=>B.connection),G=new Map,K=await Promise.allSettled(J.map(async(B)=>{try{let U=await Q.createMCPProxy(B);return{connection:B,proxy:U}}catch(U){return console.warn(`[code-execution] Failed to create proxy for connection ${B.id}:`,U),null}}));for(let B of K)if(B.status==="fulfilled"&&B.value)G.set(B.value.connection.id,B.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([B,U])=>{try{let O=(await U.proxy.listTools()).tools,M=X.get(B);if(M?.selectedTools&&M.selectedTools.length>0){let w=new Set(M.selectedTools);O=O.filter((P)=>w.has(P.name))}return{connectionId:B,connectionTitle:U.connection.title,tools:O}}catch(z){return console.error(`[code-execution] Failed to list tools for connection ${B}:`,z),null}})),Z=new Set,H=[],F=new Map;for(let B of W){if(B.status!=="fulfilled"||!B.value)continue;let{connectionId:U,connectionTitle:z,tools:O}=B.value;for(let M of O){if(Z.has(M.name))continue;Z.add(M.name),H.push({...M,_meta:{connectionId:U,connectionTitle:z}}),F.set(M.name,U)}}let $=async(B,U)=>{let z=F.get(B);if(!z)return{content:[{type:"text",text:`Tool not found: ${B}`}],isError:!0};let O=G.get(z);if(!O)return{content:[{type:"text",text:`Connection not found for tool: ${B}`}],isError:!0};return await O.proxy.callTool({name:B,arguments:U})},V=[];for(let[,B]of G)V.push(B.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:$}}async function xN(Y){let Q=B0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await t24(J,Y);else X=await Xf0(Q.id,Y)}else X=await Xf0(Q.id,Y);return e24(X,Y)}function YE4(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function QE4(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 qp(Y,Q,X){let J=YE4(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:QE4(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Bp(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 Up(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 sR({code:Y,tools:J,timeoutMs:X})}function tR(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function M$(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function m3(Y){let Q=new Set(XE4);return Y.filter((X)=>!Q.has(X.name))}var XE4;var WU=S(()=>{W$1();XE4=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var Z$1;var Jf0=S(()=>{k0();oR();WU();Z$1=k1({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.",annotations:{title:"Search Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:uy0,outputSchema:my0,handler:async(Y,Q)=>{o1(Q),B0(Q),await Q.access.check();let X=await xN(Q),J=qp(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 K$1;var Gf0=S(()=>{k0();oR();WU();K$1=k1({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.",annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:ly0,outputSchema:dy0,handler:async(Y,Q)=>{o1(Q),B0(Q),await Q.access.check();let X=await xN(Q);return Bp(Y.tools,X.tools)}})});var H$1;var Wf0=S(()=>{k0();oR();WU();H$1=k1({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.',annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:py0,outputSchema:cy0,handler:async(Y,Q)=>{o1(Q),B0(Q),await Q.access.check();let X=await xN(Q);return await Up(Y.code,X,Y.timeoutMs)}})});var Zf0=S(()=>{Jf0();Gf0();Wf0();oR()});var GE4,WE4,F$1;var Kf0=S(()=>{zY();v1();k0();pm();L3();GE4=q.object({data:CA.describe("Data for the new connection (id is auto-generated if not provided)")}),WE4=q.object({item:P5.describe("The created connection entity")}),F$1=k1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:GE4,outputSchema:WE4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=D9(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 F=LV(G.connection_url);if(!F)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let $=await Q.storage.virtualMcps.findById(F);if(!$)throw Error(`Virtual MCP not found: ${F}`);if($.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=NV(F)}let K=await iL({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?.tools?.length?K.tools:null,Z=K?.scopes?.length?K.scopes:null,H=await Q.storage.connections.create({...G,tools:W,configuration_scopes:Z});return await Q.eventBus.publish(X.id,h9.SELF(X.id),{type:"connection.created",data:H}),{item:H}}})});var ZE4,KE4,Hf0;var Ff0=S(()=>{v1();gX();ZE4=yZ.extend({avatar:q.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:q.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:q.string().describe("Virtual MCP ID to use for this assistant"),model:q.object({id:q.string().describe("Model ID"),connectionId:q.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),KE4=fZ("assistant",ZE4),Hf0=[...KE4]});var eR,l3,Vf0,HE4,FE4,qf0,$E4,VE4,qE4,BE4,UE4,zE4,Bf0,DE4,OE4,LE4,NE4,ME4,wE4,AE4,PE4,EE4,TE4,mi8,CE4,li8,$f0,RE4,IE4,$$1,di8;var Uf0=S(()=>{v1();_B();gX();eR=q.lazy(()=>q.union([q.null(),q.string(),q.number(),q.boolean(),q.record(q.string(),eR),q.array(eR)])),l3=q.record(q.string(),q.record(q.string(),eR)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),Vf0=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerOptions:l3}),HE4=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),FE4=q.string().describe("File data as URL string"),qf0=q.object({type:q.literal("file"),filename:q.string().optional().describe("Optional filename of the file"),data:FE4,mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:l3}),$E4=q.object({type:q.literal("file"),mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:q.string().describe("Generated file data as base64 encoded string")}),VE4=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerOptions:l3}),qE4=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),BE4=q.object({type:q.literal("tool-call"),toolCallId:q.string().describe("ID of the tool call, used to match with tool result"),toolName:q.string().describe("Name of the tool being called"),input:q.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:q.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:l3}),UE4=q.object({type:q.literal("tool-call"),toolCallId:q.string().describe("ID of the tool call"),toolName:q.string().describe("Name of the tool being called"),input:q.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:q.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),zE4=q.union([q.object({type:q.literal("text"),value:q.string()}),q.object({type:q.literal("json"),value:eR}),q.object({type:q.literal("error-text"),value:q.string()}),q.object({type:q.literal("error-json"),value:eR}),q.object({type:q.literal("content"),value:q.array(q.union([q.object({type:q.literal("text"),text:q.string().describe("Text content")}),q.object({type:q.literal("media"),data:q.string().describe("Base-64 encoded media data"),mediaType:q.string().describe("IANA media type")})]))}),q.object({type:q.literal("execution-denied"),reason:q.string().optional()}),q.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),Bf0=q.object({type:q.literal("tool-result"),toolCallId:q.string().describe("ID of the tool call that this result is associated with"),toolName:q.string().describe("Name of the tool that generated this result"),output:zE4.describe("Result of the tool call"),result:q.unknown().describe("Unknown result of the tool call"),providerOptions:l3}),DE4=q.object({type:q.literal("tool-result"),toolCallId:q.string().describe("ID of the tool call that this result is associated with"),toolName:q.string().describe("Name of the tool that generated this result"),result:q.any().describe("Result of the tool call (JSON-serializable)"),isError:q.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:q.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),OE4=q.union([q.object({type:q.literal("source"),sourceType:q.literal("url"),id:q.string().describe("The ID of the source"),url:q.string().describe("The URL of the source"),title:q.string().optional().describe("The title of the source"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),q.object({type:q.literal("source"),sourceType:q.literal("document"),id:q.string().describe("The ID of the source"),mediaType:q.string().describe("IANA media type of the document (e.g., application/pdf)"),title:q.string().describe("The title of the document"),filename:q.string().optional().describe("Optional filename of the document"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")})]),LE4=q.object({role:q.literal("system"),content:q.string().describe("System message content"),providerOptions:l3}),NE4=q.object({role:q.literal("user"),content:q.array(q.union([Vf0,qf0])).describe("User message content parts (text or file)"),providerOptions:l3}),ME4=q.object({role:q.literal("assistant"),content:q.array(q.union([Vf0,qf0,VE4,BE4,Bf0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:l3}),wE4=q.object({role:q.literal("tool"),content:q.array(Bf0).describe("Tool message content (tool results)"),providerOptions:l3}),AE4=q.union([LE4,NE4,ME4,wE4]),PE4=q.array(AE4).describe("A list of messages forming the prompt"),EE4=q.object({prompt:PE4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:q.number().optional().describe("Maximum number of tokens to generate"),temperature:q.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:q.number().optional().describe("Nucleus sampling parameter"),topK:q.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:q.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:q.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:q.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:q.array(q.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:q.union([q.object({type:q.literal("text")}),q.object({type:q.literal("json"),schema:q.any().optional().describe("JSON schema that the generated output should conform to"),name:q.string().optional().describe("Name of output that should be generated"),description:q.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:q.array(q.any()).optional().describe("The tools that are available for the model"),toolChoice:q.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:q.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:q.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:q.any().optional().describe("Additional provider-specific options")}),TE4=q.object({content:q.array(q.union([HE4,$E4,qE4,UE4,DE4,OE4])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:q.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:q.looseObject({inputTokens:q.number().optional(),outputTokens:q.number().optional(),totalTokens:q.number().optional(),reasoningTokens:q.number().optional()}).describe("Usage information for the language model call"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata"),request:q.object({body:q.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:q.object({id:q.string().optional().describe("ID for the generated response"),timestamp:q.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:q.string().optional().describe("The ID of the response model that was used"),headers:q.record(q.string(),q.string()).optional().describe("Response headers"),body:q.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:q.array(q.any()).describe("Warnings for the call, e.g. unsupported settings")}),mi8=q.object({stream:q.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:q.object({body:q.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:q.object({headers:q.record(q.string(),q.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),CE4=q.object({supportedUrls:q.record(q.string(),q.array(q.string())).describe("Supported URL patterns by media type for the provider")}),li8=q.object({modelId:q.string().describe("The ID of the model"),logo:q.string().nullable(),description:q.string().nullable(),capabilities:q.array(q.string()),limits:q.object({contextWindow:q.number(),maxOutputTokens:q.number()}).nullable(),costs:q.object({input:q.number(),output:q.number()}).nullable(),provider:q.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),$f0=q.object({modelId:q.string().describe("The ID of the model"),callOptions:EE4}),RE4=yZ.extend({logo:q.string().nullable(),description:q.string().nullable(),capabilities:q.array(q.string()),limits:q.object({contextWindow:q.number(),maxOutputTokens:q.number()}).nullable(),costs:q.object({input:q.number(),output:q.number()}).nullable(),provider:q.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),IE4=fZ("llm",RE4,{readOnly:!0}),$$1=[{name:"LLM_METADATA",inputSchema:q.object({modelId:q.string().describe("The ID of the model")}),outputSchema:CE4},{name:"LLM_DO_STREAM",inputSchema:$f0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:$f0,outputSchema:TE4},...IE4],di8=vZ($$1)});function gN(){return!1}function zp(Y,Q){return Y===h9.DEV_ASSETS(Q)}function uN(Y,Q){let X=zt(Q,Y),J=new Date().toISOString();return{id:X.id??h9.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:jE4,bindings:["OBJECT_STORAGE"],status:"active"}}var jE4;var Dp=S(()=>{Yl();zY();v1();jE4=uC.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:q.toJSONSchema(Y.inputSchema),outputSchema:q.toJSONSchema(Y.outputSchema)}))});function _E4(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 w$(Y){return typeof Y==="string"||typeof Y==="number"}function Op(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every((F)=>Op(Y,F));case"or":return H.some((F)=>Op(Y,F));case"not":return!H.every((F)=>Op(Y,F));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=V$1(Y,K);switch(J){case"eq":return W===G;case"gt":return w$(W)&&w$(G)&&W>G;case"gte":return w$(W)&&w$(G)&&W>=G;case"lt":return w$(W)&&w$(G)&&W<G;case"lte":return w$(W)&&w$(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=_E4(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 V$1(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 vE4(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=V$1(X,K),Z=V$1(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 SE4,kE4,yE4,q$1;var zf0=S(()=>{Xl();Ff0();gX();Uf0();Yl();zY();v1();k0();Dp();L3();SE4={LLM:$$1,ASSISTANTS:Hf0,OBJECT_STORAGE:uC};kE4=dG.extend({binding:q.union([q.object({}).passthrough(),q.string()]).optional(),include_virtual:q.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),yE4=M3(P5),q$1=k1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",annotations:{title:"List Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:kE4,outputSchema:yE4,handler:async(Y,Q)=>{await Q.access.check();let X=B0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=SE4[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?om(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(gN()){let B=AG(),U=h9.DEV_ASSETS(X.id);if(!K.some((z)=>z.id===U)){let z=uN(X.id,B);K.unshift(z)}}let W=G?await Promise.all(K.map(async(B)=>{if(!B.tools||B.tools.length===0)return null;return G.isImplementedBy(B.tools.map((z)=>({name:z.name,inputSchema:z.inputSchema,outputSchema:z.outputSchema})))?B:null})).then((B)=>B.filter((U)=>U!==null)):K;if(Y.where)W=W.filter((B)=>Op(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=vE4(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 fE4,B$1;var Df0=S(()=>{gX();k0();Dp();L3();fE4=TC(P5),B$1=k1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:EC,outputSchema:fE4,handler:async(Y,Q)=>{let X=B0(Q);if(await Q.access.check(),gN()&&zp(Y.id,X.id))return{item:uN(X.id,AG())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var Lp=(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 Of0(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 bE4(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function hE4(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function U$1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=bE4(J);if(!G)continue;let[K,W]=G,Z=Lp(K,Y),H=hE4(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function Lf0(Y,Q){let X=U$1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var z$1=()=>{};import{randomBytes as xE4}from"crypto";function gE4(){if(YI)return YI;let Y=process.env.MESH_JWT_SECRET??t9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)YI=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),YI=new Uint8Array(xE4(32));return YI}async function Nf0(Y,Q="5m"){let X=gE4();return await new DX(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}var YI=null;var Mf0=S(()=>{OX();Np()});async function wf0(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 QI{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=Y$("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 D$1=S(()=>{DC()});async function XI(Y,Q,X){let J=Y.id,G=U$1(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 Nf0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((U)=>[U,null]).catch((U)=>[null,U]):[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 QI(Q.db,Q.vault),B=await V.get(J);if(B){let U=!!B.refreshToken&&!!B.tokenEndpoint;if(V.isExpired(B,U?300000:0))if(U){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let O=await wf0(B);if(O.success&&O.accessToken)await V.upsert({connectionId:J,accessToken:O.accessToken,refreshToken:O.refreshToken??B.refreshToken,scope:O.scope??B.scope,expiresAt:O.expiresIn?new Date(Date.now()+O.expiresIn*1000):null,clientId:B.clientId,clientSecret:B.clientSecret,tokenEndpoint:B.tokenEndpoint}),$=O.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${O.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else $=B.accessToken}if(!$&&Y.connection_token)$=Y.connection_token;if($)F.Authorization=`Bearer ${$}`;if(W)F["x-mesh-token"]=W;return F}var O$1=S(()=>{z$1();Mf0();D$1()});function Af0(){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 sX({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 Pf0=S(()=>{Pz()});function Ef0(Y){let Q=new wC({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 Tf0=S(()=>{lZ1()});class JI{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 GI(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var Cf0="mcp.mesh";var Rf0,L$1,WI;var N$1=S(()=>{Rf0=class Rf0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};L$1=class L$1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};WI=class WI{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 Rf0("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 L$1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new L$1(`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[Cf0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var uE4="mcp.mesh",mN;var If0=S(()=>{N$1();mN=class mN extends JI{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 WI(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[uE4]?.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 Sf0(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 w$1(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 A$1(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function P$1(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 mE4(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}}function lE4(Y){if(!Y)return;let Q=Y.trimEnd().split(`
|
|
1470
|
+
${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 $=bN(F),V=Y.newString(`Promise resolution error: ${$}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let F=bN(H),$=Y.newString(`Promise rejection: ${F}`);Z.reject($),$.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return hN(Y,W)}catch(K){let W=bN(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 ty0=()=>{};function Yf0(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 ey0(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){Yf0(Y);let K=await Promise.race([G,s24(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 sR({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=qI(W,await oy0({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=qI(W,J.newContext({interruptAfterMs:X}),0);const K=qI(W,ny0(G),0);try{let $=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult($),B=hN(G,Y);G.setProp(G.global,"tools",B);let U=G.runtime.hasPendingJob()?G.unwrapResult(await ey0(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),O=G.typeof(z);if(O!=="function")return z.dispose(),U.dispose(),B.dispose(),{error:`Code must export default a function (tools). Got ${O}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let M=G.callFunction(z,G.undefined,B);B.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(M),P=await ey0(G,w,X);w.dispose();let j=G.unwrapResult(P);if(G.runtime.hasPendingJob())Yf0(G);let C=G.dump(j);return j.dispose(),{returnValue:C,consoleLogs:K.logs}}catch($){return console.log($),{error:bN($),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{lV1(W,H,F)}}var s24=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var Qf0=S(()=>{sy0();ty0()});var W$1=S(()=>{Qf0()});async function t24(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 Xf0(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 e24(Y,Q){let X=new Map;for(let B of Y)X.set(B.connection.id,B);let J=Y.map((B)=>B.connection),G=new Map,K=await Promise.allSettled(J.map(async(B)=>{try{let U=await Q.createMCPProxy(B);return{connection:B,proxy:U}}catch(U){return console.warn(`[code-execution] Failed to create proxy for connection ${B.id}:`,U),null}}));for(let B of K)if(B.status==="fulfilled"&&B.value)G.set(B.value.connection.id,B.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([B,U])=>{try{let O=(await U.proxy.listTools()).tools,M=X.get(B);if(M?.selectedTools&&M.selectedTools.length>0){let w=new Set(M.selectedTools);O=O.filter((P)=>w.has(P.name))}return{connectionId:B,connectionTitle:U.connection.title,tools:O}}catch(z){return console.error(`[code-execution] Failed to list tools for connection ${B}:`,z),null}})),Z=new Set,H=[],F=new Map;for(let B of W){if(B.status!=="fulfilled"||!B.value)continue;let{connectionId:U,connectionTitle:z,tools:O}=B.value;for(let M of O){if(Z.has(M.name))continue;Z.add(M.name),H.push({...M,_meta:{...M._meta,connectionId:U,connectionTitle:z}}),F.set(M.name,U)}}let $=async(B,U)=>{let z=F.get(B);if(!z)return{content:[{type:"text",text:`Tool not found: ${B}`}],isError:!0};let O=G.get(z);if(!O)return{content:[{type:"text",text:`Connection not found for tool: ${B}`}],isError:!0};return await O.proxy.callTool({name:B,arguments:U})},V=[];for(let[,B]of G)V.push(B.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:$}}async function xN(Y){let Q=B0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await t24(J,Y);else X=await Xf0(Q.id,Y)}else X=await Xf0(Q.id,Y);return e24(X,Y)}function YE4(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function QE4(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 qp(Y,Q,X){let J=YE4(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:QE4(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Bp(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 Up(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 sR({code:Y,tools:J,timeoutMs:X})}function tR(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function M$(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function m3(Y){let Q=new Set(XE4);return Y.filter((X)=>!Q.has(X.name))}var XE4;var WU=S(()=>{W$1();XE4=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var Z$1;var Jf0=S(()=>{k0();oR();WU();Z$1=k1({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.",annotations:{title:"Search Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:uy0,outputSchema:my0,handler:async(Y,Q)=>{o1(Q),B0(Q),await Q.access.check();let X=await xN(Q),J=qp(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 K$1;var Gf0=S(()=>{k0();oR();WU();K$1=k1({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.",annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:ly0,outputSchema:dy0,handler:async(Y,Q)=>{o1(Q),B0(Q),await Q.access.check();let X=await xN(Q);return Bp(Y.tools,X.tools)}})});var H$1;var Wf0=S(()=>{k0();oR();WU();H$1=k1({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.',annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:py0,outputSchema:cy0,handler:async(Y,Q)=>{o1(Q),B0(Q),await Q.access.check();let X=await xN(Q);return await Up(Y.code,X,Y.timeoutMs)}})});var Zf0=S(()=>{Jf0();Gf0();Wf0();oR()});var GE4,WE4,F$1;var Kf0=S(()=>{zY();v1();k0();pm();L3();GE4=q.object({data:CA.describe("Data for the new connection (id is auto-generated if not provided)")}),WE4=q.object({item:P5.describe("The created connection entity")}),F$1=k1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:GE4,outputSchema:WE4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=D9(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 F=LV(G.connection_url);if(!F)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let $=await Q.storage.virtualMcps.findById(F);if(!$)throw Error(`Virtual MCP not found: ${F}`);if($.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=NV(F)}let K=await iL({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?.tools?.length?K.tools:null,Z=K?.scopes?.length?K.scopes:null,H=await Q.storage.connections.create({...G,tools:W,configuration_scopes:Z});return await Q.eventBus.publish(X.id,h9.SELF(X.id),{type:"connection.created",data:H}),{item:H}}})});var ZE4,KE4,Hf0;var Ff0=S(()=>{v1();gX();ZE4=yZ.extend({avatar:q.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:q.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:q.string().describe("Virtual MCP ID to use for this assistant"),model:q.object({id:q.string().describe("Model ID"),connectionId:q.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),KE4=fZ("assistant",ZE4),Hf0=[...KE4]});var eR,l3,Vf0,HE4,FE4,qf0,$E4,VE4,qE4,BE4,UE4,zE4,Bf0,DE4,OE4,LE4,NE4,ME4,wE4,AE4,PE4,EE4,TE4,mi8,CE4,li8,$f0,RE4,IE4,$$1,di8;var Uf0=S(()=>{v1();_B();gX();eR=q.lazy(()=>q.union([q.null(),q.string(),q.number(),q.boolean(),q.record(q.string(),eR),q.array(eR)])),l3=q.record(q.string(),q.record(q.string(),eR)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),Vf0=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerOptions:l3}),HE4=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),FE4=q.string().describe("File data as URL string"),qf0=q.object({type:q.literal("file"),filename:q.string().optional().describe("Optional filename of the file"),data:FE4,mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:l3}),$E4=q.object({type:q.literal("file"),mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:q.string().describe("Generated file data as base64 encoded string")}),VE4=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerOptions:l3}),qE4=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),BE4=q.object({type:q.literal("tool-call"),toolCallId:q.string().describe("ID of the tool call, used to match with tool result"),toolName:q.string().describe("Name of the tool being called"),input:q.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:q.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:l3}),UE4=q.object({type:q.literal("tool-call"),toolCallId:q.string().describe("ID of the tool call"),toolName:q.string().describe("Name of the tool being called"),input:q.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:q.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),zE4=q.union([q.object({type:q.literal("text"),value:q.string()}),q.object({type:q.literal("json"),value:eR}),q.object({type:q.literal("error-text"),value:q.string()}),q.object({type:q.literal("error-json"),value:eR}),q.object({type:q.literal("content"),value:q.array(q.union([q.object({type:q.literal("text"),text:q.string().describe("Text content")}),q.object({type:q.literal("media"),data:q.string().describe("Base-64 encoded media data"),mediaType:q.string().describe("IANA media type")})]))}),q.object({type:q.literal("execution-denied"),reason:q.string().optional()}),q.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),Bf0=q.object({type:q.literal("tool-result"),toolCallId:q.string().describe("ID of the tool call that this result is associated with"),toolName:q.string().describe("Name of the tool that generated this result"),output:zE4.describe("Result of the tool call"),result:q.unknown().describe("Unknown result of the tool call"),providerOptions:l3}),DE4=q.object({type:q.literal("tool-result"),toolCallId:q.string().describe("ID of the tool call that this result is associated with"),toolName:q.string().describe("Name of the tool that generated this result"),result:q.any().describe("Result of the tool call (JSON-serializable)"),isError:q.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:q.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),OE4=q.union([q.object({type:q.literal("source"),sourceType:q.literal("url"),id:q.string().describe("The ID of the source"),url:q.string().describe("The URL of the source"),title:q.string().optional().describe("The title of the source"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),q.object({type:q.literal("source"),sourceType:q.literal("document"),id:q.string().describe("The ID of the source"),mediaType:q.string().describe("IANA media type of the document (e.g., application/pdf)"),title:q.string().describe("The title of the document"),filename:q.string().optional().describe("Optional filename of the document"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")})]),LE4=q.object({role:q.literal("system"),content:q.string().describe("System message content"),providerOptions:l3}),NE4=q.object({role:q.literal("user"),content:q.array(q.union([Vf0,qf0])).describe("User message content parts (text or file)"),providerOptions:l3}),ME4=q.object({role:q.literal("assistant"),content:q.array(q.union([Vf0,qf0,VE4,BE4,Bf0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:l3}),wE4=q.object({role:q.literal("tool"),content:q.array(Bf0).describe("Tool message content (tool results)"),providerOptions:l3}),AE4=q.union([LE4,NE4,ME4,wE4]),PE4=q.array(AE4).describe("A list of messages forming the prompt"),EE4=q.object({prompt:PE4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:q.number().optional().describe("Maximum number of tokens to generate"),temperature:q.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:q.number().optional().describe("Nucleus sampling parameter"),topK:q.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:q.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:q.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:q.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:q.array(q.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:q.union([q.object({type:q.literal("text")}),q.object({type:q.literal("json"),schema:q.any().optional().describe("JSON schema that the generated output should conform to"),name:q.string().optional().describe("Name of output that should be generated"),description:q.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:q.array(q.any()).optional().describe("The tools that are available for the model"),toolChoice:q.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:q.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:q.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:q.any().optional().describe("Additional provider-specific options")}),TE4=q.object({content:q.array(q.union([HE4,$E4,qE4,UE4,DE4,OE4])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:q.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:q.looseObject({inputTokens:q.number().optional(),outputTokens:q.number().optional(),totalTokens:q.number().optional(),reasoningTokens:q.number().optional()}).describe("Usage information for the language model call"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata"),request:q.object({body:q.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:q.object({id:q.string().optional().describe("ID for the generated response"),timestamp:q.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:q.string().optional().describe("The ID of the response model that was used"),headers:q.record(q.string(),q.string()).optional().describe("Response headers"),body:q.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:q.array(q.any()).describe("Warnings for the call, e.g. unsupported settings")}),mi8=q.object({stream:q.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:q.object({body:q.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:q.object({headers:q.record(q.string(),q.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),CE4=q.object({supportedUrls:q.record(q.string(),q.array(q.string())).describe("Supported URL patterns by media type for the provider")}),li8=q.object({modelId:q.string().describe("The ID of the model"),logo:q.string().nullable(),description:q.string().nullable(),capabilities:q.array(q.string()),limits:q.object({contextWindow:q.number(),maxOutputTokens:q.number()}).nullable(),costs:q.object({input:q.number(),output:q.number()}).nullable(),provider:q.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),$f0=q.object({modelId:q.string().describe("The ID of the model"),callOptions:EE4}),RE4=yZ.extend({logo:q.string().nullable(),description:q.string().nullable(),capabilities:q.array(q.string()),limits:q.object({contextWindow:q.number(),maxOutputTokens:q.number()}).nullable(),costs:q.object({input:q.number(),output:q.number()}).nullable(),provider:q.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),IE4=fZ("llm",RE4,{readOnly:!0}),$$1=[{name:"LLM_METADATA",inputSchema:q.object({modelId:q.string().describe("The ID of the model")}),outputSchema:CE4},{name:"LLM_DO_STREAM",inputSchema:$f0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:$f0,outputSchema:TE4},...IE4],di8=vZ($$1)});function gN(){return!1}function zp(Y,Q){return Y===h9.DEV_ASSETS(Q)}function uN(Y,Q){let X=zt(Q,Y),J=new Date().toISOString();return{id:X.id??h9.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:jE4,bindings:["OBJECT_STORAGE"],status:"active"}}var jE4;var Dp=S(()=>{Yl();zY();v1();jE4=uC.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:q.toJSONSchema(Y.inputSchema),outputSchema:q.toJSONSchema(Y.outputSchema)}))});function _E4(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 w$(Y){return typeof Y==="string"||typeof Y==="number"}function Op(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every((F)=>Op(Y,F));case"or":return H.some((F)=>Op(Y,F));case"not":return!H.every((F)=>Op(Y,F));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=V$1(Y,K);switch(J){case"eq":return W===G;case"gt":return w$(W)&&w$(G)&&W>G;case"gte":return w$(W)&&w$(G)&&W>=G;case"lt":return w$(W)&&w$(G)&&W<G;case"lte":return w$(W)&&w$(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=_E4(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 V$1(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 vE4(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=V$1(X,K),Z=V$1(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 SE4,kE4,yE4,q$1;var zf0=S(()=>{Xl();Ff0();gX();Uf0();Yl();zY();v1();k0();Dp();L3();SE4={LLM:$$1,ASSISTANTS:Hf0,OBJECT_STORAGE:uC};kE4=dG.extend({binding:q.union([q.object({}).passthrough(),q.string()]).optional(),include_virtual:q.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),yE4=M3(P5),q$1=k1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",annotations:{title:"List Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:kE4,outputSchema:yE4,handler:async(Y,Q)=>{await Q.access.check();let X=B0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=SE4[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?om(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(gN()){let B=AG(),U=h9.DEV_ASSETS(X.id);if(!K.some((z)=>z.id===U)){let z=uN(X.id,B);K.unshift(z)}}let W=G?await Promise.all(K.map(async(B)=>{if(!B.tools||B.tools.length===0)return null;return G.isImplementedBy(B.tools.map((z)=>({name:z.name,inputSchema:z.inputSchema,outputSchema:z.outputSchema})))?B:null})).then((B)=>B.filter((U)=>U!==null)):K;if(Y.where)W=W.filter((B)=>Op(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=vE4(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 fE4,B$1;var Df0=S(()=>{gX();k0();Dp();L3();fE4=TC(P5),B$1=k1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:EC,outputSchema:fE4,handler:async(Y,Q)=>{let X=B0(Q);if(await Q.access.check(),gN()&&zp(Y.id,X.id))return{item:uN(X.id,AG())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var Lp=(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 Of0(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 bE4(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function hE4(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function U$1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=bE4(J);if(!G)continue;let[K,W]=G,Z=Lp(K,Y),H=hE4(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function Lf0(Y,Q){let X=U$1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var z$1=()=>{};import{randomBytes as xE4}from"crypto";function gE4(){if(YI)return YI;let Y=process.env.MESH_JWT_SECRET??t9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)YI=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),YI=new Uint8Array(xE4(32));return YI}async function Nf0(Y,Q="5m"){let X=gE4();return await new DX(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}var YI=null;var Mf0=S(()=>{OX();Np()});async function wf0(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 QI{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=Y$("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 D$1=S(()=>{DC()});async function XI(Y,Q,X){let J=Y.id,G=U$1(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 Nf0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((U)=>[U,null]).catch((U)=>[null,U]):[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 QI(Q.db,Q.vault),B=await V.get(J);if(B){let U=!!B.refreshToken&&!!B.tokenEndpoint;if(V.isExpired(B,U?300000:0))if(U){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let O=await wf0(B);if(O.success&&O.accessToken)await V.upsert({connectionId:J,accessToken:O.accessToken,refreshToken:O.refreshToken??B.refreshToken,scope:O.scope??B.scope,expiresAt:O.expiresIn?new Date(Date.now()+O.expiresIn*1000):null,clientId:B.clientId,clientSecret:B.clientSecret,tokenEndpoint:B.tokenEndpoint}),$=O.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${O.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else $=B.accessToken}if(!$&&Y.connection_token)$=Y.connection_token;if($)F.Authorization=`Bearer ${$}`;if(W)F["x-mesh-token"]=W;return F}var O$1=S(()=>{z$1();Mf0();D$1()});function Af0(){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 sX({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 Pf0=S(()=>{Pz()});function Ef0(Y){let Q=new wC({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 Tf0=S(()=>{lZ1()});class JI{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 GI(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var Cf0="mcp.mesh";var Rf0,L$1,WI;var N$1=S(()=>{Rf0=class Rf0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};L$1=class L$1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};WI=class WI{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 Rf0("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 L$1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new L$1(`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[Cf0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var uE4="mcp.mesh",mN;var If0=S(()=>{N$1();mN=class mN extends JI{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 WI(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[uE4]?.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 Sf0(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 w$1(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 A$1(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function P$1(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 mE4(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}}function lE4(Y){if(!Y)return;let Q=Y.trimEnd().split(`
|
|
1471
1471
|
`);for(let X=Q.length-1;X>=0&&X>=Q.length-5;X--){let J=Q[X]?.trim();if(!J)continue;try{let G=JSON.parse(J);if(G&&typeof G==="object"&&G.type==="finish"){let K={};if(G.usage)K.usage=G.usage;if(G.providerMetadata)K.providerMetadata=G.providerMetadata;if(G.finishReason)K.finishReason=G.finishReason;return Object.keys(K).length>0?K:void 0}}catch{}}return}async function M$1(Y){let{ctx:Q,enabled:X}=Y,J=Y.organizationId??Q.organization?.id;if(!X||!J)return;if(OV(Y.connectionId))return;let G=w$1(Y.request.params.arguments),K=A$1(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 _f0(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:B,truncated:U}=await mE4(V,jf0),z=Date.now()-H,O=V.headers.get("content-type")??"",M=B;if(O.includes("application/json"))try{M=B.length?JSON.parse(B):null}catch{M=B}let w=F.status>=400,P=w&&M&&typeof M==="object"&&"error"in M?M.error:void 0,j=typeof P==="string"&&P?P:w&&typeof M==="string"&&M.trim()?M.slice(0,500):w?`HTTP ${F.status} ${F.statusText}`.trim():U?`Response body truncated to ${jf0} bytes`:void 0,C=P$1(M),E=lE4(B);if(E)Object.assign(C,E);await M$1({ctx:Q,enabled:X,organizationId:$,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:C,isError:w,errorMessage:j,durationMs:z})}catch(B){let U=Date.now()-H;await M$1({ctx:Q,enabled:X,organizationId:$,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${B.message}`,durationMs:U})}})()}return F}catch(F){let $=F,V=Date.now()-H;throw await M$1({ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:$.message,durationMs:V}),F}}}var jf0=262144;var E$1=S(()=>{zY()});var lN;var vf0=S(()=>{gh();E$1();lN=class lN extends JI{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,B=$?{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:B,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(!xh().enabled)return;let V=Q.organization?.id;if(!V)return;let B=Sf0(Z),U=P$1(Z),z=w$1(W),O=A$1(Q.metadata.properties,z);try{await Q.storage.monitoring.log({organizationId:V,connectionId:X,connectionTitle:J,toolName:K,input:W??{},output:U,isError:F,errorMessage:B,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:O})}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 kf0=S(()=>{If0();vf0()});async function yf0(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(!NW(K))throw Error("STDIO connection missing parameters");let W=Ef0({id:J,name:Y.title,command:K.command,args:K.args,env:K.envVars,cwd:K.cwd});return W=GI(W,(Z)=>new mN(Z,{ctx:Q,connection:Y,superUser:X}),(Z)=>new lN(Z,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),dE4(W,J)}case"HTTP":case"Websocket":{if(!Y.connection_url)throw Error(`${Y.connection_type} connection missing URL`);let K=await XI(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new wH(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=GI(Z,(H)=>new mN(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new lN(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 XI(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new IB(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=GI(Z,(H)=>new mN(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new lN(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}var dE4;var ff0=S(()=>{L3();mm();TA();O$1();Pf0();Tf0();kf0();dE4=Af0()});function xf0(Y){if(!Y?._meta)return!1;return typeof Y._meta["mcp.mesh"]?.["tool.fn"]==="string"}function gf0(Y){return Y._meta["mcp.mesh"]["tool.fn"]}var T$1,Zr8,pZ,bf0,hf0;var A$=S(()=>{v1();T$1=q.object({title:q.string().optional(),readOnlyHint:q.boolean().optional(),destructiveHint:q.boolean().optional(),idempotentHint:q.boolean().optional(),openWorldHint:q.boolean().optional()}),Zr8=q.object({"tool.fn":q.string().describe("JavaScript ES module code that exports a default async function")}),pZ=q.object({id:q.string().describe("Unique identifier for the virtual tool (auto-generated)"),name:q.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:q.string().optional().describe("Human-readable description of what the tool does"),inputSchema:q.record(q.string(),q.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:q.record(q.string(),q.unknown()).optional().describe("JSON Schema defining the tool's output (optional)"),annotations:T$1.optional().describe("MCP tool annotations"),code:q.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:q.array(q.string()).describe("Connection IDs that this tool depends on (specified by the creator)"),created_at:q.string().describe("When the virtual tool was created"),updated_at:q.string().describe("When the virtual tool was last updated")}),bf0=q.object({name:q.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:q.string().optional().describe("Human-readable description"),inputSchema:q.record(q.string(),q.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:q.record(q.string(),q.unknown()).optional().describe("JSON Schema for output"),annotations:T$1.optional().describe("MCP tool annotations"),code:q.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:q.array(q.string()).optional().describe("Connection IDs that this tool depends on. Creates indirect aggregations to prevent deletion of referenced connections.")}),hf0=q.object({name:q.string().min(1).max(255).optional().describe("New tool name"),description:q.string().nullable().optional().describe("New description (null to clear)"),inputSchema:q.record(q.string(),q.unknown()).optional().describe("New input schema"),outputSchema:q.record(q.string(),q.unknown()).nullable().optional().describe("New output schema (null to clear)"),annotations:T$1.nullable().optional().describe("New annotations (null to clear)"),code:q.string().optional().describe("New JavaScript code"),connection_dependencies:q.array(q.string()).optional().describe("Connection IDs that this tool depends on. Replaces existing dependencies if provided.")})});function Mp(Y){return(Q)=>{if(Q instanceof w0&&Q.code===C0.MethodNotFound)return Y;throw Q}}var C$1=S(()=>{jY()});class uf0{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 wp(Y){return new uf0(Y)}function pE4(Y,Q,X){let J=new sX({name:`lazy-${Y.id}`,version:"1.0.0"},{capabilities:{}}),G=null;function K(){if(!G)G=pN(Y,Q,X).then((H)=>{if(Y.connection_type==="HTTP"||Y.connection_type==="SSE"||Y.connection_type==="Websocket")return I$1(H,Y.id,Y,Q,{superUser:X});return H});return G}if(Y.connection_type!=="VIRTUAL"&&Array.isArray(Y.tools)&&Y.tools.length>0)J.listTools=async()=>({tools:Y.tools.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema,outputSchema:H.outputSchema,annotations:H.annotations,_meta:H._meta}))});else J.listTools=async()=>{return(await K()).listTools()};J.callTool=async(H,F,$)=>{return(await K()).callTool(H,F,$)},J.listResources=async()=>{return(await K()).listResources()},J.listPrompts=async()=>{return(await K()).listPrompts()},J.getPrompt=async(H,F)=>{return(await K()).getPrompt(H,F)},J.readResource=async(H,F)=>{return(await K()).readResource(H,F)},J.callStreamableTool=async(H,F)=>{let $=await K();if("callStreamableTool"in $&&typeof $.callStreamableTool==="function")return $.callStreamableTool(H,F);let V=await $.callTool({name:H,arguments:F});return new Response(JSON.stringify(V),{headers:{"Content-Type":"application/json"}})};let Z=J.close.bind(J);return J.close=async()=>{if(G){let H=await G.catch(()=>null);if(H)await H.close().catch(()=>{})}await Z()},J}function cE4(Y,Q,X=!1){let J=new Map;for(let G of Y)J.set(G.id,pE4(G,Q,X));return J}async function mf0(Y){let Q=[];for(let[,X]of Y)Q.push(X.close().catch(()=>{}));await Promise.all(Q)}var dN;var R$1=S(()=>{j$1();C$1();Pz();W$1();A$();dN=class dN extends sX{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=cE4(this.options.connections,this.ctx,this.options.superUser),this._cachedTools=wp(()=>this.loadToolsCache()),this._cachedResources=wp(()=>this.loadCache("resources")),this._cachedPrompts=wp(()=>this.loadCache("prompts"))}async loadToolsCache(){let Y=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 B=V.name;if(J.has(B))continue;let U={...V,_meta:{connectionId:Z,connectionTitle:$,...V?._meta}};X.push(U),J.set(B,Z)}}return{data:X,mappings:J,virtualTools:G}}async loadCache(Y){let Q=this._clients,X=await Promise.all(Array.from(Q.entries()).map(async([K,W])=>{try{let Z=Y==="resources"?await W.listResources().catch(Mp({resources:[]})).then(($)=>$.resources):await W.listPrompts().catch(Mp({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 B={...$,_meta:{connectionId:W,connectionTitle:F,...$?._meta}};J.push(B),G.set(V,W)}}return{data:J,mappings:G}}async listTools(){return{tools:(await this._cachedTools).data}}async callTool(Y){let Q=await this._cachedTools,X=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=gf0(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 B=V.content;if(B?.[0]?.type==="text"&&B[0].text)try{return JSON.parse(B[0].text)}catch{return B[0].text}return V}}try{let H=`
|
|
1472
1472
|
const __virtualToolFn = ${K.replace(/^\s*export\s+default\s+/,"").trim()};
|
|
1473
1473
|
export default async (tools) => {
|
|
@@ -1476,7 +1476,7 @@ ${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toStr
|
|
|
1476
1476
|
};
|
|
1477
1477
|
`,F=await sR({code:H,tools:W,timeoutMs:30000});if(F.error)return{content:[{type:"text",text:`Virtual tool error: ${F.error}`}],isError:!0};return{content:[{type:"text",text:JSON.stringify(F.returnValue??null)}]}}catch(Z){return{content:[{type:"text",text:`Virtual tool execution failed: ${Z instanceof Error?Z.message:String(Z)}`}],isError:!0}}}async listResources(){return{resources:(await this._cachedResources).data}}async readResource(Y){let Q=await this._cachedResources,X=this._clients,J=Q.mappings.get(Y.uri);if(!J)throw Error(`Resource not found: ${Y.uri}`);let G=X.get(J);if(!G)throw Error(`Connection not found for resource: ${Y.uri}`);return await G.readResource(Y)}async listPrompts(){return{prompts:(await this._cachedPrompts).data}}async getPrompt(Y){let Q=await this._cachedPrompts,X=this._clients,J=Q.mappings.get(Y.name);if(!J)throw Error(`Prompt not found: ${Y.name}`);let G=X.get(J);if(!G)throw Error(`Connection not found for prompt: ${Y.name}`);return await G.getPrompt(Y)}async callStreamableTool(Y,Q){let X=await this._cachedTools,J=this._clients,G=X.mappings.get(Y);if(G){let W=J.get(G);if(W&&"callStreamableTool"in W)return W.callStreamableTool(Y,Q)}let K=await this.callTool({name:Y,arguments:Q});return new Response(JSON.stringify(K),{headers:{"Content-Type":"application/json"}})}async[Symbol.asyncDispose](){await mf0(this._clients)}async close(){await mf0(this._clients),await super.close()}getInstructions(){return this.options.virtualMcp.metadata?.instructions??void 0}}});var lf0,nE4,df0,iE4,ZI;var S$1=S(()=>{v1();WU();R$1();lf0=q.object({query:q.string().min(1).describe("Search query to find tools by name or description"),limit:q.number().default(10).describe("Maximum number of results to return")}),nE4=q.toJSONSchema(lf0),df0=q.object({tools:q.array(q.string()).min(1).describe("Array of tool names to get detailed schemas for")}),iE4=q.toJSONSchema(df0);ZI=class ZI extends dN{constructor(Y,Q){super(Y,Q)}getSearchTool(Y){return{name:"GATEWAY_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 GATEWAY_DESCRIBE_TOOLS for detailed schemas. Total tools: ${Y}.`,inputSchema:nE4,annotations:{title:"Search Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}}}getDescribeTool(){return{name:"GATEWAY_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after GATEWAY_SEARCH_TOOLS to get full input/output schemas.",inputSchema:iE4,annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}}}async handleSearch(Y){let Q=lf0.safeParse(Y);if(!Q.success)return M$({error:Q.error.flatten()});let X=await this._cachedTools,J=m3(X.data),G=qp(Q.data.query,J,Q.data.limit);return tR({query:Q.data.query,results:G.map((K)=>({name:K.name,description:K.description,connection:K._meta.connectionTitle})),totalAvailable:J.length})}async handleDescribe(Y){let Q=df0.safeParse(Y);if(!Q.success)return M$({error:Q.error.flatten()});let X=await this._cachedTools,J=m3(X.data),G=Bp(Q.data.tools,J);return tR({tools:G.tools,notFound:G.notFound})}async listTools(){let Y=await this._cachedTools,Q=m3(Y.data);return{tools:[this.getSearchTool(Q.length),this.getDescribeTool()]}}async callTool(Y){if(Y.name==="GATEWAY_SEARCH_TOOLS")return this.handleSearch(Y.arguments??{});if(Y.name==="GATEWAY_DESCRIBE_TOOLS")return this.handleDescribe(Y.arguments??{});return{content:[{type:"text",text:`Unknown tool: ${Y.name}. Available: GATEWAY_SEARCH_TOOLS, GATEWAY_DESCRIBE_TOOLS`}],isError:!0}}async routeToolCall(Y){return dN.prototype.callTool.call(this,Y)}}});var pf0,aE4,_$1;var cf0=S(()=>{v1();WU();S$1();pf0=q.object({code:q.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:q.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")}),aE4=q.toJSONSchema(pf0);_$1=class _$1 extends ZI{constructor(Y,Q){super(Y,Q)}getRunCodeTool(){return{name:"GATEWAY_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 GATEWAY_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:aE4,annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}}}async handleRunCode(Y){let Q=pf0.safeParse(Y);if(!Q.success)return M$({error:Q.error.flatten()});let X=await this._cachedTools,G={tools:m3(X.data),callTool:async(W,Z)=>{return this.routeToolCall({name:W,arguments:Z})}},K=await Up(Q.data.code,G,Q.data.timeoutMs);if(K.error)return M$(K);return tR(K)}async listTools(){return{tools:[...(await super.listTools()).tools,this.getRunCodeTool()]}}async callTool(Y){if(Y.name==="GATEWAY_RUN_CODE")return this.handleRunCode(Y.arguments??{});return super.callTool(Y)}}});function if0(Y){let Q=Y.slice().sort().join(","),X=nf0.get(Q);if(!X){let J=q.object({name:(Y.length>0?q.enum(Y):q.string()).describe("The name of the tool to execute"),arguments:q.record(q.string(),q.unknown()).default({}).describe("Arguments to pass to the tool")});X={schema:J,jsonSchema:q.toJSONSchema(J)},nf0.set(Q,X)}return X}var nf0,v$1;var af0=S(()=>{v1();WU();S$1();nf0=new Map;v$1=class v$1 extends ZI{constructor(Y,Q){super(Y,Q)}async getCallTool(){let Y=await this._cachedTools,X=m3(Y.data).map((G)=>G.name),{jsonSchema:J}=if0(X);return{name:"GATEWAY_CALL_TOOL",description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:J,annotations:{title:"Call Tool",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}}}async handleCallTool(Y){let Q=await this._cachedTools,X=m3(Q.data),J=X.map((F)=>F.name),{schema:G}=if0(J),K=G.safeParse(Y);if(!K.success)return M$({error:K.error.flatten()});let{name:W,arguments:Z}=K.data;if(!new Map(X.map((F)=>[F.name,F])).has(W))return{content:[{type:"text",text:`Tool not found: ${W}. Use GATEWAY_SEARCH_TOOLS to find available tools.`}],isError:!0};return this.routeToolCall({name:W,arguments:Z})}async listTools(){let Y=await super.listTools(),Q=await this.getCallTool();return{tools:[...Y.tools,Q]}}async callTool(Y){if(Y.name==="GATEWAY_CALL_TOOL")return this.handleCallTool(Y.arguments??{});return super.callTool(Y)}}});function rE4(Y,Q){if(Y.connection_type!=="VIRTUAL")return!1;if(!Q||OV(Q))return!1;return Y.id===Q}async function rf0(Y,Q,X=!1){let J=Y.id,G=await Q.storage.virtualMcps.findById(J);if(!G)throw Error(`Virtual MCP not found: ${J}`);return oE4(G,Q,"passthrough",X)}async function oE4(Y,Q,X,J=!1){let K=Y.connections.map((V)=>V.connection_id).map((V)=>Q.storage.connections.findById(V)),W=Y.id?await Q.storage.connections.findById(Y.id):null,Z=await Promise.all(K),H=[];if(W?.tools){for(let V of W.tools)if(xf0(V))H.push(V)}let $={connections:Z.filter((V)=>V!==null&&V.status==="active"&&!rE4(V,Y.id)),virtualMcp:Y,virtualTools:H.length>0?H:void 0,superUser:J};return X==="smart_tool_selection"?new v$1($,Q):X==="code_execution"?new _$1($,Q):new dN($,Q)}var of0=S(()=>{zY();A$();cf0();R$1();af0()});async function pN(Y,Q,X=!1){if(Y.connection_type==="VIRTUAL")return rf0(Y,Q,X);return yf0(Y,Q,X)}var k$1=S(()=>{ff0();of0()});var sf0=S(()=>{zY();jY();k$1();C$1()});function sE4(Y,Q,X){return async(J,G)=>{try{let K=J.params.name,W=async()=>{let{tools:H}=await X();return H.find(($)=>$.name===K)?._meta};return await new WI(Y.authInstance,Y.auth.user?.id??Y.auth.apiKey?.userId,K,Y.boundAuth,Y.auth.user?.role,Q,W).check(K),await G()}catch(K){return new Response(JSON.stringify({error:`Authorization failed: ${K.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}function I$1(Y,Q,X,J,G){let K=async(Z,H)=>{if(X.connection_type==="VIRTUAL"){let U=await Y.callTool({name:Z,arguments:H});return new Response(JSON.stringify(U),{headers:{"Content-Type":"application/json"}})}if(!X.connection_url)throw Error("Streamable tools require HTTP connection with URL");let F=X.connection_url,$={method:"tools/call",params:{name:Z,arguments:H}};if(!G.superUser){let z=await sE4(J,Q,Y.listTools.bind(Y))($,async()=>{return new Response});if(!z.ok)return z}let V=J.connectionId&&J.connectionId!==Q?J.connectionId:void 0;return _f0({ctx:J,enabled:xh().enabled,connectionId:Q,connectionTitle:X.title,virtualMcpId:V})($,async()=>{let U=await XI(X,J,G.superUser),z=X.connection_headers;if(z&&"headers"in z)Object.assign(U,z.headers);let O=new URL(F);O.pathname=O.pathname.replace(/\/$/,"")+`/call-tool/${$.params.name}`;let M=JSON.parse(JSON.stringify($.params.arguments,(P,j)=>{if(j instanceof AbortSignal)return;if(typeof j==="function"||typeof j==="symbol")return;if(j===void 0)return;return j})),w=JSON.stringify(M);return await J.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":Q,"tool.name":$.params.name,"request.id":J.metadata.requestId}},async(P)=>{let j=Date.now();try{let C=await fetch(O.toString(),{method:"POST",redirect:"manual",body:w,headers:{...U,"Content-Type":"application/json"}}),E=Date.now()-j;return J.meter.createHistogram("connection.proxy.streamable.duration").record(E,{"connection.id":Q,"tool.name":$.params.name,status:C.ok?"success":"error"}),J.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":Q,"tool.name":$.params.name,status:C.ok?"success":"error"}),P.end(),C}catch(C){let E=C,I=Date.now()-j;throw console.error("[with-streaming-support] fetch error",{connectionId:Q,toolName:$.params.name,error:E.message,errorStack:E.stack,duration:I}),J.meter.createHistogram("connection.proxy.streamable.duration").record(I,{"connection.id":Q,"tool.name":$.params.name,status:"error"}),J.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":Q,"tool.name":$.params.name,error:E.message}),P.recordException(E),P.end(),C}})})},W=Object.assign(Object.create(Object.getPrototypeOf(Y)),Y);return W.callStreamableTool=K,W}var tf0=S(()=>{O$1();N$1();gh();E$1()});var ef0=S(()=>{tf0()});var j$1=S(()=>{k$1();sf0();ef0()});async function YT4(Y,Q,X,J){for(let K of Q){if(K==="*")continue;let[W]=Of0(K),Z=Lp(W,Y);if(Z===void 0||Z===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let G=Lf0(Y,Q);for(let K of G){if(K.endsWith("_self"))continue;let W=await J.storage.connections.findById(K);if(!W||W.organization_id!==X)throw Error(`Referenced connection not found: ${K}`);try{await J.access.check(K)}catch(Z){throw Error(`Access denied to referenced connection: ${K}. ${Z.message}`)}}}var tE4,eE4,y$1;var Yb0=S(()=>{z$1();j$1();D$1();v1();k0();pm();L3();tE4=q.object({id:q.string().describe("ID of the connection to update"),data:RA.describe("Partial connection data to update")}),eE4=q.object({item:P5.describe("The updated connection entity")});y$1=k1({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",annotations:{title:"Update Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:tE4,outputSchema:eE4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=D9(Q);if(!J)throw Error("User ID required to update connection");let{id:G,data:K}=Y,W=await Q.storage.connections.findById(G);if(!W||W.organization_id!==X.id)throw Error("Connection not found in organization");let Z=K.connection_type??W.connection_type,H=K.connection_url??W.connection_url;if(Z==="VIRTUAL"){let M=LV(H);if(!M)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let w=await Q.storage.virtualMcps.findById(M);if(!w)throw Error(`Virtual MCP not found: ${M}`);if(w.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");H=NV(M)}let F=K.configuration_state??W.configuration_state??{},$=K.configuration_scopes??W.configuration_scopes??[];if(K.configuration_state!==void 0||K.configuration_scopes!==void 0){if(K.configuration_state!==void 0)F=K.configuration_state??{};else if(F===null||F===void 0)F={};if(K.configuration_scopes!==void 0)$=K.configuration_scopes??[];if($.length>0)await YT4(F,$,X.id,Q)}let V=K.connection_token??W.connection_token;if(!V)try{let w=await new QI(Q.db,Q.vault).get(G);if(w?.accessToken)V=w.accessToken}catch{}let B=await iL({id:W.id,title:K.title??W.title,connection_type:Z,connection_url:H,connection_token:V,connection_headers:K.connection_headers??W.connection_headers}).catch(()=>null),U=B?.tools?.length?B.tools:null;if(K.configuration_scopes===void 0&&B?.scopes?.length)$=B.scopes;let z={...K,connection_url:H,tools:U,configuration_state:F,configuration_scopes:$,updated_by:J},O=await Q.storage.connections.update(G,z);if((K.configuration_state!==void 0||K.configuration_scopes!==void 0)&&F&&$)try{await(await pN(O,Q,!1)).callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:F,scopes:$}})}catch(M){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",M)}return{item:O}}})});var QT4,f$1;var Qb0=S(()=>{gX();v1();k0();L3();QT4=CC.extend({force:q.boolean().optional().describe("If true, removes this connection from all agents that reference it before deleting")}),f$1=k1({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",annotations:{title:"Delete Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:QT4,outputSchema:RC(P5),handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.connections.findById(Y.id);if(!J)throw Error(`Connection not found: ${Y.id}`);if(J.organization_id!==X.id)throw Error("Connection not found in organization");if(J.metadata?.isFixed===!0)throw Error("This connection is a fixed system connection and cannot be deleted");let K=await Q.storage.virtualMcps.listByConnectionId(X.id,Y.id);if(K.length>0)if(Y.force)await Q.storage.virtualMcps.removeConnectionReferences(Y.id);else throw Error(JSON.stringify({code:"CONNECTION_IN_USE",agentNames:K.map((W)=>W.title)}));return await Q.storage.connections.delete(Y.id),{item:J}}})});var b$1;var Xb0=S(()=>{v1();k0();b$1=k1({name:"CONNECTION_TEST",description:"Test connection health and latency",annotations:{title:"Test Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:q.object({id:q.string()}),outputSchema:q.object({id:q.string(),healthy:q.boolean(),latencyMs:q.number()}),handler:async(Y,Q)=>{let X=B0(Q);await Q.access.check();let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)throw Error("Connection not found");let G=await Q.storage.connections.testConnection(Y.id);return{id:Y.id,...G}}})});var Jb0=S(()=>{Kf0();zf0();Df0();Yb0();Qb0();Xb0()});import{sql as S4}from"kysely";function Gb0(Y){if(Y===null||Y===void 0)return"NULL";if(typeof Y==="number")return String(Y);if(typeof Y==="boolean")return Y?"TRUE":"FALSE";if(typeof Y==="string")return`'${Y.replace(/'/g,"''")}'`;if(Y instanceof Date)return`'${Y.toISOString()}'`;return`'${JSON.stringify(Y).replace(/'/g,"''")}'`}function GT4(Y,Q){let X=Y;for(let G=Q.length;G>=1;G--){let K=`$${G}`;if(X.includes(K))X=X.replaceAll(K,Gb0(Q[G-1]))}let J=[];for(let G=0;G<X.length;G++)if(X[G]==="?")J.push(G);for(let G=Math.min(J.length,Q.length)-1;G>=0;G--){let K=J[G],W=Gb0(Q[G]);X=X.slice(0,K)+W+X.slice(K+1)}return X}function Wb0(Y){return Y.replace(/-/g,"_")}function ZT4(Y){return`app_${Wb0(Y)}`}function KT4(Y){return`app_role_${Wb0(Y)}`}function HT4(Y){if(Y instanceof Error){let Q=Y.message.toLowerCase(),X=Y.code;return X==="3F000"||X==="42704"||X==="22023"||Q.includes("schema")&&Q.includes("does not exist")||Q.includes("role")&&Q.includes("does not exist")}return!1}async function FT4(Y,Q,X){if(await S4`CREATE SCHEMA IF NOT EXISTS ${S4.id(Q)}`.execute(Y),!(await S4`
|
|
1478
1478
|
SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${X}) as exists
|
|
1479
|
-
`.execute(Y)).rows[0]?.exists)await S4`CREATE ROLE ${S4.id(X)} NOLOGIN`.execute(Y);await S4`GRANT ${S4.id(X)} TO CURRENT_USER`.execute(Y),await S4`GRANT USAGE, CREATE ON SCHEMA ${S4.id(Q)} TO ${S4.id(X)}`.execute(Y),await S4`GRANT ALL ON ALL TABLES IN SCHEMA ${S4.id(Q)} TO ${S4.id(X)}`.execute(Y),await S4`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${S4.id(Q)} TO ${S4.id(X)}`.execute(Y),await S4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${S4.id(Q)} GRANT ALL ON TABLES TO ${S4.id(X)}`.execute(Y),await S4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${S4.id(Q)} GRANT ALL ON SEQUENCES TO ${S4.id(X)}`.execute(Y),await S4`REVOKE ALL ON SCHEMA public FROM ${S4.id(X)}`.execute(Y)}async function $T4(Y,Q,X,J){try{return await Y.transaction().execute(async(G)=>{return await S4`SET LOCAL ROLE ${S4.id(X)}`.execute(G),await S4`SET LOCAL search_path TO ${S4.id(Q)}`.execute(G),await S4.raw(J).execute(G)})}catch(G){if(HT4(G))return await FT4(Y,Q,X),await Y.transaction().execute(async(K)=>{return await S4`SET LOCAL ROLE ${S4.id(X)}`.execute(K),await S4`SET LOCAL search_path TO ${S4.id(Q)}`.execute(K),await S4.raw(J).execute(K)});throw G}}var JT4,WT4,Zb0;var Kb0=S(()=>{v1();k0();JT4=q.object({results:q.array(q.unknown()).optional(),success:q.boolean().optional()});WT4=q.object({sql:q.string().describe("The SQL query to run"),params:q.array(q.any()).describe("The parameters to pass to the SQL query").optional()});Zb0=k1({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",annotations:{title:"Run SQL Query",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:WT4,outputSchema:q.object({result:q.array(JT4)}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=GT4(Y.sql,Y.params||[]);if(!Q.connectionId)throw Error("Connection context required for database access");let J=ZT4(Q.connectionId),G=KT4(Q.connectionId);return{result:[{results:(await $T4(Q.db,J,G,X)).rows,success:!0}]}}})});var Hb0,qT4,Fb0;var d3=S(()=>{v1();Xl();Hb0=q.object({connectionId:q.string().optional().describe("Filter subscriptions by connection ID (optional)")}),qT4=q.object({id:q.string().describe("Subscription ID"),connectionId:q.string().describe("Subscriber connection ID"),eventType:q.string().describe("Event type pattern"),publisher:q.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:q.string().nullable().describe("JSONPath filter expression"),enabled:q.boolean().describe("Whether subscription is enabled"),createdAt:q.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:q.string().datetime().describe("Updated timestamp (ISO 8601)")}),Fb0=q.object({subscriptions:q.array(qT4).describe("List of subscriptions")})});var h$1;var $b0=S(()=>{k0();d3();h$1=k1({name:"EVENT_PUBLISH",description:"Publish an event to the event bus. Supports immediate, scheduled (deliverAt), and recurring (cron) delivery. The source is automatically set to the caller's connection ID.",annotations:{title:"Publish Event",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:IC,outputSchema:jC,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await Q.eventBus.publish(X.id,J,{type:Y.type,subject:Y.subject,data:Y.data,deliverAt:Y.deliverAt,cron:Y.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var x$1;var Vb0=S(()=>{k0();d3();x$1=k1({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",annotations:{title:"Subscribe to Events",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:SC,outputSchema:_C,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await Q.eventBus.subscribe(X.id,{connectionId:J,eventType:Y.eventType,publisher:Y.publisher,filter:Y.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var g$1;var qb0=S(()=>{k0();d3();g$1=k1({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",annotations:{title:"Unsubscribe from Events",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:yC,outputSchema:fC,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await Q.eventBus.getSubscription(X.id,Y.subscriptionId);if(!G)throw Error(`Subscription not found: ${Y.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await Q.eventBus.unsubscribe(X.id,Y.subscriptionId)).success,subscriptionId:Y.subscriptionId}}})});var u$1;var Bb0=S(()=>{k0();d3();u$1=k1({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",annotations:{title:"Cancel Recurring Event",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:bC,outputSchema:hC,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await Q.eventBus.getEvent(X.id,Y.eventId))throw Error(`Event not found: ${Y.eventId}`);if(!(await Q.eventBus.cancelEvent(X.id,Y.eventId,J)).success)throw Error("Failed to cancel event. Either the event is already completed/failed, or you are not the publisher.");return{success:!0,eventId:Y.eventId}}})});var m$1;var Ub0=S(()=>{k0();d3();m$1=k1({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",annotations:{title:"Acknowledge Event",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:xC,outputSchema:gC,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await Q.eventBus.ackEvent(X.id,Y.eventId,J)).success)throw Error("Failed to acknowledge event. Either the event was not found, already delivered, or you are not a subscriber.");return{success:!0,eventId:Y.eventId}}})});var l$1;var zb0=S(()=>{k0();d3();l$1=k1({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",annotations:{title:"List Event Subscriptions",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Hb0,outputSchema:Fb0,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);return await Q.access.check(),{subscriptions:(await Q.eventBus.listSubscriptions(X.id,Y.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}))}}})});var d$1;var Db0=S(()=>{k0();d3();d$1=k1({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",annotations:{title:"Sync Event Subscriptions",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:vC,outputSchema:kC,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await Q.eventBus.syncSubscriptions(X.id,{connectionId:J,subscriptions:Y.subscriptions});return{created:G.created,updated:G.updated,deleted:G.deleted,unchanged:G.unchanged,subscriptions:G.subscriptions.map((K)=>({id:K.id,connectionId:K.connectionId,eventType:K.eventType,publisher:K.publisher,filter:K.filter,enabled:K.enabled,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}))}}})});var Ob0=S(()=>{$b0();Vb0();qb0();Bb0();Ub0();zb0();Db0();d3()});var cN=S(()=>{Tk()});function Lb0(){return`/icons/capy-${Math.floor(Math.random()*39)+0}.png`}var UT4,zT4,p$1;var Nb0=S(()=>{v1();k0();cN();UT4=q.object({data:jA.describe("Data for the new virtual MCP")}),zT4=q.object({item:tX.describe("The created virtual MCP entity")}),p$1=k1({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new Virtual MCP",annotations:{title:"Create Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:UT4,outputSchema:zT4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=D9(Q);if(!J)throw Error("User ID required to create virtual MCP");let G={...Y.data,icon:Y.data.icon??Lb0()};return{item:await Q.storage.virtualMcps.create(X.id,J,G)}}})});function DT4(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 P$(Y){return typeof Y==="string"||typeof Y==="number"}function c$1(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 OT4(Y,Q){return Y.connections.some((X)=>X.connection_id===Q)}function Ap(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every((F)=>Ap(Y,F));case"or":return H.some((F)=>Ap(Y,F));case"not":return!H.every((F)=>Ap(Y,F));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join(".");if(K==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return OT4(Y,G)}let W=c$1(Y,K);switch(J){case"eq":return W===G;case"gt":return P$(W)&&P$(G)&&W>G;case"gte":return P$(W)&&P$(G)&&W>=G;case"lt":return P$(W)&&P$(G)&&W<G;case"lte":return P$(W)&&P$(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=DT4(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 LT4(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=c$1(X,K),Z=c$1(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 NT4,MT4,n$1;var Mb0=S(()=>{gX();k0();cN();NT4=dG,MT4=M3(tX),n$1=k1({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",annotations:{title:"List Virtual MCPs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:NT4,outputSchema:MT4,handler:async(Y,Q)=>{await Q.access.check();let X=B0(Q),J=Y.where&&!("conditions"in Y.where)&&Y.where.field.join(".")==="connection_id"&&Y.where.operator==="eq"&&typeof Y.where.value==="string"?Y.where.value:void 0,K=J?await Q.storage.virtualMcps.listByConnectionId(X.id,J):await Q.storage.virtualMcps.list(X.id);if(Y.where)K=K.filter((V)=>Ap(V,Y.where));if(Y.orderBy&&Y.orderBy.length>0)K=LT4(K,Y.orderBy);let W=K.length,Z=Y.offset??0,H=Y.limit??100,F=K.slice(Z,Z+H),$=Z+H<W;return{items:F,totalCount:W,hasMore:$}}})});var wT4,AT4,i$1;var wb0=S(()=>{v1();k0();cN();wT4=q.object({id:q.string().describe("ID of the virtual MCP to retrieve")}),AT4=q.object({item:tX.nullable().describe("The retrieved virtual MCP, or null if not found")}),i$1=k1({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",annotations:{title:"Get Virtual MCP",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:wT4,outputSchema:AT4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.id);if(J&&J.organization_id!==X.id)return{item:null};if(!J)return{item:null};return{item:J}}})});var PT4,ET4,a$1;var Ab0=S(()=>{v1();k0();cN();PT4=q.object({id:q.string().describe("ID of the virtual MCP to update"),data:SA.describe("Partial virtual MCP data to update")}),ET4=q.object({item:tX.describe("The updated virtual MCP entity")}),a$1=k1({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",annotations:{title:"Update Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:PT4,outputSchema:ET4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=D9(Q);if(!J)throw Error("User ID required to update virtual MCP");let G=await Q.storage.virtualMcps.findById(Y.id);if(!G)throw Error(`Virtual MCP not found: ${Y.id}`);if(G.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.id}`);return{item:await Q.storage.virtualMcps.update(Y.id,J,Y.data)}}})});var TT4,CT4,r$1;var Pb0=S(()=>{v1();k0();cN();TT4=q.object({id:q.string().describe("ID of the virtual MCP to delete")}),CT4=q.object({item:tX.describe("The deleted virtual MCP entity")}),r$1=k1({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",annotations:{title:"Delete Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:TT4,outputSchema:CT4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.id);if(!J)throw Error(`Virtual MCP not found: ${Y.id}`);if(J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.id}`);return await Q.storage.virtualMcps.delete(Y.id),{item:J}}})});var Eb0=S(()=>{Nb0();Mb0();wb0();Ab0();Pb0()});var IT4,jT4,o$1;var Tb0=S(()=>{v1();k0();A$();IT4=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP to add the tool to"),data:bf0.describe("Virtual tool data")}),jT4=q.object({item:pZ.describe("The created virtual tool")}),o$1=k1({name:"COLLECTION_VIRTUAL_TOOLS_CREATE",description:"Create a new virtual tool on a Virtual MCP. The tool code should be a JavaScript ES module that exports a default async function: export default async (tools, args) => { ... }. Specify connection_dependencies to indicate which connections this tool uses.",annotations:{title:"Create Virtual Tool",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:IT4,outputSchema:jT4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let G=Y.data.connection_dependencies??[];return{item:await Q.storage.virtualMcps.createVirtualTool(Y.virtual_mcp_id,Y.data,G)}}})});var ST4,_T4,s$1;var Cb0=S(()=>{v1();k0();A$();ST4=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP to list tools for"),limit:q.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:q.number().int().min(0).optional().describe("Number of items to skip")}),_T4=q.object({items:q.array(pZ).describe("Array of virtual tools"),totalCount:q.number().int().min(0).optional().describe("Total number of virtual tools"),hasMore:q.boolean().optional().describe("Whether there are more items available")}),s$1=k1({name:"COLLECTION_VIRTUAL_TOOLS_LIST",description:"List all virtual tools for a Virtual MCP",annotations:{title:"List Virtual Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:ST4,outputSchema:_T4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)return{items:[],totalCount:0,hasMore:!1};let G=await Q.storage.virtualMcps.listVirtualTools(Y.virtual_mcp_id),K=G.length,W=Y.offset??0,Z=Y.limit??100,H=G.slice(W,W+Z),F=W+Z<K;return{items:H,totalCount:K,hasMore:F}}})});var vT4,kT4,t$1;var Rb0=S(()=>{v1();k0();A$();vT4=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Name of the virtual tool to retrieve")}),kT4=q.object({item:pZ.nullable().describe("The retrieved virtual tool, or null if not found")}),t$1=k1({name:"COLLECTION_VIRTUAL_TOOLS_GET",description:"Get a virtual tool by name from a Virtual MCP",annotations:{title:"Get Virtual Tool",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:vT4,outputSchema:kT4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)return{item:null};return{item:await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name)}}})});var yT4,fT4,e$1;var Ib0=S(()=>{v1();k0();A$();yT4=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Current name of the virtual tool to update"),data:hf0.describe("Partial virtual tool data to update")}),fT4=q.object({item:pZ.describe("The updated virtual tool")}),e$1=k1({name:"COLLECTION_VIRTUAL_TOOLS_UPDATE",description:"Update an existing virtual tool on a Virtual MCP. Specify connection_dependencies to update which connections this tool uses.",annotations:{title:"Update Virtual Tool",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:yT4,outputSchema:fT4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);if(!await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name))throw Error(`Virtual tool not found: ${Y.name}`);let K=Y.data.connection_dependencies;return{item:await Q.storage.virtualMcps.updateVirtualTool(Y.virtual_mcp_id,Y.name,Y.data,K)}}})});var bT4,hT4,YV1;var jb0=S(()=>{v1();k0();A$();bT4=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Name of the virtual tool to delete")}),hT4=q.object({item:pZ.describe("The deleted virtual tool")}),YV1=k1({name:"COLLECTION_VIRTUAL_TOOLS_DELETE",description:"Delete a virtual tool from a Virtual MCP",annotations:{title:"Delete Virtual Tool",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:bT4,outputSchema:hT4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let G=await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name);if(!G)throw Error(`Virtual tool not found: ${Y.name}`);return await Q.storage.virtualMcps.deleteVirtualTool(Y.virtual_mcp_id,Y.name),{item:G}}})});var Sb0=S(()=>{Tb0();Cb0();Rb0();Ib0();jb0()});var gT4,QV1;var _b0=S(()=>{k0();v1();gT4=q.object({id:q.string().optional().describe("Unique log identifier"),organizationId:q.string().describe("Organization ID"),connectionId:q.string().describe("Connection ID"),connectionTitle:q.string().describe("Connection display name"),toolName:q.string().describe("Name of the tool that was called"),input:q.record(q.string(),q.unknown()).describe("Redacted tool input"),output:q.record(q.string(),q.unknown()).describe("Redacted tool output"),isError:q.boolean().describe("Whether the call resulted in an error"),errorMessage:q.string().nullish().describe("Error message if applicable"),durationMs:q.number().describe("Call duration in milliseconds"),timestamp:q.string().describe("ISO 8601 timestamp of the call"),userId:q.string().nullish().describe("User who triggered the call"),requestId:q.string().describe("Unique request identifier"),userAgent:q.string().nullish().describe("Client identifier (x-mesh-client header)"),virtualMcpId:q.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:q.record(q.string(),q.string()).nullish().describe("Custom key-value metadata attached to the log")}),QV1=k1({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",annotations:{title:"List Monitoring Logs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({connectionId:q.string().optional().describe("Filter by connection ID"),excludeConnectionIds:q.array(q.string()).optional().describe("Exclude logs from these connection IDs (e.g. system connections)"),virtualMcpId:q.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:q.string().optional().describe("Filter by tool name"),isError:q.boolean().optional().describe("Filter by error status"),startDate:q.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:q.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:q.number().default(20).describe("Maximum number of results"),offset:q.number().default(0).describe("Offset for pagination"),properties:q.record(q.string(),q.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:q.array(q.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:q.record(q.string(),q.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)"),propertyInValues:q.record(q.string(),q.string()).optional().describe("Filter by exact match within comma-separated values (e.g., user_tags in 'Engineering')")}),outputSchema:q.object({logs:q.array(gT4).describe("Array of monitoring logs"),total:q.number().describe("Total number of logs matching filters"),offset:q.number().describe("Current offset for pagination"),limit:q.number().describe("Current limit for pagination")}),handler:async(Y,Q)=>{let X=B0(Q),G=Y.properties||Y.propertyKeys||Y.propertyPatterns||Y.propertyInValues?{properties:Y.properties,propertyKeys:Y.propertyKeys,propertyPatterns:Y.propertyPatterns,propertyInValues:Y.propertyInValues}:void 0,K={organizationId:X.id,connectionId:Y.connectionId,excludeConnectionIds:Y.excludeConnectionIds,virtualMcpId:Y.virtualMcpId,toolName:Y.toolName,isError:Y.isError,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0,limit:Y.limit,offset:Y.offset,propertyFilters:G},W=await Q.storage.monitoring.query(K);return{logs:W.logs.map((Z)=>({...Z,timestamp:Z.timestamp instanceof Date?Z.timestamp.toISOString():Z.timestamp})),total:W.total,offset:Y.offset,limit:Y.limit}}})});var XV1;var vb0=S(()=>{k0();v1();XV1=k1({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",annotations:{title:"Get Monitoring Stats",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({startDate:q.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:q.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:q.object({totalCalls:q.number().describe("Total number of tool calls"),errorRate:q.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:q.number().describe("Average call duration in milliseconds"),errorRatePercent:q.string().describe("Error rate as a percentage string")}),handler:async(Y,Q)=>{let J={organizationId:B0(Q).id,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0},G=await Q.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var kb0=S(()=>{_b0();vb0()});var mT4,lT4,dT4,pT4,cT4,KI,HI,E$,nT4,iT4,yb0;var nN=S(()=>{v1();mT4=q.enum(["sum","avg","min","max","count","last"]).describe("Aggregation function to apply"),lT4=q.enum(["metric","timeseries","table"]).describe("Widget display type"),dT4=q.object({path:q.string().describe("JSONPath to extract value, e.g., '$.usage.total_tokens'"),from:q.enum(["input","output"]).describe("Extract from tool call input or output")}),pT4=q.object({fn:mT4,groupBy:q.string().optional().describe("Optional JSONPath for grouping results"),interval:q.string().optional().describe("For timeseries widgets: interval like '1h', '1d', '15m'")}),cT4=q.object({connectionIds:q.array(q.string()).optional().describe("Filter to specific connections"),toolNames:q.array(q.string()).optional().describe("Filter to specific tools")}),KI=q.object({id:q.string().describe("Unique widget identifier"),name:q.string().describe("Widget display name"),type:lT4,source:dT4,aggregation:pT4,filter:cT4.optional()}),HI=q.object({connectionIds:q.array(q.string()).optional().describe("Filter to specific connections"),virtualMcpIds:q.array(q.string()).optional().describe("Filter to specific virtual MCPs/agents"),toolNames:q.array(q.string()).optional().describe("Filter to specific tools"),propertyFilters:q.record(q.string(),q.string()).optional().describe("Filter by exact metadata property key=value matches (e.g., { environment: 'production' })")}),E$=q.object({id:q.string().describe("Unique dashboard identifier"),organizationId:q.string().describe("Organization ID"),name:q.string().describe("Dashboard name"),description:q.string().nullable().describe("Dashboard description"),filters:HI.nullable().describe("Global filters applied to all widgets"),widgets:q.array(KI).describe("Widget definitions"),createdBy:q.string().describe("User ID who created the dashboard"),createdAt:q.string().describe("Creation timestamp"),updatedAt:q.string().describe("Last update timestamp")}),nT4=q.object({key:q.string().describe("Group key value"),value:q.number().describe("Aggregated value for this group")}),iT4=q.object({timestamp:q.string().describe("Time bucket timestamp"),value:q.number().describe("Aggregated value for this time bucket")}),yb0=q.object({widgetId:q.string().describe("Widget ID this result is for"),value:q.number().nullable().describe("Aggregated value (for metric type)"),groups:q.array(nT4).optional().describe("Grouped results (when groupBy is specified)"),timeseries:q.array(iT4).optional().describe("Timeseries data (for timeseries type)")})});var JV1;var fb0=S(()=>{k0();v1();nN();JV1=k1({name:"MONITORING_DASHBOARD_CREATE",description:"Create a new monitoring dashboard with JSONPath widgets",annotations:{title:"Create Monitoring Dashboard",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({name:q.string().min(1).describe("Dashboard name"),description:q.string().optional().describe("Dashboard description"),filters:HI.optional().describe("Global filters applied to all widgets"),widgets:q.array(KI).min(1).describe("Widget definitions (at least one required)")}),outputSchema:E$,handler:async(Y,Q)=>{let X=B0(Q),J=Q.auth.user?.id;if(!J)throw Error("User authentication required");let G=await Q.storage.monitoringDashboards.create(X.id,J,{name:Y.name,description:Y.description,filters:Y.filters,widgets:Y.widgets});return{id:G.id,organizationId:G.organizationId,name:G.name,description:G.description,filters:G.filters,widgets:G.widgets,createdBy:G.createdBy,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}})});var GV1;var bb0=S(()=>{k0();v1();nN();GV1=k1({name:"MONITORING_DASHBOARD_GET",description:"Get a monitoring dashboard by ID",annotations:{title:"Get Monitoring Dashboard",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string().describe("Dashboard ID")}),outputSchema:E$.nullable(),handler:async(Y,Q)=>{let X=B0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)return null;return{id:J.id,organizationId:J.organizationId,name:J.name,description:J.description,filters:J.filters,widgets:J.widgets,createdBy:J.createdBy,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var WV1;var hb0=S(()=>{k0();v1();nN();WV1=k1({name:"MONITORING_DASHBOARD_LIST",description:"List all monitoring dashboards for the organization",annotations:{title:"List Monitoring Dashboards",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({dashboards:q.array(E$).describe("List of dashboards"),total:q.number().describe("Total number of dashboards")}),handler:async(Y,Q)=>{let X=B0(Q),J=await Q.storage.monitoringDashboards.list(X.id);return{dashboards:J.map((G)=>({id:G.id,organizationId:G.organizationId,name:G.name,description:G.description,filters:G.filters,widgets:G.widgets,createdBy:G.createdBy,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt})),total:J.length}}})});var ZV1;var xb0=S(()=>{k0();v1();nN();ZV1=k1({name:"MONITORING_DASHBOARD_UPDATE",description:"Update an existing monitoring dashboard",annotations:{title:"Update Monitoring Dashboard",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string().describe("Dashboard ID to update"),name:q.string().optional().describe("New dashboard name"),description:q.string().nullable().optional().describe("New dashboard description"),filters:HI.nullable().optional().describe("New global filters"),widgets:q.array(KI).optional().describe("New widget definitions")}),outputSchema:E$,handler:async(Y,Q)=>{let X=B0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.id} not found`);let G={};if(Y.name!==void 0)G.name=Y.name;if(Y.description!==void 0)G.description=Y.description;if(Y.filters!==void 0)G.filters=Y.filters;if(Y.widgets!==void 0)G.widgets=Y.widgets;let K=await Q.storage.monitoringDashboards.update(Y.id,G);return{id:K.id,organizationId:K.organizationId,name:K.name,description:K.description,filters:K.filters,widgets:K.widgets,createdBy:K.createdBy,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}}})});var KV1;var gb0=S(()=>{k0();v1();KV1=k1({name:"MONITORING_DASHBOARD_DELETE",description:"Delete a monitoring dashboard",annotations:{title:"Delete Monitoring Dashboard",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string().describe("Dashboard ID to delete")}),outputSchema:q.object({success:q.boolean().describe("Whether the deletion was successful")}),handler:async(Y,Q)=>{let X=B0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.id} not found`);return await Q.storage.monitoringDashboards.delete(Y.id),{success:!0}}})});var HV1;var ub0=S(()=>{k0();v1();nN();HV1=k1({name:"MONITORING_DASHBOARD_QUERY",description:"Execute a dashboard's widgets and return aggregated monitoring data",annotations:{title:"Query Monitoring Dashboard",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({dashboardId:q.string().describe("Dashboard ID to query"),timeRange:q.object({startDate:q.string().datetime().describe("Start of time range (ISO 8601)"),endDate:q.string().datetime().describe("End of time range (ISO 8601)")}).optional().describe("Time range for the query (defaults to last 24 hours)"),propertyFilters:q.object({properties:q.record(q.string(),q.string()).optional().describe("Exact match: property key equals value"),propertyKeys:q.array(q.string()).optional().describe("Exists: filter logs that have these property keys"),propertyPatterns:q.record(q.string(),q.string()).optional().describe("Pattern match: property value matches pattern (SQL LIKE, use % as wildcard)"),propertyInValues:q.record(q.string(),q.string()).optional().describe("In match: exact match within comma-separated values")}).optional().describe("Runtime property filters applied to all widgets (merged with dashboard-level filters)")}),outputSchema:q.object({dashboardId:q.string().describe("Dashboard ID"),results:q.array(yb0).describe("Widget query results"),timeRange:q.object({startDate:q.string(),endDate:q.string()}).describe("Time range used for the query")}),handler:async(Y,Q)=>{let X=B0(Q),J=await Q.storage.monitoringDashboards.get(Y.dashboardId);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.dashboardId} not found`);let G=new Date,K=Y.timeRange?.startDate?new Date(Y.timeRange.startDate):new Date(G.getTime()-86400000),W=Y.timeRange?.endDate?new Date(Y.timeRange.endDate):G,Z=await Promise.all(J.widgets.map(async(H)=>{let F=J.filters?.propertyFilters,$=Y.propertyFilters,V=F||$?{properties:{...F,...$?.properties},propertyKeys:$?.propertyKeys,propertyPatterns:$?.propertyPatterns,propertyInValues:$?.propertyInValues}:void 0,B={connectionIds:H.filter?.connectionIds??J.filters?.connectionIds??void 0,virtualMcpIds:J.filters?.virtualMcpIds??void 0,toolNames:H.filter?.toolNames??J.filters?.toolNames??void 0,startDate:K,endDate:W,propertyFilters:V};try{let U=await Q.storage.monitoring.aggregate({organizationId:X.id,path:H.source.path,from:H.source.from,aggregation:H.aggregation.fn,groupBy:H.aggregation.groupBy,interval:H.aggregation.interval,filters:B});return{widgetId:H.id,value:U.value,groups:U.groups,timeseries:U.timeseries}}catch(U){return console.error(`Widget ${H.id} aggregation failed:`,U),{widgetId:H.id,value:null,groups:void 0,timeseries:void 0}}}));return{dashboardId:Y.dashboardId,results:Z,timeRange:{startDate:K.toISOString(),endDate:W.toISOString()}}}})});var aT4,FV1;var mb0=S(()=>{k0();v1();aT4=q.object({type:q.enum(["metric","timeseries","table"]),source:q.object({path:q.string().describe("JSONPath to extract value from"),from:q.enum(["input","output"]).describe("Extract from input or output")}),aggregation:q.object({fn:q.enum(["sum","avg","min","max","count","last"]).describe("Aggregation function"),groupBy:q.string().optional().describe("JSONPath for grouping (table)"),interval:q.string().optional().describe("Time interval for timeseries (15m, 1h, 1d)")}),filter:q.object({connectionIds:q.array(q.string()).optional(),toolNames:q.array(q.string()).optional()}).optional()}),FV1=k1({name:"MONITORING_WIDGET_PREVIEW",description:"Preview a widget aggregation without saving. Used to test queries in the dashboard editor.",annotations:{title:"Preview Monitoring Widget",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({widget:aT4.describe("Widget configuration to preview"),timeRange:q.object({startDate:q.string().datetime().describe("Start of time range (ISO 8601)"),endDate:q.string().datetime().describe("End of time range (ISO 8601)")}).optional().describe("Time range for the query (defaults to last 24 hours)"),propertyFilters:q.object({properties:q.record(q.string(),q.string()).optional().describe("Exact match: property key equals value"),propertyKeys:q.array(q.string()).optional().describe("Exists: filter logs that have these property keys"),propertyPatterns:q.record(q.string(),q.string()).optional().describe("Pattern match: property value matches pattern (SQL LIKE)"),propertyInValues:q.record(q.string(),q.string()).optional().describe("In match: exact match within comma-separated values")}).optional().describe("Property filters to apply")}),outputSchema:q.object({value:q.number().nullable().optional().describe("Aggregated value"),groups:q.array(q.object({key:q.string(),value:q.number()})).optional().describe("Grouped results for table widgets"),timeseries:q.array(q.object({timestamp:q.string(),value:q.number()})).optional().describe("Timeseries data points"),matchedRecords:q.number().describe("Number of records that matched"),timeRange:q.object({startDate:q.string(),endDate:q.string()}).describe("Time range used for the query")}),handler:async(Y,Q)=>{let X=B0(Q),{widget:J,timeRange:G}=Y,K=new Date,W=G?.startDate?new Date(G.startDate):new Date(K.getTime()-86400000),Z=G?.endDate?new Date(G.endDate):K,H={connectionIds:J.filter?.connectionIds,toolNames:J.filter?.toolNames,startDate:W,endDate:Z,propertyFilters:Y.propertyFilters};try{let F=await Q.storage.monitoring.countMatched({organizationId:X.id,path:J.source.path,from:J.source.from,filters:H}),$=await Q.storage.monitoring.aggregate({organizationId:X.id,path:J.source.path,from:J.source.from,aggregation:J.aggregation.fn,groupBy:J.aggregation.groupBy,interval:J.aggregation.interval,filters:H});return{value:$.value,groups:$.groups,timeseries:$.timeseries,matchedRecords:F,timeRange:{startDate:W.toISOString(),endDate:Z.toISOString()}}}catch(F){return console.error("Widget preview aggregation failed:",F),{value:null,matchedRecords:0,timeRange:{startDate:W.toISOString(),endDate:Z.toISOString()}}}}})});var lb0=S(()=>{fb0();bb0();hb0();xb0();gb0();ub0();mb0()});var $V1;var db0=S(()=>{v1();k0();$V1=k1({name:"ORGANIZATION_CREATE",description:"Create a new organization",annotations:{title:"Create Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({slug:q.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:q.string().min(1).max(255),description:q.string().optional()}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),members:q.array(q.any()).optional()}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=D9(Q);if(!X)throw Error("User ID required to create organization");let J=await Q.boundAuth.organization.create({name:Y.name,slug:Y.slug,metadata:Y.description?{description:Y.description}:void 0,userId:X});if(!J)throw Error("Failed to create organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var VV1;var pb0=S(()=>{v1();k0();VV1=k1({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",annotations:{title:"List Organizations",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({userId:q.string().optional()}),outputSchema:q.object({organizations:q.array(q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=D9(Q),J=Y.userId||X;if(!J)throw Error("User ID required to list organizations");return{organizations:(await Q.boundAuth.organization.list(J)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var qV1;var cb0=S(()=>{v1();k0();qV1=k1({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",annotations:{title:"Get Organization",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),members:q.array(q.any()).optional(),invitations:q.array(q.any()).optional()}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=await Q.boundAuth.organization.get();if(!X)throw Error("No active organization found");let J=new Date,G=X.invitations?.filter((K)=>new Date(K.expiresAt)>J);return{...X,invitations:G,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt}}})});var BV1;var nb0=S(()=>{v1();k0();BV1=k1({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",annotations:{title:"Update Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string(),slug:q.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:q.string().min(1).max(255).optional(),description:q.string().optional()}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X={};if(Y.name)X.name=Y.name;if(Y.slug)X.slug=Y.slug;if(Y.description)X.metadata={description:Y.description};let J=await Q.boundAuth.organization.update({organizationId:Y.id,data:X});if(!J)throw Error("Failed to update organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var UV1;var ib0=S(()=>{v1();k0();UV1=k1({name:"ORGANIZATION_DELETE",description:"Delete an organization",annotations:{title:"Delete Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string()}),outputSchema:q.object({success:q.boolean(),id:q.string()}),handler:async(Y,Q)=>{return o1(Q),await Q.access.check(),await Q.boundAuth.organization.delete(Y.id),{success:!0,id:Y.id}}})});var FI;var zV1=S(()=>{v1();FI=q.object({title:q.string(),url:q.string(),icon:q.string()})});var DV1;var ab0=S(()=>{v1();k0();zV1();DV1=k1({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",annotations:{title:"Get Organization Settings",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({organizationId:q.string(),sidebar_items:q.array(FI).nullable().optional(),enabled_plugins:q.array(q.string()).nullable().optional(),createdAt:q.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.storage.organizationSettings.get(X);if(!J)return{organizationId:X};return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var OV1;var rb0=S(()=>{v1();k0();zV1();OV1=k1({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",annotations:{title:"Update Organization Settings",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string(),sidebar_items:q.array(FI).optional(),enabled_plugins:q.array(q.string()).optional()}),outputSchema:q.object({organizationId:q.string(),sidebar_items:q.array(FI).nullable().optional(),enabled_plugins:q.array(q.string()).nullable().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{if(o1(Q),await Q.access.check(),Q.organization&&Q.organization.id!==Y.organizationId)throw Error("Cannot update settings for a different organization");let X=await Q.storage.organizationSettings.upsert(Y.organizationId,{sidebar_items:Y.sidebar_items,enabled_plugins:Y.enabled_plugins});return{...X,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt,updatedAt:X.updatedAt instanceof Date?X.updatedAt.toISOString():X.updatedAt}}})});var LV1;var ob0=S(()=>{v1();k0();LV1=k1({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",annotations:{title:"Add Organization Member",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),userId:q.string(),role:q.array(q.string())}),outputSchema:q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.union([q.string(),q.array(q.string())]),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");if(X!==Q.organization?.id)throw Error("Organization ID does not match authenticated organization");let J=await Q.boundAuth.organization.addMember({organizationId:X,userId:Y.userId,role:Y.role});if(!J)throw Error("Failed to add member");return{...J,role:J.role,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var NV1;var sb0=S(()=>{v1();k0();NV1=k1({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",annotations:{title:"Remove Organization Member",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),memberIdOrEmail:q.string()}),outputSchema:q.object({success:q.boolean(),memberIdOrEmail:q.string()}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");return await Q.boundAuth.organization.removeMember({organizationId:X,memberIdOrEmail:Y.memberIdOrEmail}),{success:!0,memberIdOrEmail:Y.memberIdOrEmail}}})});var MV1;var tb0=S(()=>{v1();k0();MV1=k1({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",annotations:{title:"List Organization Members",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({limit:q.number().optional(),offset:q.number().optional()}),outputSchema:q.object({members:q.array(q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.string(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),user:q.object({id:q.string(),name:q.string(),email:q.string(),image:q.string().optional()}).optional()}))}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.boundAuth.organization.listMembers({organizationId:X,limit:Y.limit,offset:Y.offset});return{members:(Array.isArray(J)?J:[]).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var wV1;var eb0=S(()=>{v1();k0();wV1=k1({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",annotations:{title:"Update Member Role",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),memberId:q.string(),role:q.array(q.string())}),outputSchema:q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.union([q.literal("admin"),q.literal("member"),q.literal("owner")]),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),user:q.object({email:q.string(),name:q.string(),image:q.string().optional()})}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.boundAuth.organization.updateMemberRole({organizationId:X,memberId:Y.memberId,role:Y.role});if(!J)throw Error("Failed to update member role");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var Yh0=S(()=>{db0();pb0();cb0();nb0();ib0();ab0();rb0();ob0();sb0();tb0();eb0()});var sT4,Pp,tT4,ZU,Qh0,Ep;var KU=S(()=>{v1();sT4=q.object({banner:q.string().nullable(),bannerColor:q.string().nullable(),icon:q.string().nullable(),themeColor:q.string().nullable()}),Pp=q.object({banner:q.string().nullable().optional(),bannerColor:q.string().nullable().optional(),icon:q.string().nullable().optional(),themeColor:q.string().nullable().optional()}),tT4=q.object({id:q.string(),title:q.string(),icon:q.string().nullable()}),ZU=q.object({id:q.string(),organizationId:q.string(),slug:q.string(),name:q.string(),description:q.string().nullable(),enabledPlugins:q.array(q.string()).nullable(),ui:sT4.nullable(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")}),Qh0=ZU.omit({organizationId:!0}).extend({boundConnections:q.array(tT4)}),Ep=q.object({id:q.string(),projectId:q.string(),pluginId:q.string(),connectionId:q.string().nullable(),settings:q.record(q.string(),q.unknown()).nullable(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")})});var AV1;var Xh0=S(()=>{v1();k0();KU();AV1=k1({name:"PROJECT_LIST",description:"List all projects in an organization",annotations:{title:"List Projects",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().describe("Organization ID to list projects for")}),outputSchema:q.object({projects:q.array(Qh0)}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=await Q.storage.projects.list(Y.organizationId),J=X.map((K)=>K.id),G=await Q.storage.projectPluginConfigs.getBoundConnectionsForProjects(J);return{projects:X.map((K)=>({id:K.id,slug:K.slug,name:K.name,description:K.description,enabledPlugins:K.enabledPlugins,ui:K.ui,boundConnections:G.get(K.id)??[],createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}))}}})});var PV1;var Jh0=S(()=>{v1();k0();KU();PV1=k1({name:"PROJECT_GET",description:"Get a project by ID or slug",annotations:{title:"Get Project",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().describe("Organization ID"),projectId:q.string().optional().describe("Project ID (either this or slug required)"),slug:q.string().optional().describe("Project slug (either this or projectId required)")}).refine((Y)=>Y.projectId||Y.slug,{message:"Either projectId or slug must be provided"}),outputSchema:q.object({project:ZU.nullable()}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=null;if(Y.projectId)X=await Q.storage.projects.get(Y.projectId);else if(Y.slug)X=await Q.storage.projects.getBySlug(Y.organizationId,Y.slug);if(!X)return{project:null};return{project:{id:X.id,organizationId:X.organizationId,slug:X.slug,name:X.name,description:X.description,enabledPlugins:X.enabledPlugins,ui:X.ui,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt,updatedAt:X.updatedAt instanceof Date?X.updatedAt.toISOString():X.updatedAt}}}})});var EV1;var Gh0=S(()=>{v1();zY();k0();KU();EV1=k1({name:"PROJECT_CREATE",description:"Create a new project in an organization",annotations:{title:"Create Project",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().describe("Organization ID"),slug:q.string().min(1).max(100).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens").describe("URL-friendly identifier"),name:q.string().min(1).max(200).describe("Display name"),description:q.string().max(1000).nullable().optional().describe("Project description"),enabledPlugins:q.array(q.string()).nullable().optional().describe("Plugin IDs to enable"),ui:Pp.nullable().optional().describe("UI customization")}),outputSchema:q.object({project:ZU}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let{organizationId:X,slug:J,name:G,description:K,enabledPlugins:W,ui:Z}=Y;if(J===n7)throw Error(`Slug "${n7}" is reserved`);if(await Q.storage.projects.getBySlug(X,J))throw Error(`Project with slug "${J}" already exists in this organization`);let F=Z?{banner:Z.banner??null,bannerColor:Z.bannerColor??null,icon:Z.icon??null,themeColor:Z.themeColor??null}:null,$=await Q.storage.projects.create({organizationId:X,slug:J,name:G,description:K??null,enabledPlugins:W??null,ui:F});return{project:{id:$.id,organizationId:$.organizationId,slug:$.slug,name:$.name,description:$.description,enabledPlugins:$.enabledPlugins,ui:$.ui,createdAt:$.createdAt instanceof Date?$.createdAt.toISOString():$.createdAt,updatedAt:$.updatedAt instanceof Date?$.updatedAt.toISOString():$.updatedAt}}}})});var TV1;var Wh0=S(()=>{v1();k0();KU();TV1=k1({name:"PROJECT_UPDATE",description:"Update a project's details",annotations:{title:"Update Project",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID to update"),name:q.string().min(1).max(200).optional().describe("New display name"),description:q.string().max(1000).nullable().optional().describe("New description"),enabledPlugins:q.array(q.string()).nullable().optional().describe("Updated plugin IDs"),ui:Pp.nullable().optional().describe("Updated UI customization")}),outputSchema:q.object({project:ZU.nullable()}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let{projectId:X,name:J,description:G,enabledPlugins:K,ui:W}=Y,Z={};if(J!==void 0)Z.name=J;if(G!==void 0)Z.description=G;if(K!==void 0)Z.enabledPlugins=K;if(W!==void 0)Z.ui=W?{banner:W.banner??null,bannerColor:W.bannerColor??null,icon:W.icon??null,themeColor:W.themeColor??null}:null;let H=await Q.storage.projects.update(X,Z);if(!H)return{project:null};return{project:{id:H.id,organizationId:H.organizationId,slug:H.slug,name:H.name,description:H.description,enabledPlugins:H.enabledPlugins,ui:H.ui,createdAt:H.createdAt instanceof Date?H.createdAt.toISOString():H.createdAt,updatedAt:H.updatedAt instanceof Date?H.updatedAt.toISOString():H.updatedAt}}}})});var CV1;var Zh0=S(()=>{v1();zY();k0();CV1=k1({name:"PROJECT_DELETE",description:"Delete a project (cannot delete org-admin)",annotations:{title:"Delete Project",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID to delete")}),outputSchema:q.object({success:q.boolean(),message:q.string().optional()}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let{projectId:X}=Y,J=await Q.storage.projects.get(X);if(!J)return{success:!1,message:"Project not found"};if(J.slug===n7)return{success:!1,message:"Cannot delete the org-admin project"};return{success:await Q.storage.projects.delete(X)}}})});var RV1;var Kh0=S(()=>{v1();k0();KU();RV1=k1({name:"PROJECT_PLUGIN_CONFIG_GET",description:"Get plugin configuration for a project",annotations:{title:"Get Project Plugin Config",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID"),pluginId:q.string().describe("Plugin ID")}),outputSchema:q.object({config:Ep.nullable()}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let{projectId:X,pluginId:J}=Y,G=await Q.storage.projectPluginConfigs.get(X,J);if(!G)return{config:null};return{config:{id:G.id,projectId:G.projectId,pluginId:G.pluginId,connectionId:G.connectionId,settings:G.settings,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var IV1;var Hh0=S(()=>{v1();k0();KU();Dp();IV1=k1({name:"PROJECT_PLUGIN_CONFIG_UPDATE",description:"Update or create plugin configuration for a project",annotations:{title:"Update Project Plugin Config",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID"),pluginId:q.string().describe("Plugin ID"),connectionId:q.string().nullable().optional().describe("MCP connection to bind"),settings:q.record(q.string(),q.unknown()).nullable().optional().describe("Plugin-specific settings")}),outputSchema:q.object({config:Ep}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let{projectId:X,pluginId:J,connectionId:G,settings:K}=Y,W=D9(Q),Z=await Q.storage.projects.get(X);if(!Z)throw Error(`Project not found: ${X}`);let H=G?await Q.storage.connections.findById(G):null;if(G&&Z.organizationId&&!H&&gN()){if(zp(G,Z.organizationId)){if(!W)throw Error("User ID required to create dev-assets connection");let $=uN(Z.organizationId,AG());await Q.storage.connections.create({...$,organization_id:Z.organizationId,created_by:W})}}let F=await Q.storage.projectPluginConfigs.upsert(X,J,{connectionId:G,settings:K});return{config:{id:F.id,projectId:F.projectId,pluginId:F.pluginId,connectionId:F.connectionId,settings:F.settings,createdAt:F.createdAt instanceof Date?F.createdAt.toISOString():F.createdAt,updatedAt:F.updatedAt instanceof Date?F.updatedAt.toISOString():F.updatedAt}}}})});var Fh0=S(()=>{Xh0();Jh0();Gh0();Wh0();Zh0();Kh0();Hh0()});var jV1;var $h0=S(()=>{v1();k0();jV1=k1({name:"TAGS_LIST",description:"List all tags in an organization",annotations:{title:"List Tags",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=B0(Q);return{tags:(await Q.storage.tags.listOrgTags(X.id)).map((G)=>({...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():String(G.createdAt)}))}}})});var SV1;var Vh0=S(()=>{v1();k0();SV1=k1({name:"TAGS_CREATE",description:"Create a new tag in an organization",annotations:{title:"Create Tag",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({name:q.string().min(1).max(50).describe("Tag name")}),outputSchema:q.object({tag:q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")})}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=B0(Q),J=await Q.storage.tags.createTag(X.id,Y.name);return{tag:{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():String(J.createdAt)}}}})});var _V1;var qh0=S(()=>{v1();k0();_V1=k1({name:"TAGS_DELETE",description:"Delete a tag from an organization (removes from all members)",annotations:{title:"Delete Tag",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({tagId:q.string().describe("Tag ID to delete")}),outputSchema:q.object({success:q.boolean()}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=B0(Q),J=await Q.storage.tags.getTag(Y.tagId);if(!J)throw Error("Tag not found");if(J.organizationId!==X.id)throw Error("Tag does not belong to this organization");return await Q.storage.tags.deleteTag(Y.tagId),{success:!0}}})});var vV1;var Bh0=S(()=>{v1();k0();vV1=k1({name:"MEMBER_TAGS_GET",description:"Get tags assigned to a member",annotations:{title:"Get Member Tags",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({memberId:q.string().describe("Member ID")}),outputSchema:q.object({tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=B0(Q);if(!await Q.storage.tags.verifyMemberOrg(Y.memberId,X.id))throw Error(`Member not found in this organization: ${Y.memberId}`);return{tags:(await Q.storage.tags.getMemberTags(Y.memberId)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():String(K.createdAt)}))}}})});var kV1;var Uh0=S(()=>{v1();k0();kV1=k1({name:"MEMBER_TAGS_SET",description:"Set tags for a member (replaces all existing tags)",annotations:{title:"Set Member Tags",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({memberId:q.string().describe("Member ID"),tagIds:q.array(q.string()).describe("Array of tag IDs to assign")}),outputSchema:q.object({success:q.boolean(),tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=B0(Q);if(!await Q.storage.tags.verifyMemberOrg(Y.memberId,X.id))throw Error(`Member not found in this organization: ${Y.memberId}`);for(let K of Y.tagIds){let W=await Q.storage.tags.getTag(K);if(!W)throw Error(`Tag not found: ${K}`);if(W.organizationId!==X.id)throw Error(`Tag does not belong to this organization: ${K}`)}return await Q.storage.tags.setMemberTags(Y.memberId,Y.tagIds),{success:!0,tags:(await Q.storage.tags.getMemberTags(Y.memberId)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():String(K.createdAt)}))}}})});var zh0=S(()=>{$h0();Vh0();qh0();Bh0();Uh0()});var Dh0=S(()=>{zY()});var Oh0,cZ,Lh0,Nh0;var HU=S(()=>{v1();Dh0();Oh0=q.object({id:q.string().describe("Unique message ID"),thread_id:q.string().describe("ID of the parent thread"),metadata:q.unknown().optional().describe("Optional message metadata"),parts:q.array(q.record(q.string(),q.unknown())).describe("Message content parts (AI SDK UIMessagePart format)"),role:q.enum(["user","assistant","system"]).describe("Message role"),created_at:q.string().datetime().describe("Timestamp of creation"),updated_at:q.string().datetime().describe("Timestamp of last update")}),cZ=q.object({id:q.string().describe("Unique thread ID"),organization_id:q.string().describe("Organization this thread belongs to"),title:q.string().describe("Thread title"),description:q.string().nullable().describe("Thread description"),created_at:q.string().datetime().describe("Timestamp of creation"),updated_at:q.string().datetime().describe("Timestamp of last update"),hidden:q.boolean().optional().describe("Whether the thread is hidden"),status:q.enum([...Sz,"expired"]).describe("Thread execution status. 'expired' is virtual -- computed at read time for stale in_progress threads"),created_by:q.string().describe("User ID who created the thread"),updated_by:q.string().nullable().describe("User ID who last updated the thread")}),Lh0=q.object({id:q.string().optional().describe("Optional custom ID for the thread"),title:q.string().describe("Thread title"),description:q.string().nullish().describe("Thread description")}),Nh0=q.object({title:q.string().optional().describe("New thread title"),description:q.string().nullish().describe("New thread description"),hidden:q.boolean().optional().describe("Whether the thread is hidden")})});var QC4,XC4,yV1;var Mh0=S(()=>{v1();k0();HU();DC();QC4=q.object({data:Lh0.describe("Data for the new thread (id is auto-generated if not provided)")}),XC4=q.object({item:cZ.describe("The created thread entity")}),yV1=k1({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",annotations:{title:"Create Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:QC4,outputSchema:XC4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=D9(Q);if(!J)throw Error("User ID required to create thread");let G=Y.data.id??Y$("thrd"),K=await Q.storage.threads.create({id:G,organization_id:X.id,title:Y.data.title,description:Y.data.description,created_by:J});return{item:{...K,hidden:K.hidden??!1}}}})});function T$(Y,Q=Date.now()){let X=Y.status;if(X==="in_progress"){let J=new Date(Y.updated_at).getTime();if(!Number.isFinite(J)||Q-J>1800000)X="expired"}return{...Y,status:X,hidden:Y.hidden??!1}}var JC4,GC4,fV1;var wh0=S(()=>{gX();k0();HU();v1();JC4=dG.extend({where:q.object({created_by:q.string().optional()}).optional()}),GC4=M3(cZ),fV1=k1({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",annotations:{title:"List Threads",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:JC4,outputSchema:GC4,handler:async(Y,Q)=>{await Q.access.check();let X=Q.auth.user?.id;if(!X)throw Error("User ID required to list threads");let J=B0(Q),G=Y.offset??0,K=Y.limit??100,{threads:W,total:Z}=await Q.storage.threads.list(J.id,X,{limit:K,offset:G}),H=G+K<Z,F=Date.now();return{items:W.map(($)=>T$($,F)),totalCount:Z,hasMore:H}}})});var WC4,bV1;var Ah0=S(()=>{gX();k0();HU();WC4=TC(cZ),bV1=k1({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",annotations:{title:"Get Thread",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:EC,outputSchema:WC4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.threads.get(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:T$(J)}}})});var ZC4,KC4,hV1;var Ph0=S(()=>{v1();k0();HU();ZC4=q.object({id:q.string().describe("ID of the thread to update"),data:Nh0.describe("Partial thread data to update")}),KC4=q.object({item:cZ.describe("The updated thread entity")}),hV1=k1({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",annotations:{title:"Update Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:ZC4,outputSchema:KC4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=D9(Q);if(!J)throw Error("User ID required to update thread");let{id:G,data:K}=Y,W=await Q.storage.threads.get(G);if(!W||W.organization_id!==X.id)throw Error("Thread not found in organization");let Z=await Q.storage.threads.update(G,{title:K.title,description:K.description,hidden:K.hidden,updated_by:J});return{item:T$(Z)}}})});var xV1;var Eh0=S(()=>{gX();k0();HU();xV1=k1({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",annotations:{title:"Delete Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:CC,outputSchema:RC(cZ),handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.threads.get(Y.id);if(!J)throw Error(`Thread not found: ${Y.id}`);if(J.organization_id!==X.id)throw Error(`Thread not found: ${Y.id}`);return await Q.storage.threads.delete(Y.id),{item:T$(J)}}})});function Th0(Y){if(!Y)return null;if("field"in Y&&Y.field[0]==="thread_id"&&Y.operator==="eq")return String(Y.value);if("conditions"in Y)for(let Q of Y.conditions){let X=Th0(Q);if(X)return X}return null}var HC4,gV1;var Ch0=S(()=>{gX();k0();HU();HC4=M3(Oh0),gV1=k1({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",annotations:{title:"List Thread Messages",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:dG,outputSchema:HC4,handler:async(Y,Q)=>{let X=B0(Q);await Q.access.check();let J=Th0(Y.where);if(!J)throw Error("thread_id filter is required in where clause");let G=await Q.storage.threads.get(J);if(!G||G.organization_id!==X.id)return{items:[],totalCount:0,hasMore:!1};let K=Y.offset??0,W=Y.limit??100,{messages:Z,total:H}=await Q.storage.threads.listMessages(J,{limit:W,offset:K}),F=K+W<H;return{items:Z,totalCount:H,hasMore:F}}})});var Rh0=S(()=>{Mh0();wh0();Ah0();Ph0();Eh0();Ch0()});var $C4,VC4,uV1;var Ih0=S(()=>{v1();k0();$C4=q.object({id:q.string().min(1)}),VC4=q.object({user:q.object({id:q.string(),name:q.string(),email:q.string(),image:q.string().nullable()}).nullable()}),uV1=k1({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",annotations:{title:"Get User",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:$C4,outputSchema:VC4,handler:async(Y,Q)=>{await Q.access.check(),o1(Q);let X=D9(Q);if(!X)throw Error("Authentication required");let J=await Q.storage.users.findById(Y.id,X);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var jh0=S(()=>{Ih0()});var _h0={};t0(_h0,{managementMCP:()=>zC4,ALL_TOOLS:()=>Sh0});var BC4,UC4,Sh0,zC4=async(Y)=>{let Q=null;if(Y.organization){let G=await Y.storage.organizationSettings.get(Y.organization.id),K=await Y.storage.projects.list(Y.organization.id),W=new Set(G?.enabled_plugins??[]);for(let Z of K)if(Z.enabledPlugins)for(let H of Z.enabledPlugins)W.add(H);Q=W.size>0?[...W]:null}let X=Py0(Sh0,Q),J=new _z({name:"mcp-mesh-management",version:"1.0.0"},{capabilities:{tools:{}}});for(let G of X){let K=G.inputSchema&&typeof G.inputSchema==="object"&&"shape"in G.inputSchema?G.inputSchema:q.object({}),W=G.outputSchema&&typeof G.outputSchema==="object"&&"shape"in G.outputSchema?G.outputSchema:void 0,Z=K.shape,H=W?.shape;J.registerTool(G.name,{description:G.description??"",inputSchema:Z,outputSchema:H,annotations:G.annotations},async(F)=>{Y.access.setToolName(G.name);try{let $=await G.execute(F,Y);return{content:[{type:"text",text:JSON.stringify($)}],structuredContent:$}}catch($){return{content:[{type:"text",text:`Error: ${$.message}`}],isError:!0}}})}return J};var vh0=S(()=>{eF1();Ck();v1();gy0();Zf0();Jb0();Kb0();Ob0();Eb0();Sb0();kb0();lb0();Yh0();Fh0();zh0();Rh0();jh0();BC4=[$V1,VV1,qV1,BV1,UV1,DV1,OV1,LV1,NV1,MV1,wV1,F$1,q$1,B$1,y$1,f$1,b$1,p$1,n$1,i$1,a$1,r$1,o$1,s$1,t$1,e$1,YV1,Zb0,QV1,XV1,JV1,GV1,WV1,ZV1,KV1,HV1,FV1,Q$1,J$1,G$1,X$1,h$1,x$1,g$1,u$1,m$1,l$1,d$1,uV1,Z$1,K$1,H$1,yV1,fV1,bV1,hV1,xV1,gV1,jV1,SV1,_V1,vV1,kV1,AV1,PV1,EV1,TV1,CV1,RV1,IV1],UC4=Ey0(),Sh0=[...BC4,...UC4]});function DC4(Y){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (vh0(),_h0));return Q.map((X)=>{return{name:X.name,inputSchema:q.toJSONSchema(X.inputSchema,{unrepresentable:"any"}),outputSchema:X.outputSchema?q.toJSONSchema(X.outputSchema,{unrepresentable:"any"}):void 0,description:X.description}})},data:Ut(AG(),Y)},{data:Bt()},{data:qt(Y)}]}async function kh0(Y,Q){try{let X=qC(),J=new LZ1(process.env.ENCRYPTION_KEY||""),G=new NZ1(X.db,J),K=new MZ1(X.db),W=DC4(Y);try{await K.create({organizationId:Y,slug:n7,name:LU,description:"Organization administration and settings",enabledPlugins:null,ui:null})}catch(Z){console.warn("Could not create org-admin project (may already exist):",Z)}await Promise.all(W.map(async(Z)=>{let H=null;if(Z.permissions)H=(await iN.api.createApiKey({body:{name:`${Z.data.app_name??crypto.randomUUID()}-mcp`,userId:Q,permissions:Z.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Y},purpose:"default-org-connections"}}}))?.key;let F=await iL({id:"pending",title:Z.data.title,connection_type:Z.data.connection_type,connection_url:Z.data.connection_url,connection_token:Z.data.connection_token,connection_headers:Z.data.connection_headers}).catch(()=>null),$=await Z.getTools?.()??F?.tools??null,V=F?.scopes?.length?F.scopes:null,B=Z.data.id?Z.data.id.startsWith(`${Y}_`)?Z.data.id:`${Y}_${Z.data.id}`:void 0;await G.create({...Z.data,id:B,tools:$,configuration_scopes:V,organization_id:Y,created_by:Q,connection_token:Z.data.connection_token??H})}))}catch(X){console.error("Error creating default MCP connections:",X)}}var yh0=S(()=>{zY();xm();NM0();MM0();wM0();pm();v1();Np()});var fh0;var bh0=S(()=>{fh0=["owner","admin"]});var OC4=(Y)=>{return{defaultSSO:[{domain:Y.domain,providerId:Y.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:Y.MS_CLIENT_ID,clientSecret:Y.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:Y.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},hh0=(Y)=>{if(Y.providerId==="microsoft")return OC4(Y);throw Error(`Unsupported provider: ${Y.providerId}`)};function LC4(Y){return Y.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function NC4(){let Y=Math.floor(Math.random()*gh0.length),Q=Math.floor(Math.random()*xh0.length),X=gh0[Y]??"deco",J=xh0[Q]??"studio";return`${X}-${J}`}function jC4(){let Y=[$I],Q=new URL($I);if(Q.hostname==="localhost")Y.push($I.replace("localhost","127.0.0.1"));else if(Q.hostname==="127.0.0.1")Y.push($I.replace("127.0.0.1","localhost"));return Y}var xh0,gh0,MC4,wC4,Tp,AC4,PC4,EC4,uh0,t9,mh0=void 0,mV1=void 0,TC4=!1,CC4,RC4,IC4,$I,iN;var Np=S(()=>{D21();xk1();Ef1();c41();Db1();Ob1();gh();Pb1();xm();OZ1();UM0();yh0();bh0();xh0=["labs","agent","studio","workspace","systems","core","cloud","works"],gh0=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];MC4=Object.values(G11()).map((Y)=>Y.map((Q)=>Q.name)).flat(),wC4={...wh,self:["*",...MC4]},Tp=WZ(wC4),AC4=Tp.newRole({self:["*"],...u2.statements}),PC4=Tp.newRole({self:["*"],...u2.statements}),EC4=Tp.newRole({self:["*"],...u2.statements}),uh0=Object.values(G11()).map((Y)=>Y.map((Q)=>`self:${Q.name}`)).flat(),t9=hh.auth;if(t9.inviteEmailProviderId&&t9.emailProviders&&t9.emailProviders.length>0){let Y=UC(t9.emailProviders,t9.inviteEmailProviderId);if(Y){let Q=BC(Y);mh0=async(X)=>{let J=X.inviter.user?.name||X.inviter.user?.email,G=`${AG()}/auth/accept-invitation?invitationId=${X.invitation.id}&redirectTo=/`;await Q({to:X.email,subject:`Invitation to join ${X.organization.name}`,html:`
|
|
1479
|
+
`.execute(Y)).rows[0]?.exists)await S4`CREATE ROLE ${S4.id(X)} NOLOGIN`.execute(Y);await S4`GRANT ${S4.id(X)} TO CURRENT_USER`.execute(Y),await S4`GRANT USAGE, CREATE ON SCHEMA ${S4.id(Q)} TO ${S4.id(X)}`.execute(Y),await S4`GRANT ALL ON ALL TABLES IN SCHEMA ${S4.id(Q)} TO ${S4.id(X)}`.execute(Y),await S4`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${S4.id(Q)} TO ${S4.id(X)}`.execute(Y),await S4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${S4.id(Q)} GRANT ALL ON TABLES TO ${S4.id(X)}`.execute(Y),await S4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${S4.id(Q)} GRANT ALL ON SEQUENCES TO ${S4.id(X)}`.execute(Y),await S4`REVOKE ALL ON SCHEMA public FROM ${S4.id(X)}`.execute(Y)}async function $T4(Y,Q,X,J){try{return await Y.transaction().execute(async(G)=>{return await S4`SET LOCAL ROLE ${S4.id(X)}`.execute(G),await S4`SET LOCAL search_path TO ${S4.id(Q)}`.execute(G),await S4.raw(J).execute(G)})}catch(G){if(HT4(G))return await FT4(Y,Q,X),await Y.transaction().execute(async(K)=>{return await S4`SET LOCAL ROLE ${S4.id(X)}`.execute(K),await S4`SET LOCAL search_path TO ${S4.id(Q)}`.execute(K),await S4.raw(J).execute(K)});throw G}}var JT4,WT4,Zb0;var Kb0=S(()=>{v1();k0();JT4=q.object({results:q.array(q.unknown()).optional(),success:q.boolean().optional()});WT4=q.object({sql:q.string().describe("The SQL query to run"),params:q.array(q.any()).describe("The parameters to pass to the SQL query").optional()});Zb0=k1({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",annotations:{title:"Run SQL Query",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:WT4,outputSchema:q.object({result:q.array(JT4)}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=GT4(Y.sql,Y.params||[]);if(!Q.connectionId)throw Error("Connection context required for database access");let J=ZT4(Q.connectionId),G=KT4(Q.connectionId);return{result:[{results:(await $T4(Q.db,J,G,X)).rows,success:!0}]}}})});var Hb0,qT4,Fb0;var d3=S(()=>{v1();Xl();Hb0=q.object({connectionId:q.string().optional().describe("Filter subscriptions by connection ID (optional)")}),qT4=q.object({id:q.string().describe("Subscription ID"),connectionId:q.string().describe("Subscriber connection ID"),eventType:q.string().describe("Event type pattern"),publisher:q.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:q.string().nullable().describe("JSONPath filter expression"),enabled:q.boolean().describe("Whether subscription is enabled"),createdAt:q.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:q.string().datetime().describe("Updated timestamp (ISO 8601)")}),Fb0=q.object({subscriptions:q.array(qT4).describe("List of subscriptions")})});var h$1;var $b0=S(()=>{k0();d3();h$1=k1({name:"EVENT_PUBLISH",description:"Publish an event to the event bus. Supports immediate, scheduled (deliverAt), and recurring (cron) delivery. The source is automatically set to the caller's connection ID.",annotations:{title:"Publish Event",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:IC,outputSchema:jC,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await Q.eventBus.publish(X.id,J,{type:Y.type,subject:Y.subject,data:Y.data,deliverAt:Y.deliverAt,cron:Y.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var x$1;var Vb0=S(()=>{k0();d3();x$1=k1({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",annotations:{title:"Subscribe to Events",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:SC,outputSchema:_C,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await Q.eventBus.subscribe(X.id,{connectionId:J,eventType:Y.eventType,publisher:Y.publisher,filter:Y.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var g$1;var qb0=S(()=>{k0();d3();g$1=k1({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",annotations:{title:"Unsubscribe from Events",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:yC,outputSchema:fC,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await Q.eventBus.getSubscription(X.id,Y.subscriptionId);if(!G)throw Error(`Subscription not found: ${Y.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await Q.eventBus.unsubscribe(X.id,Y.subscriptionId)).success,subscriptionId:Y.subscriptionId}}})});var u$1;var Bb0=S(()=>{k0();d3();u$1=k1({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",annotations:{title:"Cancel Recurring Event",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:bC,outputSchema:hC,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await Q.eventBus.getEvent(X.id,Y.eventId))throw Error(`Event not found: ${Y.eventId}`);if(!(await Q.eventBus.cancelEvent(X.id,Y.eventId,J)).success)throw Error("Failed to cancel event. Either the event is already completed/failed, or you are not the publisher.");return{success:!0,eventId:Y.eventId}}})});var m$1;var Ub0=S(()=>{k0();d3();m$1=k1({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",annotations:{title:"Acknowledge Event",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:xC,outputSchema:gC,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await Q.eventBus.ackEvent(X.id,Y.eventId,J)).success)throw Error("Failed to acknowledge event. Either the event was not found, already delivered, or you are not a subscriber.");return{success:!0,eventId:Y.eventId}}})});var l$1;var zb0=S(()=>{k0();d3();l$1=k1({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",annotations:{title:"List Event Subscriptions",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Hb0,outputSchema:Fb0,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);return await Q.access.check(),{subscriptions:(await Q.eventBus.listSubscriptions(X.id,Y.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}))}}})});var d$1;var Db0=S(()=>{k0();d3();d$1=k1({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",annotations:{title:"Sync Event Subscriptions",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:vC,outputSchema:kC,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=Q.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await Q.eventBus.syncSubscriptions(X.id,{connectionId:J,subscriptions:Y.subscriptions});return{created:G.created,updated:G.updated,deleted:G.deleted,unchanged:G.unchanged,subscriptions:G.subscriptions.map((K)=>({id:K.id,connectionId:K.connectionId,eventType:K.eventType,publisher:K.publisher,filter:K.filter,enabled:K.enabled,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}))}}})});var Ob0=S(()=>{$b0();Vb0();qb0();Bb0();Ub0();zb0();Db0();d3()});var cN=S(()=>{Tk()});function Lb0(){return`/icons/capy-${Math.floor(Math.random()*39)+0}.png`}var UT4,zT4,p$1;var Nb0=S(()=>{v1();k0();cN();UT4=q.object({data:jA.describe("Data for the new virtual MCP")}),zT4=q.object({item:tX.describe("The created virtual MCP entity")}),p$1=k1({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new Virtual MCP",annotations:{title:"Create Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:UT4,outputSchema:zT4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=D9(Q);if(!J)throw Error("User ID required to create virtual MCP");let G={...Y.data,icon:Y.data.icon??Lb0()};return{item:await Q.storage.virtualMcps.create(X.id,J,G)}}})});function DT4(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 P$(Y){return typeof Y==="string"||typeof Y==="number"}function c$1(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 OT4(Y,Q){return Y.connections.some((X)=>X.connection_id===Q)}function Ap(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every((F)=>Ap(Y,F));case"or":return H.some((F)=>Ap(Y,F));case"not":return!H.every((F)=>Ap(Y,F));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join(".");if(K==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return OT4(Y,G)}let W=c$1(Y,K);switch(J){case"eq":return W===G;case"gt":return P$(W)&&P$(G)&&W>G;case"gte":return P$(W)&&P$(G)&&W>=G;case"lt":return P$(W)&&P$(G)&&W<G;case"lte":return P$(W)&&P$(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=DT4(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 LT4(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=c$1(X,K),Z=c$1(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 NT4,MT4,n$1;var Mb0=S(()=>{gX();k0();cN();NT4=dG,MT4=M3(tX),n$1=k1({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",annotations:{title:"List Virtual MCPs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:NT4,outputSchema:MT4,handler:async(Y,Q)=>{await Q.access.check();let X=B0(Q),J=Y.where&&!("conditions"in Y.where)&&Y.where.field.join(".")==="connection_id"&&Y.where.operator==="eq"&&typeof Y.where.value==="string"?Y.where.value:void 0,K=J?await Q.storage.virtualMcps.listByConnectionId(X.id,J):await Q.storage.virtualMcps.list(X.id);if(Y.where)K=K.filter((V)=>Ap(V,Y.where));if(Y.orderBy&&Y.orderBy.length>0)K=LT4(K,Y.orderBy);let W=K.length,Z=Y.offset??0,H=Y.limit??100,F=K.slice(Z,Z+H),$=Z+H<W;return{items:F,totalCount:W,hasMore:$}}})});var wT4,AT4,i$1;var wb0=S(()=>{v1();k0();cN();wT4=q.object({id:q.string().describe("ID of the virtual MCP to retrieve")}),AT4=q.object({item:tX.nullable().describe("The retrieved virtual MCP, or null if not found")}),i$1=k1({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",annotations:{title:"Get Virtual MCP",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:wT4,outputSchema:AT4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.id);if(J&&J.organization_id!==X.id)return{item:null};if(!J)return{item:null};return{item:J}}})});var PT4,ET4,a$1;var Ab0=S(()=>{v1();k0();cN();PT4=q.object({id:q.string().describe("ID of the virtual MCP to update"),data:SA.describe("Partial virtual MCP data to update")}),ET4=q.object({item:tX.describe("The updated virtual MCP entity")}),a$1=k1({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",annotations:{title:"Update Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:PT4,outputSchema:ET4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=D9(Q);if(!J)throw Error("User ID required to update virtual MCP");let G=await Q.storage.virtualMcps.findById(Y.id);if(!G)throw Error(`Virtual MCP not found: ${Y.id}`);if(G.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.id}`);return{item:await Q.storage.virtualMcps.update(Y.id,J,Y.data)}}})});var TT4,CT4,r$1;var Pb0=S(()=>{v1();k0();cN();TT4=q.object({id:q.string().describe("ID of the virtual MCP to delete")}),CT4=q.object({item:tX.describe("The deleted virtual MCP entity")}),r$1=k1({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",annotations:{title:"Delete Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:TT4,outputSchema:CT4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.id);if(!J)throw Error(`Virtual MCP not found: ${Y.id}`);if(J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.id}`);return await Q.storage.virtualMcps.delete(Y.id),{item:J}}})});var Eb0=S(()=>{Nb0();Mb0();wb0();Ab0();Pb0()});var IT4,jT4,o$1;var Tb0=S(()=>{v1();k0();A$();IT4=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP to add the tool to"),data:bf0.describe("Virtual tool data")}),jT4=q.object({item:pZ.describe("The created virtual tool")}),o$1=k1({name:"COLLECTION_VIRTUAL_TOOLS_CREATE",description:"Create a new virtual tool on a Virtual MCP. The tool code should be a JavaScript ES module that exports a default async function: export default async (tools, args) => { ... }. Specify connection_dependencies to indicate which connections this tool uses.",annotations:{title:"Create Virtual Tool",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:IT4,outputSchema:jT4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let G=Y.data.connection_dependencies??[];return{item:await Q.storage.virtualMcps.createVirtualTool(Y.virtual_mcp_id,Y.data,G)}}})});var ST4,_T4,s$1;var Cb0=S(()=>{v1();k0();A$();ST4=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP to list tools for"),limit:q.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:q.number().int().min(0).optional().describe("Number of items to skip")}),_T4=q.object({items:q.array(pZ).describe("Array of virtual tools"),totalCount:q.number().int().min(0).optional().describe("Total number of virtual tools"),hasMore:q.boolean().optional().describe("Whether there are more items available")}),s$1=k1({name:"COLLECTION_VIRTUAL_TOOLS_LIST",description:"List all virtual tools for a Virtual MCP",annotations:{title:"List Virtual Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:ST4,outputSchema:_T4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)return{items:[],totalCount:0,hasMore:!1};let G=await Q.storage.virtualMcps.listVirtualTools(Y.virtual_mcp_id),K=G.length,W=Y.offset??0,Z=Y.limit??100,H=G.slice(W,W+Z),F=W+Z<K;return{items:H,totalCount:K,hasMore:F}}})});var vT4,kT4,t$1;var Rb0=S(()=>{v1();k0();A$();vT4=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Name of the virtual tool to retrieve")}),kT4=q.object({item:pZ.nullable().describe("The retrieved virtual tool, or null if not found")}),t$1=k1({name:"COLLECTION_VIRTUAL_TOOLS_GET",description:"Get a virtual tool by name from a Virtual MCP",annotations:{title:"Get Virtual Tool",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:vT4,outputSchema:kT4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)return{item:null};return{item:await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name)}}})});var yT4,fT4,e$1;var Ib0=S(()=>{v1();k0();A$();yT4=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Current name of the virtual tool to update"),data:hf0.describe("Partial virtual tool data to update")}),fT4=q.object({item:pZ.describe("The updated virtual tool")}),e$1=k1({name:"COLLECTION_VIRTUAL_TOOLS_UPDATE",description:"Update an existing virtual tool on a Virtual MCP. Specify connection_dependencies to update which connections this tool uses.",annotations:{title:"Update Virtual Tool",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:yT4,outputSchema:fT4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);if(!await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name))throw Error(`Virtual tool not found: ${Y.name}`);let K=Y.data.connection_dependencies;return{item:await Q.storage.virtualMcps.updateVirtualTool(Y.virtual_mcp_id,Y.name,Y.data,K)}}})});var bT4,hT4,YV1;var jb0=S(()=>{v1();k0();A$();bT4=q.object({virtual_mcp_id:q.string().describe("ID of the Virtual MCP"),name:q.string().describe("Name of the virtual tool to delete")}),hT4=q.object({item:pZ.describe("The deleted virtual tool")}),YV1=k1({name:"COLLECTION_VIRTUAL_TOOLS_DELETE",description:"Delete a virtual tool from a Virtual MCP",annotations:{title:"Delete Virtual Tool",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:bT4,outputSchema:hT4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==X.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let G=await Q.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name);if(!G)throw Error(`Virtual tool not found: ${Y.name}`);return await Q.storage.virtualMcps.deleteVirtualTool(Y.virtual_mcp_id,Y.name),{item:G}}})});var Sb0=S(()=>{Tb0();Cb0();Rb0();Ib0();jb0()});var gT4,QV1;var _b0=S(()=>{k0();v1();gT4=q.object({id:q.string().optional().describe("Unique log identifier"),organizationId:q.string().describe("Organization ID"),connectionId:q.string().describe("Connection ID"),connectionTitle:q.string().describe("Connection display name"),toolName:q.string().describe("Name of the tool that was called"),input:q.record(q.string(),q.unknown()).describe("Redacted tool input"),output:q.record(q.string(),q.unknown()).describe("Redacted tool output"),isError:q.boolean().describe("Whether the call resulted in an error"),errorMessage:q.string().nullish().describe("Error message if applicable"),durationMs:q.number().describe("Call duration in milliseconds"),timestamp:q.string().describe("ISO 8601 timestamp of the call"),userId:q.string().nullish().describe("User who triggered the call"),requestId:q.string().describe("Unique request identifier"),userAgent:q.string().nullish().describe("Client identifier (x-mesh-client header)"),virtualMcpId:q.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:q.record(q.string(),q.string()).nullish().describe("Custom key-value metadata attached to the log")}),QV1=k1({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",annotations:{title:"List Monitoring Logs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({connectionId:q.string().optional().describe("Filter by connection ID"),excludeConnectionIds:q.array(q.string()).optional().describe("Exclude logs from these connection IDs (e.g. system connections)"),virtualMcpId:q.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:q.string().optional().describe("Filter by tool name"),isError:q.boolean().optional().describe("Filter by error status"),startDate:q.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:q.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:q.number().default(20).describe("Maximum number of results"),offset:q.number().default(0).describe("Offset for pagination"),properties:q.record(q.string(),q.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:q.array(q.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:q.record(q.string(),q.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)"),propertyInValues:q.record(q.string(),q.string()).optional().describe("Filter by exact match within comma-separated values (e.g., user_tags in 'Engineering')")}),outputSchema:q.object({logs:q.array(gT4).describe("Array of monitoring logs"),total:q.number().describe("Total number of logs matching filters"),offset:q.number().describe("Current offset for pagination"),limit:q.number().describe("Current limit for pagination")}),handler:async(Y,Q)=>{let X=B0(Q),G=Y.properties||Y.propertyKeys||Y.propertyPatterns||Y.propertyInValues?{properties:Y.properties,propertyKeys:Y.propertyKeys,propertyPatterns:Y.propertyPatterns,propertyInValues:Y.propertyInValues}:void 0,K={organizationId:X.id,connectionId:Y.connectionId,excludeConnectionIds:Y.excludeConnectionIds,virtualMcpId:Y.virtualMcpId,toolName:Y.toolName,isError:Y.isError,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0,limit:Y.limit,offset:Y.offset,propertyFilters:G},W=await Q.storage.monitoring.query(K);return{logs:W.logs.map((Z)=>({...Z,timestamp:Z.timestamp instanceof Date?Z.timestamp.toISOString():Z.timestamp})),total:W.total,offset:Y.offset,limit:Y.limit}}})});var XV1;var vb0=S(()=>{k0();v1();XV1=k1({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",annotations:{title:"Get Monitoring Stats",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({startDate:q.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:q.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:q.object({totalCalls:q.number().describe("Total number of tool calls"),errorRate:q.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:q.number().describe("Average call duration in milliseconds"),errorRatePercent:q.string().describe("Error rate as a percentage string")}),handler:async(Y,Q)=>{let J={organizationId:B0(Q).id,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0},G=await Q.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var kb0=S(()=>{_b0();vb0()});var mT4,lT4,dT4,pT4,cT4,KI,HI,E$,nT4,iT4,yb0;var nN=S(()=>{v1();mT4=q.enum(["sum","avg","min","max","count","last"]).describe("Aggregation function to apply"),lT4=q.enum(["metric","timeseries","table"]).describe("Widget display type"),dT4=q.object({path:q.string().describe("JSONPath to extract value, e.g., '$.usage.total_tokens'"),from:q.enum(["input","output"]).describe("Extract from tool call input or output")}),pT4=q.object({fn:mT4,groupBy:q.string().optional().describe("Optional JSONPath for grouping results"),interval:q.string().optional().describe("For timeseries widgets: interval like '1h', '1d', '15m'")}),cT4=q.object({connectionIds:q.array(q.string()).optional().describe("Filter to specific connections"),toolNames:q.array(q.string()).optional().describe("Filter to specific tools")}),KI=q.object({id:q.string().describe("Unique widget identifier"),name:q.string().describe("Widget display name"),type:lT4,source:dT4,aggregation:pT4,filter:cT4.optional()}),HI=q.object({connectionIds:q.array(q.string()).optional().describe("Filter to specific connections"),virtualMcpIds:q.array(q.string()).optional().describe("Filter to specific virtual MCPs/agents"),toolNames:q.array(q.string()).optional().describe("Filter to specific tools"),propertyFilters:q.record(q.string(),q.string()).optional().describe("Filter by exact metadata property key=value matches (e.g., { environment: 'production' })")}),E$=q.object({id:q.string().describe("Unique dashboard identifier"),organizationId:q.string().describe("Organization ID"),name:q.string().describe("Dashboard name"),description:q.string().nullable().describe("Dashboard description"),filters:HI.nullable().describe("Global filters applied to all widgets"),widgets:q.array(KI).describe("Widget definitions"),createdBy:q.string().describe("User ID who created the dashboard"),createdAt:q.string().describe("Creation timestamp"),updatedAt:q.string().describe("Last update timestamp")}),nT4=q.object({key:q.string().describe("Group key value"),value:q.number().describe("Aggregated value for this group")}),iT4=q.object({timestamp:q.string().describe("Time bucket timestamp"),value:q.number().describe("Aggregated value for this time bucket")}),yb0=q.object({widgetId:q.string().describe("Widget ID this result is for"),value:q.number().nullable().describe("Aggregated value (for metric type)"),groups:q.array(nT4).optional().describe("Grouped results (when groupBy is specified)"),timeseries:q.array(iT4).optional().describe("Timeseries data (for timeseries type)")})});var JV1;var fb0=S(()=>{k0();v1();nN();JV1=k1({name:"MONITORING_DASHBOARD_CREATE",description:"Create a new monitoring dashboard with JSONPath widgets",annotations:{title:"Create Monitoring Dashboard",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({name:q.string().min(1).describe("Dashboard name"),description:q.string().optional().describe("Dashboard description"),filters:HI.optional().describe("Global filters applied to all widgets"),widgets:q.array(KI).min(1).describe("Widget definitions (at least one required)")}),outputSchema:E$,handler:async(Y,Q)=>{let X=B0(Q),J=Q.auth.user?.id;if(!J)throw Error("User authentication required");let G=await Q.storage.monitoringDashboards.create(X.id,J,{name:Y.name,description:Y.description,filters:Y.filters,widgets:Y.widgets});return{id:G.id,organizationId:G.organizationId,name:G.name,description:G.description,filters:G.filters,widgets:G.widgets,createdBy:G.createdBy,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}})});var GV1;var bb0=S(()=>{k0();v1();nN();GV1=k1({name:"MONITORING_DASHBOARD_GET",description:"Get a monitoring dashboard by ID",annotations:{title:"Get Monitoring Dashboard",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string().describe("Dashboard ID")}),outputSchema:E$.nullable(),handler:async(Y,Q)=>{let X=B0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)return null;return{id:J.id,organizationId:J.organizationId,name:J.name,description:J.description,filters:J.filters,widgets:J.widgets,createdBy:J.createdBy,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var WV1;var hb0=S(()=>{k0();v1();nN();WV1=k1({name:"MONITORING_DASHBOARD_LIST",description:"List all monitoring dashboards for the organization",annotations:{title:"List Monitoring Dashboards",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({dashboards:q.array(E$).describe("List of dashboards"),total:q.number().describe("Total number of dashboards")}),handler:async(Y,Q)=>{let X=B0(Q),J=await Q.storage.monitoringDashboards.list(X.id);return{dashboards:J.map((G)=>({id:G.id,organizationId:G.organizationId,name:G.name,description:G.description,filters:G.filters,widgets:G.widgets,createdBy:G.createdBy,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt})),total:J.length}}})});var ZV1;var xb0=S(()=>{k0();v1();nN();ZV1=k1({name:"MONITORING_DASHBOARD_UPDATE",description:"Update an existing monitoring dashboard",annotations:{title:"Update Monitoring Dashboard",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string().describe("Dashboard ID to update"),name:q.string().optional().describe("New dashboard name"),description:q.string().nullable().optional().describe("New dashboard description"),filters:HI.nullable().optional().describe("New global filters"),widgets:q.array(KI).optional().describe("New widget definitions")}),outputSchema:E$,handler:async(Y,Q)=>{let X=B0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.id} not found`);let G={};if(Y.name!==void 0)G.name=Y.name;if(Y.description!==void 0)G.description=Y.description;if(Y.filters!==void 0)G.filters=Y.filters;if(Y.widgets!==void 0)G.widgets=Y.widgets;let K=await Q.storage.monitoringDashboards.update(Y.id,G);return{id:K.id,organizationId:K.organizationId,name:K.name,description:K.description,filters:K.filters,widgets:K.widgets,createdBy:K.createdBy,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}}})});var KV1;var gb0=S(()=>{k0();v1();KV1=k1({name:"MONITORING_DASHBOARD_DELETE",description:"Delete a monitoring dashboard",annotations:{title:"Delete Monitoring Dashboard",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string().describe("Dashboard ID to delete")}),outputSchema:q.object({success:q.boolean().describe("Whether the deletion was successful")}),handler:async(Y,Q)=>{let X=B0(Q),J=await Q.storage.monitoringDashboards.get(Y.id);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.id} not found`);return await Q.storage.monitoringDashboards.delete(Y.id),{success:!0}}})});var HV1;var ub0=S(()=>{k0();v1();nN();HV1=k1({name:"MONITORING_DASHBOARD_QUERY",description:"Execute a dashboard's widgets and return aggregated monitoring data",annotations:{title:"Query Monitoring Dashboard",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({dashboardId:q.string().describe("Dashboard ID to query"),timeRange:q.object({startDate:q.string().datetime().describe("Start of time range (ISO 8601)"),endDate:q.string().datetime().describe("End of time range (ISO 8601)")}).optional().describe("Time range for the query (defaults to last 24 hours)"),propertyFilters:q.object({properties:q.record(q.string(),q.string()).optional().describe("Exact match: property key equals value"),propertyKeys:q.array(q.string()).optional().describe("Exists: filter logs that have these property keys"),propertyPatterns:q.record(q.string(),q.string()).optional().describe("Pattern match: property value matches pattern (SQL LIKE, use % as wildcard)"),propertyInValues:q.record(q.string(),q.string()).optional().describe("In match: exact match within comma-separated values")}).optional().describe("Runtime property filters applied to all widgets (merged with dashboard-level filters)")}),outputSchema:q.object({dashboardId:q.string().describe("Dashboard ID"),results:q.array(yb0).describe("Widget query results"),timeRange:q.object({startDate:q.string(),endDate:q.string()}).describe("Time range used for the query")}),handler:async(Y,Q)=>{let X=B0(Q),J=await Q.storage.monitoringDashboards.get(Y.dashboardId);if(!J||J.organizationId!==X.id)throw Error(`Dashboard ${Y.dashboardId} not found`);let G=new Date,K=Y.timeRange?.startDate?new Date(Y.timeRange.startDate):new Date(G.getTime()-86400000),W=Y.timeRange?.endDate?new Date(Y.timeRange.endDate):G,Z=await Promise.all(J.widgets.map(async(H)=>{let F=J.filters?.propertyFilters,$=Y.propertyFilters,V=F||$?{properties:{...F,...$?.properties},propertyKeys:$?.propertyKeys,propertyPatterns:$?.propertyPatterns,propertyInValues:$?.propertyInValues}:void 0,B={connectionIds:H.filter?.connectionIds??J.filters?.connectionIds??void 0,virtualMcpIds:J.filters?.virtualMcpIds??void 0,toolNames:H.filter?.toolNames??J.filters?.toolNames??void 0,startDate:K,endDate:W,propertyFilters:V};try{let U=await Q.storage.monitoring.aggregate({organizationId:X.id,path:H.source.path,from:H.source.from,aggregation:H.aggregation.fn,groupBy:H.aggregation.groupBy,interval:H.aggregation.interval,filters:B});return{widgetId:H.id,value:U.value,groups:U.groups,timeseries:U.timeseries}}catch(U){return console.error(`Widget ${H.id} aggregation failed:`,U),{widgetId:H.id,value:null,groups:void 0,timeseries:void 0}}}));return{dashboardId:Y.dashboardId,results:Z,timeRange:{startDate:K.toISOString(),endDate:W.toISOString()}}}})});var aT4,FV1;var mb0=S(()=>{k0();v1();aT4=q.object({type:q.enum(["metric","timeseries","table"]),source:q.object({path:q.string().describe("JSONPath to extract value from"),from:q.enum(["input","output"]).describe("Extract from input or output")}),aggregation:q.object({fn:q.enum(["sum","avg","min","max","count","last"]).describe("Aggregation function"),groupBy:q.string().optional().describe("JSONPath for grouping (table)"),interval:q.string().optional().describe("Time interval for timeseries (15m, 1h, 1d)")}),filter:q.object({connectionIds:q.array(q.string()).optional(),toolNames:q.array(q.string()).optional()}).optional()}),FV1=k1({name:"MONITORING_WIDGET_PREVIEW",description:"Preview a widget aggregation without saving. Used to test queries in the dashboard editor.",annotations:{title:"Preview Monitoring Widget",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({widget:aT4.describe("Widget configuration to preview"),timeRange:q.object({startDate:q.string().datetime().describe("Start of time range (ISO 8601)"),endDate:q.string().datetime().describe("End of time range (ISO 8601)")}).optional().describe("Time range for the query (defaults to last 24 hours)"),propertyFilters:q.object({properties:q.record(q.string(),q.string()).optional().describe("Exact match: property key equals value"),propertyKeys:q.array(q.string()).optional().describe("Exists: filter logs that have these property keys"),propertyPatterns:q.record(q.string(),q.string()).optional().describe("Pattern match: property value matches pattern (SQL LIKE)"),propertyInValues:q.record(q.string(),q.string()).optional().describe("In match: exact match within comma-separated values")}).optional().describe("Property filters to apply")}),outputSchema:q.object({value:q.number().nullable().optional().describe("Aggregated value"),groups:q.array(q.object({key:q.string(),value:q.number()})).optional().describe("Grouped results for table widgets"),timeseries:q.array(q.object({timestamp:q.string(),value:q.number()})).optional().describe("Timeseries data points"),matchedRecords:q.number().describe("Number of records that matched"),timeRange:q.object({startDate:q.string(),endDate:q.string()}).describe("Time range used for the query")}),handler:async(Y,Q)=>{let X=B0(Q),{widget:J,timeRange:G}=Y,K=new Date,W=G?.startDate?new Date(G.startDate):new Date(K.getTime()-86400000),Z=G?.endDate?new Date(G.endDate):K,H={connectionIds:J.filter?.connectionIds,toolNames:J.filter?.toolNames,startDate:W,endDate:Z,propertyFilters:Y.propertyFilters};try{let F=await Q.storage.monitoring.countMatched({organizationId:X.id,path:J.source.path,from:J.source.from,filters:H}),$=await Q.storage.monitoring.aggregate({organizationId:X.id,path:J.source.path,from:J.source.from,aggregation:J.aggregation.fn,groupBy:J.aggregation.groupBy,interval:J.aggregation.interval,filters:H});return{value:$.value,groups:$.groups,timeseries:$.timeseries,matchedRecords:F,timeRange:{startDate:W.toISOString(),endDate:Z.toISOString()}}}catch(F){return console.error("Widget preview aggregation failed:",F),{value:null,matchedRecords:0,timeRange:{startDate:W.toISOString(),endDate:Z.toISOString()}}}}})});var lb0=S(()=>{fb0();bb0();hb0();xb0();gb0();ub0();mb0()});var $V1;var db0=S(()=>{v1();k0();$V1=k1({name:"ORGANIZATION_CREATE",description:"Create a new organization",annotations:{title:"Create Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({slug:q.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:q.string().min(1).max(255),description:q.string().optional()}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),members:q.array(q.any()).optional()}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=D9(Q);if(!X)throw Error("User ID required to create organization");let J=await Q.boundAuth.organization.create({name:Y.name,slug:Y.slug,metadata:Y.description?{description:Y.description}:void 0,userId:X});if(!J)throw Error("Failed to create organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var VV1;var pb0=S(()=>{v1();k0();VV1=k1({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",annotations:{title:"List Organizations",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({userId:q.string().optional()}),outputSchema:q.object({organizations:q.array(q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=D9(Q),J=Y.userId||X;if(!J)throw Error("User ID required to list organizations");return{organizations:(await Q.boundAuth.organization.list(J)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var qV1;var cb0=S(()=>{v1();k0();qV1=k1({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",annotations:{title:"Get Organization",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),members:q.array(q.any()).optional(),invitations:q.array(q.any()).optional()}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=await Q.boundAuth.organization.get();if(!X)throw Error("No active organization found");let J=new Date,G=X.invitations?.filter((K)=>new Date(K.expiresAt)>J);return{...X,invitations:G,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt}}})});var BV1;var nb0=S(()=>{v1();k0();BV1=k1({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",annotations:{title:"Update Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string(),slug:q.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:q.string().min(1).max(255).optional(),description:q.string().optional()}),outputSchema:q.object({id:q.string(),name:q.string(),slug:q.string(),logo:q.string().nullable().optional(),metadata:q.any().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X={};if(Y.name)X.name=Y.name;if(Y.slug)X.slug=Y.slug;if(Y.description)X.metadata={description:Y.description};let J=await Q.boundAuth.organization.update({organizationId:Y.id,data:X});if(!J)throw Error("Failed to update organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var UV1;var ib0=S(()=>{v1();k0();UV1=k1({name:"ORGANIZATION_DELETE",description:"Delete an organization",annotations:{title:"Delete Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({id:q.string()}),outputSchema:q.object({success:q.boolean(),id:q.string()}),handler:async(Y,Q)=>{return o1(Q),await Q.access.check(),await Q.boundAuth.organization.delete(Y.id),{success:!0,id:Y.id}}})});var FI;var zV1=S(()=>{v1();FI=q.object({title:q.string(),url:q.string(),icon:q.string()})});var DV1;var ab0=S(()=>{v1();k0();zV1();DV1=k1({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",annotations:{title:"Get Organization Settings",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({organizationId:q.string(),sidebar_items:q.array(FI).nullable().optional(),enabled_plugins:q.array(q.string()).nullable().optional(),createdAt:q.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.storage.organizationSettings.get(X);if(!J)return{organizationId:X};return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var OV1;var rb0=S(()=>{v1();k0();zV1();OV1=k1({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",annotations:{title:"Update Organization Settings",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string(),sidebar_items:q.array(FI).optional(),enabled_plugins:q.array(q.string()).optional()}),outputSchema:q.object({organizationId:q.string(),sidebar_items:q.array(FI).nullable().optional(),enabled_plugins:q.array(q.string()).nullable().optional(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{if(o1(Q),await Q.access.check(),Q.organization&&Q.organization.id!==Y.organizationId)throw Error("Cannot update settings for a different organization");let X=await Q.storage.organizationSettings.upsert(Y.organizationId,{sidebar_items:Y.sidebar_items,enabled_plugins:Y.enabled_plugins});return{...X,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt,updatedAt:X.updatedAt instanceof Date?X.updatedAt.toISOString():X.updatedAt}}})});var LV1;var ob0=S(()=>{v1();k0();LV1=k1({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",annotations:{title:"Add Organization Member",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),userId:q.string(),role:q.array(q.string())}),outputSchema:q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.union([q.string(),q.array(q.string())]),createdAt:q.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");if(X!==Q.organization?.id)throw Error("Organization ID does not match authenticated organization");let J=await Q.boundAuth.organization.addMember({organizationId:X,userId:Y.userId,role:Y.role});if(!J)throw Error("Failed to add member");return{...J,role:J.role,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var NV1;var sb0=S(()=>{v1();k0();NV1=k1({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",annotations:{title:"Remove Organization Member",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),memberIdOrEmail:q.string()}),outputSchema:q.object({success:q.boolean(),memberIdOrEmail:q.string()}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");return await Q.boundAuth.organization.removeMember({organizationId:X,memberIdOrEmail:Y.memberIdOrEmail}),{success:!0,memberIdOrEmail:Y.memberIdOrEmail}}})});var MV1;var tb0=S(()=>{v1();k0();MV1=k1({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",annotations:{title:"List Organization Members",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({limit:q.number().optional(),offset:q.number().optional()}),outputSchema:q.object({members:q.array(q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.string(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),user:q.object({id:q.string(),name:q.string(),email:q.string(),image:q.string().optional()}).optional()}))}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.boundAuth.organization.listMembers({organizationId:X,limit:Y.limit,offset:Y.offset});return{members:(Array.isArray(J)?J:[]).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var wV1;var eb0=S(()=>{v1();k0();wV1=k1({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",annotations:{title:"Update Member Role",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().optional(),memberId:q.string(),role:q.array(q.string())}),outputSchema:q.object({id:q.string(),organizationId:q.string(),userId:q.string(),role:q.union([q.literal("admin"),q.literal("member"),q.literal("owner")]),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),user:q.object({email:q.string(),name:q.string(),image:q.string().optional()})}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=Y.organizationId||Q.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let J=await Q.boundAuth.organization.updateMemberRole({organizationId:X,memberId:Y.memberId,role:Y.role});if(!J)throw Error("Failed to update member role");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var Yh0=S(()=>{db0();pb0();cb0();nb0();ib0();ab0();rb0();ob0();sb0();tb0();eb0()});var sT4,Pp,tT4,ZU,Qh0,Ep;var KU=S(()=>{v1();sT4=q.object({banner:q.string().nullable(),bannerColor:q.string().nullable(),icon:q.string().nullable(),themeColor:q.string().nullable()}),Pp=q.object({banner:q.string().nullable().optional(),bannerColor:q.string().nullable().optional(),icon:q.string().nullable().optional(),themeColor:q.string().nullable().optional()}),tT4=q.object({id:q.string(),title:q.string(),icon:q.string().nullable()}),ZU=q.object({id:q.string(),organizationId:q.string(),slug:q.string(),name:q.string(),description:q.string().nullable(),enabledPlugins:q.array(q.string()).nullable(),ui:sT4.nullable(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")}),Qh0=ZU.omit({organizationId:!0}).extend({boundConnections:q.array(tT4)}),Ep=q.object({id:q.string(),projectId:q.string(),pluginId:q.string(),connectionId:q.string().nullable(),settings:q.record(q.string(),q.unknown()).nullable(),createdAt:q.string().datetime().describe("ISO 8601 timestamp"),updatedAt:q.string().datetime().describe("ISO 8601 timestamp")})});var AV1;var Xh0=S(()=>{v1();k0();KU();AV1=k1({name:"PROJECT_LIST",description:"List all projects in an organization",annotations:{title:"List Projects",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().describe("Organization ID to list projects for")}),outputSchema:q.object({projects:q.array(Qh0)}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=await Q.storage.projects.list(Y.organizationId),J=X.map((K)=>K.id),G=await Q.storage.projectPluginConfigs.getBoundConnectionsForProjects(J);return{projects:X.map((K)=>({id:K.id,slug:K.slug,name:K.name,description:K.description,enabledPlugins:K.enabledPlugins,ui:K.ui,boundConnections:G.get(K.id)??[],createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}))}}})});var PV1;var Jh0=S(()=>{v1();k0();KU();PV1=k1({name:"PROJECT_GET",description:"Get a project by ID or slug",annotations:{title:"Get Project",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().describe("Organization ID"),projectId:q.string().optional().describe("Project ID (either this or slug required)"),slug:q.string().optional().describe("Project slug (either this or projectId required)")}).refine((Y)=>Y.projectId||Y.slug,{message:"Either projectId or slug must be provided"}),outputSchema:q.object({project:ZU.nullable()}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=null;if(Y.projectId)X=await Q.storage.projects.get(Y.projectId);else if(Y.slug)X=await Q.storage.projects.getBySlug(Y.organizationId,Y.slug);if(!X)return{project:null};return{project:{id:X.id,organizationId:X.organizationId,slug:X.slug,name:X.name,description:X.description,enabledPlugins:X.enabledPlugins,ui:X.ui,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt,updatedAt:X.updatedAt instanceof Date?X.updatedAt.toISOString():X.updatedAt}}}})});var EV1;var Gh0=S(()=>{v1();zY();k0();KU();EV1=k1({name:"PROJECT_CREATE",description:"Create a new project in an organization",annotations:{title:"Create Project",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({organizationId:q.string().describe("Organization ID"),slug:q.string().min(1).max(100).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens").describe("URL-friendly identifier"),name:q.string().min(1).max(200).describe("Display name"),description:q.string().max(1000).nullable().optional().describe("Project description"),enabledPlugins:q.array(q.string()).nullable().optional().describe("Plugin IDs to enable"),ui:Pp.nullable().optional().describe("UI customization")}),outputSchema:q.object({project:ZU}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let{organizationId:X,slug:J,name:G,description:K,enabledPlugins:W,ui:Z}=Y;if(J===n7)throw Error(`Slug "${n7}" is reserved`);if(await Q.storage.projects.getBySlug(X,J))throw Error(`Project with slug "${J}" already exists in this organization`);let F=Z?{banner:Z.banner??null,bannerColor:Z.bannerColor??null,icon:Z.icon??null,themeColor:Z.themeColor??null}:null,$=await Q.storage.projects.create({organizationId:X,slug:J,name:G,description:K??null,enabledPlugins:W??null,ui:F});return{project:{id:$.id,organizationId:$.organizationId,slug:$.slug,name:$.name,description:$.description,enabledPlugins:$.enabledPlugins,ui:$.ui,createdAt:$.createdAt instanceof Date?$.createdAt.toISOString():$.createdAt,updatedAt:$.updatedAt instanceof Date?$.updatedAt.toISOString():$.updatedAt}}}})});var TV1;var Wh0=S(()=>{v1();k0();KU();TV1=k1({name:"PROJECT_UPDATE",description:"Update a project's details",annotations:{title:"Update Project",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID to update"),name:q.string().min(1).max(200).optional().describe("New display name"),description:q.string().max(1000).nullable().optional().describe("New description"),enabledPlugins:q.array(q.string()).nullable().optional().describe("Updated plugin IDs"),ui:Pp.nullable().optional().describe("Updated UI customization")}),outputSchema:q.object({project:ZU.nullable()}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let{projectId:X,name:J,description:G,enabledPlugins:K,ui:W}=Y,Z={};if(J!==void 0)Z.name=J;if(G!==void 0)Z.description=G;if(K!==void 0)Z.enabledPlugins=K;if(W!==void 0)Z.ui=W?{banner:W.banner??null,bannerColor:W.bannerColor??null,icon:W.icon??null,themeColor:W.themeColor??null}:null;let H=await Q.storage.projects.update(X,Z);if(!H)return{project:null};return{project:{id:H.id,organizationId:H.organizationId,slug:H.slug,name:H.name,description:H.description,enabledPlugins:H.enabledPlugins,ui:H.ui,createdAt:H.createdAt instanceof Date?H.createdAt.toISOString():H.createdAt,updatedAt:H.updatedAt instanceof Date?H.updatedAt.toISOString():H.updatedAt}}}})});var CV1;var Zh0=S(()=>{v1();zY();k0();CV1=k1({name:"PROJECT_DELETE",description:"Delete a project (cannot delete org-admin)",annotations:{title:"Delete Project",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID to delete")}),outputSchema:q.object({success:q.boolean(),message:q.string().optional()}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let{projectId:X}=Y,J=await Q.storage.projects.get(X);if(!J)return{success:!1,message:"Project not found"};if(J.slug===n7)return{success:!1,message:"Cannot delete the org-admin project"};return{success:await Q.storage.projects.delete(X)}}})});var RV1;var Kh0=S(()=>{v1();k0();KU();RV1=k1({name:"PROJECT_PLUGIN_CONFIG_GET",description:"Get plugin configuration for a project",annotations:{title:"Get Project Plugin Config",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID"),pluginId:q.string().describe("Plugin ID")}),outputSchema:q.object({config:Ep.nullable()}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let{projectId:X,pluginId:J}=Y,G=await Q.storage.projectPluginConfigs.get(X,J);if(!G)return{config:null};return{config:{id:G.id,projectId:G.projectId,pluginId:G.pluginId,connectionId:G.connectionId,settings:G.settings,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var IV1;var Hh0=S(()=>{v1();k0();KU();Dp();IV1=k1({name:"PROJECT_PLUGIN_CONFIG_UPDATE",description:"Update or create plugin configuration for a project",annotations:{title:"Update Project Plugin Config",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({projectId:q.string().describe("Project ID"),pluginId:q.string().describe("Plugin ID"),connectionId:q.string().nullable().optional().describe("MCP connection to bind"),settings:q.record(q.string(),q.unknown()).nullable().optional().describe("Plugin-specific settings")}),outputSchema:q.object({config:Ep}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let{projectId:X,pluginId:J,connectionId:G,settings:K}=Y,W=D9(Q),Z=await Q.storage.projects.get(X);if(!Z)throw Error(`Project not found: ${X}`);let H=G?await Q.storage.connections.findById(G):null;if(G&&Z.organizationId&&!H&&gN()){if(zp(G,Z.organizationId)){if(!W)throw Error("User ID required to create dev-assets connection");let $=uN(Z.organizationId,AG());await Q.storage.connections.create({...$,organization_id:Z.organizationId,created_by:W})}}let F=await Q.storage.projectPluginConfigs.upsert(X,J,{connectionId:G,settings:K});return{config:{id:F.id,projectId:F.projectId,pluginId:F.pluginId,connectionId:F.connectionId,settings:F.settings,createdAt:F.createdAt instanceof Date?F.createdAt.toISOString():F.createdAt,updatedAt:F.updatedAt instanceof Date?F.updatedAt.toISOString():F.updatedAt}}}})});var Fh0=S(()=>{Xh0();Jh0();Gh0();Wh0();Zh0();Kh0();Hh0()});var jV1;var $h0=S(()=>{v1();k0();jV1=k1({name:"TAGS_LIST",description:"List all tags in an organization",annotations:{title:"List Tags",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({}),outputSchema:q.object({tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=B0(Q);return{tags:(await Q.storage.tags.listOrgTags(X.id)).map((G)=>({...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():String(G.createdAt)}))}}})});var SV1;var Vh0=S(()=>{v1();k0();SV1=k1({name:"TAGS_CREATE",description:"Create a new tag in an organization",annotations:{title:"Create Tag",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q.object({name:q.string().min(1).max(50).describe("Tag name")}),outputSchema:q.object({tag:q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")})}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=B0(Q),J=await Q.storage.tags.createTag(X.id,Y.name);return{tag:{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():String(J.createdAt)}}}})});var _V1;var qh0=S(()=>{v1();k0();_V1=k1({name:"TAGS_DELETE",description:"Delete a tag from an organization (removes from all members)",annotations:{title:"Delete Tag",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({tagId:q.string().describe("Tag ID to delete")}),outputSchema:q.object({success:q.boolean()}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=B0(Q),J=await Q.storage.tags.getTag(Y.tagId);if(!J)throw Error("Tag not found");if(J.organizationId!==X.id)throw Error("Tag does not belong to this organization");return await Q.storage.tags.deleteTag(Y.tagId),{success:!0}}})});var vV1;var Bh0=S(()=>{v1();k0();vV1=k1({name:"MEMBER_TAGS_GET",description:"Get tags assigned to a member",annotations:{title:"Get Member Tags",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({memberId:q.string().describe("Member ID")}),outputSchema:q.object({tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=B0(Q);if(!await Q.storage.tags.verifyMemberOrg(Y.memberId,X.id))throw Error(`Member not found in this organization: ${Y.memberId}`);return{tags:(await Q.storage.tags.getMemberTags(Y.memberId)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():String(K.createdAt)}))}}})});var kV1;var Uh0=S(()=>{v1();k0();kV1=k1({name:"MEMBER_TAGS_SET",description:"Set tags for a member (replaces all existing tags)",annotations:{title:"Set Member Tags",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q.object({memberId:q.string().describe("Member ID"),tagIds:q.array(q.string()).describe("Array of tag IDs to assign")}),outputSchema:q.object({success:q.boolean(),tags:q.array(q.object({id:q.string(),organizationId:q.string(),name:q.string(),createdAt:q.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,Q)=>{o1(Q),await Q.access.check();let X=B0(Q);if(!await Q.storage.tags.verifyMemberOrg(Y.memberId,X.id))throw Error(`Member not found in this organization: ${Y.memberId}`);for(let K of Y.tagIds){let W=await Q.storage.tags.getTag(K);if(!W)throw Error(`Tag not found: ${K}`);if(W.organizationId!==X.id)throw Error(`Tag does not belong to this organization: ${K}`)}return await Q.storage.tags.setMemberTags(Y.memberId,Y.tagIds),{success:!0,tags:(await Q.storage.tags.getMemberTags(Y.memberId)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():String(K.createdAt)}))}}})});var zh0=S(()=>{$h0();Vh0();qh0();Bh0();Uh0()});var Dh0=S(()=>{zY()});var Oh0,cZ,Lh0,Nh0;var HU=S(()=>{v1();Dh0();Oh0=q.object({id:q.string().describe("Unique message ID"),thread_id:q.string().describe("ID of the parent thread"),metadata:q.unknown().optional().describe("Optional message metadata"),parts:q.array(q.record(q.string(),q.unknown())).describe("Message content parts (AI SDK UIMessagePart format)"),role:q.enum(["user","assistant","system"]).describe("Message role"),created_at:q.string().datetime().describe("Timestamp of creation"),updated_at:q.string().datetime().describe("Timestamp of last update")}),cZ=q.object({id:q.string().describe("Unique thread ID"),organization_id:q.string().describe("Organization this thread belongs to"),title:q.string().describe("Thread title"),description:q.string().nullable().describe("Thread description"),created_at:q.string().datetime().describe("Timestamp of creation"),updated_at:q.string().datetime().describe("Timestamp of last update"),hidden:q.boolean().optional().describe("Whether the thread is hidden"),status:q.enum([...Sz,"expired"]).describe("Thread execution status. 'expired' is virtual -- computed at read time for stale in_progress threads"),created_by:q.string().describe("User ID who created the thread"),updated_by:q.string().nullable().describe("User ID who last updated the thread")}),Lh0=q.object({id:q.string().optional().describe("Optional custom ID for the thread"),title:q.string().describe("Thread title"),description:q.string().nullish().describe("Thread description")}),Nh0=q.object({title:q.string().optional().describe("New thread title"),description:q.string().nullish().describe("New thread description"),hidden:q.boolean().optional().describe("Whether the thread is hidden")})});var QC4,XC4,yV1;var Mh0=S(()=>{v1();k0();HU();DC();QC4=q.object({data:Lh0.describe("Data for the new thread (id is auto-generated if not provided)")}),XC4=q.object({item:cZ.describe("The created thread entity")}),yV1=k1({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",annotations:{title:"Create Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:QC4,outputSchema:XC4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=D9(Q);if(!J)throw Error("User ID required to create thread");let G=Y.data.id??Y$("thrd"),K=await Q.storage.threads.create({id:G,organization_id:X.id,title:Y.data.title,description:Y.data.description,created_by:J});return{item:{...K,hidden:K.hidden??!1}}}})});function T$(Y,Q=Date.now()){let X=Y.status;if(X==="in_progress"){let J=new Date(Y.updated_at).getTime();if(!Number.isFinite(J)||Q-J>1800000)X="expired"}return{...Y,status:X,hidden:Y.hidden??!1}}var JC4,GC4,fV1;var wh0=S(()=>{gX();k0();HU();v1();JC4=dG.extend({where:q.object({created_by:q.string().optional()}).optional()}),GC4=M3(cZ),fV1=k1({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",annotations:{title:"List Threads",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:JC4,outputSchema:GC4,handler:async(Y,Q)=>{await Q.access.check();let X=Q.auth.user?.id;if(!X)throw Error("User ID required to list threads");let J=B0(Q),G=Y.offset??0,K=Y.limit??100,{threads:W,total:Z}=await Q.storage.threads.list(J.id,X,{limit:K,offset:G}),H=G+K<Z,F=Date.now();return{items:W.map(($)=>T$($,F)),totalCount:Z,hasMore:H}}})});var WC4,bV1;var Ah0=S(()=>{gX();k0();HU();WC4=TC(cZ),bV1=k1({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",annotations:{title:"Get Thread",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:EC,outputSchema:WC4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.threads.get(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:T$(J)}}})});var ZC4,KC4,hV1;var Ph0=S(()=>{v1();k0();HU();ZC4=q.object({id:q.string().describe("ID of the thread to update"),data:Nh0.describe("Partial thread data to update")}),KC4=q.object({item:cZ.describe("The updated thread entity")}),hV1=k1({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",annotations:{title:"Update Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:ZC4,outputSchema:KC4,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=D9(Q);if(!J)throw Error("User ID required to update thread");let{id:G,data:K}=Y,W=await Q.storage.threads.get(G);if(!W||W.organization_id!==X.id)throw Error("Thread not found in organization");let Z=await Q.storage.threads.update(G,{title:K.title,description:K.description,hidden:K.hidden,updated_by:J});return{item:T$(Z)}}})});var xV1;var Eh0=S(()=>{gX();k0();HU();xV1=k1({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",annotations:{title:"Delete Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:CC,outputSchema:RC(cZ),handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=await Q.storage.threads.get(Y.id);if(!J)throw Error(`Thread not found: ${Y.id}`);if(J.organization_id!==X.id)throw Error(`Thread not found: ${Y.id}`);return await Q.storage.threads.delete(Y.id),{item:T$(J)}}})});function Th0(Y){if(!Y)return null;if("field"in Y&&Y.field[0]==="thread_id"&&Y.operator==="eq")return String(Y.value);if("conditions"in Y)for(let Q of Y.conditions){let X=Th0(Q);if(X)return X}return null}var HC4,gV1;var Ch0=S(()=>{gX();k0();HU();HC4=M3(Oh0),gV1=k1({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",annotations:{title:"List Thread Messages",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:dG,outputSchema:HC4,handler:async(Y,Q)=>{let X=B0(Q);await Q.access.check();let J=Th0(Y.where);if(!J)throw Error("thread_id filter is required in where clause");let G=await Q.storage.threads.get(J);if(!G||G.organization_id!==X.id)return{items:[],totalCount:0,hasMore:!1};let K=Y.offset??0,W=Y.limit??100,{messages:Z,total:H}=await Q.storage.threads.listMessages(J,{limit:W,offset:K}),F=K+W<H;return{items:Z,totalCount:H,hasMore:F}}})});var Rh0=S(()=>{Mh0();wh0();Ah0();Ph0();Eh0();Ch0()});var $C4,VC4,uV1;var Ih0=S(()=>{v1();k0();$C4=q.object({id:q.string().min(1)}),VC4=q.object({user:q.object({id:q.string(),name:q.string(),email:q.string(),image:q.string().nullable()}).nullable()}),uV1=k1({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",annotations:{title:"Get User",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:$C4,outputSchema:VC4,handler:async(Y,Q)=>{await Q.access.check(),o1(Q);let X=D9(Q);if(!X)throw Error("Authentication required");let J=await Q.storage.users.findById(Y.id,X);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var jh0=S(()=>{Ih0()});var _h0={};t0(_h0,{managementMCP:()=>zC4,ALL_TOOLS:()=>Sh0});var BC4,UC4,Sh0,zC4=async(Y)=>{let Q=null;if(Y.organization){let G=await Y.storage.organizationSettings.get(Y.organization.id),K=await Y.storage.projects.list(Y.organization.id),W=new Set(G?.enabled_plugins??[]);for(let Z of K)if(Z.enabledPlugins)for(let H of Z.enabledPlugins)W.add(H);Q=W.size>0?[...W]:null}let X=Py0(Sh0,Q),J=new _z({name:"mcp-mesh-management",version:"1.0.0"},{capabilities:{tools:{}}});for(let G of X){let K=G.inputSchema&&typeof G.inputSchema==="object"&&"shape"in G.inputSchema?G.inputSchema:q.object({}),W=G.outputSchema&&typeof G.outputSchema==="object"&&"shape"in G.outputSchema?G.outputSchema:void 0,Z=K.shape,H=W?.shape;J.registerTool(G.name,{description:G.description??"",inputSchema:Z,outputSchema:H,annotations:G.annotations,_meta:G._meta},async(F)=>{Y.access.setToolName(G.name);try{let $=await G.execute(F,Y);return{content:[{type:"text",text:JSON.stringify($)}],structuredContent:$}}catch($){return{content:[{type:"text",text:`Error: ${$.message}`}],isError:!0}}})}return J};var vh0=S(()=>{eF1();Ck();v1();gy0();Zf0();Jb0();Kb0();Ob0();Eb0();Sb0();kb0();lb0();Yh0();Fh0();zh0();Rh0();jh0();BC4=[$V1,VV1,qV1,BV1,UV1,DV1,OV1,LV1,NV1,MV1,wV1,F$1,q$1,B$1,y$1,f$1,b$1,p$1,n$1,i$1,a$1,r$1,o$1,s$1,t$1,e$1,YV1,Zb0,QV1,XV1,JV1,GV1,WV1,ZV1,KV1,HV1,FV1,Q$1,J$1,G$1,X$1,h$1,x$1,g$1,u$1,m$1,l$1,d$1,uV1,Z$1,K$1,H$1,yV1,fV1,bV1,hV1,xV1,gV1,jV1,SV1,_V1,vV1,kV1,AV1,PV1,EV1,TV1,CV1,RV1,IV1],UC4=Ey0(),Sh0=[...BC4,...UC4]});function DC4(Y){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (vh0(),_h0));return Q.map((X)=>{return{name:X.name,inputSchema:q.toJSONSchema(X.inputSchema,{unrepresentable:"any"}),outputSchema:X.outputSchema?q.toJSONSchema(X.outputSchema,{unrepresentable:"any"}):void 0,description:X.description}})},data:Ut(AG(),Y)},{data:Bt()},{data:qt(Y)}]}async function kh0(Y,Q){try{let X=qC(),J=new LZ1(process.env.ENCRYPTION_KEY||""),G=new NZ1(X.db,J),K=new MZ1(X.db),W=DC4(Y);try{await K.create({organizationId:Y,slug:n7,name:LU,description:"Organization administration and settings",enabledPlugins:null,ui:null})}catch(Z){console.warn("Could not create org-admin project (may already exist):",Z)}await Promise.all(W.map(async(Z)=>{let H=null;if(Z.permissions)H=(await iN.api.createApiKey({body:{name:`${Z.data.app_name??crypto.randomUUID()}-mcp`,userId:Q,permissions:Z.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Y},purpose:"default-org-connections"}}}))?.key;let F=await iL({id:"pending",title:Z.data.title,connection_type:Z.data.connection_type,connection_url:Z.data.connection_url,connection_token:Z.data.connection_token,connection_headers:Z.data.connection_headers}).catch(()=>null),$=await Z.getTools?.()??F?.tools??null,V=F?.scopes?.length?F.scopes:null,B=Z.data.id?Z.data.id.startsWith(`${Y}_`)?Z.data.id:`${Y}_${Z.data.id}`:void 0;await G.create({...Z.data,id:B,tools:$,configuration_scopes:V,organization_id:Y,created_by:Q,connection_token:Z.data.connection_token??H})}))}catch(X){console.error("Error creating default MCP connections:",X)}}var yh0=S(()=>{zY();xm();NM0();MM0();wM0();pm();v1();Np()});var fh0;var bh0=S(()=>{fh0=["owner","admin"]});var OC4=(Y)=>{return{defaultSSO:[{domain:Y.domain,providerId:Y.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:Y.MS_CLIENT_ID,clientSecret:Y.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:Y.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},hh0=(Y)=>{if(Y.providerId==="microsoft")return OC4(Y);throw Error(`Unsupported provider: ${Y.providerId}`)};function LC4(Y){return Y.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function NC4(){let Y=Math.floor(Math.random()*gh0.length),Q=Math.floor(Math.random()*xh0.length),X=gh0[Y]??"deco",J=xh0[Q]??"studio";return`${X}-${J}`}function jC4(){let Y=[$I],Q=new URL($I);if(Q.hostname==="localhost")Y.push($I.replace("localhost","127.0.0.1"));else if(Q.hostname==="127.0.0.1")Y.push($I.replace("127.0.0.1","localhost"));return Y}var xh0,gh0,MC4,wC4,Tp,AC4,PC4,EC4,uh0,t9,mh0=void 0,mV1=void 0,TC4=!1,CC4,RC4,IC4,$I,iN;var Np=S(()=>{D21();xk1();Ef1();c41();Db1();Ob1();gh();Pb1();xm();OZ1();UM0();yh0();bh0();xh0=["labs","agent","studio","workspace","systems","core","cloud","works"],gh0=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];MC4=Object.values(G11()).map((Y)=>Y.map((Q)=>Q.name)).flat(),wC4={...wh,self:["*",...MC4]},Tp=WZ(wC4),AC4=Tp.newRole({self:["*"],...u2.statements}),PC4=Tp.newRole({self:["*"],...u2.statements}),EC4=Tp.newRole({self:["*"],...u2.statements}),uh0=Object.values(G11()).map((Y)=>Y.map((Q)=>`self:${Q.name}`)).flat(),t9=hh.auth;if(t9.inviteEmailProviderId&&t9.emailProviders&&t9.emailProviders.length>0){let Y=UC(t9.emailProviders,t9.inviteEmailProviderId);if(Y){let Q=BC(Y);mh0=async(X)=>{let J=X.inviter.user?.name||X.inviter.user?.email,G=`${AG()}/auth/accept-invitation?invitationId=${X.invitation.id}&redirectTo=/`;await Q({to:X.email,subject:`Invitation to join ${X.organization.name}`,html:`
|
|
1480
1480
|
<h2>You've been invited!</h2>
|
|
1481
1481
|
<p>${J} has invited you to join <strong>${X.organization.name}</strong>.</p>
|
|
1482
1482
|
<p><a href="${G}">Click here to accept the invitation</a></p>
|