@mastra/core 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (498) hide show
  1. package/CHANGELOG.md +218 -0
  2. package/dist/agent/agent-legacy.d.ts +15 -0
  3. package/dist/agent/agent-legacy.d.ts.map +1 -1
  4. package/dist/agent/agent.d.ts +7 -0
  5. package/dist/agent/agent.d.ts.map +1 -1
  6. package/dist/agent/agent.types.d.ts +311 -2
  7. package/dist/agent/agent.types.d.ts.map +1 -1
  8. package/dist/agent/index.cjs +13 -13
  9. package/dist/agent/index.d.ts +3 -1
  10. package/dist/agent/index.d.ts.map +1 -1
  11. package/dist/agent/index.js +2 -2
  12. package/dist/agent/message-list/index.cjs +18 -18
  13. package/dist/agent/message-list/index.js +1 -1
  14. package/dist/agent/message-list/merge/MessageMerger.d.ts.map +1 -1
  15. package/dist/agent/message-list/message-list.d.ts.map +1 -1
  16. package/dist/agent/workflows/prepare-stream/map-results-step.d.ts.map +1 -1
  17. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts.map +1 -1
  18. package/dist/{chunk-A72NTLFT.cjs → chunk-2IO5Q7OZ.cjs} +7 -7
  19. package/dist/{chunk-A72NTLFT.cjs.map → chunk-2IO5Q7OZ.cjs.map} +1 -1
  20. package/dist/{chunk-DFCRXDVK.js → chunk-2KHPZJNU.js} +10 -8
  21. package/dist/chunk-2KHPZJNU.js.map +1 -0
  22. package/dist/{chunk-R4N65TLG.js → chunk-2R5MQMSA.js} +35 -16
  23. package/dist/chunk-2R5MQMSA.js.map +1 -0
  24. package/dist/{chunk-ZSBM2SVU.js → chunk-4H5F6AFP.js} +1064 -226
  25. package/dist/chunk-4H5F6AFP.js.map +1 -0
  26. package/dist/{chunk-BQHWJLXU.js → chunk-63G75DJE.js} +9 -3
  27. package/dist/chunk-63G75DJE.js.map +1 -0
  28. package/dist/{chunk-SBOHDNIZ.cjs → chunk-6GSWC5ZA.cjs} +2 -2
  29. package/dist/{chunk-SBOHDNIZ.cjs.map → chunk-6GSWC5ZA.cjs.map} +1 -1
  30. package/dist/{chunk-QTAS3HND.cjs → chunk-6Q2UD3XF.cjs} +21 -14
  31. package/dist/chunk-6Q2UD3XF.cjs.map +1 -0
  32. package/dist/{chunk-GPJGPARM.js → chunk-DTPR3JAM.js} +2 -2
  33. package/dist/{chunk-GPJGPARM.js.map → chunk-DTPR3JAM.js.map} +1 -1
  34. package/dist/{chunk-NN26FSKL.js → chunk-FHJ2KIU5.js} +3 -3
  35. package/dist/{chunk-NN26FSKL.js.map → chunk-FHJ2KIU5.js.map} +1 -1
  36. package/dist/{chunk-RABITNTG.cjs → chunk-HWG7NPJA.cjs} +55 -55
  37. package/dist/{chunk-RABITNTG.cjs.map → chunk-HWG7NPJA.cjs.map} +1 -1
  38. package/dist/{chunk-HB6T4554.cjs → chunk-KH3G65IS.cjs} +10 -8
  39. package/dist/chunk-KH3G65IS.cjs.map +1 -0
  40. package/dist/{chunk-YQG7NBPR.cjs → chunk-KZ4IKNPN.cjs} +25 -23
  41. package/dist/chunk-KZ4IKNPN.cjs.map +1 -0
  42. package/dist/{chunk-6DUTLERJ.js → chunk-MRV5NCPC.js} +3 -3
  43. package/dist/{chunk-6DUTLERJ.js.map → chunk-MRV5NCPC.js.map} +1 -1
  44. package/dist/{chunk-O7PZ4VOO.cjs → chunk-N3ROEJG4.cjs} +12 -10
  45. package/dist/chunk-N3ROEJG4.cjs.map +1 -0
  46. package/dist/{chunk-7EXW4AAG.js → chunk-NXKI2L4X.js} +6 -4
  47. package/dist/chunk-NXKI2L4X.js.map +1 -0
  48. package/dist/{chunk-QWTB53GS.js → chunk-OSEPGSLN.js} +6 -6
  49. package/dist/{chunk-QWTB53GS.js.map → chunk-OSEPGSLN.js.map} +1 -1
  50. package/dist/{chunk-6OXW5E2O.js → chunk-PI7ONENO.js} +4 -4
  51. package/dist/{chunk-6OXW5E2O.js.map → chunk-PI7ONENO.js.map} +1 -1
  52. package/dist/{chunk-KUXNBWN7.js → chunk-Q4MV4XKX.js} +8 -6
  53. package/dist/chunk-Q4MV4XKX.js.map +1 -0
  54. package/dist/{chunk-7UAJ6LMR.cjs → chunk-QKQGKEN7.cjs} +1078 -241
  55. package/dist/chunk-QKQGKEN7.cjs.map +1 -0
  56. package/dist/{chunk-IC5OUWKJ.js → chunk-SP7P6Z4L.js} +19 -2
  57. package/dist/chunk-SP7P6Z4L.js.map +1 -0
  58. package/dist/{chunk-QDH6MVJ7.cjs → chunk-TGUDI64A.cjs} +14 -14
  59. package/dist/{chunk-QDH6MVJ7.cjs.map → chunk-TGUDI64A.cjs.map} +1 -1
  60. package/dist/{chunk-EAZ6YDCQ.cjs → chunk-U3HBG2GU.cjs} +9 -2
  61. package/dist/chunk-U3HBG2GU.cjs.map +1 -0
  62. package/dist/{chunk-6QBN6MZY.cjs → chunk-VAKB5EXJ.cjs} +42 -23
  63. package/dist/chunk-VAKB5EXJ.cjs.map +1 -0
  64. package/dist/{chunk-QSHV7GPT.js → chunk-VBPU6CLZ.js} +3808 -3026
  65. package/dist/chunk-VBPU6CLZ.js.map +1 -0
  66. package/dist/{chunk-2X66GWF5.cjs → chunk-VTVCMIAI.cjs} +3905 -3121
  67. package/dist/chunk-VTVCMIAI.cjs.map +1 -0
  68. package/dist/{chunk-PHHJLGZU.cjs → chunk-XNWF6CYR.cjs} +6 -6
  69. package/dist/{chunk-PHHJLGZU.cjs.map → chunk-XNWF6CYR.cjs.map} +1 -1
  70. package/dist/{chunk-T6GAM3SQ.js → chunk-ZRPTWYWJ.js} +18 -11
  71. package/dist/chunk-ZRPTWYWJ.js.map +1 -0
  72. package/dist/{chunk-DB7U2C5B.cjs → chunk-ZXOWG32X.cjs} +19 -2
  73. package/dist/chunk-ZXOWG32X.cjs.map +1 -0
  74. package/dist/datasets/experiment/index.d.ts.map +1 -1
  75. package/dist/datasets/experiment/scorer.d.ts +1 -1
  76. package/dist/datasets/experiment/scorer.d.ts.map +1 -1
  77. package/dist/datasets/index.cjs +17 -17
  78. package/dist/datasets/index.js +2 -2
  79. package/dist/docs/SKILL.md +300 -0
  80. package/dist/docs/assets/SOURCE_MAP.json +1423 -0
  81. package/dist/docs/references/docs-agents-adding-voice.md +349 -0
  82. package/dist/docs/references/docs-agents-agent-approval.md +558 -0
  83. package/dist/docs/references/docs-agents-agent-memory.md +209 -0
  84. package/dist/docs/references/docs-agents-guardrails.md +374 -0
  85. package/dist/docs/references/docs-agents-network-approval.md +275 -0
  86. package/dist/docs/references/docs-agents-networks.md +299 -0
  87. package/dist/docs/references/docs-agents-overview.md +304 -0
  88. package/dist/docs/references/docs-agents-processors.md +622 -0
  89. package/dist/docs/references/docs-agents-structured-output.md +273 -0
  90. package/dist/docs/references/docs-agents-supervisor-agents.md +304 -0
  91. package/dist/docs/references/docs-agents-using-tools.md +214 -0
  92. package/dist/docs/references/docs-evals-custom-scorers.md +519 -0
  93. package/dist/docs/references/docs-evals-overview.md +141 -0
  94. package/dist/docs/references/docs-evals-running-in-ci.md +124 -0
  95. package/dist/docs/references/docs-memory-memory-processors.md +314 -0
  96. package/dist/docs/references/docs-memory-observational-memory.md +248 -0
  97. package/dist/docs/references/docs-memory-overview.md +45 -0
  98. package/dist/docs/references/docs-memory-semantic-recall.md +272 -0
  99. package/dist/docs/references/docs-memory-storage.md +261 -0
  100. package/dist/docs/references/docs-memory-working-memory.md +400 -0
  101. package/dist/docs/references/docs-observability-datasets-overview.md +198 -0
  102. package/dist/docs/references/docs-observability-datasets-running-experiments.md +274 -0
  103. package/dist/docs/references/docs-observability-logging.md +99 -0
  104. package/dist/docs/references/docs-observability-overview.md +70 -0
  105. package/dist/docs/references/docs-observability-tracing-bridges-otel.md +209 -0
  106. package/dist/docs/references/docs-observability-tracing-exporters-arize.md +272 -0
  107. package/dist/docs/references/docs-observability-tracing-exporters-braintrust.md +111 -0
  108. package/dist/docs/references/docs-observability-tracing-exporters-cloud.md +127 -0
  109. package/dist/docs/references/docs-observability-tracing-exporters-datadog.md +187 -0
  110. package/dist/docs/references/docs-observability-tracing-exporters-default.md +209 -0
  111. package/dist/docs/references/docs-observability-tracing-exporters-laminar.md +100 -0
  112. package/dist/docs/references/docs-observability-tracing-exporters-langfuse.md +213 -0
  113. package/dist/docs/references/docs-observability-tracing-exporters-langsmith.md +198 -0
  114. package/dist/docs/references/docs-observability-tracing-exporters-otel.md +476 -0
  115. package/dist/docs/references/docs-observability-tracing-exporters-posthog.md +148 -0
  116. package/dist/docs/references/docs-observability-tracing-overview.md +1112 -0
  117. package/dist/docs/references/docs-rag-chunking-and-embedding.md +183 -0
  118. package/dist/docs/references/docs-rag-graph-rag.md +215 -0
  119. package/dist/docs/references/docs-rag-overview.md +72 -0
  120. package/dist/docs/references/docs-rag-retrieval.md +515 -0
  121. package/dist/docs/references/docs-rag-vector-databases.md +645 -0
  122. package/dist/docs/references/docs-server-auth-auth0.md +220 -0
  123. package/dist/docs/references/docs-server-auth-clerk.md +132 -0
  124. package/dist/docs/references/docs-server-auth-composite-auth.md +234 -0
  125. package/dist/docs/references/docs-server-auth-custom-auth-provider.md +513 -0
  126. package/dist/docs/references/docs-server-auth-firebase.md +272 -0
  127. package/dist/docs/references/docs-server-auth-jwt.md +110 -0
  128. package/dist/docs/references/docs-server-auth-simple-auth.md +180 -0
  129. package/dist/docs/references/docs-server-auth-supabase.md +117 -0
  130. package/dist/docs/references/docs-server-auth-workos.md +186 -0
  131. package/dist/docs/references/docs-server-custom-adapters.md +378 -0
  132. package/dist/docs/references/docs-server-custom-api-routes.md +267 -0
  133. package/dist/docs/references/docs-server-mastra-client.md +243 -0
  134. package/dist/docs/references/docs-server-mastra-server.md +71 -0
  135. package/dist/docs/references/docs-server-middleware.md +225 -0
  136. package/dist/docs/references/docs-server-request-context.md +471 -0
  137. package/dist/docs/references/docs-streaming-events.md +237 -0
  138. package/dist/docs/references/docs-streaming-tool-streaming.md +175 -0
  139. package/dist/docs/references/docs-streaming-workflow-streaming.md +109 -0
  140. package/dist/docs/references/docs-voice-overview.md +959 -0
  141. package/dist/docs/references/docs-voice-speech-to-speech.md +102 -0
  142. package/dist/docs/references/docs-voice-speech-to-text.md +79 -0
  143. package/dist/docs/references/docs-voice-text-to-speech.md +83 -0
  144. package/dist/docs/references/docs-workflows-agents-and-tools.md +166 -0
  145. package/dist/docs/references/docs-workflows-control-flow.md +822 -0
  146. package/dist/docs/references/docs-workflows-error-handling.md +360 -0
  147. package/dist/docs/references/docs-workflows-human-in-the-loop.md +215 -0
  148. package/dist/docs/references/docs-workflows-overview.md +370 -0
  149. package/dist/docs/references/docs-workflows-snapshots.md +238 -0
  150. package/dist/docs/references/docs-workflows-suspend-and-resume.md +205 -0
  151. package/dist/docs/references/docs-workflows-time-travel.md +309 -0
  152. package/dist/docs/references/docs-workflows-workflow-state.md +181 -0
  153. package/dist/docs/references/docs-workspace-filesystem.md +164 -0
  154. package/dist/docs/references/docs-workspace-overview.md +239 -0
  155. package/dist/docs/references/docs-workspace-sandbox.md +63 -0
  156. package/dist/docs/references/docs-workspace-search.md +243 -0
  157. package/dist/docs/references/docs-workspace-skills.md +169 -0
  158. package/dist/docs/references/guides-agent-frameworks-ai-sdk.md +140 -0
  159. package/dist/docs/references/reference-agents-agent.md +141 -0
  160. package/dist/docs/references/reference-agents-generate.md +186 -0
  161. package/dist/docs/references/reference-agents-generateLegacy.md +173 -0
  162. package/dist/docs/references/reference-agents-getDefaultGenerateOptions.md +36 -0
  163. package/dist/docs/references/reference-agents-getDefaultOptions.md +34 -0
  164. package/dist/docs/references/reference-agents-getDefaultStreamOptions.md +36 -0
  165. package/dist/docs/references/reference-agents-getDescription.md +21 -0
  166. package/dist/docs/references/reference-agents-getInstructions.md +34 -0
  167. package/dist/docs/references/reference-agents-getLLM.md +37 -0
  168. package/dist/docs/references/reference-agents-getMemory.md +34 -0
  169. package/dist/docs/references/reference-agents-getModel.md +34 -0
  170. package/dist/docs/references/reference-agents-getTools.md +29 -0
  171. package/dist/docs/references/reference-agents-getVoice.md +34 -0
  172. package/dist/docs/references/reference-agents-listAgents.md +35 -0
  173. package/dist/docs/references/reference-agents-listScorers.md +34 -0
  174. package/dist/docs/references/reference-agents-listTools.md +34 -0
  175. package/dist/docs/references/reference-agents-listWorkflows.md +34 -0
  176. package/dist/docs/references/reference-agents-network.md +133 -0
  177. package/dist/docs/references/reference-ai-sdk-chat-route.md +82 -0
  178. package/dist/docs/references/reference-ai-sdk-network-route.md +74 -0
  179. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-stream.md +231 -0
  180. package/dist/docs/references/reference-ai-sdk-with-mastra.md +59 -0
  181. package/dist/docs/references/reference-ai-sdk-workflow-route.md +79 -0
  182. package/dist/docs/references/reference-auth-auth0.md +73 -0
  183. package/dist/docs/references/reference-auth-clerk.md +36 -0
  184. package/dist/docs/references/reference-auth-firebase.md +80 -0
  185. package/dist/docs/references/reference-auth-jwt.md +26 -0
  186. package/dist/docs/references/reference-auth-supabase.md +33 -0
  187. package/dist/docs/references/reference-auth-workos.md +84 -0
  188. package/dist/docs/references/reference-client-js-agents.md +437 -0
  189. package/dist/docs/references/reference-configuration.md +752 -0
  190. package/dist/docs/references/reference-core-addGateway.md +42 -0
  191. package/dist/docs/references/reference-core-getAgent.md +21 -0
  192. package/dist/docs/references/reference-core-getAgentById.md +21 -0
  193. package/dist/docs/references/reference-core-getDeployer.md +22 -0
  194. package/dist/docs/references/reference-core-getGateway.md +38 -0
  195. package/dist/docs/references/reference-core-getGatewayById.md +41 -0
  196. package/dist/docs/references/reference-core-getLogger.md +22 -0
  197. package/dist/docs/references/reference-core-getMCPServer.md +47 -0
  198. package/dist/docs/references/reference-core-getMCPServerById.md +55 -0
  199. package/dist/docs/references/reference-core-getMemory.md +50 -0
  200. package/dist/docs/references/reference-core-getScorer.md +54 -0
  201. package/dist/docs/references/reference-core-getScorerById.md +54 -0
  202. package/dist/docs/references/reference-core-getServer.md +22 -0
  203. package/dist/docs/references/reference-core-getStorage.md +22 -0
  204. package/dist/docs/references/reference-core-getStoredAgentById.md +89 -0
  205. package/dist/docs/references/reference-core-getTelemetry.md +22 -0
  206. package/dist/docs/references/reference-core-getVector.md +22 -0
  207. package/dist/docs/references/reference-core-getWorkflow.md +42 -0
  208. package/dist/docs/references/reference-core-listAgents.md +21 -0
  209. package/dist/docs/references/reference-core-listGateways.md +40 -0
  210. package/dist/docs/references/reference-core-listLogs.md +38 -0
  211. package/dist/docs/references/reference-core-listLogsByRunId.md +36 -0
  212. package/dist/docs/references/reference-core-listMCPServers.md +55 -0
  213. package/dist/docs/references/reference-core-listMemory.md +56 -0
  214. package/dist/docs/references/reference-core-listScorers.md +29 -0
  215. package/dist/docs/references/reference-core-listStoredAgents.md +93 -0
  216. package/dist/docs/references/reference-core-listVectors.md +22 -0
  217. package/dist/docs/references/reference-core-listWorkflows.md +21 -0
  218. package/dist/docs/references/reference-core-mastra-class.md +66 -0
  219. package/dist/docs/references/reference-core-mastra-model-gateway.md +153 -0
  220. package/dist/docs/references/reference-core-setLogger.md +26 -0
  221. package/dist/docs/references/reference-core-setStorage.md +27 -0
  222. package/dist/docs/references/reference-datasets-addItem.md +37 -0
  223. package/dist/docs/references/reference-datasets-addItems.md +35 -0
  224. package/dist/docs/references/reference-datasets-compareExperiments.md +52 -0
  225. package/dist/docs/references/reference-datasets-create.md +51 -0
  226. package/dist/docs/references/reference-datasets-dataset.md +82 -0
  227. package/dist/docs/references/reference-datasets-datasets-manager.md +94 -0
  228. package/dist/docs/references/reference-datasets-delete.md +25 -0
  229. package/dist/docs/references/reference-datasets-deleteExperiment.md +27 -0
  230. package/dist/docs/references/reference-datasets-deleteItem.md +27 -0
  231. package/dist/docs/references/reference-datasets-deleteItems.md +29 -0
  232. package/dist/docs/references/reference-datasets-get.md +31 -0
  233. package/dist/docs/references/reference-datasets-getDetails.md +47 -0
  234. package/dist/docs/references/reference-datasets-getExperiment.md +30 -0
  235. package/dist/docs/references/reference-datasets-getItem.md +33 -0
  236. package/dist/docs/references/reference-datasets-getItemHistory.md +31 -0
  237. package/dist/docs/references/reference-datasets-list.md +31 -0
  238. package/dist/docs/references/reference-datasets-listExperimentResults.md +39 -0
  239. package/dist/docs/references/reference-datasets-listExperiments.md +33 -0
  240. package/dist/docs/references/reference-datasets-listItems.md +46 -0
  241. package/dist/docs/references/reference-datasets-listVersions.md +33 -0
  242. package/dist/docs/references/reference-datasets-startExperiment.md +62 -0
  243. package/dist/docs/references/reference-datasets-startExperimentAsync.md +43 -0
  244. package/dist/docs/references/reference-datasets-update.md +48 -0
  245. package/dist/docs/references/reference-datasets-updateItem.md +38 -0
  246. package/dist/docs/references/reference-evals-answer-relevancy.md +105 -0
  247. package/dist/docs/references/reference-evals-answer-similarity.md +99 -0
  248. package/dist/docs/references/reference-evals-bias.md +120 -0
  249. package/dist/docs/references/reference-evals-completeness.md +136 -0
  250. package/dist/docs/references/reference-evals-content-similarity.md +101 -0
  251. package/dist/docs/references/reference-evals-context-precision.md +196 -0
  252. package/dist/docs/references/reference-evals-create-scorer.md +270 -0
  253. package/dist/docs/references/reference-evals-faithfulness.md +114 -0
  254. package/dist/docs/references/reference-evals-hallucination.md +213 -0
  255. package/dist/docs/references/reference-evals-keyword-coverage.md +128 -0
  256. package/dist/docs/references/reference-evals-mastra-scorer.md +123 -0
  257. package/dist/docs/references/reference-evals-run-evals.md +179 -0
  258. package/dist/docs/references/reference-evals-scorer-utils.md +326 -0
  259. package/dist/docs/references/reference-evals-textual-difference.md +113 -0
  260. package/dist/docs/references/reference-evals-tone-consistency.md +119 -0
  261. package/dist/docs/references/reference-evals-toxicity.md +123 -0
  262. package/dist/docs/references/reference-harness-harness-class.md +708 -0
  263. package/dist/docs/references/reference-logging-pino-logger.md +117 -0
  264. package/dist/docs/references/reference-memory-deleteMessages.md +38 -0
  265. package/dist/docs/references/reference-memory-memory-class.md +147 -0
  266. package/dist/docs/references/reference-memory-observational-memory.md +565 -0
  267. package/dist/docs/references/reference-observability-tracing-bridges-otel.md +131 -0
  268. package/dist/docs/references/reference-observability-tracing-configuration.md +178 -0
  269. package/dist/docs/references/reference-observability-tracing-exporters-console-exporter.md +138 -0
  270. package/dist/docs/references/reference-observability-tracing-exporters-datadog.md +116 -0
  271. package/dist/docs/references/reference-observability-tracing-instances.md +107 -0
  272. package/dist/docs/references/reference-observability-tracing-interfaces.md +743 -0
  273. package/dist/docs/references/reference-observability-tracing-processors-sensitive-data-filter.md +144 -0
  274. package/dist/docs/references/reference-observability-tracing-spans.md +224 -0
  275. package/dist/docs/references/reference-processors-batch-parts-processor.md +61 -0
  276. package/dist/docs/references/reference-processors-language-detector.md +82 -0
  277. package/dist/docs/references/reference-processors-message-history-processor.md +85 -0
  278. package/dist/docs/references/reference-processors-moderation-processor.md +104 -0
  279. package/dist/docs/references/reference-processors-pii-detector.md +108 -0
  280. package/dist/docs/references/reference-processors-processor-interface.md +521 -0
  281. package/dist/docs/references/reference-processors-prompt-injection-detector.md +72 -0
  282. package/dist/docs/references/reference-processors-semantic-recall-processor.md +117 -0
  283. package/dist/docs/references/reference-processors-system-prompt-scrubber.md +80 -0
  284. package/dist/docs/references/reference-processors-token-limiter-processor.md +115 -0
  285. package/dist/docs/references/reference-processors-tool-call-filter.md +85 -0
  286. package/dist/docs/references/reference-processors-tool-search-processor.md +111 -0
  287. package/dist/docs/references/reference-processors-unicode-normalizer.md +62 -0
  288. package/dist/docs/references/reference-processors-working-memory-processor.md +152 -0
  289. package/dist/docs/references/reference-rag-database-config.md +261 -0
  290. package/dist/docs/references/reference-rag-embeddings.md +92 -0
  291. package/dist/docs/references/reference-server-mastra-server.md +298 -0
  292. package/dist/docs/references/reference-server-register-api-route.md +249 -0
  293. package/dist/docs/references/reference-storage-cloudflare-d1.md +218 -0
  294. package/dist/docs/references/reference-storage-composite.md +235 -0
  295. package/dist/docs/references/reference-storage-lance.md +131 -0
  296. package/dist/docs/references/reference-storage-libsql.md +135 -0
  297. package/dist/docs/references/reference-storage-mongodb.md +262 -0
  298. package/dist/docs/references/reference-storage-mssql.md +157 -0
  299. package/dist/docs/references/reference-storage-overview.md +121 -0
  300. package/dist/docs/references/reference-storage-postgresql.md +526 -0
  301. package/dist/docs/references/reference-storage-upstash.md +160 -0
  302. package/dist/docs/references/reference-streaming-ChunkType.md +292 -0
  303. package/dist/docs/references/reference-streaming-agents-MastraModelOutput.md +182 -0
  304. package/dist/docs/references/reference-streaming-agents-streamLegacy.md +142 -0
  305. package/dist/docs/references/reference-streaming-workflows-observeStream.md +42 -0
  306. package/dist/docs/references/reference-streaming-workflows-resumeStream.md +61 -0
  307. package/dist/docs/references/reference-streaming-workflows-stream.md +88 -0
  308. package/dist/docs/references/reference-streaming-workflows-timeTravelStream.md +142 -0
  309. package/dist/docs/references/reference-templates-overview.md +194 -0
  310. package/dist/docs/references/reference-tools-create-tool.md +237 -0
  311. package/dist/docs/references/reference-tools-graph-rag-tool.md +182 -0
  312. package/dist/docs/references/reference-tools-mcp-client.md +954 -0
  313. package/dist/docs/references/reference-tools-mcp-server.md +1271 -0
  314. package/dist/docs/references/reference-tools-vector-query-tool.md +459 -0
  315. package/dist/docs/references/reference-vectors-libsql.md +305 -0
  316. package/dist/docs/references/reference-vectors-mongodb.md +295 -0
  317. package/dist/docs/references/reference-vectors-pg.md +408 -0
  318. package/dist/docs/references/reference-vectors-upstash.md +294 -0
  319. package/dist/docs/references/reference-voice-composite-voice.md +121 -0
  320. package/dist/docs/references/reference-voice-mastra-voice.md +311 -0
  321. package/dist/docs/references/reference-voice-voice.addInstructions.md +55 -0
  322. package/dist/docs/references/reference-voice-voice.addTools.md +67 -0
  323. package/dist/docs/references/reference-voice-voice.connect.md +94 -0
  324. package/dist/docs/references/reference-voice-voice.events.md +37 -0
  325. package/dist/docs/references/reference-voice-voice.listen.md +164 -0
  326. package/dist/docs/references/reference-voice-voice.on.md +111 -0
  327. package/dist/docs/references/reference-voice-voice.speak.md +157 -0
  328. package/dist/docs/references/reference-workflows-run-methods-cancel.md +86 -0
  329. package/dist/docs/references/reference-workflows-run-methods-restart.md +33 -0
  330. package/dist/docs/references/reference-workflows-run-methods-resume.md +59 -0
  331. package/dist/docs/references/reference-workflows-run-methods-start.md +58 -0
  332. package/dist/docs/references/reference-workflows-run-methods-startAsync.md +67 -0
  333. package/dist/docs/references/reference-workflows-run-methods-timeTravel.md +142 -0
  334. package/dist/docs/references/reference-workflows-run.md +59 -0
  335. package/dist/docs/references/reference-workflows-step.md +119 -0
  336. package/dist/docs/references/reference-workflows-workflow-methods-branch.md +25 -0
  337. package/dist/docs/references/reference-workflows-workflow-methods-commit.md +17 -0
  338. package/dist/docs/references/reference-workflows-workflow-methods-create-run.md +63 -0
  339. package/dist/docs/references/reference-workflows-workflow-methods-dountil.md +25 -0
  340. package/dist/docs/references/reference-workflows-workflow-methods-dowhile.md +25 -0
  341. package/dist/docs/references/reference-workflows-workflow-methods-foreach.md +118 -0
  342. package/dist/docs/references/reference-workflows-workflow-methods-map.md +93 -0
  343. package/dist/docs/references/reference-workflows-workflow-methods-parallel.md +21 -0
  344. package/dist/docs/references/reference-workflows-workflow-methods-sleep.md +35 -0
  345. package/dist/docs/references/reference-workflows-workflow-methods-sleepUntil.md +35 -0
  346. package/dist/docs/references/reference-workflows-workflow-methods-then.md +21 -0
  347. package/dist/docs/references/reference-workflows-workflow.md +157 -0
  348. package/dist/docs/references/reference-workspace-filesystem.md +255 -0
  349. package/dist/docs/references/reference-workspace-local-filesystem.md +343 -0
  350. package/dist/docs/references/reference-workspace-local-sandbox.md +301 -0
  351. package/dist/docs/references/reference-workspace-sandbox.md +87 -0
  352. package/dist/docs/references/reference-workspace-workspace-class.md +244 -0
  353. package/dist/docs/references/reference.md +277 -0
  354. package/dist/evals/index.cjs +20 -20
  355. package/dist/evals/index.js +3 -3
  356. package/dist/evals/run/index.d.ts +9 -2
  357. package/dist/evals/run/index.d.ts.map +1 -1
  358. package/dist/evals/scoreTraces/index.cjs +5 -5
  359. package/dist/evals/scoreTraces/index.js +2 -2
  360. package/dist/harness/harness.d.ts +6 -0
  361. package/dist/harness/harness.d.ts.map +1 -1
  362. package/dist/harness/index.cjs +28 -13
  363. package/dist/harness/index.cjs.map +1 -1
  364. package/dist/harness/index.js +20 -5
  365. package/dist/harness/index.js.map +1 -1
  366. package/dist/index.cjs +2 -2
  367. package/dist/index.js +1 -1
  368. package/dist/integration/index.cjs +2 -2
  369. package/dist/integration/index.js +1 -1
  370. package/dist/llm/index.cjs +6 -6
  371. package/dist/llm/index.js +1 -1
  372. package/dist/llm/model/embedding-router.d.ts.map +1 -1
  373. package/dist/llm/model/model.loop.d.ts +1 -1
  374. package/dist/llm/model/model.loop.d.ts.map +1 -1
  375. package/dist/loop/index.cjs +20 -12
  376. package/dist/loop/index.js +1 -1
  377. package/dist/loop/network/index.d.ts.map +1 -1
  378. package/dist/loop/network/validation.d.ts +51 -0
  379. package/dist/loop/network/validation.d.ts.map +1 -1
  380. package/dist/loop/test-utils/generateText.d.ts.map +1 -1
  381. package/dist/loop/test-utils/options.d.ts.map +1 -1
  382. package/dist/loop/test-utils/streamObject.d.ts.map +1 -1
  383. package/dist/loop/types.d.ts +15 -0
  384. package/dist/loop/types.d.ts.map +1 -1
  385. package/dist/loop/workflows/agentic-execution/index.d.ts +3 -0
  386. package/dist/loop/workflows/agentic-execution/index.d.ts.map +1 -1
  387. package/dist/loop/workflows/agentic-execution/is-task-complete-step.d.ts +126 -0
  388. package/dist/loop/workflows/agentic-execution/is-task-complete-step.d.ts.map +1 -0
  389. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +3 -1
  390. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts.map +1 -1
  391. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts +1 -0
  392. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts.map +1 -1
  393. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts.map +1 -1
  394. package/dist/loop/workflows/agentic-loop/index.d.ts +3 -0
  395. package/dist/loop/workflows/agentic-loop/index.d.ts.map +1 -1
  396. package/dist/loop/workflows/schema.d.ts +3 -0
  397. package/dist/loop/workflows/schema.d.ts.map +1 -1
  398. package/dist/mastra/index.cjs +2 -2
  399. package/dist/mastra/index.d.ts +9 -5
  400. package/dist/mastra/index.d.ts.map +1 -1
  401. package/dist/mastra/index.js +1 -1
  402. package/dist/memory/index.cjs +14 -14
  403. package/dist/memory/index.js +1 -1
  404. package/dist/processor-provider/index.cjs +10 -10
  405. package/dist/processor-provider/index.js +1 -1
  406. package/dist/processors/index.cjs +42 -42
  407. package/dist/processors/index.js +1 -1
  408. package/dist/processors/processors/skills.d.ts.map +1 -1
  409. package/dist/relevance/index.cjs +3 -3
  410. package/dist/relevance/index.js +1 -1
  411. package/dist/storage/constants.cjs +56 -56
  412. package/dist/storage/constants.js +1 -1
  413. package/dist/storage/domains/memory/inmemory.d.ts.map +1 -1
  414. package/dist/storage/index.cjs +160 -160
  415. package/dist/storage/index.js +2 -2
  416. package/dist/storage/types.d.ts +2 -3
  417. package/dist/storage/types.d.ts.map +1 -1
  418. package/dist/stream/aisdk/v5/compat/prepare-tools.d.ts.map +1 -1
  419. package/dist/stream/base/output.d.ts +1 -0
  420. package/dist/stream/base/output.d.ts.map +1 -1
  421. package/dist/stream/index.cjs +11 -11
  422. package/dist/stream/index.js +2 -2
  423. package/dist/stream/types.d.ts +27 -1
  424. package/dist/stream/types.d.ts.map +1 -1
  425. package/dist/test-utils/llm-mock.cjs +4 -4
  426. package/dist/test-utils/llm-mock.js +1 -1
  427. package/dist/tool-loop-agent/index.cjs +4 -4
  428. package/dist/tool-loop-agent/index.js +1 -1
  429. package/dist/tools/index.cjs +9 -5
  430. package/dist/tools/index.d.ts +1 -1
  431. package/dist/tools/index.d.ts.map +1 -1
  432. package/dist/tools/index.js +1 -1
  433. package/dist/tools/is-vercel-tool.cjs +2 -2
  434. package/dist/tools/is-vercel-tool.js +1 -1
  435. package/dist/tools/toolchecks.d.ts +10 -0
  436. package/dist/tools/toolchecks.d.ts.map +1 -1
  437. package/dist/utils.cjs +23 -23
  438. package/dist/utils.js +1 -1
  439. package/dist/vector/index.cjs +7 -7
  440. package/dist/vector/index.js +1 -1
  441. package/dist/vector/types.d.ts +9 -1
  442. package/dist/vector/types.d.ts.map +1 -1
  443. package/dist/workflows/evented/index.cjs +10 -10
  444. package/dist/workflows/evented/index.js +1 -1
  445. package/dist/workflows/index.cjs +25 -25
  446. package/dist/workflows/index.js +1 -1
  447. package/dist/workflows/types.d.ts +14 -1
  448. package/dist/workflows/types.d.ts.map +1 -1
  449. package/dist/workflows/workflow.d.ts +3 -17
  450. package/dist/workflows/workflow.d.ts.map +1 -1
  451. package/dist/workspace/filesystem/composite-filesystem.d.ts +5 -0
  452. package/dist/workspace/filesystem/composite-filesystem.d.ts.map +1 -1
  453. package/dist/workspace/filesystem/filesystem.d.ts +12 -0
  454. package/dist/workspace/filesystem/filesystem.d.ts.map +1 -1
  455. package/dist/workspace/filesystem/fs-utils.d.ts +12 -0
  456. package/dist/workspace/filesystem/fs-utils.d.ts.map +1 -1
  457. package/dist/workspace/filesystem/local-filesystem.d.ts +6 -0
  458. package/dist/workspace/filesystem/local-filesystem.d.ts.map +1 -1
  459. package/dist/workspace/index.cjs +66 -66
  460. package/dist/workspace/index.js +1 -1
  461. package/dist/workspace/lsp/client.d.ts +76 -0
  462. package/dist/workspace/lsp/client.d.ts.map +1 -0
  463. package/dist/workspace/lsp/index.d.ts +6 -0
  464. package/dist/workspace/lsp/index.d.ts.map +1 -0
  465. package/dist/workspace/lsp/language.d.ts +16 -0
  466. package/dist/workspace/lsp/language.d.ts.map +1 -0
  467. package/dist/workspace/lsp/manager.d.ts +72 -0
  468. package/dist/workspace/lsp/manager.d.ts.map +1 -0
  469. package/dist/workspace/lsp/servers.d.ts +43 -0
  470. package/dist/workspace/lsp/servers.d.ts.map +1 -0
  471. package/dist/workspace/lsp/types.d.ts +45 -0
  472. package/dist/workspace/lsp/types.d.ts.map +1 -0
  473. package/dist/workspace/tools/ast-edit.d.ts.map +1 -1
  474. package/dist/workspace/tools/edit-file.d.ts.map +1 -1
  475. package/dist/workspace/tools/helpers.d.ts +13 -0
  476. package/dist/workspace/tools/helpers.d.ts.map +1 -1
  477. package/dist/workspace/tools/write-file.d.ts.map +1 -1
  478. package/dist/workspace/workspace.d.ts +33 -0
  479. package/dist/workspace/workspace.d.ts.map +1 -1
  480. package/package.json +10 -8
  481. package/dist/chunk-2X66GWF5.cjs.map +0 -1
  482. package/dist/chunk-6QBN6MZY.cjs.map +0 -1
  483. package/dist/chunk-7EXW4AAG.js.map +0 -1
  484. package/dist/chunk-7UAJ6LMR.cjs.map +0 -1
  485. package/dist/chunk-BQHWJLXU.js.map +0 -1
  486. package/dist/chunk-DB7U2C5B.cjs.map +0 -1
  487. package/dist/chunk-DFCRXDVK.js.map +0 -1
  488. package/dist/chunk-EAZ6YDCQ.cjs.map +0 -1
  489. package/dist/chunk-HB6T4554.cjs.map +0 -1
  490. package/dist/chunk-IC5OUWKJ.js.map +0 -1
  491. package/dist/chunk-KUXNBWN7.js.map +0 -1
  492. package/dist/chunk-O7PZ4VOO.cjs.map +0 -1
  493. package/dist/chunk-QSHV7GPT.js.map +0 -1
  494. package/dist/chunk-QTAS3HND.cjs.map +0 -1
  495. package/dist/chunk-R4N65TLG.js.map +0 -1
  496. package/dist/chunk-T6GAM3SQ.js.map +0 -1
  497. package/dist/chunk-YQG7NBPR.cjs.map +0 -1
  498. package/dist/chunk-ZSBM2SVU.js.map +0 -1
