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