@mastra/server 1.83.0-alpha.11 → 1.83.0-alpha.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (552) hide show
  1. package/dist/_types/@internal_voice@0.0.44/dist/_types/@internal_core@0.1.4/dist/request-context/index.d.ts +19 -0
  2. package/dist/{a2a-DIcMx6x-.cjs → a2a-Bz7vRGfF.cjs} +9 -6
  3. package/dist/a2a-Bz7vRGfF.cjs.map +1 -0
  4. package/dist/{a2a-DTTGA2Xg.js → a2a-CY85JalK.js} +9 -6
  5. package/dist/a2a-CY85JalK.js.map +1 -0
  6. package/dist/{agent-builder-BNfBksTT.js → agent-builder-Ce1pjSjg.js} +6 -6
  7. package/dist/{agent-builder-BNfBksTT.js.map → agent-builder-Ce1pjSjg.js.map} +1 -1
  8. package/dist/{agent-builder-CopkMfWF.cjs → agent-builder-DWtgp1cb.cjs} +6 -6
  9. package/dist/{agent-builder-CopkMfWF.cjs.map → agent-builder-DWtgp1cb.cjs.map} +1 -1
  10. package/dist/{agents-BCgiMlDq.js → agents-B0OpLdbp.js} +444 -3
  11. package/dist/agents-B0OpLdbp.js.map +1 -0
  12. package/dist/{agents-DjpBmwhv.cjs → agents-BgaBbcwb.cjs} +136 -53
  13. package/dist/agents-BgaBbcwb.cjs.map +1 -0
  14. package/dist/{agents-CTgjTASj.js → agents-BjlUjmb1.js} +136 -53
  15. package/dist/agents-BjlUjmb1.js.map +1 -0
  16. package/dist/{agents-CjcvdF2e.cjs → agents-CH_G37hG.cjs} +521 -2
  17. package/dist/agents-CH_G37hG.cjs.map +1 -0
  18. package/dist/{api-schema-manifest-LHpJSi-Y.js → api-schema-manifest-CsTpd03O.js} +9 -9
  19. package/dist/api-schema-manifest-CsTpd03O.js.map +1 -0
  20. package/dist/{api-schema-manifest-hPT7_FSw.cjs → api-schema-manifest-DT9X0fAm.cjs} +9 -9
  21. package/dist/api-schema-manifest-DT9X0fAm.cjs.map +1 -0
  22. package/dist/{background-tasks-CYvlxFz3.js → background-tasks-BKnoXtUN.js} +3 -3
  23. package/dist/{background-tasks-CYvlxFz3.js.map → background-tasks-BKnoXtUN.js.map} +1 -1
  24. package/dist/{background-tasks-Dv9o8cR7.cjs → background-tasks-BqW1_VmH.cjs} +3 -3
  25. package/dist/{background-tasks-Dv9o8cR7.cjs.map → background-tasks-BqW1_VmH.cjs.map} +1 -1
  26. package/dist/{builder-registry-BmrttdGj.js → builder-registry-ByghMyfA.js} +3 -3
  27. package/dist/{builder-registry-BmrttdGj.js.map → builder-registry-ByghMyfA.js.map} +1 -1
  28. package/dist/{builder-registry-CmbtZzbE.cjs → builder-registry-DPsdmtZG.cjs} +3 -3
  29. package/dist/{builder-registry-CmbtZzbE.cjs.map → builder-registry-DPsdmtZG.cjs.map} +1 -1
  30. package/dist/catalogue-CGQdyojN.cjs +1378 -0
  31. package/dist/catalogue-CGQdyojN.cjs.map +1 -0
  32. package/dist/catalogue-CUJevxy3.js +1376 -0
  33. package/dist/catalogue-CUJevxy3.js.map +1 -0
  34. package/dist/{channels-KHhb7hAm.js → channels-DIE-lJkq.js} +3 -3
  35. package/dist/{channels-KHhb7hAm.js.map → channels-DIE-lJkq.js.map} +1 -1
  36. package/dist/{channels-CXwFVxi2.cjs → channels-k5dF1IBc.cjs} +3 -3
  37. package/dist/{channels-CXwFVxi2.cjs.map → channels-k5dF1IBc.cjs.map} +1 -1
  38. package/dist/{constants-CXAvBYcz.js → constants-0xZU_h4R.js} +10 -2
  39. package/dist/constants-0xZU_h4R.js.map +1 -0
  40. package/dist/{constants-DMg8hUOR.cjs → constants-1yTmKUZD.cjs} +15 -1
  41. package/dist/constants-1yTmKUZD.cjs.map +1 -0
  42. package/dist/{conversations-BFqmDglO.cjs → conversations-Bvk5VVVJ.cjs} +6 -5
  43. package/dist/conversations-Bvk5VVVJ.cjs.map +1 -0
  44. package/dist/{conversations-BkX00xDs.js → conversations-DYqwqCWH.js} +6 -5
  45. package/dist/conversations-DYqwqCWH.js.map +1 -0
  46. package/dist/dist-BVw6-hMs.js +1 -0
  47. package/dist/{dist-G8g-Cg67.js → dist-C-Hmkkat.js} +6 -6
  48. package/dist/{dist-G8g-Cg67.js.map → dist-C-Hmkkat.js.map} +1 -1
  49. package/dist/{dist-COfASzWw.cjs → dist-Clh3uSOV.cjs} +11 -11
  50. package/dist/{dist-COfASzWw.cjs.map → dist-Clh3uSOV.cjs.map} +1 -1
  51. package/dist/{dist-3WMLkPSs.cjs → dist-DPgpEz_7.cjs} +1 -1
  52. package/dist/docs/SKILL.md +3 -1
  53. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  54. package/dist/docs/references/docs-server-mcp.md +315 -0
  55. package/dist/docs/references/reference-observability-tracing-advanced-queries.md +2 -1
  56. package/dist/docs/references/reference-server-dispatch-route.md +124 -0
  57. package/dist/docs/references/reference-server-invoke-route.md +10 -0
  58. package/dist/{dynamic-workflows-QgKLYkiC.cjs → dynamic-workflows-DPgV6qtS.cjs} +2 -2
  59. package/dist/{dynamic-workflows-QgKLYkiC.cjs.map → dynamic-workflows-DPgV6qtS.cjs.map} +1 -1
  60. package/dist/{dynamic-workflows-CYtakeIQ.js → dynamic-workflows-DmkCJ4Lp.js} +2 -2
  61. package/dist/{dynamic-workflows-CYtakeIQ.js.map → dynamic-workflows-DmkCJ4Lp.js.map} +1 -1
  62. package/dist/{editor-builder-C4H2l6tz.js → editor-builder-CGM0scw2.js} +10 -4
  63. package/dist/editor-builder-CGM0scw2.js.map +1 -0
  64. package/dist/{editor-builder-fe70YP8g.js → editor-builder-CXLdplIj.js} +2 -2
  65. package/dist/{editor-builder-fe70YP8g.js.map → editor-builder-CXLdplIj.js.map} +1 -1
  66. package/dist/{editor-builder-Cqw1npOK.cjs → editor-builder-SP_ledm3.cjs} +10 -4
  67. package/dist/editor-builder-SP_ledm3.cjs.map +1 -0
  68. package/dist/{editor-builder-xQmDgVgJ.cjs → editor-builder-eF2IetF2.cjs} +2 -2
  69. package/dist/{editor-builder-xQmDgVgJ.cjs.map → editor-builder-eF2IetF2.cjs.map} +1 -1
  70. package/dist/{helpers-C9QZKOhz.js → helpers-B56oH6qp.js} +27 -8
  71. package/dist/helpers-B56oH6qp.js.map +1 -0
  72. package/dist/{helpers-0LJI4DxR.cjs → helpers-Dpdta8ai.cjs} +31 -6
  73. package/dist/helpers-Dpdta8ai.cjs.map +1 -0
  74. package/dist/{knowledge-CRkWkTBC.cjs → knowledge-2fms70NN.cjs} +4 -4
  75. package/dist/{knowledge-CRkWkTBC.cjs.map → knowledge-2fms70NN.cjs.map} +1 -1
  76. package/dist/{knowledge-Dfe_CFtt.js → knowledge-BblTTH3z.js} +4 -4
  77. package/dist/{knowledge-Dfe_CFtt.js.map → knowledge-BblTTH3z.js.map} +1 -1
  78. package/dist/{logs-Dg2AWexF.js → logs-D_hKQuvQ.js} +3 -3
  79. package/dist/{logs-Dg2AWexF.js.map → logs-D_hKQuvQ.js.map} +1 -1
  80. package/dist/{logs-B2ov1yZQ.cjs → logs-Deoh0l4I.cjs} +3 -3
  81. package/dist/{logs-B2ov1yZQ.cjs.map → logs-Deoh0l4I.cjs.map} +1 -1
  82. package/dist/{mcp-bsPRIGFX.js → mcp-CSRuYaWN.js} +3 -3
  83. package/dist/{mcp-bsPRIGFX.js.map → mcp-CSRuYaWN.js.map} +1 -1
  84. package/dist/{mcp-Bon4eIV1.cjs → mcp-oWjcmsQb.cjs} +3 -3
  85. package/dist/{mcp-Bon4eIV1.cjs.map → mcp-oWjcmsQb.cjs.map} +1 -1
  86. package/dist/{memory-Dw7xG5nn.js → memory-CGlo-6_V.js} +105 -12
  87. package/dist/memory-CGlo-6_V.js.map +1 -0
  88. package/dist/{memory-BRE3ofvI.cjs → memory-CzSke9Em.cjs} +105 -12
  89. package/dist/memory-CzSke9Em.cjs.map +1 -0
  90. package/dist/{observability-DHJ7mzoE.cjs → observability-BCJsmSH0.cjs} +27 -3
  91. package/dist/observability-BCJsmSH0.cjs.map +1 -0
  92. package/dist/{observability-BYIy4kPf.js → observability-Z2tDxHS1.js} +27 -3
  93. package/dist/observability-Z2tDxHS1.js.map +1 -0
  94. package/dist/{observability-new-endpoints-BOe3wej1.cjs → observability-new-endpoints-C_HEkpZ1.cjs} +157 -5
  95. package/dist/observability-new-endpoints-C_HEkpZ1.cjs.map +1 -0
  96. package/dist/{observability-new-endpoints-COy7lpeR.js → observability-new-endpoints-dr0XcNkP.js} +158 -6
  97. package/dist/observability-new-endpoints-dr0XcNkP.js.map +1 -0
  98. package/dist/{plans-D_GKFz2x.js → plans-BemJO4-7.js} +7 -6
  99. package/dist/plans-BemJO4-7.js.map +1 -0
  100. package/dist/{plans-_nR8lqgD.cjs → plans-CffjV2_6.cjs} +7 -6
  101. package/dist/plans-CffjV2_6.cjs.map +1 -0
  102. package/dist/{probe-image-size-C2b8QfA7.js → probe-image-size-jA5gozO6.js} +2 -2
  103. package/dist/{probe-image-size-C2b8QfA7.js.map → probe-image-size-jA5gozO6.js.map} +1 -1
  104. package/dist/{probe-image-size-DLuC8QsM.cjs → probe-image-size-qOT5Pn0l.cjs} +2 -2
  105. package/dist/{probe-image-size-DLuC8QsM.cjs.map → probe-image-size-qOT5Pn0l.cjs.map} +1 -1
  106. package/dist/{responses-C_OEJoxU.js → responses-BofWEQYg.js} +11 -8
  107. package/dist/responses-BofWEQYg.js.map +1 -0
  108. package/dist/{responses-CdWbS4jA.cjs → responses-D0mb5ubj.cjs} +11 -8
  109. package/dist/responses-D0mb5ubj.cjs.map +1 -0
  110. package/dist/{route-builder-B9C5vT54.cjs → route-builder-DjTBxSZN.cjs} +10 -10
  111. package/dist/{route-builder-B9C5vT54.cjs.map → route-builder-DjTBxSZN.cjs.map} +1 -1
  112. package/dist/{route-builder-DfDT1g4L.js → route-builder-Dz18c3qm.js} +9 -9
  113. package/dist/{route-builder-DfDT1g4L.js.map → route-builder-Dz18c3qm.js.map} +1 -1
  114. package/dist/{routes-Brf5Qfbu.cjs → routes-01JAJiMe.cjs} +646 -27
  115. package/dist/routes-01JAJiMe.cjs.map +1 -0
  116. package/dist/{routes-BR7W0b_u.js → routes-CmkPohqd.js} +593 -28
  117. package/dist/routes-CmkPohqd.js.map +1 -0
  118. package/dist/{schedules-BQvnAe1j.cjs → schedules-BRwhbppl.cjs} +77 -22
  119. package/dist/schedules-BRwhbppl.cjs.map +1 -0
  120. package/dist/{schedules-BcAIELfB.js → schedules-Zct_0ZwE.js} +77 -22
  121. package/dist/schedules-Zct_0ZwE.js.map +1 -0
  122. package/dist/{schema-xsUy1mlm-CAPin6jE.js → schema-TQPB_dl2-CCzMcdDx.js} +9 -6
  123. package/dist/{schema-xsUy1mlm-CAPin6jE.js.map → schema-TQPB_dl2-CCzMcdDx.js.map} +1 -1
  124. package/dist/{schema-xsUy1mlm-pvZI8YC0.cjs → schema-TQPB_dl2-CJX1q58F.cjs} +9 -6
  125. package/dist/{schema-xsUy1mlm-pvZI8YC0.cjs.map → schema-TQPB_dl2-CJX1q58F.cjs.map} +1 -1
  126. package/dist/{scores-DEvPN0kz.cjs → scores-0MyV08tL.cjs} +26 -11
  127. package/dist/scores-0MyV08tL.cjs.map +1 -0
  128. package/dist/{scores-Dm0yu1Pt.js → scores-CVssMyoQ.js} +26 -11
  129. package/dist/scores-CVssMyoQ.js.map +1 -0
  130. package/dist/server/auth/helpers.d.ts +7 -1
  131. package/dist/server/auth/helpers.d.ts.map +1 -1
  132. package/dist/server/auth/index.cjs +4 -2
  133. package/dist/server/auth/index.js +3 -3
  134. package/dist/server/constants.d.ts +8 -1
  135. package/dist/server/constants.d.ts.map +1 -1
  136. package/dist/server/handlers/a2a.cjs +1 -1
  137. package/dist/server/handlers/a2a.d.ts +4 -0
  138. package/dist/server/handlers/a2a.d.ts.map +1 -1
  139. package/dist/server/handlers/a2a.js +1 -1
  140. package/dist/server/handlers/agent-access.cjs +42 -0
  141. package/dist/server/handlers/agent-access.cjs.map +1 -0
  142. package/dist/server/handlers/agent-access.d.ts +19 -0
  143. package/dist/server/handlers/agent-access.d.ts.map +1 -0
  144. package/dist/server/handlers/agent-access.js +39 -0
  145. package/dist/server/handlers/agent-access.js.map +1 -0
  146. package/dist/server/handlers/agent-builder.cjs +1 -1
  147. package/dist/server/handlers/agent-builder.d.ts +32 -0
  148. package/dist/server/handlers/agent-builder.d.ts.map +1 -1
  149. package/dist/server/handlers/agent-builder.js +1 -1
  150. package/dist/server/handlers/agent-controller.cjs +3 -3
  151. package/dist/server/handlers/agent-controller.d.ts +72 -0
  152. package/dist/server/handlers/agent-controller.d.ts.map +1 -1
  153. package/dist/server/handlers/agent-controller.js +3 -3
  154. package/dist/server/handlers/agent-versions.cjs +30 -2
  155. package/dist/server/handlers/agent-versions.cjs.map +1 -1
  156. package/dist/server/handlers/agent-versions.d.ts +12 -0
  157. package/dist/server/handlers/agent-versions.d.ts.map +1 -1
  158. package/dist/server/handlers/agent-versions.js +30 -2
  159. package/dist/server/handlers/agent-versions.js.map +1 -1
  160. package/dist/server/handlers/agents.cjs +1 -1
  161. package/dist/server/handlers/agents.d.ts +91 -2
  162. package/dist/server/handlers/agents.d.ts.map +1 -1
  163. package/dist/server/handlers/agents.js +1 -1
  164. package/dist/server/handlers/auth.cjs +3 -3
  165. package/dist/server/handlers/auth.d.ts +40 -0
  166. package/dist/server/handlers/auth.d.ts.map +1 -1
  167. package/dist/server/handlers/auth.js +3 -3
  168. package/dist/server/handlers/authorship.cjs +1 -1
  169. package/dist/server/handlers/authorship.js +1 -1
  170. package/dist/server/handlers/background-tasks.cjs +1 -1
  171. package/dist/server/handlers/background-tasks.d.ts +8 -0
  172. package/dist/server/handlers/background-tasks.d.ts.map +1 -1
  173. package/dist/server/handlers/background-tasks.js +1 -1
  174. package/dist/server/handlers/builder-registry.cjs +1 -1
  175. package/dist/server/handlers/builder-registry.d.ts +10 -0
  176. package/dist/server/handlers/builder-registry.d.ts.map +1 -1
  177. package/dist/server/handlers/builder-registry.js +1 -1
  178. package/dist/server/handlers/channels.cjs +1 -1
  179. package/dist/server/handlers/channels.d.ts +10 -0
  180. package/dist/server/handlers/channels.d.ts.map +1 -1
  181. package/dist/server/handlers/channels.js +1 -1
  182. package/dist/server/handlers/conversations.cjs +1 -1
  183. package/dist/server/handlers/conversations.d.ts +8 -0
  184. package/dist/server/handlers/conversations.d.ts.map +1 -1
  185. package/dist/server/handlers/conversations.js +1 -1
  186. package/dist/server/handlers/datasets.cjs +2 -2
  187. package/dist/server/handlers/datasets.d.ts +66 -0
  188. package/dist/server/handlers/datasets.d.ts.map +1 -1
  189. package/dist/server/handlers/datasets.js +2 -2
  190. package/dist/server/handlers/dynamic-workflows.cjs +1 -1
  191. package/dist/server/handlers/dynamic-workflows.d.ts +8 -0
  192. package/dist/server/handlers/dynamic-workflows.d.ts.map +1 -1
  193. package/dist/server/handlers/dynamic-workflows.js +1 -1
  194. package/dist/server/handlers/editor-builder.cjs +1 -1
  195. package/dist/server/handlers/editor-builder.d.ts +6 -0
  196. package/dist/server/handlers/editor-builder.d.ts.map +1 -1
  197. package/dist/server/handlers/editor-builder.js +1 -1
  198. package/dist/server/handlers/favorites-enrichment.cjs +1 -1
  199. package/dist/server/handlers/favorites-enrichment.js +1 -1
  200. package/dist/server/handlers/knowledge.cjs +1 -1
  201. package/dist/server/handlers/knowledge.d.ts +18 -0
  202. package/dist/server/handlers/knowledge.d.ts.map +1 -1
  203. package/dist/server/handlers/knowledge.js +1 -1
  204. package/dist/server/handlers/logs.cjs +1 -1
  205. package/dist/server/handlers/logs.d.ts +6 -0
  206. package/dist/server/handlers/logs.d.ts.map +1 -1
  207. package/dist/server/handlers/logs.js +1 -1
  208. package/dist/server/handlers/mcp-client-versions.cjs +2 -2
  209. package/dist/server/handlers/mcp-client-versions.d.ts +14 -0
  210. package/dist/server/handlers/mcp-client-versions.d.ts.map +1 -1
  211. package/dist/server/handlers/mcp-client-versions.js +2 -2
  212. package/dist/server/handlers/mcp.cjs +1 -1
  213. package/dist/server/handlers/mcp.d.ts +42 -0
  214. package/dist/server/handlers/mcp.d.ts.map +1 -1
  215. package/dist/server/handlers/mcp.js +1 -1
  216. package/dist/server/handlers/memory.cjs +1 -1
  217. package/dist/server/handlers/memory.d.ts +52 -0
  218. package/dist/server/handlers/memory.d.ts.map +1 -1
  219. package/dist/server/handlers/memory.js +1 -1
  220. package/dist/server/handlers/observability-new-endpoints.cjs +1 -1
  221. package/dist/server/handlers/observability-new-endpoints.d.ts +163 -3
  222. package/dist/server/handlers/observability-new-endpoints.d.ts.map +1 -1
  223. package/dist/server/handlers/observability-new-endpoints.js +1 -1
  224. package/dist/server/handlers/observability-shared.cjs +8 -1
  225. package/dist/server/handlers/observability-shared.cjs.map +1 -1
  226. package/dist/server/handlers/observability-shared.d.ts +13 -0
  227. package/dist/server/handlers/observability-shared.d.ts.map +1 -1
  228. package/dist/server/handlers/observability-shared.js +7 -2
  229. package/dist/server/handlers/observability-shared.js.map +1 -1
  230. package/dist/server/handlers/observability-signal-context.cjs +1 -1
  231. package/dist/server/handlers/observability-signal-context.js +1 -1
  232. package/dist/server/handlers/observability.cjs +2 -2
  233. package/dist/server/handlers/observability.d.ts +12 -0
  234. package/dist/server/handlers/observability.d.ts.map +1 -1
  235. package/dist/server/handlers/observability.js +2 -2
  236. package/dist/server/handlers/plans.cjs +1 -1
  237. package/dist/server/handlers/plans.d.ts +2 -0
  238. package/dist/server/handlers/plans.d.ts.map +1 -1
  239. package/dist/server/handlers/plans.js +1 -1
  240. package/dist/server/handlers/processor-providers.cjs +1 -1
  241. package/dist/server/handlers/processor-providers.d.ts +4 -0
  242. package/dist/server/handlers/processor-providers.d.ts.map +1 -1
  243. package/dist/server/handlers/processor-providers.js +1 -1
  244. package/dist/server/handlers/processors.cjs +57 -6
  245. package/dist/server/handlers/processors.cjs.map +1 -1
  246. package/dist/server/handlers/processors.d.ts +6 -0
  247. package/dist/server/handlers/processors.d.ts.map +1 -1
  248. package/dist/server/handlers/processors.js +57 -6
  249. package/dist/server/handlers/processors.js.map +1 -1
  250. package/dist/server/handlers/prompt-block-versions.cjs +2 -2
  251. package/dist/server/handlers/prompt-block-versions.d.ts +14 -0
  252. package/dist/server/handlers/prompt-block-versions.d.ts.map +1 -1
  253. package/dist/server/handlers/prompt-block-versions.js +2 -2
  254. package/dist/server/handlers/responses.cjs +1 -1
  255. package/dist/server/handlers/responses.d.ts +17 -11
  256. package/dist/server/handlers/responses.d.ts.map +1 -1
  257. package/dist/server/handlers/responses.js +1 -1
  258. package/dist/server/handlers/responses.storage.cjs +4 -3
  259. package/dist/server/handlers/responses.storage.cjs.map +1 -1
  260. package/dist/server/handlers/responses.storage.d.ts.map +1 -1
  261. package/dist/server/handlers/responses.storage.js +4 -3
  262. package/dist/server/handlers/responses.storage.js.map +1 -1
  263. package/dist/server/handlers/schedules.cjs +1 -1
  264. package/dist/server/handlers/schedules.d.ts +18 -0
  265. package/dist/server/handlers/schedules.d.ts.map +1 -1
  266. package/dist/server/handlers/schedules.js +1 -1
  267. package/dist/server/handlers/scorer-versions.cjs +2 -2
  268. package/dist/server/handlers/scorer-versions.d.ts +14 -0
  269. package/dist/server/handlers/scorer-versions.d.ts.map +1 -1
  270. package/dist/server/handlers/scorer-versions.js +2 -2
  271. package/dist/server/handlers/scores.cjs +1 -1
  272. package/dist/server/handlers/scores.d.ts +12 -0
  273. package/dist/server/handlers/scores.d.ts.map +1 -1
  274. package/dist/server/handlers/scores.js +1 -1
  275. package/dist/server/handlers/stored-agent-favorites.cjs +3 -3
  276. package/dist/server/handlers/stored-agent-favorites.d.ts +4 -0
  277. package/dist/server/handlers/stored-agent-favorites.d.ts.map +1 -1
  278. package/dist/server/handlers/stored-agent-favorites.js +3 -3
  279. package/dist/server/handlers/stored-agents.cjs +41 -3
  280. package/dist/server/handlers/stored-agents.cjs.map +1 -1
  281. package/dist/server/handlers/stored-agents.d.ts +14 -0
  282. package/dist/server/handlers/stored-agents.d.ts.map +1 -1
  283. package/dist/server/handlers/stored-agents.js +41 -3
  284. package/dist/server/handlers/stored-agents.js.map +1 -1
  285. package/dist/server/handlers/stored-mcp-clients.cjs +2 -2
  286. package/dist/server/handlers/stored-mcp-clients.d.ts +10 -0
  287. package/dist/server/handlers/stored-mcp-clients.d.ts.map +1 -1
  288. package/dist/server/handlers/stored-mcp-clients.js +2 -2
  289. package/dist/server/handlers/stored-prompt-blocks.cjs +2 -2
  290. package/dist/server/handlers/stored-prompt-blocks.d.ts +10 -0
  291. package/dist/server/handlers/stored-prompt-blocks.d.ts.map +1 -1
  292. package/dist/server/handlers/stored-prompt-blocks.js +2 -2
  293. package/dist/server/handlers/stored-scorers.cjs +2 -2
  294. package/dist/server/handlers/stored-scorers.d.ts +10 -0
  295. package/dist/server/handlers/stored-scorers.d.ts.map +1 -1
  296. package/dist/server/handlers/stored-scorers.js +2 -2
  297. package/dist/server/handlers/stored-skill-favorites.cjs +3 -3
  298. package/dist/server/handlers/stored-skill-favorites.d.ts +4 -0
  299. package/dist/server/handlers/stored-skill-favorites.d.ts.map +1 -1
  300. package/dist/server/handlers/stored-skill-favorites.js +3 -3
  301. package/dist/server/handlers/stored-skills.cjs +3 -3
  302. package/dist/server/handlers/stored-skills.d.ts +12 -0
  303. package/dist/server/handlers/stored-skills.d.ts.map +1 -1
  304. package/dist/server/handlers/stored-skills.js +3 -3
  305. package/dist/server/handlers/stored-workspaces.cjs +2 -2
  306. package/dist/server/handlers/stored-workspaces.d.ts +10 -0
  307. package/dist/server/handlers/stored-workspaces.d.ts.map +1 -1
  308. package/dist/server/handlers/stored-workspaces.js +2 -2
  309. package/dist/server/handlers/system.cjs +3 -3
  310. package/dist/server/handlers/system.d.ts +6 -0
  311. package/dist/server/handlers/system.d.ts.map +1 -1
  312. package/dist/server/handlers/system.js +3 -3
  313. package/dist/server/handlers/tool-providers.cjs +2 -2
  314. package/dist/server/handlers/tool-providers.d.ts +26 -0
  315. package/dist/server/handlers/tool-providers.d.ts.map +1 -1
  316. package/dist/server/handlers/tool-providers.js +2 -2
  317. package/dist/server/handlers/tools.cjs +2 -1
  318. package/dist/server/handlers/tools.d.ts +20 -0
  319. package/dist/server/handlers/tools.d.ts.map +1 -1
  320. package/dist/server/handlers/tools.js +1 -1
  321. package/dist/server/handlers/utils.cjs +1 -1
  322. package/dist/server/handlers/utils.js +1 -1
  323. package/dist/server/handlers/validate-agent-instructions.cjs +1 -1
  324. package/dist/server/handlers/validate-agent-instructions.js +1 -1
  325. package/dist/server/handlers/vector.cjs +1 -1
  326. package/dist/server/handlers/vector.d.ts +16 -0
  327. package/dist/server/handlers/vector.d.ts.map +1 -1
  328. package/dist/server/handlers/vector.js +1 -1
  329. package/dist/server/handlers/voice.cjs +1 -1
  330. package/dist/server/handlers/voice.d.ts.map +1 -1
  331. package/dist/server/handlers/voice.js +1 -1
  332. package/dist/server/handlers/workflow-builder.cjs +1 -1
  333. package/dist/server/handlers/workflow-builder.d.ts +4 -0
  334. package/dist/server/handlers/workflow-builder.d.ts.map +1 -1
  335. package/dist/server/handlers/workflow-builder.js +1 -1
  336. package/dist/server/handlers/workflows.cjs +2 -1
  337. package/dist/server/handlers/workflows.d.ts +57 -0
  338. package/dist/server/handlers/workflows.d.ts.map +1 -1
  339. package/dist/server/handlers/workflows.js +1 -1
  340. package/dist/server/handlers/workspace.cjs +1 -1
  341. package/dist/server/handlers/workspace.d.ts +103 -23
  342. package/dist/server/handlers/workspace.d.ts.map +1 -1
  343. package/dist/server/handlers/workspace.js +1 -1
  344. package/dist/server/handlers.cjs +17 -17
  345. package/dist/server/handlers.js +17 -17
  346. package/dist/server/mcp/capabilities.d.ts +25 -0
  347. package/dist/server/mcp/capabilities.d.ts.map +1 -0
  348. package/dist/server/mcp/catalogue.d.ts +76 -0
  349. package/dist/server/mcp/catalogue.d.ts.map +1 -0
  350. package/dist/server/mcp/config.d.ts +49 -0
  351. package/dist/server/mcp/config.d.ts.map +1 -0
  352. package/dist/server/mcp/descriptor.d.ts +40 -0
  353. package/dist/server/mcp/descriptor.d.ts.map +1 -0
  354. package/dist/server/mcp/oauth.d.ts +46 -0
  355. package/dist/server/mcp/oauth.d.ts.map +1 -0
  356. package/dist/server/mcp/result-size.d.ts +26 -0
  357. package/dist/server/mcp/result-size.d.ts.map +1 -0
  358. package/dist/server/mcp/route.d.ts +21 -0
  359. package/dist/server/mcp/route.d.ts.map +1 -0
  360. package/dist/server/mcp/schema.d.ts +13 -0
  361. package/dist/server/mcp/schema.d.ts.map +1 -0
  362. package/dist/server/mcp/toolsets/memory.d.ts +8 -0
  363. package/dist/server/mcp/toolsets/memory.d.ts.map +1 -0
  364. package/dist/server/mcp/toolsets/observability.d.ts +4 -0
  365. package/dist/server/mcp/toolsets/observability.d.ts.map +1 -0
  366. package/dist/server/mcp/toolsets/stored-agents.d.ts +8 -0
  367. package/dist/server/mcp/toolsets/stored-agents.d.ts.map +1 -0
  368. package/dist/server/schemas/index.cjs +9 -10
  369. package/dist/server/schemas/index.js +3 -4
  370. package/dist/server/schemas/system.d.ts +2 -0
  371. package/dist/server/schemas/system.d.ts.map +1 -1
  372. package/dist/server/server-adapter/api-schema-manifest.d.ts +1 -1
  373. package/dist/server/server-adapter/index.cjs +45 -1831
  374. package/dist/server/server-adapter/index.d.ts +126 -3
  375. package/dist/server/server-adapter/index.d.ts.map +1 -1
  376. package/dist/server/server-adapter/index.js +7 -1805
  377. package/dist/server/server-adapter/openapi-utils.d.ts +2 -2
  378. package/dist/server/server-adapter/openapi-utils.d.ts.map +1 -1
  379. package/dist/server/server-adapter/routes/a2a.d.ts +4 -0
  380. package/dist/server/server-adapter/routes/a2a.d.ts.map +1 -1
  381. package/dist/server/server-adapter/routes/agent-builder.d.ts +32 -0
  382. package/dist/server/server-adapter/routes/agent-builder.d.ts.map +1 -1
  383. package/dist/server/server-adapter/routes/channels.d.ts +10 -0
  384. package/dist/server/server-adapter/routes/channels.d.ts.map +1 -1
  385. package/dist/server/server-adapter/routes/conversations.d.ts +11 -3
  386. package/dist/server/server-adapter/routes/conversations.d.ts.map +1 -1
  387. package/dist/server/server-adapter/routes/datasets.d.ts +66 -0
  388. package/dist/server/server-adapter/routes/datasets.d.ts.map +1 -1
  389. package/dist/server/server-adapter/routes/editor-builder.d.ts +20 -0
  390. package/dist/server/server-adapter/routes/editor-builder.d.ts.map +1 -1
  391. package/dist/server/server-adapter/routes/index.d.ts +26 -1
  392. package/dist/server/server-adapter/routes/index.d.ts.map +1 -1
  393. package/dist/server/server-adapter/routes/knowledge.d.ts +18 -0
  394. package/dist/server/server-adapter/routes/knowledge.d.ts.map +1 -1
  395. package/dist/server/server-adapter/routes/legacy.d.ts +8 -0
  396. package/dist/server/server-adapter/routes/legacy.d.ts.map +1 -1
  397. package/dist/server/server-adapter/routes/logs.d.ts +6 -0
  398. package/dist/server/server-adapter/routes/logs.d.ts.map +1 -1
  399. package/dist/server/server-adapter/routes/mcp.d.ts +37 -1
  400. package/dist/server/server-adapter/routes/mcp.d.ts.map +1 -1
  401. package/dist/server/server-adapter/routes/memory.d.ts +52 -0
  402. package/dist/server/server-adapter/routes/memory.d.ts.map +1 -1
  403. package/dist/server/server-adapter/routes/observability.d.ts +97 -1
  404. package/dist/server/server-adapter/routes/observability.d.ts.map +1 -1
  405. package/dist/server/server-adapter/routes/processor-providers.d.ts +4 -0
  406. package/dist/server/server-adapter/routes/processor-providers.d.ts.map +1 -1
  407. package/dist/server/server-adapter/routes/processors.d.ts +6 -0
  408. package/dist/server/server-adapter/routes/processors.d.ts.map +1 -1
  409. package/dist/server/server-adapter/routes/responses.d.ts +6 -0
  410. package/dist/server/server-adapter/routes/responses.d.ts.map +1 -1
  411. package/dist/server/server-adapter/routes/route-builder.d.ts +5 -1
  412. package/dist/server/server-adapter/routes/route-builder.d.ts.map +1 -1
  413. package/dist/server/server-adapter/routes/scorers.d.ts +12 -0
  414. package/dist/server/server-adapter/routes/scorers.d.ts.map +1 -1
  415. package/dist/server/server-adapter/routes/stored-mcp-clients.d.ts +24 -0
  416. package/dist/server/server-adapter/routes/stored-mcp-clients.d.ts.map +1 -1
  417. package/dist/server/server-adapter/routes/stored-prompt-blocks.d.ts +24 -0
  418. package/dist/server/server-adapter/routes/stored-prompt-blocks.d.ts.map +1 -1
  419. package/dist/server/server-adapter/routes/stored-scorers.d.ts +24 -0
  420. package/dist/server/server-adapter/routes/stored-scorers.d.ts.map +1 -1
  421. package/dist/server/server-adapter/routes/stored-skills.d.ts +16 -0
  422. package/dist/server/server-adapter/routes/stored-skills.d.ts.map +1 -1
  423. package/dist/server/server-adapter/routes/stored-workspaces.d.ts +10 -0
  424. package/dist/server/server-adapter/routes/stored-workspaces.d.ts.map +1 -1
  425. package/dist/server/server-adapter/routes/system.d.ts +6 -0
  426. package/dist/server/server-adapter/routes/system.d.ts.map +1 -1
  427. package/dist/server/server-adapter/routes/tool-providers.d.ts +26 -0
  428. package/dist/server/server-adapter/routes/tool-providers.d.ts.map +1 -1
  429. package/dist/server/server-adapter/routes/tools.d.ts +6 -0
  430. package/dist/server/server-adapter/routes/tools.d.ts.map +1 -1
  431. package/dist/server/server-adapter/routes/vectors.d.ts +16 -0
  432. package/dist/server/server-adapter/routes/vectors.d.ts.map +1 -1
  433. package/dist/server/server-adapter/routes/workflows.d.ts +50 -0
  434. package/dist/server/server-adapter/routes/workflows.d.ts.map +1 -1
  435. package/dist/server/server-adapter/routes/workspace.d.ts +42 -0
  436. package/dist/server/server-adapter/routes/workspace.d.ts.map +1 -1
  437. package/dist/server-adapter-B7dLE5si.cjs +2386 -0
  438. package/dist/server-adapter-B7dLE5si.cjs.map +1 -0
  439. package/dist/server-adapter-BywLWVKp.js +2189 -0
  440. package/dist/server-adapter-BywLWVKp.js.map +1 -0
  441. package/dist/{system-zL047vEq.cjs → system-DdMSBAOY.cjs} +2 -1
  442. package/dist/system-DdMSBAOY.cjs.map +1 -0
  443. package/dist/{system-DlW760k2.js → system-FnU7vyxd.js} +2 -1
  444. package/dist/system-FnU7vyxd.js.map +1 -0
  445. package/dist/{tools-Daot5Zgz.cjs → tools-CawMeeZg.cjs} +71 -29
  446. package/dist/tools-CawMeeZg.cjs.map +1 -0
  447. package/dist/{tools-BJFq9JKF.js → tools-oHRh4msa.js} +65 -29
  448. package/dist/tools-oHRh4msa.js.map +1 -0
  449. package/dist/{utils-yedETkNk.js → utils-BfySxdfF.js} +3 -3
  450. package/dist/{utils-yedETkNk.js.map → utils-BfySxdfF.js.map} +1 -1
  451. package/dist/{utils-BXEJ6FZC.cjs → utils-DFhesFfA.cjs} +2 -2
  452. package/dist/{utils-BXEJ6FZC.cjs.map → utils-DFhesFfA.cjs.map} +1 -1
  453. package/dist/{utils-DptI_ERr.cjs → utils-Dn_OA_6N.cjs} +6 -6
  454. package/dist/{utils-DptI_ERr.cjs.map → utils-Dn_OA_6N.cjs.map} +1 -1
  455. package/dist/{utils-CTYtskHa.js → utils-Dv1D6ob-.js} +2 -2
  456. package/dist/{utils-CTYtskHa.js.map → utils-Dv1D6ob-.js.map} +1 -1
  457. package/dist/{vector-CZ26vo6u.js → vector-Bz-glead.js} +2 -2
  458. package/dist/{vector-CZ26vo6u.js.map → vector-Bz-glead.js.map} +1 -1
  459. package/dist/{vector-DBe45tnv.cjs → vector-DIFU_fwU.cjs} +2 -2
  460. package/dist/{vector-DBe45tnv.cjs.map → vector-DIFU_fwU.cjs.map} +1 -1
  461. package/dist/voice-C6bAqs79.js +42 -0
  462. package/dist/voice-C6bAqs79.js.map +1 -0
  463. package/dist/{voice-CBbxcsCM.cjs → voice-Dk0O5mVD.cjs} +29 -9
  464. package/dist/voice-Dk0O5mVD.cjs.map +1 -0
  465. package/dist/{workflow-builder-CkrdTcoM.cjs → workflow-builder-BPUjAdaC.cjs} +5 -5
  466. package/dist/{workflow-builder-CkrdTcoM.cjs.map → workflow-builder-BPUjAdaC.cjs.map} +1 -1
  467. package/dist/{workflow-builder-C5ufahUw.js → workflow-builder-D2fwGsLw.js} +5 -5
  468. package/dist/{workflow-builder-C5ufahUw.js.map → workflow-builder-D2fwGsLw.js.map} +1 -1
  469. package/dist/{workflows-C_Mqj_80.js → workflows-B-QJ0Tnv.js} +38 -7
  470. package/dist/workflows-B-QJ0Tnv.js.map +1 -0
  471. package/dist/{workflows-B5uWFrJ1.cjs → workflows-CwkEHIKW.cjs} +43 -6
  472. package/dist/workflows-CwkEHIKW.cjs.map +1 -0
  473. package/dist/{workspace-BwlPQO3M.js → workspace-CbTB2svI.js} +99 -41
  474. package/dist/workspace-CbTB2svI.js.map +1 -0
  475. package/dist/{workspace-CD9pQ61P.cjs → workspace-CsPtSXQd.cjs} +99 -41
  476. package/dist/workspace-CsPtSXQd.cjs.map +1 -0
  477. package/package.json +13 -6
  478. package/dist/a2a-DIcMx6x-.cjs.map +0 -1
  479. package/dist/a2a-DTTGA2Xg.js.map +0 -1
  480. package/dist/agents-BCgiMlDq.js.map +0 -1
  481. package/dist/agents-CTgjTASj.js.map +0 -1
  482. package/dist/agents-CjcvdF2e.cjs.map +0 -1
  483. package/dist/agents-DjpBmwhv.cjs.map +0 -1
  484. package/dist/api-schema-manifest-LHpJSi-Y.js.map +0 -1
  485. package/dist/api-schema-manifest-hPT7_FSw.cjs.map +0 -1
  486. package/dist/constants-CXAvBYcz.js.map +0 -1
  487. package/dist/constants-DMg8hUOR.cjs.map +0 -1
  488. package/dist/conversations-BFqmDglO.cjs.map +0 -1
  489. package/dist/conversations-BkX00xDs.js.map +0 -1
  490. package/dist/dist-4NnakSte.js +0 -1
  491. package/dist/editor-builder-C4H2l6tz.js.map +0 -1
  492. package/dist/editor-builder-Cqw1npOK.cjs.map +0 -1
  493. package/dist/helpers-0LJI4DxR.cjs.map +0 -1
  494. package/dist/helpers-C9QZKOhz.js.map +0 -1
  495. package/dist/memory-BRE3ofvI.cjs.map +0 -1
  496. package/dist/memory-Dw7xG5nn.js.map +0 -1
  497. package/dist/observability-BYIy4kPf.js.map +0 -1
  498. package/dist/observability-DHJ7mzoE.cjs.map +0 -1
  499. package/dist/observability-new-endpoints-BOe3wej1.cjs.map +0 -1
  500. package/dist/observability-new-endpoints-COy7lpeR.js.map +0 -1
  501. package/dist/plans-D_GKFz2x.js.map +0 -1
  502. package/dist/plans-_nR8lqgD.cjs.map +0 -1
  503. package/dist/responses-C_OEJoxU.js.map +0 -1
  504. package/dist/responses-CdWbS4jA.cjs.map +0 -1
  505. package/dist/routes-BR7W0b_u.js.map +0 -1
  506. package/dist/routes-Brf5Qfbu.cjs.map +0 -1
  507. package/dist/routes-CtGp_lBn.cjs +0 -523
  508. package/dist/routes-CtGp_lBn.cjs.map +0 -1
  509. package/dist/routes-MRZFTKei.js +0 -446
  510. package/dist/routes-MRZFTKei.js.map +0 -1
  511. package/dist/schedules-BQvnAe1j.cjs.map +0 -1
  512. package/dist/schedules-BcAIELfB.js.map +0 -1
  513. package/dist/scores-DEvPN0kz.cjs.map +0 -1
  514. package/dist/scores-Dm0yu1Pt.js.map +0 -1
  515. package/dist/server/server-adapter/index.cjs.map +0 -1
  516. package/dist/server/server-adapter/index.js.map +0 -1
  517. package/dist/system-DlW760k2.js.map +0 -1
  518. package/dist/system-zL047vEq.cjs.map +0 -1
  519. package/dist/tools-BJFq9JKF.js.map +0 -1
  520. package/dist/tools-Daot5Zgz.cjs.map +0 -1
  521. package/dist/voice-CBbxcsCM.cjs.map +0 -1
  522. package/dist/voice-CzFWhWPJ.js +0 -22
  523. package/dist/voice-CzFWhWPJ.js.map +0 -1
  524. package/dist/workflows-B5uWFrJ1.cjs.map +0 -1
  525. package/dist/workflows-C_Mqj_80.js.map +0 -1
  526. package/dist/workspace-BwlPQO3M.js.map +0 -1
  527. package/dist/workspace-CD9pQ61P.cjs.map +0 -1
  528. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/_types/@internal_ai-sdk-v4@0.0.95/dist/index.d.ts +0 -0
  529. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/_types/@internal_ai-sdk-v5@0.0.95/dist/index.d.ts +0 -0
  530. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/_types/@internal_ai-v6@0.0.95/dist/index.d.ts +0 -0
  531. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/_types/@standard-schema_spec@1.1.0/dist/index.d.ts +0 -0
  532. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/_types/@types_json-schema@7.0.15/index.d.ts +0 -0
  533. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/index.d.ts +0 -0
  534. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/null-to-undefined.d.ts +0 -0
  535. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/provider-compats/anthropic.d.ts +0 -0
  536. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/provider-compats/deepseek.d.ts +0 -0
  537. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/provider-compats/google.d.ts +0 -0
  538. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/provider-compats/meta.d.ts +0 -0
  539. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/provider-compats/openai-reasoning.d.ts +0 -0
  540. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/provider-compats/openai.d.ts +0 -0
  541. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/schema-compatibility-v3.d.ts +0 -0
  542. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/schema-compatibility-v4.d.ts +0 -0
  543. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/schema-compatibility.d.ts +0 -0
  544. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/schema.d.ts +0 -0
  545. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/schema.types.d.ts +0 -0
  546. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/standard-schema/standard-schema.d.ts +0 -0
  547. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/standard-schema/standard-schema.types.d.ts +0 -0
  548. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/standard-schema-compat.d.ts +0 -0
  549. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/types.d.ts +0 -0
  550. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/utils.d.ts +0 -0
  551. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/zod-to-json.d.ts +0 -0
  552. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/package.json +0 -0