@@ -0,0 +1,1271 @@
1
+ # MCPServer
2
+
3
+ The `MCPServer` class provides the functionality to expose your existing Mastra tools and Agents as a Model Context Protocol (MCP) server. This allows any MCP client (like Cursor, Windsurf, or Claude Desktop) to connect to these capabilities and make them available to an agent.
4
+
5
+ Note that if you only need to use your tools or agents directly within your Mastra application, you don't necessarily need to create an MCP server. This API is specifically for exposing your Mastra tools and agents to _external_ MCP clients.
6
+
7
+ It supports both [stdio (subprocess) and SSE (HTTP) MCP transports](https://modelcontextprotocol.io/docs/concepts/transports).
8
+
9
+ ## Constructor
10
+
11
+ To create a new `MCPServer`, you need to provide some basic information about your server, the tools it will offer, and optionally, any agents you want to expose as tools.
12
+
13
+ ```typescript
14
+ import { Agent } from '@mastra/core/agent'
15
+ import { createTool } from '@mastra/core/tools'
16
+ import { MCPServer } from '@mastra/mcp'
17
+ import { z } from 'zod'
18
+ import { dataProcessingWorkflow } from '../workflows/dataProcessingWorkflow'
19
+
20
+ const myAgent = new Agent({
21
+ id: 'my-example-agent',
22
+ name: 'MyExampleAgent',
23
+ description: 'A generalist to help with basic questions.',
24
+ instructions: 'You are a helpful assistant.',
25
+ model: 'openai/gpt-5.1',
26
+ })
27
+
28
+ const weatherTool = createTool({
29
+ id: 'getWeather',
30
+ description: 'Gets the current weather for a location.',
31
+ inputSchema: z.object({ location: z.string() }),
32
+ execute: async inputData => `Weather in ${inputData.location} is sunny.`,
33
+ })
34
+
35
+ const server = new MCPServer({
36
+ id: 'my-custom-server',
37
+ name: 'My Custom Server',
38
+ version: '1.0.0',
39
+ description: 'A server that provides weather data and agent capabilities',
40
+ instructions:
41
+ 'Use the available tools to help users with weather information and data processing tasks.',
42
+ tools: { weatherTool },
43
+ agents: { myAgent }, // this agent will become tool "ask_myAgent"
44
+ workflows: {
45
+ dataProcessingWorkflow, // this workflow will become tool "run_dataProcessingWorkflow"
46
+ },
47
+ })
48
+ ```
49
+
50
+ ### Configuration Properties
51
+
52
+ The constructor accepts an `MCPServerConfig` object with the following properties:
53
+
54
+ **id:** (`string`): Unique identifier for the server. This ID is preserved when the server is registered with Mastra and can be used to retrieve the server via getMCPServerById().
55
+
56
+ **name:** (`string`): A descriptive name for your server (e.g., 'My Weather and Agent Server').
57
+
58
+ **version:** (`string`): The semantic version of your server (e.g., '1.0.0').
59
+
60
+ **tools:** (`ToolsInput`): An object where keys are tool names and values are Mastra tool definitions (created with \`createTool\` or Vercel AI SDK). These tools will be directly exposed.
61
+
62
+ **agents?:** (`Record<string, Agent>`): An object where keys are agent identifiers and values are Mastra Agent instances. Each agent will be automatically converted into a tool named \`ask\_\<agentIdentifier>\`. The agent \*\*must\*\* have a non-empty \`description\` string property defined in its constructor configuration. This description will be used in the tool's description. If an agent's description is missing or empty, an error will be thrown during MCPServer initialization.
63
+
64
+ **workflows?:** (`Record<string, Workflow>`): An object where keys are workflow identifiers and values are Mastra Workflow instances. Each workflow is converted into a tool named \`run\_\<workflowKey>\`. The workflow's \`inputSchema\` becomes the tool's input schema. The workflow \*\*must\*\* have a non-empty \`description\` string property, which is used for the tool's description. If a workflow's description is missing or empty, an error will be thrown. The tool executes the workflow by calling \`workflow\.createRun()\` followed by \`run.start({ inputData: \<tool\_input> })\`. If a tool name derived from an agent or workflow (e.g., \`ask\_myAgent\` or \`run\_myWorkflow\`) collides with an explicitly defined tool name or another derived name, the explicitly defined tool takes precedence, and a warning is logged. Agents/workflows leading to subsequent collisions are skipped.
65
+
66
+ **description?:** (`string`): Optional description of what the MCP server does.
67
+
68
+ **instructions?:** (`string`): Optional instructions describing how to use the server and its features.
69
+
70
+ **repository?:** (`Repository`): Optional repository information for the server's source code.
71
+
72
+ **releaseDate?:** (`string`): Optional release date of this server version (ISO 8601 string). Defaults to the time of instantiation if not provided.
73
+
74
+ **isLatest?:** (`boolean`): Optional flag indicating if this is the latest version. Defaults to true if not provided.
75
+
76
+ **packageCanonical?:** (`'npm' | 'docker' | 'pypi' | 'crates' | string`): Optional canonical packaging format if the server is distributed as a package (e.g., 'npm', 'docker').
77
+
78
+ **packages?:** (`PackageInfo[]`): Optional list of installable packages for this server.
79
+
80
+ **remotes?:** (`RemoteInfo[]`): Optional list of remote access points for this server.
81
+
82
+ **resources?:** (`MCPServerResources`): An object defining how the server should handle MCP resources. See Resource Handling section for details.
83
+
84
+ **prompts?:** (`MCPServerPrompts`): An object defining how the server should handle MCP prompts. See Prompt Handling section for details.
85
+
86
+ ## Exposing Agents as Tools
87
+
88
+ A powerful feature of `MCPServer` is its ability to automatically expose your Mastra Agents as callable tools. When you provide agents in the `agents` property of the configuration:
89
+
90
+ - **Tool Naming**: Each agent is converted into a tool named `ask_<agentKey>`, where `<agentKey>` is the key you used for that agent in the `agents` object. For instance, if you configure `agents: { myAgentKey: myAgentInstance }`, a tool named `ask_myAgentKey` will be created.
91
+
92
+ - **Tool Functionality**:
93
+
94
+ - **Description**: The generated tool's description will be in the format: "Ask agent `<AgentName>` a question. Original agent instructions: `<agent description>`".
95
+ - **Input**: The tool expects a single object argument with a `message` property (string): `{ message: "Your question for the agent" }`.
96
+ - **Execution**: When this tool is called, it invokes the `generate()` method of the corresponding agent, passing the provided `query`.
97
+ - **Output**: The direct result from the agent's `generate()` method is returned as the output of the tool.
98
+
99
+ - **Name Collisions**: If an explicit tool defined in the `tools` configuration has the same name as an agent-derived tool (e.g., you have a tool named `ask_myAgentKey` and also an agent with the key `myAgentKey`), the _explicitly defined tool will take precedence_. The agent will not be converted into a tool in this conflicting case, and a warning will be logged.
100
+
101
+ This makes it straightforward to allow MCP clients to interact with your agents using natural language queries, just like any other tool.
102
+
103
+ ### Agent-to-Tool Conversion
104
+
105
+ When you provide agents in the `agents` configuration property, `MCPServer` will automatically create a corresponding tool for each agent. The tool will be named `ask_<agentIdentifier>`, where `<agentIdentifier>` is the key you used in the `agents` object.
106
+
107
+ The description for this generated tool will be: "Ask agent `<agent.name>` a question. Agent description: `<agent.description>`".
108
+
109
+ **Important**: For an agent to be converted into a tool, it **must** have a non-empty `description` string property set in its configuration when it was instantiated (e.g., `new Agent({ name: 'myAgent', description: 'This agent does X.', ... })`). If an agent is passed to `MCPServer` with a missing or empty `description`, an error will be thrown when the `MCPServer` is instantiated, and server setup will fail.
110
+
111
+ This allows you to quickly expose the generative capabilities of your agents through the MCP, enabling clients to "ask" your agents questions directly.
112
+
113
+ ### Accessing MCP Context in Tools
114
+
115
+ Tools exposed through `MCPServer` can access MCP request context (authentication, session IDs, etc.) via two different properties depending on how the tool is invoked:
116
+
117
+ | Call Pattern | Access Method |
118
+ | ---------------- | ------------------------------------------- |
119
+ | Direct tool call | `context?.mcp?.extra` |
120
+ | Agent tool call | `context?.requestContext?.get("mcp.extra")` |
121
+
122
+ **Universal pattern** (works in both contexts):
123
+
124
+ ```typescript
125
+ const mcpExtra = context?.mcp?.extra ?? context?.requestContext?.get('mcp.extra')
126
+ const authInfo = mcpExtra?.authInfo
127
+ ```
128
+
129
+ #### Example: Tool that works in both contexts
130
+
131
+ ```typescript
132
+ import { createTool } from '@mastra/core/tools'
133
+ import { z } from 'zod'
134
+
135
+ const fetchUserData = createTool({
136
+ id: 'fetchUserData',
137
+ description: 'Fetches user data using authentication from MCP context',
138
+ inputSchema: z.object({
139
+ userId: z.string().describe('The ID of the user to fetch'),
140
+ }),
141
+ execute: async (inputData, context) => {
142
+ // Access MCP authentication context
143
+ // When called directly via MCP: context.mcp.extra
144
+ // When called via agent: context.requestContext.get('mcp.extra')
145
+ const mcpExtra = context?.mcp?.extra || context?.requestContext?.get('mcp.extra')
146
+ const authInfo = mcpExtra?.authInfo
147
+
148
+ if (!authInfo?.token) {
149
+ throw new Error('Authentication required')
150
+ }
151
+
152
+ const response = await fetch(`https://api.example.com/users/${inputData.userId}`, {
153
+ headers: {
154
+ Authorization: `Bearer ${authInfo.token}`,
155
+ },
156
+ })
157
+
158
+ return response.json()
159
+ },
160
+ })
161
+ ```
162
+
163
+ ## Methods
164
+
165
+ These are the functions you can call on an `MCPServer` instance to control its behavior and get information.
166
+
167
+ ### startStdio()
168
+
169
+ Use this method to start the server so it communicates using standard input and output (stdio). This is typical when running the server as a command-line program.
170
+
171
+ ```typescript
172
+ async startStdio(): Promise<void>
173
+ ```
174
+
175
+ Here's how you would start the server using stdio:
176
+
177
+ ```typescript
178
+ const server = new MCPServer({
179
+ id: 'my-server',
180
+ name: 'My Server',
181
+ version: '1.0.0',
182
+ tools: {
183
+ /* ... */
184
+ },
185
+ })
186
+ await server.startStdio()
187
+ ```
188
+
189
+ ### startSSE()
190
+
191
+ This method helps you integrate the MCP server with an existing web server to use Server-Sent Events (SSE) for communication. You'll call this from your web server's code when it receives a request for the SSE or message paths.
192
+
193
+ ```typescript
194
+ async startSSE({
195
+ url,
196
+ ssePath,
197
+ messagePath,
198
+ req,
199
+ res,
200
+ }: {
201
+ url: URL;
202
+ ssePath: string;
203
+ messagePath: string;
204
+ req: any;
205
+ res: any;
206
+ }): Promise<void>
207
+ ```
208
+
209
+ Here's an example of how you might use `startSSE` within an HTTP server request handler. In this example an MCP client could connect to your MCP server at `http://localhost:1234/sse`:
210
+
211
+ ```typescript
212
+ import http from 'http'
213
+
214
+ const httpServer = http.createServer(async (req, res) => {
215
+ await server.startSSE({
216
+ url: new URL(req.url || '', `http://localhost:1234`),
217
+ ssePath: '/sse',
218
+ messagePath: '/message',
219
+ req,
220
+ res,
221
+ })
222
+ })
223
+
224
+ httpServer.listen(PORT, () => {
225
+ console.log(`HTTP server listening on port ${PORT}`)
226
+ })
227
+ ```
228
+
229
+ Here are the details for the values needed by the `startSSE` method:
230
+
231
+ **url:** (`URL`): The web address the user is requesting.
232
+
233
+ **ssePath:** (`string`): The specific part of the URL where clients will connect for SSE (e.g., '/sse').
234
+
235
+ **messagePath:** (`string`): The specific part of the URL where clients will send messages (e.g., '/message').
236
+
237
+ **req:** (`any`): The incoming request object from your web server.
238
+
239
+ **res:** (`any`): The response object from your web server, used to send data back.
240
+
241
+ ### startHonoSSE()
242
+
243
+ This method helps you integrate the MCP server with an existing web server to use Server-Sent Events (SSE) for communication. You'll call this from your web server's code when it receives a request for the SSE or message paths.
244
+
245
+ ```typescript
246
+ async startHonoSSE({
247
+ url,
248
+ ssePath,
249
+ messagePath,
250
+ req,
251
+ res,
252
+ }: {
253
+ url: URL;
254
+ ssePath: string;
255
+ messagePath: string;
256
+ req: any;
257
+ res: any;
258
+ }): Promise<void>
259
+ ```
260
+
261
+ Here's an example of how you might use `startHonoSSE` within an HTTP server request handler. In this example an MCP client could connect to your MCP server at `http://localhost:1234/hono-sse`:
262
+
263
+ ```typescript
264
+ import http from 'http'
265
+
266
+ const httpServer = http.createServer(async (req, res) => {
267
+ await server.startHonoSSE({
268
+ url: new URL(req.url || '', `http://localhost:1234`),
269
+ ssePath: '/hono-sse',
270
+ messagePath: '/message',
271
+ req,
272
+ res,
273
+ })
274
+ })
275
+
276
+ httpServer.listen(PORT, () => {
277
+ console.log(`HTTP server listening on port ${PORT}`)
278
+ })
279
+ ```
280
+
281
+ Here are the details for the values needed by the `startHonoSSE` method:
282
+
283
+ **url:** (`URL`): The web address the user is requesting.
284
+
285
+ **ssePath:** (`string`): The specific part of the URL where clients will connect for SSE (e.g., '/hono-sse').
286
+
287
+ **messagePath:** (`string`): The specific part of the URL where clients will send messages (e.g., '/message').
288
+
289
+ **req:** (`any`): The incoming request object from your web server.
290
+
291
+ **res:** (`any`): The response object from your web server, used to send data back.
292
+
293
+ ### startHTTP()
294
+
295
+ This method helps you integrate the MCP server with an existing web server to use streamable HTTP for communication. You'll call this from your web server's code when it receives HTTP requests.
296
+
297
+ ```typescript
298
+ async startHTTP({
299
+ url,
300
+ httpPath,
301
+ req,
302
+ res,
303
+ options = { sessionIdGenerator: () => randomUUID() },
304
+ }: {
305
+ url: URL;
306
+ httpPath: string;
307
+ req: http.IncomingMessage;
308
+ res: http.ServerResponse<http.IncomingMessage>;
309
+ options?: StreamableHTTPServerTransportOptions;
310
+ }): Promise<void>
311
+ ```
312
+
313
+ Here's an example of how you might use `startHTTP` within an HTTP server request handler. In this example an MCP client could connect to your MCP server at `http://localhost:1234/http`:
314
+
315
+ ```typescript
316
+ import http from 'http'
317
+
318
+ const httpServer = http.createServer(async (req, res) => {
319
+ await server.startHTTP({
320
+ url: new URL(req.url || '', 'http://localhost:1234'),
321
+ httpPath: `/mcp`,
322
+ req,
323
+ res,
324
+ options: {
325
+ sessionIdGenerator: () => randomUUID(),
326
+ },
327
+ })
328
+ })
329
+
330
+ httpServer.listen(PORT, () => {
331
+ console.log(`HTTP server listening on port ${PORT}`)
332
+ })
333
+ ```
334
+
335
+ For **serverless environments** (Supabase Edge Functions, Cloudflare Workers, Vercel Edge, etc.), use `serverless: true` to enable stateless operation:
336
+
337
+ ```typescript
338
+ // Supabase Edge Function example
339
+ import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
340
+ import { MCPServer } from '@mastra/mcp'
341
+ // Note: You will need to convert req/res format from Deno to Node
342
+ import { toReqRes, toFetchResponse } from 'fetch-to-node'
343
+
344
+ const server = new MCPServer({
345
+ id: 'my-serverless-mcp',
346
+ name: 'My Serverless MCP',
347
+ version: '1.0.0',
348
+ tools: {
349
+ /* your tools */
350
+ },
351
+ })
352
+
353
+ serve(async req => {
354
+ const url = new URL(req.url)
355
+
356
+ if (url.pathname === '/mcp') {
357
+ // Convert Deno Request to Node.js-compatible format
358
+ const { req: nodeReq, res: nodeRes } = toReqRes(req)
359
+
360
+ await server.startHTTP({
361
+ url,
362
+ httpPath: '/mcp',
363
+ req: nodeReq,
364
+ res: nodeRes,
365
+ options: {
366
+ serverless: true, // ← Enable stateless mode for serverless
367
+ },
368
+ })
369
+
370
+ return toFetchResponse(nodeRes)
371
+ }
372
+
373
+ return new Response('Not found', { status: 404 })
374
+ })
375
+ ```
376
+
377
+ > **When to use serverless: true:** Use `serverless: true` when deploying to environments where each request runs in a fresh, stateless execution context:
378
+ >
379
+ > - Supabase Edge Functions
380
+ > - Cloudflare Workers
381
+ > - Vercel Edge Functions
382
+ > - Netlify Edge Functions
383
+ > - AWS Lambda
384
+ > - Deno Deploy
385
+ >
386
+ > Use the default session-based mode (without `serverless: true`) for:
387
+ >
388
+ > - Long-lived Node.js servers
389
+ > - Docker containers
390
+ > - Traditional hosting (VPS, dedicated servers)
391
+ >
392
+ > The serverless mode disables session management and creates fresh server instances per request, which is necessary for stateless environments where memory doesn't persist between invocations.
393
+ >
394
+ > **Note:** The following MCP features require session state or persistent connections and will **not work** in serverless mode:
395
+ >
396
+ > - **Elicitation** - Interactive user input requests during tool execution require session management to route responses back to the correct client
397
+ > - **Resource subscriptions** - `resources/subscribe` and `resources/unsubscribe` need persistent connections to maintain subscription state
398
+ > - **Resource update notifications** - `resources.notifyUpdated()` requires active subscriptions and persistent connections to notify clients
399
+ > - **Prompt list change notifications** - `prompts.notifyListChanged()` requires persistent connections to push updates to clients
400
+ >
401
+ > These features work normally in long-lived server environments (Node.js servers, Docker containers, etc.).
402
+
403
+ Here are the details for the values needed by the `startHTTP` method:
404
+
405
+ **url:** (`URL`): The web address the user is requesting.
406
+
407
+ **httpPath:** (`string`): The specific part of the URL where the MCP server will handle HTTP requests (e.g., '/mcp').
408
+
409
+ **req:** (`http.IncomingMessage`): The incoming request object from your web server.
410
+
411
+ **res:** (`http.ServerResponse`): The response object from your web server, used to send data back.
412
+
413
+ **options:** (`StreamableHTTPServerTransportOptions`): Optional configuration for the HTTP transport. See the options table below for more details.
414
+
415
+ The `StreamableHTTPServerTransportOptions` object allows you to customize the behavior of the HTTP transport. Here are the available options:
416
+
417
+ **serverless:** (`boolean`): If \`true\`, runs in stateless mode without session management. Each request is handled independently with a fresh server instance. Essential for serverless environments (Cloudflare Workers, Supabase Edge Functions, Vercel Edge, etc.) where sessions cannot persist between invocations. Defaults to \`false\`.
418
+
419
+ **sessionIdGenerator:** (`(() => string) | undefined`): A function that generates a unique session ID. This should be a cryptographically secure, globally unique string. Return \`undefined\` to disable session management.
420
+
421
+ **onsessioninitialized:** (`(sessionId: string) => void`): A callback that is invoked when a new session is initialized. This is useful for tracking active MCP sessions.
422
+
423
+ **enableJsonResponse:** (`boolean`): If \`true\`, the server will return plain JSON responses instead of using Server-Sent Events (SSE) for streaming. Defaults to \`false\`.
424
+
425
+ **eventStore:** (`EventStore`): An event store for message resumability. Providing this enables clients to reconnect and resume message streams.
426
+
427
+ ### close()
428
+
429
+ This method closes the server and releases all resources.
430
+
431
+ ```typescript
432
+ async close(): Promise<void>
433
+ ```
434
+
435
+ ### getServerInfo()
436
+
437
+ This method gives you a look at the server's basic information.
438
+
439
+ ```typescript
440
+ getServerInfo(): ServerInfo
441
+ ```
442
+
443
+ ### getServerDetail()
444
+
445
+ This method gives you a detailed look at the server's information.
446
+
447
+ ```typescript
448
+ getServerDetail(): ServerDetail
449
+ ```
450
+
451
+ ### getToolListInfo()
452
+
453
+ This method gives you a look at the tools that were set up when you created the server. It's a read-only list, useful for debugging purposes.
454
+
455
+ ```typescript
456
+ getToolListInfo(): ToolListInfo
457
+ ```
458
+
459
+ ### getToolInfo()
460
+
461
+ This method gives you detailed information about a specific tool.
462
+
463
+ ```typescript
464
+ getToolInfo(toolName: string): ToolInfo
465
+ ```
466
+
467
+ ### executeTool()
468
+
469
+ This method executes a specific tool and returns the result.
470
+
471
+ ```typescript
472
+ executeTool(toolName: string, input: any): Promise<any>
473
+ ```
474
+
475
+ ### getStdioTransport()
476
+
477
+ If you started the server with `startStdio()`, you can use this to get the object that manages the stdio communication. This is mostly for checking things internally or for testing.
478
+
479
+ ```typescript
480
+ getStdioTransport(): StdioServerTransport | undefined
481
+ ```
482
+
483
+ ### getSseTransport()
484
+
485
+ If you started the server with `startSSE()`, you can use this to get the object that manages the SSE communication. Like `getStdioTransport`, this is mainly for internal checks or testing.
486
+
487
+ ```typescript
488
+ getSseTransport(): SSEServerTransport | undefined
489
+ ```
490
+
491
+ ### getSseHonoTransport()
492
+
493
+ If you started the server with `startHonoSSE()`, you can use this to get the object that manages the SSE communication. Like `getSseTransport`, this is mainly for internal checks or testing.
494
+
495
+ ```typescript
496
+ getSseHonoTransport(): SSETransport | undefined
497
+ ```
498
+
499
+ ### getStreamableHTTPTransport()
500
+
501
+ If you started the server with `startHTTP()`, you can use this to get the object that manages the HTTP communication. Like `getSseTransport`, this is mainly for internal checks or testing.
502
+
503
+ ```typescript
504
+ getStreamableHTTPTransport(): StreamableHTTPServerTransport | undefined
505
+ ```
506
+
507
+ ### tools()
508
+
509
+ Executes a specific tool provided by this MCP server.
510
+
511
+ ```typescript
512
+ async executeTool(
513
+ toolId: string,
514
+ args: any,
515
+ executionContext?: { messages?: any[]; toolCallId?: string },
516
+ ): Promise<any>
517
+ ```
518
+
519
+ **toolId:** (`string`): The ID/name of the tool to execute.
520
+
521
+ **args:** (`any`): The arguments to pass to the tool's execute function.
522
+
523
+ **executionContext?:** (`object`): Optional context for the tool execution, like messages or a toolCallId.
524
+
525
+ ## Resource Handling
526
+
527
+ ### What are MCP Resources?
528
+
529
+ Resources are a core primitive in the Model Context Protocol (MCP) that allow servers to expose data and content that can be read by clients and used as context for LLM interactions. They represent any kind of data that an MCP server wants to make available, such as:
530
+
531
+ - File contents
532
+ - Database records
533
+ - API responses
534
+ - Live system data
535
+ - Screenshots and images
536
+ - Log files
537
+
538
+ Resources are identified by unique URIs (e.g., `file:///home/user/documents/report.pdf`, `postgres://database/customers/schema`) and can contain either text (UTF-8 encoded) or binary data (base64 encoded).
539
+
540
+ Clients can discover resources through:
541
+
542
+ 1. **Direct resources**: Servers expose a list of concrete resources via a `resources/list` endpoint.
543
+ 2. **Resource templates**: For dynamic resources, servers can expose URI templates (RFC 6570) that clients use to construct resource URIs.
544
+
545
+ To read a resource, clients make a `resources/read` request with the URI. Servers can also notify clients about changes to the resource list (`notifications/resources/list_changed`) or updates to specific resource content (`notifications/resources/updated`) if a client has subscribed to that resource.
546
+
547
+ For more detailed information, refer to the [official MCP documentation on Resources](https://modelcontextprotocol.io/docs/concepts/resources).
548
+
549
+ ### `MCPServerResources` Type
550
+
551
+ The `resources` option takes an object of type `MCPServerResources`. This type defines the callbacks your server will use to handle resource requests:
552
+
553
+ ```typescript
554
+ export type MCPServerResources = {
555
+ // Callback to list available resources
556
+ listResources: () => Promise<Resource[]>
557
+
558
+ // Callback to get the content of a specific resource
559
+ getResourceContent: ({
560
+ uri,
561
+ }: {
562
+ uri: string
563
+ }) => Promise<MCPServerResourceContent | MCPServerResourceContent[]>
564
+
565
+ // Optional callback to list available resource templates
566
+ resourceTemplates?: () => Promise<ResourceTemplate[]>
567
+ }
568
+
569
+ export type MCPServerResourceContent = { text?: string } | { blob?: string }
570
+ ```
571
+
572
+ Example:
573
+
574
+ ```typescript
575
+ import { MCPServer } from '@mastra/mcp'
576
+ import type { MCPServerResourceContent, Resource, ResourceTemplate } from '@mastra/mcp'
577
+
578
+ // Resources/resource templates will generally be dynamically fetched.
579
+ const myResources: Resource[] = [
580
+ { uri: 'file://data/123.txt', name: 'Data File', mimeType: 'text/plain' },
581
+ ]
582
+
583
+ const myResourceContents: Record<string, MCPServerResourceContent> = {
584
+ 'file://data.txt/123': { text: 'This is the content of the data file.' },
585
+ }
586
+
587
+ const myResourceTemplates: ResourceTemplate[] = [
588
+ {
589
+ uriTemplate: 'file://data/{id}',
590
+ name: 'Data File',
591
+ description: 'A file containing data.',
592
+ mimeType: 'text/plain',
593
+ },
594
+ ]
595
+
596
+ const myResourceHandlers: MCPServerResources = {
597
+ listResources: async () => myResources,
598
+ getResourceContent: async ({ uri }) => {
599
+ if (myResourceContents[uri]) {
600
+ return myResourceContents[uri]
601
+ }
602
+ throw new Error(`Resource content not found for ${uri}`)
603
+ },
604
+ resourceTemplates: async () => myResourceTemplates,
605
+ }
606
+
607
+ const serverWithResources = new MCPServer({
608
+ id: 'resourceful-server',
609
+ name: 'Resourceful Server',
610
+ version: '1.0.0',
611
+ tools: {
612
+ /* ... your tools ... */
613
+ },
614
+ resources: myResourceHandlers,
615
+ })
616
+ ```
617
+
618
+ ### Notifying Clients of Resource Changes
619
+
620
+ If the available resources or their content change, your server can notify connected clients that are subscribed to the specific resource.
621
+
622
+ #### `server.resources.notifyUpdated({ uri: string })`
623
+
624
+ Call this method when the content of a specific resource (identified by its `uri`) has been updated. If any clients are subscribed to this URI, they will receive a `notifications/resources/updated` message.
625
+
626
+ ```typescript
627
+ async server.resources.notifyUpdated({ uri: string }): Promise<void>
628
+ ```
629
+
630
+ Example:
631
+
632
+ ```typescript
633
+ // After updating the content of 'file://data.txt'
634
+ await serverWithResources.resources.notifyUpdated({ uri: 'file://data.txt' })
635
+ ```
636
+
637
+ #### `server.resources.notifyListChanged()`
638
+
639
+ Call this method when the overall list of available resources has changed (e.g., a resource was added or removed). This will send a `notifications/resources/list_changed` message to clients, prompting them to re-fetch the list of resources.
640
+
641
+ ```typescript
642
+ async server.resources.notifyListChanged(): Promise<void>
643
+ ```
644
+
645
+ Example:
646
+
647
+ ```typescript
648
+ // After adding a new resource to the list managed by 'myResourceHandlers.listResources'
649
+ await serverWithResources.resources.notifyListChanged()
650
+ ```
651
+
652
+ ## Prompt Handling
653
+
654
+ ### What are MCP Prompts?
655
+
656
+ Prompts are reusable templates or workflows that MCP servers expose to clients. They can accept arguments, include resource context, support versioning, and be used to standardize LLM interactions.
657
+
658
+ Prompts are identified by a unique name (and optional version) and can be dynamic or static.
659
+
660
+ ### `MCPServerPrompts` Type
661
+
662
+ The `prompts` option takes an object of type `MCPServerPrompts`. This type defines the callbacks your server will use to handle prompt requests:
663
+
664
+ ```typescript
665
+ export type MCPServerPrompts = {
666
+ // Callback to list available prompts
667
+ listPrompts: () => Promise<Prompt[]>
668
+
669
+ // Callback to get the messages/content for a specific prompt
670
+ getPromptMessages?: ({
671
+ name,
672
+ version,
673
+ args,
674
+ }: {
675
+ name: string
676
+ version?: string
677
+ args?: any
678
+ }) => Promise<{ prompt: Prompt; messages: PromptMessage[] }>
679
+ }
680
+ ```
681
+
682
+ Example:
683
+
684
+ ```typescript
685
+ import { MCPServer } from '@mastra/mcp'
686
+ import type { Prompt, PromptMessage, MCPServerPrompts } from '@mastra/mcp'
687
+
688
+ const prompts: Prompt[] = [
689
+ {
690
+ name: 'analyze-code',
691
+ description: 'Analyze code for improvements',
692
+ version: 'v1',
693
+ },
694
+ {
695
+ name: 'analyze-code',
696
+ description: 'Analyze code for improvements (new logic)',
697
+ version: 'v2',
698
+ },
699
+ ]
700
+
701
+ const myPromptHandlers: MCPServerPrompts = {
702
+ listPrompts: async () => prompts,
703
+ getPromptMessages: async ({ name, version, args }) => {
704
+ if (name === 'analyze-code') {
705
+ if (version === 'v2') {
706
+ const prompt = prompts.find(p => p.name === name && p.version === 'v2')
707
+ if (!prompt) throw new Error('Prompt version not found')
708
+ return {
709
+ prompt,
710
+ messages: [
711
+ {
712
+ role: 'user',
713
+ content: {
714
+ type: 'text',
715
+ text: `Analyze this code with the new logic: ${args.code}`,
716
+ },
717
+ },
718
+ ],
719
+ }
720
+ }
721
+ // Default or v1
722
+ const prompt = prompts.find(p => p.name === name && p.version === 'v1')
723
+ if (!prompt) throw new Error('Prompt version not found')
724
+ return {
725
+ prompt,
726
+ messages: [
727
+ {
728
+ role: 'user',
729
+ content: { type: 'text', text: `Analyze this code: ${args.code}` },
730
+ },
731
+ ],
732
+ }
733
+ }
734
+ throw new Error('Prompt not found')
735
+ },
736
+ }
737
+
738
+ const serverWithPrompts = new MCPServer({
739
+ id: 'promptful-server',
740
+ name: 'Promptful Server',
741
+ version: '1.0.0',
742
+ tools: {
743
+ /* ... */
744
+ },
745
+ prompts: myPromptHandlers,
746
+ })
747
+ ```
748
+
749
+ ### Notifying Clients of Prompt Changes
750
+
751
+ If the available prompts change, your server can notify connected clients:
752
+
753
+ #### `server.prompts.notifyListChanged()`
754
+
755
+ Call this method when the overall list of available prompts has changed (e.g., a prompt was added or removed). This will send a `notifications/prompts/list_changed` message to clients, prompting them to re-fetch the list of prompts.
756
+
757
+ ```typescript
758
+ await serverWithPrompts.prompts.notifyListChanged()
759
+ ```
760
+
761
+ ### Best Practices for Prompt Handling
762
+
763
+ - Use clear, descriptive prompt names and descriptions.
764
+ - Validate all required arguments in `getPromptMessages`.
765
+ - Include a `version` field if you expect to make breaking changes.
766
+ - Use the `version` parameter to select the correct prompt logic.
767
+ - Notify clients when prompt lists change.
768
+ - Handle errors with informative messages.
769
+ - Document argument expectations and available versions.
770
+
771
+ ***
772
+
773
+ ## Examples
774
+
775
+ For practical examples of setting up and deploying an MCPServer, see the [Publishing an MCP Server guide](https://mastra.ai/docs/mcp/publishing-mcp-server).
776
+
777
+ The example at the beginning of this page also demonstrates how to instantiate `MCPServer` with both tools and agents.
778
+
779
+ ## Elicitation
780
+
781
+ ### What is Elicitation?
782
+
783
+ Elicitation is a feature in the Model Context Protocol (MCP) that allows servers to request structured information from users. This enables interactive workflows where servers can collect additional data dynamically.
784
+
785
+ The `MCPServer` class automatically includes elicitation capabilities. Tools receive a `context.mcp` object in their `execute` function that includes an `elicitation.sendRequest()` method for requesting user input.
786
+
787
+ ### Tool Execution Signature
788
+
789
+ When tools are executed within an MCP server context, they receive MCP-specific capabilities via the `context.mcp` object:
790
+
791
+ ```typescript
792
+ execute: async (inputData, context) => {
793
+ // input contains the tool's inputData parameters
794
+ // context.mcp contains server capabilities like elicitation and authentication info
795
+
796
+ // Access authentication information (when available)
797
+ if (context.mcp?.extra?.authInfo) {
798
+ console.log('Authenticated request from:', context.mcp.extra.authInfo.clientId)
799
+ }
800
+
801
+ // Use elicitation capabilities
802
+ const result = await context.mcp.elicitation.sendRequest({
803
+ message: 'Please provide information',
804
+ requestedSchema: {
805
+ /* schema */
806
+ },
807
+ })
808
+
809
+ return result
810
+ }
811
+ ```
812
+
813
+ ### How Elicitation Works
814
+
815
+ A common use case is during tool execution. When a tool needs user input, it can use the elicitation functionality provided through the context parameter:
816
+
817
+ 1. The tool calls `context.mcp.elicitation.sendRequest()` with a message and schema
818
+ 2. The request is sent to the connected MCP client
819
+ 3. The client presents the request to the user (via UI, command line, etc.)
820
+ 4. The user provides input, declines, or cancels the request
821
+ 5. The client sends the response back to the server
822
+ 6. The tool receives the response and continues execution
823
+
824
+ ### Using Elicitation in Tools
825
+
826
+ Here's an example of a tool that uses elicitation to collect user contact information:
827
+
828
+ ```typescript
829
+ import { MCPServer } from '@mastra/mcp'
830
+ import { createTool } from '@mastra/core/tools'
831
+ import { z } from 'zod'
832
+
833
+ const server = new MCPServer({
834
+ id: 'interactive-server',
835
+ name: 'Interactive Server',
836
+ version: '1.0.0',
837
+ tools: {
838
+ collectContactInfo: createTool({
839
+ id: 'collectContactInfo',
840
+ description: 'Collects user contact information through elicitation',
841
+ inputSchema: z.object({
842
+ reason: z.string().optional().describe('Reason for collecting contact info'),
843
+ }),
844
+ execute: async (inputData, context) => {
845
+ const { reason } = inputData
846
+
847
+ // Log session info if available
848
+ console.log('Request from session:', context.mcp?.extra?.sessionId)
849
+
850
+ try {
851
+ // Request user input via elicitation
852
+ const result = await context.mcp.elicitation.sendRequest({
853
+ message: reason
854
+ ? `Please provide your contact information. ${reason}`
855
+ : 'Please provide your contact information',
856
+ requestedSchema: {
857
+ type: 'object',
858
+ properties: {
859
+ name: {
860
+ type: 'string',
861
+ title: 'Full Name',
862
+ description: 'Your full name',
863
+ },
864
+ email: {
865
+ type: 'string',
866
+ title: 'Email Address',
867
+ description: 'Your email address',
868
+ format: 'email',
869
+ },
870
+ phone: {
871
+ type: 'string',
872
+ title: 'Phone Number',
873
+ description: 'Your phone number (optional)',
874
+ },
875
+ },
876
+ required: ['name', 'email'],
877
+ },
878
+ })
879
+
880
+ // Handle the user's response
881
+ if (result.action === 'accept') {
882
+ return `Contact information collected: ${JSON.stringify(result.content, null, 2)}`
883
+ } else if (result.action === 'decline') {
884
+ return 'Contact information collection was declined by the user.'
885
+ } else {
886
+ return 'Contact information collection was cancelled by the user.'
887
+ }
888
+ } catch (error) {
889
+ return `Error collecting contact information: ${error}`
890
+ }
891
+ },
892
+ }),
893
+ },
894
+ })
895
+ ```
896
+
897
+ ### Elicitation Request Schema
898
+
899
+ The `requestedSchema` must be a flat object with primitive properties only. Supported types include:
900
+
901
+ - **String**: `{ type: 'string', title: 'Display Name', description: 'Help text' }`
902
+ - **Number**: `{ type: 'number', minimum: 0, maximum: 100 }`
903
+ - **Boolean**: `{ type: 'boolean', default: false }`
904
+ - **Enum**: `{ type: 'string', enum: ['option1', 'option2'] }`
905
+
906
+ Example schema:
907
+
908
+ ```typescript
909
+ {
910
+ type: 'object',
911
+ properties: {
912
+ name: {
913
+ type: 'string',
914
+ title: 'Full Name',
915
+ description: 'Your complete name',
916
+ },
917
+ age: {
918
+ type: 'number',
919
+ title: 'Age',
920
+ minimum: 18,
921
+ maximum: 120,
922
+ },
923
+ newsletter: {
924
+ type: 'boolean',
925
+ title: 'Subscribe to Newsletter',
926
+ default: false,
927
+ },
928
+ },
929
+ required: ['name'],
930
+ }
931
+ ```
932
+
933
+ ### Response Actions
934
+
935
+ Users can respond to elicitation requests in three ways:
936
+
937
+ 1. **Accept** (`action: 'accept'`): User provided data and confirmed submission
938
+ - Contains `content` field with the submitted data
939
+ 2. **Decline** (`action: 'decline'`): User explicitly declined to provide information
940
+ - No content field
941
+ 3. **Cancel** (`action: 'cancel'`): User dismissed the request without deciding
942
+ - No content field
943
+
944
+ Tools should handle all three response types appropriately.
945
+
946
+ ### Security Considerations
947
+
948
+ - **Never request sensitive information** like passwords, SSNs, or credit card numbers
949
+ - Validate all user input against the provided schema
950
+ - Handle declining and cancellation gracefully
951
+ - Provide clear reasons for data collection
952
+ - Respect user privacy and preferences
953
+
954
+ ### Tool Execution API
955
+
956
+ The elicitation functionality is available through the `options` parameter in tool execution:
957
+
958
+ ```typescript
959
+ // Within a tool's execute function
960
+ execute: async (inputData, context) => {
961
+ // Use elicitation for user input
962
+ const result = await context.mcp.elicitation.sendRequest({
963
+ message: string, // Message to display to user
964
+ requestedSchema: object // JSON schema defining expected response structure
965
+ }): Promise<ElicitResult>
966
+
967
+ // Access authentication info if needed
968
+ if (context.mcp?.extra?.authInfo) {
969
+ // Use context.mcp.extra.authInfo.token, etc.
970
+ }
971
+ }
972
+ ```
973
+
974
+ Note that elicitation is **session-aware** when using HTTP-based transports (SSE or HTTP). This means that when multiple clients are connected to the same server, elicitation requests are routed to the correct client session that initiated the tool execution.
975
+
976
+ The `ElicitResult` type:
977
+
978
+ ```typescript
979
+ type ElicitResult = {
980
+ action: 'accept' | 'decline' | 'cancel'
981
+ content?: any // Only present when action is 'accept'
982
+ }
983
+ ```
984
+
985
+ ## OAuth Protection
986
+
987
+ To protect your MCP server with OAuth authentication per the [MCP Auth Specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization), use the `createOAuthMiddleware` function:
988
+
989
+ ```typescript
990
+ import http from 'node:http'
991
+ import { MCPServer, createOAuthMiddleware, createStaticTokenValidator } from '@mastra/mcp'
992
+
993
+ const mcpServer = new MCPServer({
994
+ id: 'protected-server',
995
+ name: 'Protected MCP Server',
996
+ version: '1.0.0',
997
+ tools: {
998
+ /* your tools */
999
+ },
1000
+ })
1001
+
1002
+ // Create OAuth middleware
1003
+ const oauthMiddleware = createOAuthMiddleware({
1004
+ oauth: {
1005
+ resource: 'https://mcp.example.com/mcp',
1006
+ authorizationServers: ['https://auth.example.com'],
1007
+ scopesSupported: ['mcp:read', 'mcp:write'],
1008
+ resourceName: 'My Protected MCP Server',
1009
+ validateToken: createStaticTokenValidator(['allowed-token-1']),
1010
+ },
1011
+ mcpPath: '/mcp',
1012
+ })
1013
+
1014
+ // Create HTTP server with OAuth protection
1015
+ const httpServer = http.createServer(async (req, res) => {
1016
+ const url = new URL(req.url || '', 'https://mcp.example.com')
1017
+
1018
+ // Apply OAuth middleware first
1019
+ const result = await oauthMiddleware(req, res, url)
1020
+ if (!result.proceed) return // Middleware handled response (401, metadata, etc.)
1021
+
1022
+ // Token is valid, proceed to MCP handler
1023
+ await mcpServer.startHTTP({ url, httpPath: '/mcp', req, res })
1024
+ })
1025
+
1026
+ httpServer.listen(3000)
1027
+ ```
1028
+
1029
+ The middleware automatically:
1030
+
1031
+ - Serves **Protected Resource Metadata** at `/.well-known/oauth-protected-resource` (RFC 9728)
1032
+ - Returns `401 Unauthorized` with proper `WWW-Authenticate` headers when authentication is required
1033
+ - Validates bearer tokens using your provided validator
1034
+
1035
+ ### Token Validation
1036
+
1037
+ For production, use proper token validation:
1038
+
1039
+ ```typescript
1040
+ import { createOAuthMiddleware, createIntrospectionValidator } from '@mastra/mcp'
1041
+
1042
+ // Option 1: Token introspection (RFC 7662)
1043
+ const middleware = createOAuthMiddleware({
1044
+ oauth: {
1045
+ resource: 'https://mcp.example.com/mcp',
1046
+ authorizationServers: ['https://auth.example.com'],
1047
+ validateToken: createIntrospectionValidator('https://auth.example.com/oauth/introspect', {
1048
+ clientId: 'mcp-server',
1049
+ clientSecret: 'secret',
1050
+ }),
1051
+ },
1052
+ })
1053
+
1054
+ // Option 2: Custom validation (JWT, database lookup, etc.)
1055
+ const customMiddleware = createOAuthMiddleware({
1056
+ oauth: {
1057
+ resource: 'https://mcp.example.com/mcp',
1058
+ authorizationServers: ['https://auth.example.com'],
1059
+ validateToken: async (token, resource) => {
1060
+ const decoded = await verifyJWT(token)
1061
+ if (!decoded) {
1062
+ return { valid: false, error: 'invalid_token' }
1063
+ }
1064
+ return {
1065
+ valid: true,
1066
+ scopes: decoded.scope?.split(' ') || [],
1067
+ subject: decoded.sub,
1068
+ }
1069
+ },
1070
+ },
1071
+ })
1072
+ ```
1073
+
1074
+ ### OAuth Middleware Options
1075
+
1076
+ **oauth.resource:** (`string`): The canonical URL of your MCP server. This is returned in Protected Resource Metadata.
1077
+
1078
+ **oauth.authorizationServers:** (`string[]`): URLs of authorization servers that can issue tokens for this resource.
1079
+
1080
+ **oauth.scopesSupported?:** (`string[]`): Scopes supported by this MCP server. (Default: `['mcp:read', 'mcp:write']`)
1081
+
1082
+ **oauth.resourceName?:** (`string`): Human-readable name for this resource server.
1083
+
1084
+ **oauth.validateToken?:** (`(token: string, resource: string) => Promise<TokenValidationResult>`): Function to validate access tokens. If not provided, tokens are accepted without validation (NOT recommended for production).
1085
+
1086
+ **mcpPath?:** (`string`): Path where the MCP endpoint is served. Only requests to this path require authentication. (Default: `'/mcp'`)
1087
+
1088
+ ## Authentication Context
1089
+
1090
+ Tools can access request metadata via `context.mcp.extra` when using HTTP-based transports. This allows you to pass authentication info, user context, or any custom data from your HTTP middleware to your MCP tools.
1091
+
1092
+ ### How It Works
1093
+
1094
+ Whatever you set on `req.auth` in your HTTP middleware becomes available as `context.mcp.extra.authInfo` in your tools:
1095
+
1096
+ ```text
1097
+ req.auth = { ... } → context?.mcp?.extra?.authInfo.extra = { ... }
1098
+ ```
1099
+
1100
+ ### Setting Up Authentication Middleware
1101
+
1102
+ To pass data to your tools, populate `req.auth` on the Node.js request object in your HTTP server middleware before calling `server.startHTTP()`.
1103
+
1104
+ ```typescript
1105
+ import express from 'express'
1106
+
1107
+ const app = express()
1108
+
1109
+ // Auth middleware - set req.auth before the MCP handler
1110
+ app.use('/mcp', (req, res, next) => {
1111
+ const token = req.headers.authorization?.replace('Bearer ', '')
1112
+ const user = verifyToken(token)
1113
+
1114
+ // This entire object becomes context.mcp.extra.authInfo
1115
+ // @ts-ignore - req.auth is read by the MCP SDK
1116
+ req.auth = {
1117
+ token,
1118
+ userId: user.userId,
1119
+ email: user.email,
1120
+ }
1121
+ next()
1122
+ })
1123
+
1124
+ app.all('/mcp', async (req, res) => {
1125
+ const url = new URL(req.url, `http://${req.headers.host}`)
1126
+ await server.startHTTP({ url, httpPath: '/mcp', req, res })
1127
+ })
1128
+ ```
1129
+
1130
+ ### Accessing Auth Data in Tools
1131
+
1132
+ The `req.auth` object is available as `context.mcp.extra.authInfo` in your tool's execute function:
1133
+
1134
+ ```typescript
1135
+ execute: async (inputData, context) => {
1136
+ // Access the auth data you set in middleware
1137
+ const authInfo = context?.mcp?.extra?.authInfo
1138
+
1139
+ if (!authInfo?.extra?.userId) {
1140
+ return { error: 'Authentication required' }
1141
+ }
1142
+
1143
+ // Use the auth data
1144
+ console.log('User ID:', authInfo.extra.userId)
1145
+ console.log('Email:', authInfo.extra.email)
1146
+
1147
+ const response = await fetch('/api/data', {
1148
+ headers: { Authorization: `Bearer ${authInfo.token}` },
1149
+ signal: context?.mcp?.extra?.signal,
1150
+ })
1151
+
1152
+ return response.json()
1153
+ }
1154
+ ```
1155
+
1156
+ ### Passing `RequestContext` through to agent
1157
+
1158
+ ```typescript
1159
+ execute: async (inputData, context) => {
1160
+ // Access the auth data you set in middleware
1161
+ const authInfo = context?.mcp?.extra?.authInfo
1162
+
1163
+ const requestContext = context.requestContext || new RequestContext().set('someKey', authInfo)
1164
+
1165
+ if (!authInfo?.extra?.userId) {
1166
+ return { error: 'Authentication required' }
1167
+ }
1168
+
1169
+ // Use the auth data
1170
+ console.log('User ID:', authInfo.extra.userId)
1171
+ console.log('Email:', authInfo.extra.email)
1172
+
1173
+ const agent = context?.mastra?.getAgentById('some-agent-id')
1174
+
1175
+ if (!agent) {
1176
+ return { error: "Agent 'some-agent-id' not found" }
1177
+ }
1178
+
1179
+ const response = await agent.generate(prompt, { requestContext })
1180
+
1181
+ return response.text
1182
+ }
1183
+ ```
1184
+
1185
+ ### The `extra` Object
1186
+
1187
+ The full `context.mcp.extra` object contains:
1188
+
1189
+ | Property | Description |
1190
+ | ------------------ | ------------------------------------------------- |
1191
+ | `authInfo` | Whatever you set on `req.auth` in your middleware |
1192
+ | `sessionId` | Session identifier for the MCP connection |
1193
+ | `signal` | AbortSignal for request cancellation |
1194
+ | `sendNotification` | MCP protocol function for sending notifications |
1195
+ | `sendRequest` | MCP protocol function for sending requests |
1196
+
1197
+ ### Complete Example
1198
+
1199
+ Here's a complete example showing the data flow from middleware to tool:
1200
+
1201
+ ```typescript
1202
+ import express from 'express'
1203
+ import { MCPServer } from '@mastra/mcp'
1204
+ import { createTool } from '@mastra/core/tools'
1205
+ import { z } from 'zod'
1206
+
1207
+ const verifyToken = (token: string) => {
1208
+ // TODO: Implement token verification
1209
+ return {
1210
+ userId: '123',
1211
+ email: 'test@test.com',
1212
+ }
1213
+ }
1214
+
1215
+ // 1. Define your tool that uses auth context
1216
+ const getUserData = createTool({
1217
+ id: 'get-user-data',
1218
+ description: 'Fetches data for the authenticated user',
1219
+ inputSchema: z.object({}),
1220
+ execute: async (inputData, context) => {
1221
+ const authInfo = context?.mcp?.extra?.authInfo
1222
+
1223
+ if (!authInfo?.extra?.userId) {
1224
+ return { error: 'Authentication required' }
1225
+ }
1226
+
1227
+ // Access the data you set in middleware
1228
+ return {
1229
+ userId: authInfo.extra.userId,
1230
+ email: authInfo.extra.email,
1231
+ }
1232
+ },
1233
+ })
1234
+
1235
+ // 2. Create the MCP server with your tools
1236
+ const server = new MCPServer({
1237
+ id: 'my-server',
1238
+ name: 'My Server',
1239
+ version: '1.0.0',
1240
+ tools: { getUserData },
1241
+ })
1242
+
1243
+ // 3. Set up Express with auth middleware
1244
+ const app = express()
1245
+
1246
+ app.use('/mcp', (req, res, next) => {
1247
+ const token = req.headers.authorization?.replace('Bearer ', '')
1248
+ const user = verifyToken(token)
1249
+
1250
+ // This entire object becomes context.mcp.extra.authInfo
1251
+ // @ts-ignore - req.auth is read by the MCP SDK
1252
+ req.auth = {
1253
+ token,
1254
+ userId: user.userId,
1255
+ email: user.email,
1256
+ }
1257
+ next()
1258
+ })
1259
+
1260
+ app.all('/mcp', async (req, res) => {
1261
+ const url = new URL(req.url, `http://${req.headers.host}`)
1262
+ await server.startHTTP({ url, httpPath: '/mcp', req, res })
1263
+ })
1264
+
1265
+ app.listen(3000)
1266
+ ```
1267
+
1268
+ ## Related Information
1269
+
1270
+ - For connecting to MCP servers in Mastra, see the [MCPClient documentation](https://mastra.ai/reference/tools/mcp-client).
1271
+ - For more about the Model Context Protocol, see the [@modelcontextprotocol/sdk documentation](https://github.com/modelcontextprotocol/typescript-sdk).