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