@@ -0,0 +1,2189 @@
1
+ import { _ as CustomRouteMatcher, a as findMatchingCustomRoute, c as isCustomRoutePublic, i as coreAuthMiddleware, n as canAccessPublicly, p as pathMatchesPattern, t as authorizeAuthenticatedUser, u as isProtectedCustomRoute } from "./helpers-B56oH6qp.js";
2
+ import { _ as isStudioClientTypeHeader, c as MASTRA_RESOURCE_ID_KEY$1, d as MASTRA_USER_KEY, f as MASTRA_USER_PERMISSIONS_KEY, g as isReservedRequestContextKey, i as MASTRA_IS_STUDIO_KEY, m as RESERVED_REQUEST_CONTEXT_KEYS, n as MASTRA_AUTH_TOKEN_KEY, r as MASTRA_CLIENT_TYPE_HEADER, t as MASTRA_AUTH_MODE_KEY } from "./constants-0xZU_h4R.js";
3
+ import { formatZodError, isZodError } from "./server/handlers/error.js";
4
+ import { t as HTTPException } from "./http-exception-CzaWkxMl.js";
5
+ import { n as createRoute, o as convertCustomRoutesToOpenAPIPaths, s as generateOpenAPIDocument } from "./route-builder-Dz18c3qm.js";
6
+ import { d as resolveServerRoute, f as isBuiltinMCPEnabled, n as OPT_IN_ROUTES, p as resolveBuiltinMCPPath, r as SERVER_ROUTES, s as getEffectivePermission } from "./routes-CmkPohqd.js";
7
+ import { o as normalizeRoutePath } from "./utils-BfySxdfF.js";
8
+ import { z } from "zod/v4";
9
+ import { Readable } from "stream";
10
+ import { hasPermission } from "@mastra/core/auth/ee";
11
+ import { RequestContext } from "@mastra/core/request-context";
12
+ import { MastraServerBase } from "@mastra/core/server";
13
+ import { Hono } from "hono";
14
+ import { safeStringify } from "@mastra/core/utils";
15
+ import { pipeline } from "stream/promises";
16
+ // src/server/mcp/oauth.ts
17
+ /** RFC 9728 well-known path for OAuth protected-resource metadata. */
18
+ const OAUTH_PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource";
19
+ const warnedAudience = /* @__PURE__ */ new WeakSet();
20
+ const resourceValidity = /* @__PURE__ */ new WeakMap();
21
+ const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
22
+ "localhost",
23
+ "127.0.0.1",
24
+ "[::1]"
25
+ ]);
26
+ /** `server.auth` when it is a provider instance (only providers carry the OAuth hooks). */
27
+ function getAuthProvider(mastra) {
28
+ const auth = mastra.getServer()?.auth;
29
+ return auth && typeof auth.authenticateToken === "function" ? auth : void 0;
30
+ }
31
+ function getOAuthConfig(mastra) {
32
+ return mastra.getServer()?.mcp?.oauth ?? {};
33
+ }
34
+ /** RFC 9728 resource identifier: absolute https URL (http only for loopback hosts) without a fragment. */
35
+ function isValidResourceUrl(resource) {
36
+ let url;
37
+ try {
38
+ url = new URL(resource);
39
+ } catch {
40
+ return false;
41
+ }
42
+ if (resource.includes("#")) return false;
43
+ return url.protocol === "https:" || url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname);
44
+ }
45
+ /** Whether `server.mcp.oauth.resource` is unset or valid. Logs one error per instance when it isn't. */
46
+ function hasValidResource(mastra) {
47
+ const { resource } = getOAuthConfig(mastra);
48
+ if (resource === void 0) return true;
49
+ let valid = resourceValidity.get(mastra);
50
+ if (valid === void 0) {
51
+ valid = isValidResourceUrl(resource);
52
+ resourceValidity.set(mastra, valid);
53
+ if (!valid) mastra.getLogger()?.error(`server.mcp.oauth.resource "${resource}" is not an absolute https URL without a fragment (http is only allowed for localhost). OAuth discovery for the built-in MCP server is disabled. Token audience checks still use this value, so MCP requests are rejected unless the token audience matches it exactly.`);
54
+ }
55
+ return valid;
56
+ }
57
+ function isBuiltinMCPAuthenticated(mastra) {
58
+ return Boolean(mastra.getServer()?.auth) && isBuiltinMCPEnabled(mastra);
59
+ }
60
+ /**
61
+ * Whether OAuth discovery applies: the built-in MCP endpoint is on, requires auth, and any configured
62
+ * `server.mcp.oauth.resource` is valid. Gates the well-known routes and the `resource_metadata` challenge.
63
+ */
64
+ function isMCPOAuthDiscoveryEnabled(mastra) {
65
+ return isBuiltinMCPAuthenticated(mastra) && hasValidResource(mastra);
66
+ }
67
+ /**
68
+ * Whether the built-in MCP endpoint checks token audience: `server.mcp.oauth.resource` is set. An invalid value
69
+ * only turns discovery off; the audience is still checked against it, so a config typo fails closed.
70
+ */
71
+ function isMCPAudienceEnforced(mastra) {
72
+ return isBuiltinMCPAuthenticated(mastra) && getOAuthConfig(mastra).resource !== void 0;
73
+ }
74
+ /** Canonical URL of the MCP endpoint: `server.mcp.oauth.resource`, else derived from the request. */
75
+ function resolveMCPResource(mastra, prefix, requestUrl) {
76
+ return getOAuthConfig(mastra).resource ?? `${new URL(requestUrl).origin}${prefix}${resolveBuiltinMCPPath(mastra)}`;
77
+ }
78
+ /** Absolute URL of the path-suffixed metadata document advertised in `WWW-Authenticate`. */
79
+ function mcpResourceMetadataUrl(mastra, prefix, requestUrl) {
80
+ return `${new URL(getOAuthConfig(mastra).resource ?? requestUrl).origin}${OAUTH_PROTECTED_RESOURCE_PATH}${prefix}${resolveBuiltinMCPPath(mastra)}`;
81
+ }
82
+ /** RFC 9728 metadata for the built-in MCP endpoint. Unset optional fields are omitted. */
83
+ function resolveMCPResourceMetadata(mastra, prefix, requestUrl) {
84
+ const config = getOAuthConfig(mastra);
85
+ const hints = getAuthProvider(mastra)?.getOAuthMetadata?.();
86
+ const authorizationServers = config.authorizationServers ?? hints?.authorizationServers;
87
+ const scopesSupported = config.scopesSupported ?? hints?.scopesSupported;
88
+ return {
89
+ resource: resolveMCPResource(mastra, prefix, requestUrl),
90
+ ...authorizationServers?.length ? { authorization_servers: authorizationServers } : {},
91
+ ...scopesSupported?.length ? { scopes_supported: scopesSupported } : {},
92
+ bearer_methods_supported: ["header"]
93
+ };
94
+ }
95
+ /**
96
+ * `WWW-Authenticate` value for a 401 from the built-in MCP endpoint (RFC 6750 §3 auth-params, quoted and escaped).
97
+ * `resource_metadata` is only included while discovery is enabled.
98
+ */
99
+ function mcpWWWAuthenticate(mastra, prefix, requestUrl, error) {
100
+ const params = {
101
+ ...isMCPOAuthDiscoveryEnabled(mastra) ? { resource_metadata: mcpResourceMetadataUrl(mastra, prefix, requestUrl) } : {},
102
+ ...error
103
+ };
104
+ return `Bearer ${Object.entries(params).filter(([, value]) => value !== void 0).map(([key, value]) => `${key}="${value.replace(/[\\"]/g, "\\$&")}"`).join(", ")}`;
105
+ }
106
+ /** The innermost provider that authenticated `user`, looking through `CompositeAuth`. Undefined when unknown. */
107
+ function authenticatingLeaf(provider, user) {
108
+ const composite = provider;
109
+ if (typeof composite.getAuthenticatedProvider !== "function") return provider;
110
+ const inner = composite.getAuthenticatedProvider(user);
111
+ return inner && authenticatingLeaf(inner, user);
112
+ }
113
+ /**
114
+ * When `server.mcp.oauth.resource` is set, the token's audience must include it. A provider that can't check the
115
+ * audience is accepted, unless `requireAudience` is on: then the request is rejected.
116
+ */
117
+ async function checkMCPAudience(mastra, user) {
118
+ const { resource, requireAudience } = getOAuthConfig(mastra);
119
+ if (resource === void 0) return true;
120
+ const provider = getAuthProvider(mastra);
121
+ if (requireAudience) {
122
+ if (typeof (provider && authenticatingLeaf(provider, user))?.verifyAudience !== "function") return false;
123
+ }
124
+ if (typeof provider?.verifyAudience !== "function") return true;
125
+ return provider.verifyAudience(user, resource);
126
+ }
127
+ function leafProviders(provider) {
128
+ const inner = provider.getProviders?.();
129
+ return inner ? inner.flatMap(leafProviders) : [provider];
130
+ }
131
+ /** Warns once when `server.mcp.oauth.resource` is set but some provider cannot check token audience. */
132
+ function warnOnUnenforcedMCPAudience(mastra) {
133
+ if (warnedAudience.has(mastra) || getOAuthConfig(mastra).resource === void 0) return;
134
+ warnedAudience.add(mastra);
135
+ if (!mastra.getServer()?.auth) return;
136
+ const provider = getAuthProvider(mastra);
137
+ const unenforced = provider ? leafProviders(provider).filter((p) => typeof p.verifyAudience !== "function").map((p) => p.name || "server.auth") : ["server.auth"];
138
+ if (!unenforced.length) return;
139
+ const consequence = getOAuthConfig(mastra).requireAudience ? "requireAudience is on, so MCP requests authenticated by them are rejected." : "MCP requests authenticated by them are accepted for any audience. Set server.mcp.oauth.requireAudience to reject them.";
140
+ mastra.getLogger()?.warn(`server.mcp.oauth.resource is set, but ${unenforced.join(", ")} cannot check the token audience: ${consequence}`);
141
+ }
142
+ /**
143
+ * Public routes serving the metadata at `/.well-known/oauth-protected-resource` and its path-suffixed
144
+ * form for the MCP endpoint. Mounted at the server root (outside the API prefix), not in SERVER_ROUTES.
145
+ */
146
+ function createMCPOAuthMetadataRoutes(mastra, prefix) {
147
+ return [OAUTH_PROTECTED_RESOURCE_PATH, `${OAUTH_PROTECTED_RESOURCE_PATH}${prefix}${resolveBuiltinMCPPath(mastra)}`].map((path) => createRoute({
148
+ method: "GET",
149
+ path,
150
+ responseType: "datastream-response",
151
+ summary: "OAuth protected-resource metadata",
152
+ description: "RFC 9728 metadata for the built-in MCP endpoint",
153
+ tags: ["MCP"],
154
+ requiresAuth: false,
155
+ handler: async ({ mastra, request }) => Response.json(resolveMCPResourceMetadata(mastra, prefix, request?.url ?? `http://localhost${path}`), { headers: { "Cache-Control": "no-store" } })
156
+ }));
157
+ }
158
+ // src/server/server-adapter/routes/fga-manifest.ts
159
+ function isProtectedFGARoute$1(route) {
160
+ return route.requiresAuth !== false;
161
+ }
162
+ function getToolRoutePermission(path) {
163
+ return path.includes("/execute") ? "tools:execute" : "tools:read";
164
+ }
165
+ function getAgentToolResourceId(agentId, toolId) {
166
+ return `${agentId}:${toolId}`;
167
+ }
168
+ function getMCPToolResourceId(serverId, toolId) {
169
+ return JSON.stringify([serverId, toolId]);
170
+ }
171
+ const STORED_ROUTE_FGA = {
172
+ agents: {
173
+ resourceType: "stored-agents",
174
+ idParams: ["storedAgentId", "agentId"]
175
+ },
176
+ "mcp-clients": {
177
+ resourceType: "stored-mcp-clients",
178
+ idParams: ["storedMCPClientId", "mcpClientId"]
179
+ },
180
+ "prompt-blocks": {
181
+ resourceType: "stored-prompt-blocks",
182
+ idParams: ["storedPromptBlockId", "promptBlockId"]
183
+ },
184
+ scorers: {
185
+ resourceType: "stored-scorers",
186
+ idParams: ["storedScorerId", "scorerId"]
187
+ },
188
+ skills: {
189
+ resourceType: "stored-skills",
190
+ idParams: ["storedSkillId"]
191
+ },
192
+ workspaces: {
193
+ resourceType: "stored-workspaces",
194
+ idParams: ["storedWorkspaceId"]
195
+ }
196
+ };
197
+ function getStoredResourceRouteFGAConfig(path, permission) {
198
+ const match = path.match(/^\/stored\/([^/]+)/);
199
+ if (!match?.[1]) return null;
200
+ const config = STORED_ROUTE_FGA[match[1]];
201
+ if (!config) return null;
202
+ return {
203
+ resourceType: config.resourceType,
204
+ resourceId: (params, { requestContext }) => {
205
+ for (const idParam of config.idParams) {
206
+ const id = params[idParam];
207
+ if (typeof id === "string" && id) return id;
208
+ }
209
+ const scopedResourceId = requestContext?.get(MASTRA_RESOURCE_ID_KEY$1);
210
+ return typeof scopedResourceId === "string" && scopedResourceId ? scopedResourceId : config.resourceType;
211
+ },
212
+ permission
213
+ };
214
+ }
215
+ function getBuiltInRouteFGAConfig(route) {
216
+ if (!isProtectedFGARoute$1(route) || !route.path || !route.method) return null;
217
+ const permission = getEffectivePermission(route);
218
+ if (!permission) return null;
219
+ const path = route.path;
220
+ const storedRouteConfig = getStoredResourceRouteFGAConfig(path, permission);
221
+ if (storedRouteConfig) return storedRouteConfig;
222
+ if (path.startsWith("/agents/:agentId/tools/:toolId")) return {
223
+ resourceType: "tool",
224
+ resourceId: ({ agentId, toolId }) => getAgentToolResourceId(String(agentId), String(toolId)),
225
+ permission: getToolRoutePermission(path)
226
+ };
227
+ if (path.startsWith("/agents/:agentId")) return {
228
+ resourceType: "agent",
229
+ resourceIdParam: "agentId",
230
+ permission
231
+ };
232
+ if (path.startsWith("/workflows/:workflowId")) return {
233
+ resourceType: "workflow",
234
+ resourceIdParam: "workflowId",
235
+ permission
236
+ };
237
+ if (path.startsWith("/tools/:toolId")) return {
238
+ resourceType: "tool",
239
+ resourceIdParam: "toolId",
240
+ permission
241
+ };
242
+ if (path.startsWith("/mcp/:serverId/tools/:toolId")) return {
243
+ resourceType: "tool",
244
+ resourceId: ({ serverId, toolId }) => getMCPToolResourceId(String(serverId), String(toolId)),
245
+ permission: getToolRoutePermission(path)
246
+ };
247
+ if (path.startsWith("/mcp/:serverId")) return {
248
+ resourceType: "mcp",
249
+ resourceIdParam: "serverId",
250
+ permission
251
+ };
252
+ if (path.startsWith("/knowledge/:knowledgeKey")) return {
253
+ resourceType: "knowledge",
254
+ resourceIdParam: "knowledgeKey",
255
+ permission
256
+ };
257
+ if (path.startsWith("/memory/threads/:threadId") || path.startsWith("/memory/network/threads/:threadId")) return {
258
+ resourceType: "thread",
259
+ resourceIdParam: "threadId",
260
+ permission
261
+ };
262
+ if (path === "/memory/threads" || path === "/memory/network/threads") return {
263
+ resourceType: "thread",
264
+ resourceId: ({ threadId, resourceId }) => {
265
+ if (typeof threadId === "string") return threadId;
266
+ return typeof resourceId === "string" ? resourceId : void 0;
267
+ },
268
+ permission
269
+ };
270
+ if (path === "/memory/save-messages" || path === "/memory/network/save-messages") return {
271
+ resourceType: "thread",
272
+ resourceId: ({ messages }) => {
273
+ if (!Array.isArray(messages)) return void 0;
274
+ const threadId = messages.find((message) => message && typeof message === "object" && "threadId" in message)?.threadId;
275
+ return typeof threadId === "string" ? threadId : void 0;
276
+ },
277
+ permission
278
+ };
279
+ if (path === "/v1/responses") return {
280
+ resourceType: "agent",
281
+ resourceIdParam: "agent_id",
282
+ permission
283
+ };
284
+ if (path.startsWith("/v1/responses/:responseId")) return {
285
+ resourceType: "response",
286
+ resourceIdParam: "responseId",
287
+ permission
288
+ };
289
+ if (path === "/v1/conversations") return {
290
+ resourceType: "agent",
291
+ resourceIdParam: "agent_id",
292
+ permission
293
+ };
294
+ if (path.startsWith("/v1/conversations/:conversationId")) return {
295
+ resourceType: "conversation",
296
+ resourceIdParam: "conversationId",
297
+ permission
298
+ };
299
+ return null;
300
+ }
301
+ // src/server/server-adapter/mcp-auth.ts
302
+ /**
303
+ * Key under which `applyMcpRequestAuth` attaches the trusted request context to
304
+ * `req.auth`. `@mastra/mcp` reads the same registered symbol and copies the
305
+ * values into the request context its tools receive. A symbol cannot come out
306
+ * of a token or JSON payload, so only server code can supply it.
307
+ */
308
+ const MCP_TRUSTED_REQUEST_CONTEXT = Symbol.for("mastra.mcp.trustedRequestContext");
309
+ function normalizeScopes(value) {
310
+ if (Array.isArray(value)) return value.filter((s) => typeof s === "string");
311
+ if (typeof value === "string") return value.split(/[\s,]+/).filter(Boolean);
312
+ return [];
313
+ }
314
+ function resolveClientId(user) {
315
+ for (const key of [
316
+ "id",
317
+ "sub",
318
+ "userId",
319
+ "email"
320
+ ]) {
321
+ const value = user[key];
322
+ if (typeof value === "string" && value) return value;
323
+ }
324
+ return "";
325
+ }
326
+ /**
327
+ * Build the default `AuthInfo` from the Mastra request context.
328
+ *
329
+ * Returns `undefined` when the request carries no identity at all, so servers
330
+ * without auth keep behaving exactly as before.
331
+ */
332
+ function buildMcpAuthInfoFromRequestContext(requestContext) {
333
+ const user = requestContext.get(MASTRA_USER_KEY);
334
+ const token = requestContext.get(MASTRA_AUTH_TOKEN_KEY);
335
+ const hasUser = !!user && typeof user === "object";
336
+ const hasToken = typeof token === "string" && token.length > 0;
337
+ if (!hasUser && !hasToken) return void 0;
338
+ const userRecord = hasUser ? user : {};
339
+ return {
340
+ token: hasToken ? token : "",
341
+ clientId: resolveClientId(userRecord),
342
+ scopes: normalizeScopes(userRecord.scopes ?? userRecord.scope ?? userRecord.permissions),
343
+ ...hasUser ? { extra: { user: userRecord } } : {}
344
+ };
345
+ }
346
+ /**
347
+ * Populate `req.auth` on the Node request that is about to be handed to an MCP
348
+ * transport.
349
+ *
350
+ * Resolution order:
351
+ * 1. An already-set `req.auth` keeps its identity.
352
+ * 2. A configured `setRequestAuth` hook runs and fully owns the result.
353
+ * 3. Otherwise the principal resolved by Mastra server auth is bridged from the
354
+ * request context using the default mapping.
355
+ *
356
+ * Whichever way `req.auth` is set, the trusted request context is attached to
357
+ * it so MCP tools see the same principal as Mastra routes.
358
+ */
359
+ async function applyMcpRequestAuth({ req, requestContext, setRequestAuth }) {
360
+ const request = req;
361
+ if (!requestContext) return;
362
+ if (!request.auth) {
363
+ if (setRequestAuth) await setRequestAuth(req, requestContext);
364
+ else {
365
+ const authInfo = buildMcpAuthInfoFromRequestContext(requestContext);
366
+ if (authInfo) request.auth = authInfo;
367
+ }
368
+ }
369
+ if (request.auth && typeof request.auth === "object") attachTrustedRequestContext(request.auth, requestContext);
370
+ }
371
+ /**
372
+ * Hands MCP tools the values Mastra server auth resolved for this request
373
+ * (user, permissions, roles, resource id, tenant, auth mode), so a tool called
374
+ * over MCP is authorized the same way as the matching HTTP route. The token is
375
+ * left out; it is already on `authInfo`.
376
+ */
377
+ function attachTrustedRequestContext(auth, requestContext) {
378
+ const trusted = {};
379
+ for (const key of RESERVED_REQUEST_CONTEXT_KEYS) {
380
+ if (key === "mastra__authToken" || !requestContext.has(key)) continue;
381
+ trusted[key] = requestContext.get(key);
382
+ }
383
+ Object.defineProperty(auth, MCP_TRUSTED_REQUEST_CONTEXT, {
384
+ value: trusted,
385
+ configurable: true
386
+ });
387
+ }
388
+ // src/server/server-adapter/mcp-disconnect.ts
389
+ /**
390
+ * Forwards a fetch `Request` abort to the simulated Node response used by fetch-based
391
+ * adapters (Hono, Elysia, Next) to drive the MCP Node transport.
392
+ *
393
+ * `fetch-to-node`'s `toReqRes` ignores `Request.signal`, and the MCP Node transport only
394
+ * aborts an in-flight request when `res` emits `close`. Without this, a client that
395
+ * disconnects before any response bytes are sent leaves the tool call running to completion.
396
+ *
397
+ * Call it after `startHTTP` has been invoked so the transport's `close` listener is attached.
398
+ */
399
+ function propagateRequestAbort(signal, res) {
400
+ if (!signal) return;
401
+ const onAbort = () => {
402
+ if (res.writableFinished) return;
403
+ try {
404
+ res.emit("close");
405
+ } catch {}
406
+ };
407
+ if (signal.aborted) {
408
+ onAbort();
409
+ return;
410
+ }
411
+ signal.addEventListener("abort", onAbort, { once: true });
412
+ res.once("finish", () => signal.removeEventListener("abort", onAbort));
413
+ }
414
+ // src/server/server-adapter/redact.ts
415
+ /**
416
+ * Redacts request data from a v2 format payload.
417
+ * Removes `metadata.request` and `output.steps[].request` from the payload.
418
+ */
419
+ function redactV2Payload(payload) {
420
+ const redactedPayload = { ...payload };
421
+ if (redactedPayload.metadata && typeof redactedPayload.metadata === "object") {
422
+ const { request, ...metadataRest } = redactedPayload.metadata;
423
+ redactedPayload.metadata = metadataRest;
424
+ }
425
+ if (redactedPayload.output && typeof redactedPayload.output === "object") {
426
+ const output = { ...redactedPayload.output };
427
+ if (Array.isArray(output.steps)) output.steps = output.steps.map((step) => {
428
+ if (step && typeof step === "object") {
429
+ const { request, ...stepRest } = step;
430
+ return stepRest;
431
+ }
432
+ return step;
433
+ });
434
+ redactedPayload.output = output;
435
+ }
436
+ return redactedPayload;
437
+ }
438
+ /**
439
+ * Redacts sensitive data from stream chunks before they are sent to clients.
440
+ *
441
+ * This function strips out request bodies that may contain sensitive information
442
+ * such as system prompts, tool definitions, API keys, and other configuration data.
443
+ *
444
+ * Handles both v1 (legacy) and v2 stream formats:
445
+ *
446
+ * v1 format (fields at root level):
447
+ * - `step-start.request` - Contains the full LLM request body
448
+ * - `step-finish.request` - Contains the request body
449
+ * - `finish.request` - Contains the request body (if present)
450
+ *
451
+ * v2 format (fields nested in payload):
452
+ * - `step-start.payload.request` - Contains the full LLM request body
453
+ * - `step-finish.payload.metadata.request` - Contains the request metadata
454
+ * - `step-finish.payload.output.steps[].request` - Contains request data for each step
455
+ * - `finish.payload.metadata.request` - Contains the request metadata
456
+ * - `finish.payload.output.steps[].request` - Contains request data for each step
457
+ *
458
+ * @param chunk - The stream chunk to redact
459
+ * @returns A new chunk with sensitive data removed, or the original chunk if no redaction needed
460
+ */
461
+ function redactStreamChunk(chunk) {
462
+ if (!chunk || typeof chunk !== "object") return chunk;
463
+ const typedChunk = chunk;
464
+ switch (chunk.type) {
465
+ case "step-start":
466
+ if ("payload" in typedChunk && typedChunk.payload && typeof typedChunk.payload === "object") {
467
+ const { payload, ...rest } = typedChunk;
468
+ const { request, ...payloadRest } = payload;
469
+ return {
470
+ ...rest,
471
+ type: "step-start",
472
+ payload: {
473
+ ...payloadRest,
474
+ request: {}
475
+ }
476
+ };
477
+ } else if ("request" in typedChunk) {
478
+ const { request, ...rest } = typedChunk;
479
+ return {
480
+ ...rest,
481
+ type: "step-start",
482
+ request: {}
483
+ };
484
+ }
485
+ return chunk;
486
+ case "step-finish":
487
+ if ("payload" in typedChunk && typedChunk.payload && typeof typedChunk.payload === "object") {
488
+ const { payload, ...rest } = typedChunk;
489
+ return {
490
+ ...rest,
491
+ type: "step-finish",
492
+ payload: redactV2Payload(payload)
493
+ };
494
+ } else if ("request" in typedChunk) {
495
+ const { request, ...rest } = typedChunk;
496
+ return {
497
+ ...rest,
498
+ type: "step-finish"
499
+ };
500
+ }
501
+ return chunk;
502
+ case "finish":
503
+ if ("payload" in typedChunk && typedChunk.payload && typeof typedChunk.payload === "object") {
504
+ const { payload, ...rest } = typedChunk;
505
+ return {
506
+ ...rest,
507
+ type: "finish",
508
+ payload: redactV2Payload(payload)
509
+ };
510
+ } else if ("request" in typedChunk) {
511
+ const { request, ...rest } = typedChunk;
512
+ return {
513
+ ...rest,
514
+ type: "finish"
515
+ };
516
+ }
517
+ return chunk;
518
+ default: return chunk;
519
+ }
520
+ }
521
+ // src/server/server-adapter/serialize.ts
522
+ /**
523
+ * Serializes a stream chunk to JSON for wire transport.
524
+ *
525
+ * Stream chunks can contain values that plain `JSON.stringify` throws on
526
+ * (e.g. BigInt produced by zod coercions/transforms in structuredOutput
527
+ * schemas, or circular references) — `safeStringify` handles those. A single
528
+ * bad chunk must never kill the whole stream — Studio relies on later chunks
529
+ * (`workflow-step-result`, `workflow-finish`) to render run state.
530
+ *
531
+ * Returns `{ ok: false, error }` if the chunk cannot be serialized at all
532
+ * (e.g. a throwing getter/toJSON) — callers should log the error, skip the
533
+ * chunk, and keep streaming.
534
+ */
535
+ function serializeStreamChunk(chunk) {
536
+ try {
537
+ return {
538
+ ok: true,
539
+ json: safeStringify(withPlainPayloadError(chunk))
540
+ };
541
+ } catch (error) {
542
+ return {
543
+ ok: false,
544
+ error: error instanceof Error ? error : new Error(String(error))
545
+ };
546
+ }
547
+ }
548
+ /**
549
+ * `JSON.stringify(new Error('x'))` keeps only own enumerable fields, so an Error subclass that sets `name`
550
+ * arrives as `{ name }` and clients show `[object Object]`. Send the message too; never the stack. An
551
+ * error whose class curates its JSON (`toJSON`, e.g. MastraError) keeps that shape, so fields it leaves
552
+ * out stay out.
553
+ */
554
+ function withPlainPayloadError(chunk) {
555
+ if (!chunk || typeof chunk !== "object" || !("payload" in chunk)) return chunk;
556
+ const { payload } = chunk;
557
+ if (!payload || typeof payload !== "object" || !("error" in payload)) return chunk;
558
+ const { error } = payload;
559
+ if (!(error instanceof Error)) return withoutStack(chunk, payload, error);
560
+ const plain = {
561
+ ...curatedJson(error) ?? error,
562
+ message: error.message
563
+ };
564
+ delete plain.stack;
565
+ if (!plain.name && error.name !== "Error") plain.name = error.name;
566
+ return {
567
+ ...chunk,
568
+ payload: {
569
+ ...payload,
570
+ error: plain
571
+ }
572
+ };
573
+ }
574
+ /** An error that is already a plain object (a replayed one) is kept as is, minus its stack. */
575
+ function withoutStack(chunk, payload, error) {
576
+ if (!error || typeof error !== "object" || Array.isArray(error) || !("stack" in error)) return chunk;
577
+ const { stack: _stack, ...rest } = error;
578
+ return {
579
+ ...chunk,
580
+ payload: {
581
+ ...payload,
582
+ error: rest
583
+ }
584
+ };
585
+ }
586
+ function curatedJson(error) {
587
+ const toJSON = error.toJSON;
588
+ if (typeof toJSON !== "function") return void 0;
589
+ try {
590
+ const json = toJSON.call(error);
591
+ return json && typeof json === "object" ? json : void 0;
592
+ } catch {
593
+ return;
594
+ }
595
+ }
596
+ // src/server/server-adapter/stream-disconnect.ts
597
+ /**
598
+ * Cancels `reader` once when the Node response closes, so a disconnected client stops the upstream stream.
599
+ *
600
+ * Cancels right away when the response is already destroyed: if the client dropped while the route handler
601
+ * was still running, `close` fired before this listener existed. Call `dispose()` before ending the response
602
+ * so the close that follows a normal end does not cancel.
603
+ */
604
+ function cancelReaderOnResponseClose(reader, res) {
605
+ let canceled = false;
606
+ const cancel = (reason) => {
607
+ if (canceled) return;
608
+ canceled = true;
609
+ reader.cancel(reason).catch(() => {});
610
+ };
611
+ const onClose = () => cancel("request aborted");
612
+ res.on("close", onClose);
613
+ if (res.destroyed) onClose();
614
+ return {
615
+ cancel,
616
+ dispose: () => res.off("close", onClose)
617
+ };
618
+ }
619
+ const pendingWrites = /* @__PURE__ */ new WeakMap();
620
+ function getPendingWrites(res) {
621
+ const existing = pendingWrites.get(res);
622
+ if (existing) return existing;
623
+ const queue = [];
624
+ const release = () => {
625
+ for (const resolve of queue.splice(0)) resolve();
626
+ };
627
+ res.on("drain", release);
628
+ res.on("close", release);
629
+ pendingWrites.set(res, queue);
630
+ return queue;
631
+ }
632
+ /**
633
+ * Writes `chunk` and, when the socket buffer is full, waits for `drain` so a slow client pauses reads from the
634
+ * upstream stream instead of growing the buffer. Resolves on `close` too, so a dropped client never stalls the caller.
635
+ */
636
+ async function writeWithBackpressure(res, chunk) {
637
+ if (res.write(chunk) !== false || res.destroyed) return;
638
+ await new Promise((resolve) => getPendingWrites(res).push(resolve));
639
+ }
640
+ // src/server/server-adapter/index.ts
641
+ function getCustomHTTPExceptionResponse(error) {
642
+ if (!(error instanceof HTTPException) || !error.res) return;
643
+ return error.getResponse();
644
+ }
645
+ /**
646
+ * Response for an HTTPException thrown from a `registerApiRoute` handler, or undefined for
647
+ * any other error (which callers keep behind a generic 500). Duck-typed so an HTTPException
648
+ * from `hono/http-exception`, possibly a separate Hono install, is recognised too.
649
+ */
650
+ function getCustomRouteHTTPExceptionResponse(error) {
651
+ if (!(error instanceof Error)) return void 0;
652
+ const httpError = error;
653
+ const status = httpError.status;
654
+ if (typeof httpError.getResponse !== "function" || typeof status !== "number" || !Number.isInteger(status) || status < 400 || status > 599) return;
655
+ if (httpError.res) return httpError.getResponse.call(httpError);
656
+ return Response.json({ error: httpError.message }, { status });
657
+ }
658
+ /**
659
+ * Only allowlisted causes are exposed to clients; any other cause stays server-side:
660
+ * - `cause.failingItems` (dataset schema-update rejections)
661
+ * - `cause.field` + `cause.errors` (schema validation failures), reduced to each error's path and message
662
+ */
663
+ function getSafeErrorCause(error) {
664
+ try {
665
+ const raw = error instanceof Error ? error.cause : void 0;
666
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
667
+ if (Array.isArray(raw.failingItems)) return { failingItems: raw.failingItems };
668
+ const { field, errors } = raw;
669
+ if (typeof field === "string" && Array.isArray(errors)) return {
670
+ field,
671
+ errors: errors.flatMap((e) => e && typeof e.path === "string" && typeof e.message === "string" ? [{
672
+ path: e.path,
673
+ message: e.message
674
+ }] : [])
675
+ };
676
+ } catch {}
677
+ }
678
+ /**
679
+ * Maps a handler error to the status and JSON body every adapter sends:
680
+ * `error.status` (HTTPException) first, then `error.details.status` (MastraError), else 500.
681
+ */
682
+ function getHTTPErrorResponse(error) {
683
+ const message = error instanceof Error ? error.message : "Unknown error";
684
+ if (error && typeof error === "object") {
685
+ if ("status" in error) {
686
+ const cause = getSafeErrorCause(error);
687
+ return {
688
+ status: error.status,
689
+ body: {
690
+ error: message,
691
+ ...cause ? { cause } : {}
692
+ }
693
+ };
694
+ }
695
+ if ("details" in error && error.details && typeof error.details === "object" && "status" in error.details) return {
696
+ status: error.details.status,
697
+ body: { error: message }
698
+ };
699
+ }
700
+ return {
701
+ status: 500,
702
+ body: { error: message }
703
+ };
704
+ }
705
+ /**
706
+ * Hono/adapter context key set by the framework-public middleware.
707
+ *
708
+ * When true, the current request targets a route the framework has declared
709
+ * public (via `createPublicRoute()` / `requiresAuth: false`). Adapter authors
710
+ * MUST short-circuit any user-registered middleware for such requests so that
711
+ * users cannot accidentally (or intentionally) 401 routes the framework needs
712
+ * to keep reachable (e.g. Studio sign-in endpoints).
713
+ */
714
+ const MASTRA_FRAMEWORK_PUBLIC_KEY = "__mastraFrameworkPublic";
715
+ const AGENT_CHANNEL_WEBHOOK_PATH = /^\/api\/agents\/([^/]+)\/channels\/([^/]+)\/webhook\/?$/;
716
+ function isAbortSignalError(error) {
717
+ if (!error || typeof error !== "object") return false;
718
+ const { code, name } = error;
719
+ return name === "AbortError" || code === "ABORT_ERR";
720
+ }
721
+ function isExpectedResponseCloseError(error) {
722
+ if (!error || typeof error !== "object") return false;
723
+ const { code } = error;
724
+ return code === "ECONNRESET" || code === "EPIPE" || code === "ERR_STREAM_DESTROYED" || code === "ERR_STREAM_WRITE_AFTER_END" || code === "ERR_STREAM_PREMATURE_CLOSE";
725
+ }
726
+ /**
727
+ * Returns `response` with a pass-through body that holds the re-dispatched
728
+ * custom route `request` until that body is fully read, errors or is cancelled.
729
+ *
730
+ * `new Request(url, { signal })` gives the request its own signal and forwards
731
+ * the outer abort to it through a listener that only weakly references the
732
+ * request's controller (nodejs/undici#4068). Once a custom route returns a
733
+ * streaming Response, nothing else holds that inner Request, so a GC can drop
734
+ * it and a client disconnect never reaches `c.req.raw.signal` (#29154).
735
+ *
736
+ * The reference lives on the body because the body is reachable exactly while
737
+ * an adapter is still sending the response. Anything reachable from the outer
738
+ * signal (a WeakMap keyed by it, or an abort listener on it) would leak instead:
739
+ * undici's request finalizer holds the outer signal strongly while the inner
740
+ * controller is alive, so signal -> request -> controller -> signal is never
741
+ * collected when the signal never aborts, as after a normal Express response.
742
+ * An abort ends or cancels the body, which releases the request too.
743
+ */
744
+ function retainRequestWhileBodyIsOpen(response, request) {
745
+ const source = response.body;
746
+ if (!source) return response;
747
+ const reader = source.getReader();
748
+ const retained = { request };
749
+ const release = () => {
750
+ retained.request = void 0;
751
+ };
752
+ const body = new ReadableStream({
753
+ async pull(controller) {
754
+ try {
755
+ const { done, value } = await reader.read();
756
+ if (done) {
757
+ release();
758
+ controller.close();
759
+ } else controller.enqueue(value);
760
+ } catch (error) {
761
+ release();
762
+ controller.error(error);
763
+ }
764
+ },
765
+ cancel(reason) {
766
+ release();
767
+ return reader.cancel(reason);
768
+ }
769
+ }, { highWaterMark: 0 });
770
+ return new Response(body, {
771
+ status: response.status,
772
+ statusText: response.statusText,
773
+ headers: response.headers
774
+ });
775
+ }
776
+ function isResponseClosed(response) {
777
+ return Boolean(response.writableEnded || response.destroyed);
778
+ }
779
+ function isProtectedFGARoute(route) {
780
+ return route.requiresAuth !== false;
781
+ }
782
+ function formatRoute(route) {
783
+ return `${route.method} ${route.path}`;
784
+ }
785
+ function isSchemaApiRoute(route) {
786
+ return "_mastraSchemaRoute" in route && route._mastraSchemaRoute === true;
787
+ }
788
+ function getFGAProvider(mastra, requestContext) {
789
+ if (requestContext) {
790
+ if (requestContext.get("mastra__authMode") === "studio") {
791
+ const studioFga = mastra?.getStudio?.()?.fga;
792
+ if (studioFga) return studioFga;
793
+ }
794
+ }
795
+ return mastra?.getServer?.()?.fga;
796
+ }
797
+ function getFGARouteInfo(route) {
798
+ return {
799
+ path: route.path,
800
+ method: route.method,
801
+ requiresAuth: route.requiresAuth,
802
+ requiresPermission: route.requiresPermission,
803
+ fga: route.fga
804
+ };
805
+ }
806
+ function getRoutePermissions(route) {
807
+ return [getEffectivePermission(route), route.fga?.permission].flatMap((value) => Array.isArray(value) ? value : [value]).filter((permission) => Boolean(permission));
808
+ }
809
+ async function resolveRouteFGAConfig(fgaProvider, route, requestContext, params) {
810
+ if (route.fga) return route.fga;
811
+ const resolvedConfig = await fgaProvider.resolveRouteFGA?.({
812
+ route: getFGARouteInfo(route),
813
+ params,
814
+ requestContext
815
+ });
816
+ if (resolvedConfig) return resolvedConfig;
817
+ return getBuiltInRouteFGAConfig(route);
818
+ }
819
+ function getSchemaTypeName(schema) {
820
+ const schemaDef = schema?._def ?? schema?.def;
821
+ return schemaDef?.typeName ?? schemaDef?.type;
822
+ }
823
+ function unwrapOptionalNullable(schema) {
824
+ let inner = schema;
825
+ let typeName = getSchemaTypeName(inner);
826
+ while (typeName === "ZodOptional" || typeName === "ZodNullable" || typeName === "optional" || typeName === "nullable") {
827
+ const innerDef = inner?._def ?? inner?.def;
828
+ if (!innerDef?.innerType) return inner;
829
+ inner = innerDef.innerType;
830
+ typeName = getSchemaTypeName(inner);
831
+ }
832
+ return inner;
833
+ }
834
+ function parseComplexQueryParams(queryParamSchema, params) {
835
+ if (!(queryParamSchema instanceof z.ZodObject)) return params;
836
+ const parsedParams = { ...params };
837
+ const shape = queryParamSchema.shape;
838
+ for (const [key, fieldSchema] of Object.entries(shape)) {
839
+ const rawValue = parsedParams[key];
840
+ if (typeof rawValue !== "string") continue;
841
+ const typeName = getSchemaTypeName(unwrapOptionalNullable(fieldSchema));
842
+ if (!(typeName === "ZodObject" || typeName === "ZodArray" || typeName === "ZodRecord" || typeName === "object" || typeName === "array" || typeName === "record")) continue;
843
+ try {
844
+ parsedParams[key] = JSON.parse(rawValue);
845
+ } catch {}
846
+ }
847
+ return parsedParams;
848
+ }
849
+ /**
850
+ * Property names that must never be written onto objects built from untrusted
851
+ * input: assigning them can mutate the object's prototype chain.
852
+ */
853
+ const UNSAFE_OBJECT_KEYS = /* @__PURE__ */ new Set([
854
+ "__proto__",
855
+ "prototype",
856
+ "constructor"
857
+ ]);
858
+ /**
859
+ * Returns whether `key` is safe to use as a property name when building an
860
+ * object from untrusted input (query strings, form fields, etc.).
861
+ */
862
+ function isSafeObjectKey(key) {
863
+ return !UNSAFE_OBJECT_KEYS.has(key);
864
+ }
865
+ /**
866
+ * Normalizes query parameters from various HTTP framework formats to a consistent structure.
867
+ * Handles both single string values and arrays (for repeated query params like ?tag=a&tag=b).
868
+ * Reconstructs bracket-notation keys (e.g., `orderBy[field]=createdAt`) into JSON strings
869
+ * so that z.preprocess JSON.parse can handle them.
870
+ * Filters out non-string values that some frameworks may include.
871
+ *
872
+ * @param rawQuery - Raw query parameters from the HTTP framework (may contain strings, arrays, or nested objects)
873
+ * @returns Normalized query parameters as Record<string, string | string[]>
874
+ */
875
+ function normalizeQueryParams(rawQuery) {
876
+ const queryParams = {};
877
+ const bracketGroups = {};
878
+ for (const [key, value] of Object.entries(rawQuery)) {
879
+ const bracketMatch = key.match(/^([^[]+)\[([^\]]+)\]$/);
880
+ if (bracketMatch) {
881
+ const parent = bracketMatch[1];
882
+ const child = bracketMatch[2];
883
+ const strValue = Array.isArray(value) ? value.filter((v) => typeof v === "string")[0] : typeof value === "string" ? value : void 0;
884
+ if (strValue !== void 0 && isSafeObjectKey(parent) && isSafeObjectKey(child)) {
885
+ if (!Object.hasOwn(bracketGroups, parent)) bracketGroups[parent] = {};
886
+ bracketGroups[parent][child] = strValue;
887
+ }
888
+ } else if (typeof value === "string") {
889
+ if (isSafeObjectKey(key)) queryParams[key] = value;
890
+ } else if (Array.isArray(value)) {
891
+ if (!isSafeObjectKey(key)) continue;
892
+ const stringValues = value.filter((v) => typeof v === "string");
893
+ queryParams[key] = stringValues.length === 1 ? stringValues[0] : stringValues;
894
+ }
895
+ }
896
+ for (const [parent, children] of Object.entries(bracketGroups)) if (!Object.hasOwn(queryParams, parent)) queryParams[parent] = JSON.stringify(children);
897
+ return queryParams;
898
+ }
899
+ /**
900
+ * Abstract base class for server adapters that handle HTTP requests.
901
+ *
902
+ * This class extends `MastraServerBase` to inherit app storage functionality
903
+ * and provides the framework for registering routes, middleware, and handling requests.
904
+ *
905
+ * Framework-specific adapters in @mastra/hono and @mastra/express extend this class
906
+ * (both named `MastraServer` in their respective packages) and implement the abstract
907
+ * methods for their specific framework.
908
+ *
909
+ * @template TApp - The type of the server app (e.g., Hono, Express Application)
910
+ * @template TRequest - The type of the request object
911
+ * @template TResponse - The type of the response object
912
+ */
913
+ var MastraServer = class extends MastraServerBase {
914
+ /** Request bodies cannot set agent scopes: handlers strip `scopes`, and `mastra__scopes` is a reserved key. */
915
+ reservesAgentScopes = true;
916
+ mastra;
917
+ bodyLimitOptions;
918
+ tools;
919
+ prefix;
920
+ openapiPath;
921
+ taskStore;
922
+ customRouteAuthConfig;
923
+ streamOptions;
924
+ httpLoggingConfig;
925
+ customApiRoutes;
926
+ mcpOptions;
927
+ /** This adapter's `registerDispatchAdapter` handle, recorded on each request it serves. */
928
+ dispatchAdapter;
929
+ customRouteHandler = null;
930
+ /** Mirrors the custom-route app's router so auth can ask which route a request runs. */
931
+ customRouteMatcher = null;
932
+ /**
933
+ * Whether custom (non-schema) API routes were registered. Adapters use this
934
+ * at request time to decide if they need to preserve a pristine copy of the
935
+ * request body for the custom-route bridge.
936
+ */
937
+ get hasCustomRouteHandler() {
938
+ return this.customRouteHandler !== null;
939
+ }
940
+ constructor({ app, mastra, bodyLimitOptions, tools, prefix = "/api", openapiPath = "", taskStore, customRouteAuthConfig, streamOptions, customApiRoutes, mcpOptions }) {
941
+ super({
942
+ app,
943
+ name: "MastraServer"
944
+ });
945
+ this.mastra = mastra;
946
+ this.bodyLimitOptions = bodyLimitOptions;
947
+ this.tools = tools;
948
+ this.prefix = normalizeRoutePath(prefix);
949
+ this.dispatchAdapter = registerDispatchAdapter(mastra, {
950
+ prefix: this.prefix,
951
+ getCustomRouteAuthConfig: () => this.customRouteAuthConfig,
952
+ getCustomApiRoutes: () => this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes ?? [],
953
+ checkRouteRBAC: (route, requestContext) => this.checkRouteRBAC(route, requestContext)
954
+ });
955
+ this.openapiPath = openapiPath;
956
+ this.taskStore = taskStore;
957
+ this.customRouteAuthConfig = customRouteAuthConfig;
958
+ this.streamOptions = {
959
+ redact: true,
960
+ ...streamOptions
961
+ };
962
+ this.customApiRoutes = customApiRoutes;
963
+ this.mcpOptions = mcpOptions;
964
+ const serverConfig = mastra.getServer();
965
+ this.httpLoggingConfig = this.parseLoggingConfig(serverConfig?.build?.apiReqLogs);
966
+ mastra.setMastraServer(this);
967
+ }
968
+ /**
969
+ * Parses the apiReqLogs configuration into a normalized HttpLoggingConfig.
970
+ * @param config - The raw config value from server.build.apiReqLogs
971
+ * @returns Normalized HttpLoggingConfig or undefined if disabled
972
+ */
973
+ parseLoggingConfig(config) {
974
+ if (config === true) return {
975
+ enabled: true,
976
+ level: "info",
977
+ redactHeaders: ["authorization", "cookie"]
978
+ };
979
+ if (typeof config === "object" && config.enabled) return {
980
+ enabled: true,
981
+ level: config.level || "info",
982
+ excludePaths: config.excludePaths,
983
+ includeHeaders: config.includeHeaders,
984
+ includeQueryParams: config.includeQueryParams,
985
+ redactHeaders: [.../* @__PURE__ */ new Set([...["authorization", "cookie"], ...config.redactHeaders || []])]
986
+ };
987
+ }
988
+ /**
989
+ * Determines if a request to the given path should be logged.
990
+ * @param path - The request path to check
991
+ * @returns true if the request should be logged, false otherwise
992
+ */
993
+ shouldLogRequest(path) {
994
+ if (!this.httpLoggingConfig?.enabled) return false;
995
+ return !(this.httpLoggingConfig.excludePaths || []).some((excluded) => path === excluded || path.startsWith(excluded + "/"));
996
+ }
997
+ /** Warn when a request looks like an agent channel webhook whose route was never registered. */
998
+ warnIfUnregisteredChannelWebhook(path, method, status) {
999
+ if (status !== 404 || method.toUpperCase() !== "POST") return;
1000
+ const match = AGENT_CHANNEL_WEBHOOK_PATH.exec(path);
1001
+ if (!match) return;
1002
+ const routes = this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes;
1003
+ if (findMatchingCustomRoute(path, method.toUpperCase(), routes)) return;
1004
+ const agentId = match[1];
1005
+ const platform = match[2];
1006
+ const platformLabel = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/i.test(platform) ? platform.split(/[-_]/).map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1)).join(" ") : "channel";
1007
+ this.mastra.getLogger()?.warn(`Received a ${platformLabel} webhook, but this agent doesn't have a ${platformLabel} adapter. Add one to the agent's channels.adapters configuration and restart the server.`, {
1008
+ agentId,
1009
+ platform
1010
+ });
1011
+ }
1012
+ mergeRequestContext({ paramsRequestContext, bodyRequestContext }) {
1013
+ const requestContext = new RequestContext();
1014
+ bindDispatchAdapter(requestContext, this.dispatchAdapter);
1015
+ if (bodyRequestContext) for (const [key, value] of Object.entries(bodyRequestContext)) {
1016
+ if (isReservedRequestContextKey(key)) continue;
1017
+ requestContext.set(key, value);
1018
+ }
1019
+ if (paramsRequestContext) for (const [key, value] of Object.entries(paramsRequestContext)) {
1020
+ if (isReservedRequestContextKey(key)) continue;
1021
+ requestContext.set(key, value);
1022
+ }
1023
+ return requestContext;
1024
+ }
1025
+ applyRequestMetadataToContext({ requestContext, getHeader }) {
1026
+ if (isStudioClientTypeHeader(getHeader("x-mastra-client-type"))) requestContext.set(MASTRA_IS_STUDIO_KEY, true);
1027
+ }
1028
+ /**
1029
+ * Determines which auth configuration to use for the current request.
1030
+ *
1031
+ * Request routing logic:
1032
+ * 1. If `x-mastra-client-type: studio` header is present AND `studio.auth` is configured:
1033
+ * → Use studio auth (for internal team members accessing Studio UI)
1034
+ * 2. If studio header is present but `studio.auth` is NOT configured:
1035
+ * → No auth required (Studio development mode)
1036
+ * 3. Otherwise:
1037
+ * → Use server auth (for external customers calling API)
1038
+ *
1039
+ * Security note: The header is only for routing - auth validation happens
1040
+ * via session cookies/tokens. If someone spoofs the studio header but doesn't
1041
+ * have a valid studio session, they'll get a 401 (not fall back to server auth).
1042
+ */
1043
+ getEffectiveAuthConfig(getHeader) {
1044
+ return resolveEffectiveAuthConfig(this.mastra, getHeader);
1045
+ }
1046
+ /**
1047
+ * Gets the effective RBAC provider for the current request based on auth mode.
1048
+ *
1049
+ * @deprecated Never consulted by route permission checks, so overriding it has no effect.
1050
+ * Override `checkRoutePermission` to change how a route's permission is decided.
1051
+ */
1052
+ getEffectiveRBACProvider(requestContext) {
1053
+ return getEffectiveRBACProvider(this.mastra, requestContext);
1054
+ }
1055
+ /**
1056
+ * Gets the effective FGA provider for the current request based on auth mode.
1057
+ */
1058
+ getEffectiveFGAProvider(requestContext) {
1059
+ if (requestContext.get("mastra__authMode") === "studio") return this.mastra.getStudio?.()?.fga ?? this.mastra.getServer()?.fga;
1060
+ return this.mastra.getServer()?.fga;
1061
+ }
1062
+ /**
1063
+ * Check if the current request should be authenticated/authorized.
1064
+ * Returns null if auth passes, or an error response if it fails.
1065
+ *
1066
+ * This is a thin wrapper around coreAuthMiddleware that:
1067
+ * 1. Routes to the correct auth provider (studio vs server) based on request headers
1068
+ * 2. Handles route-level requiresAuth opt-out (not available in global middleware)
1069
+ * 3. Delegates all other auth logic to coreAuthMiddleware
1070
+ * 4. Translates the AuthResult into the {status, error} format adapters expect
1071
+ *
1072
+ * Security: When `x-mastra-client-type: studio` header is present and studio auth
1073
+ * is configured, we ONLY use studio auth. If authentication fails, we return 401
1074
+ * and redirect to login - we do NOT fall back to server auth. This prevents
1075
+ * external users from spoofing the studio header to access Studio UI.
1076
+ */
1077
+ async checkRouteAuth(route, context) {
1078
+ if (route.authTransport === "bearer") return this.checkBearerRouteAuth(route, context);
1079
+ const effectiveAuth = this.getEffectiveAuthConfig(context.getHeader);
1080
+ if (!effectiveAuth) return null;
1081
+ const { authConfig, authMode } = effectiveAuth;
1082
+ context.requestContext.set(MASTRA_AUTH_MODE_KEY, authMode);
1083
+ if (route.requiresAuth === false) return null;
1084
+ const authHeader = context.getHeader("authorization");
1085
+ let token = authHeader ? authHeader.replace("Bearer ", "") : null;
1086
+ if (!token) token = context.getQuery("apiKey") || null;
1087
+ const fallbackHeaders = new Headers();
1088
+ for (const headerName of ["authorization", "cookie"]) {
1089
+ const headerValue = context.getHeader(headerName);
1090
+ if (headerValue) fallbackHeaders.set(headerName, headerValue);
1091
+ }
1092
+ const result = await coreAuthMiddleware({
1093
+ path: context.path,
1094
+ method: context.method,
1095
+ getHeader: context.getHeader,
1096
+ mastra: this.mastra,
1097
+ authConfig,
1098
+ customRouteAuthConfig: context.customRouteAuthConfig ?? this.customRouteAuthConfig,
1099
+ requestContext: context.requestContext,
1100
+ rawRequest: context.request ?? new Request(`http://localhost${context.path}`, {
1101
+ method: context.method,
1102
+ headers: fallbackHeaders
1103
+ }),
1104
+ token,
1105
+ buildAuthorizeContext: context.buildAuthorizeContext ?? (() => null),
1106
+ requiresAuth: route.requiresAuth
1107
+ });
1108
+ if (result.action === "next") {
1109
+ if (result.headers) return {
1110
+ status: 200,
1111
+ error: "",
1112
+ headers: result.headers
1113
+ };
1114
+ return null;
1115
+ }
1116
+ const errorBody = result.body;
1117
+ return {
1118
+ status: result.status,
1119
+ error: errorBody?.error ?? "Access denied",
1120
+ headers: result.headers
1121
+ };
1122
+ }
1123
+ /**
1124
+ * Auth for routes with `authTransport: 'bearer'` (the built-in MCP server): only the
1125
+ * `Authorization` header counts, always against `server.auth`. Studio client-type routing,
1126
+ * cookies, and the `apiKey` query parameter are ignored, so a browser session can't be used.
1127
+ *
1128
+ * 401s carry `WWW-Authenticate` pointing at the OAuth protected-resource metadata, and when
1129
+ * `server.mcp.oauth.resource` is set the token audience must include it.
1130
+ */
1131
+ async checkBearerRouteAuth(route, context) {
1132
+ context.requestContext.set(MASTRA_IS_STUDIO_KEY, false);
1133
+ const authorization = context.getHeader("authorization");
1134
+ const getHeader = (name) => {
1135
+ const lower = name.toLowerCase();
1136
+ return lower === "cookie" || lower === "x-mastra-client-type" ? void 0 : context.getHeader(name);
1137
+ };
1138
+ const result = await this.checkRouteAuth({
1139
+ ...route,
1140
+ authTransport: void 0
1141
+ }, {
1142
+ ...context,
1143
+ getHeader,
1144
+ getQuery: (name) => name === "apiKey" ? void 0 : context.getQuery(name),
1145
+ request: new Request(context.request?.url ?? `http://localhost${context.path}`, {
1146
+ method: context.method,
1147
+ headers: authorization ? { authorization } : {}
1148
+ })
1149
+ });
1150
+ const discovery = isMCPOAuthDiscoveryEnabled(this.mastra);
1151
+ if (!discovery && !isMCPAudienceEnforced(this.mastra)) return result;
1152
+ const requestUrl = context.request?.url ?? `http://localhost${context.path}`;
1153
+ const prefix = this.prefix ?? "";
1154
+ if (result?.status === 401) {
1155
+ if (!discovery) return result;
1156
+ const error = authorization?.trim() ? { error: "invalid_token" } : void 0;
1157
+ const challenge = mcpWWWAuthenticate(this.mastra, prefix, requestUrl, error);
1158
+ return {
1159
+ ...result,
1160
+ headers: {
1161
+ ...result.headers,
1162
+ "WWW-Authenticate": challenge
1163
+ }
1164
+ };
1165
+ }
1166
+ const user = context.requestContext.get(MASTRA_USER_KEY);
1167
+ if (user !== void 0 && !await checkMCPAudience(this.mastra, user)) {
1168
+ const challenge = mcpWWWAuthenticate(this.mastra, prefix, requestUrl, {
1169
+ error: "invalid_token",
1170
+ error_description: "The token audience does not include this MCP server"
1171
+ });
1172
+ return {
1173
+ status: 401,
1174
+ error: "Invalid token audience",
1175
+ headers: {
1176
+ ...result?.headers,
1177
+ "WWW-Authenticate": challenge
1178
+ }
1179
+ };
1180
+ }
1181
+ return result;
1182
+ }
1183
+ /**
1184
+ * Check if the user has the required permission for a route.
1185
+ *
1186
+ * Uses convention-based permission derivation:
1187
+ * 1. If route has explicit `requiresPermission`, use that
1188
+ * 2. Otherwise, derive permission from path/method (e.g., GET /agents → agents:read)
1189
+ * 3. Routes with `requiresAuth: false` skip permission checks
1190
+ *
1191
+ * When the route specifies an array of permissions, the user needs ANY ONE
1192
+ * of them (logical OR).
1193
+ *
1194
+ * @param route - The route being accessed
1195
+ * @param userPermissions - The user's permissions from the request context
1196
+ * @returns Error response if permission denied, null if allowed
1197
+ */
1198
+ /**
1199
+ * Check if the user has the required permission for a route.
1200
+ *
1201
+ * Uses convention-based permission derivation:
1202
+ * 1. If route has explicit `requiresPermission`, use that
1203
+ * 2. Otherwise, derive permission from path/method (e.g., GET /agents → agents:read)
1204
+ * 3. Routes with `requiresAuth: false` skip permission checks
1205
+ *
1206
+ * Permission checks use the RBAC provider that corresponds to the auth mode
1207
+ * (studio vs server) that was used for authentication.
1208
+ *
1209
+ * @param route - The route being accessed
1210
+ * @param userPermissions - The user's permissions from the request context
1211
+ * @param hasPermissionFn - Function to check if user permissions match required permission
1212
+ * @param requestContext - Request context to determine which RBAC provider to use
1213
+ * @returns Error response if permission denied, null if allowed
1214
+ */
1215
+ checkRoutePermission(route, userPermissions, hasPermissionFn, requestContext) {
1216
+ return getRoutePermissionError(this.mastra, route, userPermissions, hasPermissionFn, requestContext);
1217
+ }
1218
+ /**
1219
+ * RBAC check for a route this adapter serves. Skipped when no auth is configured;
1220
+ * otherwise decided by `checkRoutePermission`, so a subclass override of it still applies.
1221
+ */
1222
+ checkRouteRBAC(route, requestContext) {
1223
+ if (!this.mastra.getStudio?.()?.auth && !this.mastra.getServer()?.auth) return null;
1224
+ const userPermissions = requestContext.get(MASTRA_USER_PERMISSIONS_KEY);
1225
+ return this.checkRoutePermission(route, userPermissions, hasPermission, requestContext);
1226
+ }
1227
+ /** RBAC (`checkRouteRBAC`) then FGA on the parsed params, after authentication and validation. */
1228
+ async authorizeRoute(route, params, requestContext) {
1229
+ return this.checkRouteRBAC(route, requestContext) ?? await checkRouteFGA(this.mastra, route, requestContext, params);
1230
+ }
1231
+ /**
1232
+ * Build a matcher that answers "is this (path, method) a framework-public
1233
+ * route?" — i.e. registered with `requiresAuth: false`.
1234
+ *
1235
+ * Adapters call this once at registration time and use the returned function
1236
+ * inside their context middleware to stash a boolean on the per-request
1237
+ * context under `MASTRA_FRAMEWORK_PUBLIC_KEY`. That boolean is then read by
1238
+ * per-user-middleware wrappers to short-circuit user middleware for
1239
+ * framework-public routes, guaranteeing that user middleware cannot 401
1240
+ * routes the framework declared public (e.g. Studio sign-in endpoints).
1241
+ *
1242
+ * The matcher considers:
1243
+ * - Built-in `SERVER_ROUTES` entries with `requiresAuth === false`
1244
+ * (paths joined with the adapter's configured `prefix`).
1245
+ * - Custom user API routes registered with `requiresAuth: false` via the
1246
+ * `customRouteAuthConfig` map.
1247
+ */
1248
+ getFrameworkPublicMatcher() {
1249
+ const prefix = this.prefix ?? "";
1250
+ const publicRoutes = SERVER_ROUTES.filter((r) => r.requiresAuth === false).map((r) => ({
1251
+ method: r.method.toUpperCase(),
1252
+ pattern: `${prefix}${r.path}`
1253
+ }));
1254
+ if (isMCPOAuthDiscoveryEnabled(this.mastra)) for (const route of createMCPOAuthMetadataRoutes(this.mastra, prefix)) publicRoutes.push({
1255
+ method: route.method.toUpperCase(),
1256
+ pattern: route.path
1257
+ });
1258
+ return (path, method) => {
1259
+ const upperMethod = method.toUpperCase();
1260
+ for (const r of publicRoutes) if ((r.method === upperMethod || r.method === "ALL") && pathMatchesPattern(path, r.pattern)) return true;
1261
+ return isCustomRoutePublic(path, upperMethod, this.customRouteAuthConfig);
1262
+ };
1263
+ }
1264
+ async init() {
1265
+ this.registerContextMiddleware();
1266
+ this.registerAuthMiddleware();
1267
+ this.validateAuthResourceScoping();
1268
+ this.registerUserMiddleware();
1269
+ this.registerHttpLoggingMiddleware();
1270
+ await this.validateEELicense();
1271
+ await this.validateAgentBuilderLicense();
1272
+ await this.validateFGAPolicyCoverage();
1273
+ await this.registerCustomApiRoutes();
1274
+ await this.registerRoutes();
1275
+ }
1276
+ /**
1277
+ * Validate that EE features have a valid license in production.
1278
+ * Throws if RBAC or FGA is configured without a valid license outside dev/test environments.
1279
+ */
1280
+ async validateEELicense() {
1281
+ const serverConfig = this.mastra.getServer();
1282
+ const studioConfig = this.mastra.getStudio?.();
1283
+ const configuredFeatures = [serverConfig?.rbac || studioConfig?.rbac ? "RBAC" : null, serverConfig?.fga || studioConfig?.fga ? "FGA" : null].filter((feature) => feature !== null);
1284
+ if (configuredFeatures.length === 0) return;
1285
+ try {
1286
+ const { isEEEnabled } = await import("@mastra/core/auth/ee");
1287
+ if (!isEEEnabled()) {
1288
+ const featureList = configuredFeatures.join(" and ");
1289
+ throw new Error(`[mastra/auth-ee] ${featureList} ${configuredFeatures.length === 1 ? "is" : "are"} configured but no valid EE license was found.\n${featureList} ${configuredFeatures.length === 1 ? "requires" : "require"} a Mastra Enterprise License for production use.\nSet the MASTRA_EE_LICENSE environment variable with your license key.
1290
+ Learn more: https://github.com/mastra-ai/mastra/blob/main/ee/LICENSE`);
1291
+ }
1292
+ } catch (err) {
1293
+ if (err instanceof Error && err.message.startsWith("[mastra/auth-ee]")) throw err;
1294
+ throw new Error(`[mastra/auth-ee] ${configuredFeatures.join(" and ")} ${configuredFeatures.length === 1 ? "is" : "are"} configured but the EE module (@mastra/core/auth/ee) could not be loaded.\nEnsure @mastra/core is updated to a version that includes EE support.`);
1295
+ }
1296
+ }
1297
+ /**
1298
+ * Validate that an Agent Builder configuration has a valid EE license.
1299
+ * Throws if the editor is configured with builder support but no valid EE license is available.
1300
+ */
1301
+ async validateAgentBuilderLicense() {
1302
+ if (!this.mastra.getEditor()?.hasEnabledBuilderConfig?.()) return;
1303
+ try {
1304
+ const { isEEEnabled } = await import("@mastra/core/auth/ee");
1305
+ if (!isEEEnabled()) throw new Error("[mastra/auth-ee] Agent Builder is configured but no valid EE license was found.\nAgent Builder requires a Mastra Enterprise License for production use.\nSet the MASTRA_EE_LICENSE environment variable with your license key.\nLearn more: https://github.com/mastra-ai/mastra/blob/main/ee/LICENSE");
1306
+ } catch (err) {
1307
+ if (err instanceof Error && err.message.startsWith("[mastra/auth-ee]")) throw err;
1308
+ throw new Error("[mastra/auth-ee] Agent Builder is configured but the EE module (@mastra/core/auth/ee) could not be loaded.\nEnsure @mastra/core is updated to a version that includes EE support.");
1309
+ }
1310
+ }
1311
+ /**
1312
+ * Warn when `server.auth` is configured without `mapUserToResourceId`.
1313
+ *
1314
+ * Without it, MASTRA_RESOURCE_ID_KEY is never set in the request context, so
1315
+ * built-in routes fall back to the client-supplied resource ID (for example
1316
+ * `memory.resource`) and ownership checks run against a caller-chosen value.
1317
+ */
1318
+ validateAuthResourceScoping() {
1319
+ const auth = this.mastra.getServer()?.auth;
1320
+ if (!auth || typeof auth.mapUserToResourceId === "function") return;
1321
+ this.mastra.getLogger()?.warn("[mastra/auth] server.auth is configured without mapUserToResourceId. Memory, thread and workflow ownership checks will trust the resource ID supplied by the client (e.g. memory.resource in the request body), so an authenticated user can read or write another user's threads. Configure server.auth.mapUserToResourceId to derive the resource ID from the authenticated user.");
1322
+ }
1323
+ /**
1324
+ * Validate route-level FGA policy coverage when an FGA provider opts into
1325
+ * startup checks.
1326
+ */
1327
+ async validateFGAPolicyCoverage() {
1328
+ const serverConfig = this.mastra.getServer();
1329
+ const studioConfig = this.mastra.getStudio?.();
1330
+ const fgaProvider = serverConfig?.fga ?? studioConfig?.fga;
1331
+ if (!fgaProvider) return;
1332
+ const customRoutes = (this.customApiRoutes ?? serverConfig?.apiRoutes ?? []).filter((route) => !route._mastraInternal);
1333
+ const routes = [...SERVER_ROUTES, ...customRoutes];
1334
+ if (fgaProvider.validatePermissions) {
1335
+ const permissions = [...new Set(routes.flatMap((route) => getRoutePermissions(route)))];
1336
+ await fgaProvider.validatePermissions(permissions);
1337
+ }
1338
+ const auditMode = fgaProvider.auditProtectedRoutes ?? (fgaProvider.requireForProtectedRoutes ? "warn" : false);
1339
+ if (!auditMode || fgaProvider.resolveRouteFGA) return;
1340
+ const missingRoutes = routes.filter((route) => isProtectedFGARoute(route) && !route.fga && !getBuiltInRouteFGAConfig(route));
1341
+ if (missingRoutes.length === 0) return;
1342
+ const routeList = missingRoutes.map((route) => formatRoute(route));
1343
+ const message = `[mastra/auth-ee] FGA is configured but ${missingRoutes.length} protected route${missingRoutes.length === 1 ? " is" : "s are"} missing FGA metadata: ${routeList.join(", ")}`;
1344
+ if (auditMode === "error") throw new Error(message);
1345
+ this.mastra.getLogger()?.warn(message, {
1346
+ routes: routeList,
1347
+ count: missingRoutes.length
1348
+ });
1349
+ }
1350
+ /**
1351
+ * Register user-provided middleware from the Mastra config (`server.middleware`)
1352
+ * and from `mastra.setServerMiddleware()`. Called by init() between
1353
+ * registerAuthMiddleware() and registerHttpLoggingMiddleware().
1354
+ *
1355
+ * Mastra middleware handlers use Hono's `(c, next)` signature, so only
1356
+ * Hono-based adapters can run them. Those adapters override this method and
1357
+ * MUST wrap each handler with `skipIfFrameworkPublic` (exported by
1358
+ * `@mastra/hono`) so user middleware cannot block framework-public routes.
1359
+ * The default implementation warns when middleware is configured so the
1360
+ * config is not silently ignored on adapters that cannot honor it.
1361
+ */
1362
+ registerUserMiddleware() {
1363
+ const instanceMiddleware = this.mastra.getServerMiddleware?.() ?? [];
1364
+ const configMiddleware = this.mastra.getServer()?.middleware;
1365
+ const hasConfigMiddleware = Array.isArray(configMiddleware) ? configMiddleware.length > 0 : !!configMiddleware;
1366
+ if (instanceMiddleware.length === 0 && !hasConfigMiddleware) return;
1367
+ this.mastra.getLogger()?.warn("Mastra server middleware (`server.middleware` or `setServerMiddleware()`) is configured, but this server adapter cannot run Hono middleware handlers. The configured middleware will not run — register middleware through your server framework instead.");
1368
+ }
1369
+ /**
1370
+ * Override in adapters to register custom API routes defined via registerApiRoute().
1371
+ * Called by init() between registerAuthMiddleware() and registerRoutes().
1372
+ */
1373
+ async registerCustomApiRoutes() {}
1374
+ /** Ensures every custom route has an auth entry without overriding supplied values. */
1375
+ initializeCustomRouteAuthConfig(routes) {
1376
+ this.customRouteAuthConfig ??= /* @__PURE__ */ new Map();
1377
+ for (const route of routes) {
1378
+ const routeKey = `${route.method}:${route.path}`;
1379
+ if (!this.customRouteAuthConfig.has(routeKey)) this.customRouteAuthConfig.set(routeKey, route.requiresAuth !== false);
1380
+ }
1381
+ }
1382
+ /**
1383
+ * Registers schema-aware custom routes through the adapter's native route pipeline.
1384
+ * Returns the remaining Hono-style routes for the custom-route bridge.
1385
+ */
1386
+ async registerSchemaApiRoutes() {
1387
+ const routes = this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes ?? [];
1388
+ this.validateCustomRoutePaths(routes);
1389
+ this.initializeCustomRouteAuthConfig(routes);
1390
+ const schemaRoutes = routes.filter(isSchemaApiRoute);
1391
+ for (const route of schemaRoutes) {
1392
+ const prefix = OPT_IN_ROUTES.includes(route) ? this.prefix : "";
1393
+ await this.registerRoute(this.app, route, { prefix });
1394
+ }
1395
+ return routes.filter((route) => !isSchemaApiRoute(route));
1396
+ }
1397
+ /**
1398
+ * Validates that no custom route path collides with the built-in route prefix.
1399
+ * Throws if any route path starts with the server's `apiPrefix`.
1400
+ */
1401
+ validateCustomRoutePaths(routes) {
1402
+ const prefix = this.prefix ?? "";
1403
+ if (!prefix) return;
1404
+ for (const route of routes) {
1405
+ if (route._mastraInternal) continue;
1406
+ if (route.path.startsWith(`${prefix}/`) || route.path === prefix) throw new Error(`Custom API route "${route.path}" must not start with "${prefix}" — that path is reserved for built-in Mastra routes. Choose a different path (e.g. "${route.path.replace(prefix, "/custom")}").`);
1407
+ }
1408
+ }
1409
+ /**
1410
+ * Creates an internal Hono sub-app with all custom API routes registered.
1411
+ * Stores the handler on this instance for use by handleCustomRouteRequest().
1412
+ * Returns true if custom routes were found and registered.
1413
+ */
1414
+ async buildCustomRouteHandler(routes) {
1415
+ if (routes.length === 0) return false;
1416
+ const NOT_FOUND_HEADER = "x-mastra-custom-route-not-found";
1417
+ const mastra = this.mastra;
1418
+ const app = new Hono();
1419
+ app.use("*", async (c, next) => {
1420
+ c.set("mastra", mastra);
1421
+ c.set("requestContext", c.env?.requestContext ?? new RequestContext());
1422
+ await next();
1423
+ });
1424
+ const serverOnError = this.mastra.getServer()?.onError;
1425
+ app.onError((err, c) => {
1426
+ if (serverOnError) return serverOnError(err, c);
1427
+ const httpExceptionResponse = getCustomRouteHTTPExceptionResponse(err);
1428
+ if (httpExceptionResponse) return httpExceptionResponse;
1429
+ this.mastra.getLogger()?.error(`Custom route handler failed: ${c.req.method} ${c.req.path}`, {
1430
+ method: c.req.method,
1431
+ path: c.req.path,
1432
+ error: err instanceof Error ? err.stack ?? err.message : String(err)
1433
+ });
1434
+ return c.json({ error: "Internal Server Error" }, 500);
1435
+ });
1436
+ const matcherEntries = [];
1437
+ for (const route of routes) {
1438
+ const handler = "handler" in route && route.handler ? route.handler : "createHandler" in route ? await route.createHandler({ mastra }) : void 0;
1439
+ if (!handler) continue;
1440
+ const middlewares = [];
1441
+ if (route.middleware) middlewares.push(...Array.isArray(route.middleware) ? route.middleware : [route.middleware]);
1442
+ const allHandlers = [...middlewares, handler];
1443
+ matcherEntries.push({
1444
+ method: route.method,
1445
+ path: route.path,
1446
+ handlerCount: allHandlers.length,
1447
+ route
1448
+ });
1449
+ if (route.method === "ALL") app.all(route.path, allHandlers[0], ...allHandlers.slice(1));
1450
+ else app.on(route.method, route.path, allHandlers[0], ...allHandlers.slice(1));
1451
+ }
1452
+ app.notFound(() => new Response(null, {
1453
+ status: 404,
1454
+ headers: { [NOT_FOUND_HEADER]: "true" }
1455
+ }));
1456
+ this.customRouteHandler = async (request, env, executionCtx) => app.fetch(request, env, executionCtx);
1457
+ this.customRouteMatcher = new CustomRouteMatcher(matcherEntries);
1458
+ return true;
1459
+ }
1460
+ /**
1461
+ * Returns the custom route the custom-route app will run for `url` (the same URL
1462
+ * passed to `handleCustomRouteRequest`), with its decoded path params, or
1463
+ * undefined if none will.
1464
+ */
1465
+ matchCustomRoute(url, method) {
1466
+ if (!this.customRouteMatcher) return void 0;
1467
+ try {
1468
+ const match = this.customRouteMatcher.matchUrl(url, method);
1469
+ return match ? {
1470
+ route: match.entry.route,
1471
+ params: match.params
1472
+ } : void 0;
1473
+ } catch {
1474
+ return;
1475
+ }
1476
+ }
1477
+ /**
1478
+ * Works out what auth applies to a request before it's forwarded to the
1479
+ * custom-route app. The route that decides is the one the app will dispatch
1480
+ * `dispatchUrl` to, not the route the outer framework matched, because the two
1481
+ * routers can disagree on precedence, case, trailing slashes and encoding.
1482
+ *
1483
+ * `requestPath` is the path passed to `checkRouteAuth`. When the dispatched route
1484
+ * requires auth, the returned `customRouteAuthConfig` marks that path protected so
1485
+ * the auth middleware can't skip auth on it. `fallbackRoute` is used when the app
1486
+ * won't dispatch the request (it 404s and nothing runs); pass the framework's own
1487
+ * route when there is one so its auth still applies.
1488
+ */
1489
+ resolveCustomRouteAuth(dispatchUrl, method, requestPath, fallbackRoute) {
1490
+ const match = this.matchCustomRoute(dispatchUrl, method);
1491
+ const route = match?.route ?? fallbackRoute;
1492
+ const requiresAuth = route ? this.customRouteAuthConfig?.get(`${route.method}:${route.path}`) ?? route.requiresAuth !== false : isProtectedCustomRoute(requestPath, method, this.customRouteAuthConfig);
1493
+ const serverRoute = {
1494
+ method: route?.method ?? method,
1495
+ path: route?.path ?? requestPath,
1496
+ responseType: "json",
1497
+ handler: async () => {},
1498
+ requiresAuth: requiresAuth ? route?.requiresAuth === true ? true : void 0 : false,
1499
+ requiresPermission: route?.requiresPermission,
1500
+ fga: route?.fga
1501
+ };
1502
+ let customRouteAuthConfig;
1503
+ if (requiresAuth) {
1504
+ customRouteAuthConfig = new Map(this.customRouteAuthConfig ?? []);
1505
+ customRouteAuthConfig.set(`${method.toUpperCase()}:${requestPath}`, true);
1506
+ }
1507
+ return {
1508
+ match,
1509
+ requiresAuth,
1510
+ serverRoute,
1511
+ customRouteAuthConfig
1512
+ };
1513
+ }
1514
+ /**
1515
+ * Forwards a request to the internal custom route handler.
1516
+ * Returns the Response if a custom route matched, or null to fall through.
1517
+ */
1518
+ async handleCustomRouteRequest(url, method, headers, body, requestContext, signal, executionCtx) {
1519
+ if (!this.customRouteHandler) return null;
1520
+ const fetchHeaders = new Headers();
1521
+ for (const [key, value] of Object.entries(headers)) if (typeof value === "string") fetchHeaders.set(key, value);
1522
+ else if (Array.isArray(value)) value.forEach((v) => {
1523
+ fetchHeaders.append(key, v);
1524
+ });
1525
+ const init = {
1526
+ method,
1527
+ headers: fetchHeaders,
1528
+ signal
1529
+ };
1530
+ if ([
1531
+ "POST",
1532
+ "PUT",
1533
+ "PATCH",
1534
+ "DELETE"
1535
+ ].includes(method) && body !== void 0) {
1536
+ if (body instanceof ArrayBuffer || body instanceof Uint8Array || body instanceof ReadableStream) {
1537
+ init.body = body;
1538
+ if (body instanceof ReadableStream) init.duplex = "half";
1539
+ } else if (((typeof headers["content-type"] === "string" ? headers["content-type"] : "") || "").includes("application/json")) init.body = JSON.stringify(body);
1540
+ else if (typeof body === "string") init.body = body;
1541
+ }
1542
+ const request = new globalThis.Request(url, init);
1543
+ const response = await this.customRouteHandler(request, { requestContext }, executionCtx);
1544
+ if (response.headers.get("x-mastra-custom-route-not-found") === "true") return null;
1545
+ return signal ? retainRequestWhileBodyIsOpen(response, request) : response;
1546
+ }
1547
+ /**
1548
+ * Pipes a custom route Response to a Node.js ServerResponse (http.ServerResponse).
1549
+ * Works with Koa (ctx.res), Express (res), and Fastify (reply.raw).
1550
+ */
1551
+ async writeCustomRouteResponse(response, nodeRes, signal) {
1552
+ const headers = {};
1553
+ response.headers.forEach((value, key) => {
1554
+ if (key.toLowerCase() !== "set-cookie") headers[key] = value;
1555
+ });
1556
+ const setCookies = response.headers.getSetCookie?.();
1557
+ if (setCookies && setCookies.length > 0) headers["set-cookie"] = setCookies;
1558
+ if (isResponseClosed(nodeRes)) {
1559
+ await response.body?.cancel();
1560
+ return;
1561
+ }
1562
+ nodeRes.writeHead(response.status, headers);
1563
+ if (response.body) {
1564
+ let responseBodyError;
1565
+ let responseBodyErrorAfterResponseClosed = false;
1566
+ try {
1567
+ const responseStream = Readable.fromWeb(response.body);
1568
+ responseStream.once("error", (error) => {
1569
+ responseBodyError = error;
1570
+ responseBodyErrorAfterResponseClosed = isResponseClosed(nodeRes);
1571
+ });
1572
+ if (signal) await pipeline(responseStream, nodeRes, { signal });
1573
+ else await pipeline(responseStream, nodeRes);
1574
+ } catch (error) {
1575
+ const expectedSignalAbort = signal?.aborted && isAbortSignalError(error) && (!responseBodyError || responseBodyErrorAfterResponseClosed);
1576
+ const expectedResponseClose = (!responseBodyError || responseBodyErrorAfterResponseClosed) && isResponseClosed(nodeRes) && isExpectedResponseCloseError(error);
1577
+ if (!expectedSignalAbort && !expectedResponseClose) throw error;
1578
+ }
1579
+ } else {
1580
+ const text = await response.text();
1581
+ if (!isResponseClosed(nodeRes)) nodeRes.end(text);
1582
+ }
1583
+ }
1584
+ /**
1585
+ * Builds the OpenAPI spec object with servers field and custom route paths.
1586
+ */
1587
+ buildOpenAPISpec(config, prefix) {
1588
+ const openApiSpec = generateOpenAPIDocument(SERVER_ROUTES, config);
1589
+ if (prefix) openApiSpec.servers = [{ url: prefix }];
1590
+ const allCustomRoutes = this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes;
1591
+ if (allCustomRoutes && allCustomRoutes.length > 0) {
1592
+ const componentSchemas = openApiSpec.components?.schemas ?? Object.create(null);
1593
+ const isPrefixed = (route) => OPT_IN_ROUTES.includes(route);
1594
+ const customPaths = convertCustomRoutesToOpenAPIPaths(allCustomRoutes.filter((route) => !isPrefixed(route)), componentSchemas);
1595
+ const prefixedPaths = convertCustomRoutesToOpenAPIPaths(allCustomRoutes.filter(isPrefixed), componentSchemas);
1596
+ if (Object.keys(componentSchemas).length > 0) openApiSpec.components = {
1597
+ ...openApiSpec.components,
1598
+ schemas: componentSchemas
1599
+ };
1600
+ if (prefix) {
1601
+ for (const pathKey of Object.keys(customPaths)) if (!customPaths[pathKey].servers) customPaths[pathKey].servers = [{ url: "/" }];
1602
+ }
1603
+ Object.assign(customPaths, prefixedPaths);
1604
+ openApiSpec.paths = {
1605
+ ...openApiSpec.paths,
1606
+ ...customPaths
1607
+ };
1608
+ }
1609
+ return openApiSpec;
1610
+ }
1611
+ async registerOpenAPIRoute(app, config = {}, { prefix }) {
1612
+ const { title = "Mastra API", version = "1.0.0", description = "Mastra Server API", path = "/openapi.json" } = config;
1613
+ const openApiSpec = this.buildOpenAPISpec({
1614
+ title,
1615
+ version,
1616
+ description
1617
+ }, prefix);
1618
+ const openApiRoute = {
1619
+ method: "GET",
1620
+ path,
1621
+ responseType: "json",
1622
+ handler: async () => openApiSpec
1623
+ };
1624
+ await this.registerRoute(app, openApiRoute, { prefix });
1625
+ }
1626
+ async registerRoutes() {
1627
+ for (const route of SERVER_ROUTES) await this.registerRoute(this.app, resolveServerRoute(route, this.mastra, SERVER_ROUTES), { prefix: this.prefix });
1628
+ if (isMCPAudienceEnforced(this.mastra)) warnOnUnenforcedMCPAudience(this.mastra);
1629
+ if (isMCPOAuthDiscoveryEnabled(this.mastra)) for (const route of createMCPOAuthMetadataRoutes(this.mastra, this.prefix ?? "")) await this.registerRoute(this.app, route, { prefix: "" });
1630
+ if (this.openapiPath) await this.registerOpenAPIRoute(this.app, {
1631
+ title: "Mastra API",
1632
+ version: "1.0.0",
1633
+ description: "Mastra Server API",
1634
+ path: this.openapiPath
1635
+ }, { prefix: this.prefix });
1636
+ }
1637
+ async parsePathParams(route, params) {
1638
+ return parseRoutePathParams(route, params);
1639
+ }
1640
+ async parseQueryParams(route, params) {
1641
+ return parseRouteQueryParams(route, params);
1642
+ }
1643
+ async parseBody(route, body) {
1644
+ return parseRouteBody(route, body);
1645
+ }
1646
+ resolveValidationError(route, error, context) {
1647
+ return resolveRouteValidationError(this.mastra, route, error, context);
1648
+ }
1649
+ };
1650
+ /**
1651
+ * The RBAC provider for the auth mode the request was authenticated with
1652
+ * (studio vs server).
1653
+ */
1654
+ function getEffectiveRBACProvider(mastra, requestContext) {
1655
+ if (requestContext.get("mastra__authMode") === "studio") return mastra.getStudio?.()?.rbac ?? mastra.getServer()?.rbac;
1656
+ return mastra.getServer()?.rbac;
1657
+ }
1658
+ /**
1659
+ * Check if the user has the required permission for a route.
1660
+ *
1661
+ * Uses convention-based permission derivation:
1662
+ * 1. If route has explicit `requiresPermission`, use that
1663
+ * 2. Otherwise, derive permission from path/method (e.g., GET /agents → agents:read)
1664
+ * 3. Routes with `requiresAuth: false` skip permission checks
1665
+ *
1666
+ * When the route specifies an array of permissions, the user needs ANY ONE
1667
+ * of them (logical OR). Without an RBAC provider, authenticated users get full access.
1668
+ *
1669
+ * @returns Error response if permission denied, null if allowed
1670
+ */
1671
+ function getRoutePermissionError(mastra, route, userPermissions, hasPermissionFn, requestContext) {
1672
+ if (!getEffectiveRBACProvider(mastra, requestContext)) return null;
1673
+ const requiredPermission = getEffectivePermission(route);
1674
+ if (!requiredPermission) return null;
1675
+ const permissions = Array.isArray(requiredPermission) ? requiredPermission : [requiredPermission];
1676
+ if (!(userPermissions && permissions.some((perm) => hasPermissionFn(userPermissions, perm)))) return {
1677
+ status: 403,
1678
+ error: "Forbidden",
1679
+ message: `Missing required permission: ${permissions.join(" or ")}`
1680
+ };
1681
+ return null;
1682
+ }
1683
+ async function parseRoutePathParams(route, params) {
1684
+ const pathParamSchema = route.pathParamSchema;
1685
+ if (!pathParamSchema) return params;
1686
+ return pathParamSchema.parseAsync(params);
1687
+ }
1688
+ async function parseRouteQueryParams(route, params) {
1689
+ const queryParamSchema = route.queryParamSchema;
1690
+ if (!queryParamSchema) return params;
1691
+ const normalizedParams = parseComplexQueryParams(queryParamSchema, params);
1692
+ return queryParamSchema.parseAsync(normalizedParams);
1693
+ }
1694
+ async function parseRouteBody(route, body) {
1695
+ const bodySchema = route.bodySchema;
1696
+ if (!bodySchema) return body;
1697
+ if (body === void 0) {
1698
+ const omitted = await bodySchema.safeParseAsync(void 0);
1699
+ if (omitted.success) return omitted.data;
1700
+ const schemaType = getSchemaTypeName(unwrapOptionalNullable(bodySchema));
1701
+ if (schemaType === "object" || schemaType === "ZodObject") {
1702
+ const emptyObject = await bodySchema.safeParseAsync({});
1703
+ if (emptyObject.success) return emptyObject.data;
1704
+ }
1705
+ throw omitted.error;
1706
+ }
1707
+ return bodySchema.parseAsync(body);
1708
+ }
1709
+ const VALIDATION_CONTEXT_LABELS = {
1710
+ query: "query parameters",
1711
+ body: "request body",
1712
+ path: "path parameters"
1713
+ };
1714
+ function resolveRouteValidationError(mastra, route, error, context) {
1715
+ const hook = route.onValidationError ?? mastra.getServer()?.onValidationError;
1716
+ if (hook) try {
1717
+ const result = hook(error, context);
1718
+ if (result) return result;
1719
+ } catch (hookError) {
1720
+ mastra.getLogger()?.error("Error in custom onValidationError hook", { error: hookError instanceof Error ? {
1721
+ message: hookError.message,
1722
+ stack: hookError.stack
1723
+ } : hookError });
1724
+ }
1725
+ return {
1726
+ status: 400,
1727
+ body: formatZodError(error, VALIDATION_CONTEXT_LABELS[context])
1728
+ };
1729
+ }
1730
+ /**
1731
+ * Check the route's RBAC permission (explicit `requiresPermission` or derived from
1732
+ * path/method) against the permissions `checkRouteAuth` stored in the request context.
1733
+ * Skipped when no auth or no RBAC provider is configured, matching what adapters enforce.
1734
+ * Uses the studio RBAC provider for studio-authenticated requests.
1735
+ * Returns null if allowed, or a 403 error object if denied.
1736
+ */
1737
+ function checkRouteRBAC(mastra, route, requestContext) {
1738
+ if (!mastra.getStudio?.()?.auth && !mastra.getServer()?.auth) return null;
1739
+ return getRoutePermissionError(mastra, route, requestContext.get(MASTRA_USER_PERMISSIONS_KEY), hasPermission, requestContext);
1740
+ }
1741
+ /**
1742
+ * Run the route authorization adapters enforce after authentication and schema
1743
+ * validation: RBAC (`checkRouteRBAC`) then FGA (`checkRouteFGA`) on the parsed params.
1744
+ * Returns null if allowed, or a 403 error object if denied.
1745
+ */
1746
+ async function authorizeRoute(mastra, route, params, requestContext) {
1747
+ return checkRouteRBAC(mastra, route, requestContext) ?? await checkRouteFGA(mastra, route, requestContext, params);
1748
+ }
1749
+ const dispatchAdapters = /* @__PURE__ */ new WeakMap();
1750
+ const servingAdapters = /* @__PURE__ */ new WeakMap();
1751
+ /**
1752
+ * Record that `handle`'s adapter is serving the request `requestContext` belongs to. Adapters
1753
+ * built on `MastraServer` do this for every request; other adapters must call it.
1754
+ */
1755
+ function bindDispatchAdapter(requestContext, handle) {
1756
+ servingAdapters.set(requestContext, handle);
1757
+ }
1758
+ /**
1759
+ * Tell `dispatchRoute` where an adapter serves a Mastra instance's routes. Adapters built on
1760
+ * `MastraServer` register themselves; adapters that are not must call this, and bind the returned
1761
+ * handle to each request context they create with `bindDispatchAdapter`.
1762
+ */
1763
+ function registerDispatchAdapter(mastra, info) {
1764
+ const adapters = dispatchAdapters.get(mastra) ?? /* @__PURE__ */ new Map();
1765
+ const handle = Object.freeze({});
1766
+ adapters.set(handle, info);
1767
+ dispatchAdapters.set(mastra, adapters);
1768
+ return handle;
1769
+ }
1770
+ /**
1771
+ * The adapter whose HTTP paths and checks a dispatched route gets. Among the adapters serving
1772
+ * `routePrefix` (all of them when it is not given), that is the one serving the current request
1773
+ * (`bindDispatchAdapter`), else the only one. `prefix` is undefined when it cannot be
1774
+ * told: several candidates and none serving this request, a `routePrefix` no registered adapter
1775
+ * serves (a custom route's own `routePrefix` is empty, for one), or nothing to go on. Guessing
1776
+ * between adapters could skip one's stricter checks, so it is never done.
1777
+ */
1778
+ function resolveDispatchAdapter(mastra, routePrefix, requestContext) {
1779
+ const adapters = [...dispatchAdapters.get(mastra) ?? /* @__PURE__ */ new Map()];
1780
+ if (routePrefix !== void 0 && adapters.length === 0) return { prefix: normalizeRoutePath(routePrefix) };
1781
+ const candidates = routePrefix === void 0 ? adapters : adapters.filter(([, adapter]) => normalizeRoutePath(adapter.prefix ?? "") === normalizeRoutePath(routePrefix));
1782
+ const serving = servingAdapters.get(requestContext);
1783
+ const match = candidates.find(([handle]) => handle === serving) ?? (candidates.length === 1 ? candidates[0] : void 0);
1784
+ if (!match) return { prefix: void 0 };
1785
+ const [, adapter] = match;
1786
+ return {
1787
+ prefix: normalizeRoutePath(adapter.prefix ?? ""),
1788
+ adapter
1789
+ };
1790
+ }
1791
+ /** Studio auth for Studio requests when `studio.auth` is configured, otherwise `server.auth`. */
1792
+ function resolveEffectiveAuthConfig(mastra, getHeader) {
1793
+ const isStudioRequest = isStudioClientTypeHeader(getHeader(MASTRA_CLIENT_TYPE_HEADER));
1794
+ const studioAuth = mastra.getStudio?.()?.auth;
1795
+ const serverAuth = mastra.getServer()?.auth;
1796
+ if (isStudioRequest && studioAuth) return {
1797
+ authConfig: studioAuth,
1798
+ authMode: "studio"
1799
+ };
1800
+ if (serverAuth) return {
1801
+ authConfig: serverAuth,
1802
+ authMode: "server"
1803
+ };
1804
+ return null;
1805
+ }
1806
+ const ROUTE_PATH_PARAM = /\/:([A-Za-z0-9_]+)(\?)?/g;
1807
+ /**
1808
+ * A URL can only carry a path param as a non-empty segment, and `.` / `..` segments are
1809
+ * resolved away before routing. Anything else names a path no HTTP request to this route
1810
+ * has, so it is rejected instead of being authorized as some other path.
1811
+ */
1812
+ function findInvalidPathParams(path, pathParams) {
1813
+ const issues = [];
1814
+ for (const [, name, optional] of path.matchAll(ROUTE_PATH_PARAM)) {
1815
+ const value = pathParams[name];
1816
+ if (value === void 0 && optional) continue;
1817
+ if (typeof value !== "string" || value === "") issues.push({
1818
+ field: name,
1819
+ message: "Path parameter must be a non-empty string"
1820
+ });
1821
+ else if (value === "." || value === "..") issues.push({
1822
+ field: name,
1823
+ message: "Path parameter cannot be \".\" or \"..\""
1824
+ });
1825
+ }
1826
+ return issues;
1827
+ }
1828
+ /** Fill `:param` / `:param?` segments of a route path the way a client would put them in a URL. */
1829
+ function fillRoutePath(path, pathParams) {
1830
+ return path.replace(ROUTE_PATH_PARAM, (_segment, name) => {
1831
+ const value = pathParams[name];
1832
+ return value === void 0 ? "" : `/${encodeURIComponent(String(value))}`;
1833
+ });
1834
+ }
1835
+ const DISPATCH_ROUTE_POLICY = {
1836
+ honorPublicPaths: true,
1837
+ pathParamsWin: true,
1838
+ authPath: "adapter",
1839
+ validationOrder: "query-body-path",
1840
+ nonZodParseError: "respond",
1841
+ customErrorResponses: true,
1842
+ reserveServerContext: true
1843
+ };
1844
+ /** `invokeRoute`'s contract as it shipped; changing any of these changes a public API. */
1845
+ const INVOKE_ROUTE_POLICY = {
1846
+ honorPublicPaths: false,
1847
+ pathParamsWin: false,
1848
+ authPath: "apiPrefix",
1849
+ validationOrder: "path-query-body",
1850
+ nonZodParseError: "throw",
1851
+ customErrorResponses: false,
1852
+ reserveServerContext: false
1853
+ };
1854
+ /**
1855
+ * The path-scoped half of `checkRouteAuth` for a route run in-process: `requiresAuth: false`,
1856
+ * protected/public path handling, then `authorizeUser` / `authorize` / `rules` / the RBAC
1857
+ * default rules, all evaluated against the route's own request path and method.
1858
+ * Uses the user Mastra server auth already put in the request context; never re-authenticates.
1859
+ */
1860
+ async function checkDispatchedRouteAuth(route, pathParams, context, policy) {
1861
+ if (route.requiresAuth === false) return null;
1862
+ const { mastra, requestContext } = context;
1863
+ const outerHeaders = context.request?.headers;
1864
+ const getHeader = (name) => outerHeaders?.get(name) ?? void 0;
1865
+ const studioAuth = mastra.getStudio?.()?.auth;
1866
+ const serverAuth = mastra.getServer()?.auth;
1867
+ const user = requestContext.get(MASTRA_USER_KEY);
1868
+ if (!policy.honorPublicPaths && (studioAuth || serverAuth) && !user) return {
1869
+ status: 401,
1870
+ body: { error: "Authentication required" }
1871
+ };
1872
+ const authMode = requestContext.get(MASTRA_AUTH_MODE_KEY);
1873
+ const authConfig = (authMode === "studio" ? studioAuth : authMode === "server" ? serverAuth : void 0) ?? resolveEffectiveAuthConfig(mastra, getHeader)?.authConfig;
1874
+ if (!authConfig) return null;
1875
+ const method = route.method;
1876
+ let path;
1877
+ let customRouteAuthConfig;
1878
+ if (policy.authPath === "adapter") {
1879
+ const { prefix, adapter } = resolveDispatchAdapter(mastra, context.routePrefix, requestContext);
1880
+ customRouteAuthConfig = adapter?.getCustomRouteAuthConfig?.();
1881
+ const isUnprefixed = (adapter?.getCustomApiRoutes?.() ?? mastra.getServer()?.apiRoutes ?? []).includes(route) && !OPT_IN_ROUTES.includes(route);
1882
+ if (isUnprefixed || prefix !== void 0) path = `${isUnprefixed ? "" : prefix}${fillRoutePath(route.path, pathParams)}` || "/";
1883
+ } else path = `${normalizeRoutePath(mastra.getServer()?.apiPrefix ?? "/api")}${route.path.replace(/:(\w+)/g, (_, name) => encodeURIComponent(String(pathParams[name] ?? "")))}`;
1884
+ if (policy.honorPublicPaths && path !== void 0) {
1885
+ const isDevPlayground = typeof authConfig.authenticateToken !== "function" && process.env.MASTRA_DEV === "true" && getHeader("x-mastra-dev-playground") === "true";
1886
+ const isPublic = !route.requiresAuth && (canAccessPublicly(path, method, authConfig) || isCustomRoutePublic(path, method, customRouteAuthConfig));
1887
+ if (isDevPlayground || isPublic) return null;
1888
+ }
1889
+ if (!user) return {
1890
+ status: 401,
1891
+ body: { error: "Invalid or expired token" }
1892
+ };
1893
+ if (path === void 0) throw new Error(`dispatchRoute cannot tell which path ${method} ${route.path} is served under, so it cannot apply server auth to it. Set \`routePrefix\` in the context to the prefix the server adapter serves its built-in routes under (such as "/api").`);
1894
+ const token = requestContext.get(MASTRA_AUTH_TOKEN_KEY);
1895
+ const headers = outerHeaders ?? (typeof token === "string" && token ? { authorization: `Bearer ${token}` } : void 0);
1896
+ return authorizeAuthenticatedUser({
1897
+ path,
1898
+ method,
1899
+ user,
1900
+ mastra,
1901
+ authConfig,
1902
+ customRouteAuthConfig,
1903
+ requestContext,
1904
+ rawRequest: new Request(`http://localhost${path}`, {
1905
+ method,
1906
+ headers
1907
+ }),
1908
+ buildAuthorizeContext: () => null
1909
+ });
1910
+ }
1911
+ /** The one in-process pipeline behind `dispatchRoute` and `invokeRoute`: path-scoped auth → validate → RBAC → FGA → handler. */
1912
+ async function runRoutePipeline(route, input, context, policy) {
1913
+ const { mastra, requestContext } = context;
1914
+ if (policy.authPath === "adapter") {
1915
+ const issues = findInvalidPathParams(route.path, input.pathParams ?? {});
1916
+ if (issues.length > 0) return {
1917
+ ok: false,
1918
+ status: 400,
1919
+ body: {
1920
+ error: "Invalid path parameters",
1921
+ issues
1922
+ }
1923
+ };
1924
+ }
1925
+ const pathAuthError = await checkDispatchedRouteAuth(route, input.pathParams ?? {}, context, policy);
1926
+ if (pathAuthError) return {
1927
+ ok: false,
1928
+ ...pathAuthError
1929
+ };
1930
+ const validate = async (kind, label, parse) => {
1931
+ try {
1932
+ return { value: await parse() };
1933
+ } catch (error) {
1934
+ if (isZodError(error)) {
1935
+ const { status, body } = resolveRouteValidationError(mastra, route, error, kind);
1936
+ return { error: {
1937
+ ok: false,
1938
+ status,
1939
+ body
1940
+ } };
1941
+ }
1942
+ if (policy.nonZodParseError === "throw") throw error;
1943
+ return { error: {
1944
+ ok: false,
1945
+ status: 400,
1946
+ body: {
1947
+ error: `Invalid ${label}`,
1948
+ issues: [{
1949
+ field: "unknown",
1950
+ message: error instanceof Error ? error.message : "Unknown error"
1951
+ }]
1952
+ }
1953
+ } };
1954
+ }
1955
+ };
1956
+ const parsed = { body: input.body };
1957
+ const steps = {
1958
+ query: async () => {
1959
+ const result = await validate("query", "query parameters", () => parseRouteQueryParams(route, input.query ?? {}));
1960
+ if ("error" in result) return result.error;
1961
+ parsed.query = result.value;
1962
+ },
1963
+ body: async () => {
1964
+ if (input.body === void 0 && !route.bodySchema) return;
1965
+ const result = await validate("body", "request body", () => parseRouteBody(route, input.body));
1966
+ if ("error" in result) return result.error;
1967
+ parsed.body = result.value;
1968
+ },
1969
+ path: async () => {
1970
+ const result = await validate("path", "path parameters", () => parseRoutePathParams(route, input.pathParams ?? {}));
1971
+ if ("error" in result) return result.error;
1972
+ parsed.path = result.value;
1973
+ }
1974
+ };
1975
+ const order = policy.validationOrder === "path-query-body" ? [
1976
+ steps.path,
1977
+ steps.query,
1978
+ steps.body
1979
+ ] : [
1980
+ steps.query,
1981
+ steps.body,
1982
+ steps.path
1983
+ ];
1984
+ for (const step of order) {
1985
+ const validationError = await step();
1986
+ if (validationError) return validationError;
1987
+ }
1988
+ const { body } = parsed;
1989
+ const params = {
1990
+ ...policy.pathParamsWin ? {} : parsed.path,
1991
+ ...parsed.query,
1992
+ ...typeof body === "object" ? body : {},
1993
+ ...policy.pathParamsWin ? parsed.path : {}
1994
+ };
1995
+ const adapter = policy.authPath === "adapter" ? resolveDispatchAdapter(mastra, context.routePrefix, requestContext).adapter : void 0;
1996
+ const authError = adapter?.checkRouteRBAC ? adapter.checkRouteRBAC(route, requestContext) ?? await checkRouteFGA(mastra, route, requestContext, params) : await authorizeRoute(mastra, route, params, requestContext);
1997
+ if (authError) return {
1998
+ ok: false,
1999
+ status: authError.status,
2000
+ body: {
2001
+ error: authError.error,
2002
+ message: authError.message
2003
+ }
2004
+ };
2005
+ try {
2006
+ const serverContext = policy.reserveServerContext ? {
2007
+ registeredTools: void 0,
2008
+ taskStore: void 0,
2009
+ routePrefix: void 0,
2010
+ request: void 0,
2011
+ ...context
2012
+ } : context;
2013
+ return {
2014
+ ok: true,
2015
+ result: await route.handler({
2016
+ ...params,
2017
+ ...serverContext
2018
+ })
2019
+ };
2020
+ } catch (error) {
2021
+ const customResponse = policy.customErrorResponses ? getCustomHTTPExceptionResponse(error) : void 0;
2022
+ if (customResponse) {
2023
+ const text = await customResponse.text();
2024
+ let responseBody = text;
2025
+ try {
2026
+ responseBody = JSON.parse(text);
2027
+ } catch {}
2028
+ return {
2029
+ ok: false,
2030
+ status: customResponse.status,
2031
+ body: responseBody
2032
+ };
2033
+ }
2034
+ const { status, body: errorBody } = getHTTPErrorResponse(error);
2035
+ return {
2036
+ ok: false,
2037
+ status,
2038
+ body: errorBody
2039
+ };
2040
+ }
2041
+ }
2042
+ /**
2043
+ * Invoke a route in-process, enforcing what an adapter enforces for an HTTP request to it,
2044
+ * and never allowing more than that request would:
2045
+ *
2046
+ * 1. Path params must be what a URL can carry: a non-empty string for every `:param` (optional
2047
+ * `:param?` may be left out), and never `.` or `..`. Anything else is a 400.
2048
+ * 2. Path-scoped authorization from `checkRouteAuth`, evaluated against the route's own
2049
+ * path (the serving adapter's prefix + filled path params) and method: `requiresAuth: false`,
2050
+ * public paths, and `authorizeUser` / `authorize` / `rules` / the RBAC default rules.
2051
+ * Authentication is not repeated: the user (`MASTRA_USER_KEY`), permissions, and auth mode
2052
+ * must already be in `context.requestContext` from the caller's authenticated request, and
2053
+ * the auth config used is the one recorded there (`studio.auth` or `server.auth`), falling
2054
+ * back to the request's client-type header only when none was recorded. `authorizeUser`
2055
+ * receives the same `{ raw, headers, header() }` shape as over HTTP, wrapping a synthetic
2056
+ * `Request` for the route's path/method with the caller's headers (no body).
2057
+ * 3. Schema validation: query, then body, then path params.
2058
+ * 4. RBAC (the serving adapter's `checkRoutePermission`), then FGA (`checkRouteFGA`) on the
2059
+ * parsed params.
2060
+ * 5. `route.handler` with the parsed params and `context`.
2061
+ *
2062
+ * The adapter's paths and checks apply: the adapter serving the request `requestContext` came
2063
+ * from, else the only adapter serving the Mastra instance (or `context.routePrefix`, when set).
2064
+ * With none registered, `routePrefix` is required. When the adapter cannot be told (several
2065
+ * serve the prefix and none served this request), or `routePrefix` is one no registered adapter
2066
+ * serves, a caller without a user gets 401 and the call otherwise throws rather than guess.
2067
+ *
2068
+ * It is stricter than HTTP in three ways. With auth configured, a route needs a user unless
2069
+ * its path is declared public; a path merely outside the `protected` patterns is not let
2070
+ * through. Path params win over same-named query or body fields, so authorization and the
2071
+ * handler act on the resource named in the path. And request fields never stand in for
2072
+ * server context (`request`, `routePrefix`, `registeredTools`, `taskStore`) left out of `context`.
2073
+ *
2074
+ * Failures resolve to the status and JSON body an adapter would send; successful calls
2075
+ * return the raw handler result (streams are not converted).
2076
+ *
2077
+ * `invokeRoute` runs the same pipeline for JSON routes with a stricter contract: it never
2078
+ * skips auth for public paths and answers with `{ status, body }`.
2079
+ */
2080
+ async function dispatchRoute(route, input, context) {
2081
+ return runRoutePipeline(route, input, context, DISPATCH_ROUTE_POLICY);
2082
+ }
2083
+ /**
2084
+ * Runs a server route in-process as the caller, with the checks its HTTP
2085
+ * endpoint applies on every adapter: authentication, auth's `authorizeUser`,
2086
+ * `authorize` and `rules` (against the route's path under `apiPrefix`), input
2087
+ * validation, RBAC permission and FGA. Lets code outside an HTTP request (such
2088
+ * as an MCP tool) reuse a route without proxying through the HTTP server.
2089
+ *
2090
+ * Authentication is not re-run: when server or studio auth is configured, the
2091
+ * request context must already carry the user Mastra server auth resolved
2092
+ * (`MASTRA_USER_KEY`), otherwise the call is refused with 401.
2093
+ *
2094
+ * Only JSON routes are supported; other response types throw. The handler gets
2095
+ * the parsed params, `mastra`, `requestContext` and `abortSignal`, but not the
2096
+ * HTTP-only `request`, `registeredTools`, `taskStore` or `routePrefix`, so
2097
+ * routes that read those are not suitable.
2098
+ *
2099
+ * Shares its pipeline with `dispatchRoute`, which follows the HTTP request more
2100
+ * closely (public paths, the adapter's prefix, custom error responses), passes a
2101
+ * full `ServerContext` and returns raw handler results.
2102
+ */
2103
+ async function invokeRoute(route, options) {
2104
+ if (route.responseType !== "json") throw new Error(`invokeRoute only runs JSON routes; ${route.method} ${route.path} answers with '${route.responseType}'`);
2105
+ const result = await runRoutePipeline(route, {
2106
+ pathParams: options.pathParams,
2107
+ query: options.query,
2108
+ body: options.body
2109
+ }, {
2110
+ mastra: options.mastra,
2111
+ requestContext: options.requestContext,
2112
+ abortSignal: options.abortSignal ?? new AbortController().signal
2113
+ }, INVOKE_ROUTE_POLICY);
2114
+ return result.ok ? {
2115
+ status: 200,
2116
+ body: result.result
2117
+ } : {
2118
+ status: result.status,
2119
+ body: result.body
2120
+ };
2121
+ }
2122
+ /**
2123
+ * Check FGA authorization for an HTTP route.
2124
+ * Returns null if authorized or FGA not configured, or an error object if denied.
2125
+ */
2126
+ async function checkRouteFGA(mastra, route, requestContext, params) {
2127
+ const fgaProvider = getFGAProvider(mastra, requestContext);
2128
+ if (!fgaProvider) return null;
2129
+ const fgaConfig = await resolveRouteFGAConfig(fgaProvider, route, requestContext, params);
2130
+ if (!fgaConfig) {
2131
+ if (fgaProvider.requireForProtectedRoutes && isProtectedFGARoute(route)) return {
2132
+ status: 403,
2133
+ error: "Forbidden",
2134
+ message: "FGA authorization denied: route FGA metadata is required"
2135
+ };
2136
+ return null;
2137
+ }
2138
+ const user = requestContext?.get("user");
2139
+ if (!user) return {
2140
+ status: 403,
2141
+ error: "Forbidden",
2142
+ message: "FGA authorization denied: authenticated user is required"
2143
+ };
2144
+ const resourceId = typeof fgaConfig.resourceId === "function" ? fgaConfig.resourceId(params, { requestContext }) : fgaConfig.resourceId || (fgaConfig.resourceIdParam ? params[fgaConfig.resourceIdParam] : void 0);
2145
+ if (!fgaConfig.resourceType || !resourceId) return {
2146
+ status: 403,
2147
+ error: "Forbidden",
2148
+ message: "FGA authorization denied: route FGA metadata is incomplete"
2149
+ };
2150
+ const effectivePermission = route.path ? getEffectivePermission(route) : null;
2151
+ const permission = fgaConfig.permission || effectivePermission || `${getFGAResourcePermissionSlug(fgaConfig.resourceType)}:${deriveFGAAction(route.method)}`;
2152
+ if (!await fgaProvider.check(user, {
2153
+ resource: {
2154
+ type: fgaConfig.resourceType,
2155
+ id: resourceId
2156
+ },
2157
+ permission,
2158
+ context: {
2159
+ resourceId,
2160
+ requestContext
2161
+ }
2162
+ })) return {
2163
+ status: 403,
2164
+ error: "Forbidden",
2165
+ message: `FGA authorization denied: cannot ${permission} on ${fgaConfig.resourceType}:${resourceId}`
2166
+ };
2167
+ return null;
2168
+ }
2169
+ function deriveFGAAction(method) {
2170
+ switch (method.toUpperCase()) {
2171
+ case "GET": return "read";
2172
+ case "DELETE": return "delete";
2173
+ case "POST":
2174
+ case "PUT":
2175
+ case "PATCH": return "write";
2176
+ default: return "read";
2177
+ }
2178
+ }
2179
+ function getFGAResourcePermissionSlug(resourceType) {
2180
+ return {
2181
+ agent: "agents",
2182
+ workflow: "workflows",
2183
+ tool: "tools",
2184
+ thread: "memory"
2185
+ }[resourceType] ?? resourceType;
2186
+ }
2187
+ export { createMCPOAuthMetadataRoutes as A, writeWithBackpressure as C, applyMcpRequestAuth as D, propagateRequestAbort as E, isMCPOAuthDiscoveryEnabled as M, mcpWWWAuthenticate as N, buildMcpAuthInfoFromRequestContext as O, cancelReaderOnResponseClose as S, redactStreamChunk as T, parseRouteBody as _, checkRouteFGA as a, registerDispatchAdapter as b, getCustomHTTPExceptionResponse as c, getFGAProvider as d, getHTTPErrorResponse as f, normalizeQueryParams as g, isSafeObjectKey as h, bindDispatchAdapter as i, isMCPAudienceEnforced as j, checkMCPAudience as k, getCustomRouteHTTPExceptionResponse as l, invokeRoute as m, MastraServer as n, checkRouteRBAC as o, getRoutePermissionError as p, authorizeRoute as r, dispatchRoute as s, MASTRA_FRAMEWORK_PUBLIC_KEY as t, getEffectiveRBACProvider as u, parseRoutePathParams as v, serializeStreamChunk as w, resolveRouteValidationError as x, parseRouteQueryParams as y };
2188
+
2189
+ //# sourceMappingURL=server-adapter-BywLWVKp.js.map