@mastra/mcp-docs-server 1.1.4 → 1.1.5

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 (547) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/package.json +5 -5
  3. package/.docs/docs/agents/adding-voice.md +0 -353
  4. package/.docs/docs/agents/agent-approval.md +0 -377
  5. package/.docs/docs/agents/agent-memory.md +0 -212
  6. package/.docs/docs/agents/guardrails.md +0 -382
  7. package/.docs/docs/agents/network-approval.md +0 -275
  8. package/.docs/docs/agents/networks.md +0 -290
  9. package/.docs/docs/agents/overview.md +0 -309
  10. package/.docs/docs/agents/processors.md +0 -632
  11. package/.docs/docs/agents/structured-output.md +0 -271
  12. package/.docs/docs/agents/using-tools.md +0 -214
  13. package/.docs/docs/build-with-ai/mcp-docs-server.md +0 -241
  14. package/.docs/docs/build-with-ai/skills.md +0 -35
  15. package/.docs/docs/community/contributing-templates.md +0 -3
  16. package/.docs/docs/community/discord.md +0 -9
  17. package/.docs/docs/community/licensing.md +0 -66
  18. package/.docs/docs/deployment/cloud-providers.md +0 -15
  19. package/.docs/docs/deployment/mastra-server.md +0 -122
  20. package/.docs/docs/deployment/monorepo.md +0 -142
  21. package/.docs/docs/deployment/overview.md +0 -62
  22. package/.docs/docs/deployment/studio.md +0 -234
  23. package/.docs/docs/deployment/web-framework.md +0 -52
  24. package/.docs/docs/deployment/workflow-runners.md +0 -9
  25. package/.docs/docs/evals/built-in-scorers.md +0 -47
  26. package/.docs/docs/evals/custom-scorers.md +0 -519
  27. package/.docs/docs/evals/overview.md +0 -146
  28. package/.docs/docs/evals/running-in-ci.md +0 -106
  29. package/.docs/docs/getting-started/build-with-ai.md +0 -68
  30. package/.docs/docs/getting-started/manual-install.md +0 -226
  31. package/.docs/docs/getting-started/project-structure.md +0 -60
  32. package/.docs/docs/getting-started/start.md +0 -28
  33. package/.docs/docs/getting-started/studio.md +0 -101
  34. package/.docs/docs/index.md +0 -43
  35. package/.docs/docs/mastra-cloud/deployment.md +0 -77
  36. package/.docs/docs/mastra-cloud/observability.md +0 -38
  37. package/.docs/docs/mastra-cloud/overview.md +0 -23
  38. package/.docs/docs/mastra-cloud/setup.md +0 -42
  39. package/.docs/docs/mastra-cloud/studio.md +0 -24
  40. package/.docs/docs/mcp/overview.md +0 -370
  41. package/.docs/docs/mcp/publishing-mcp-server.md +0 -95
  42. package/.docs/docs/memory/memory-processors.md +0 -316
  43. package/.docs/docs/memory/message-history.md +0 -260
  44. package/.docs/docs/memory/observational-memory.md +0 -246
  45. package/.docs/docs/memory/overview.md +0 -45
  46. package/.docs/docs/memory/semantic-recall.md +0 -272
  47. package/.docs/docs/memory/storage.md +0 -261
  48. package/.docs/docs/memory/working-memory.md +0 -400
  49. package/.docs/docs/observability/datasets/overview.md +0 -188
  50. package/.docs/docs/observability/datasets/running-experiments.md +0 -266
  51. package/.docs/docs/observability/logging.md +0 -99
  52. package/.docs/docs/observability/overview.md +0 -70
  53. package/.docs/docs/observability/tracing/bridges/otel.md +0 -209
  54. package/.docs/docs/observability/tracing/exporters/arize.md +0 -274
  55. package/.docs/docs/observability/tracing/exporters/braintrust.md +0 -111
  56. package/.docs/docs/observability/tracing/exporters/cloud.md +0 -129
  57. package/.docs/docs/observability/tracing/exporters/datadog.md +0 -187
  58. package/.docs/docs/observability/tracing/exporters/default.md +0 -211
  59. package/.docs/docs/observability/tracing/exporters/laminar.md +0 -100
  60. package/.docs/docs/observability/tracing/exporters/langfuse.md +0 -217
  61. package/.docs/docs/observability/tracing/exporters/langsmith.md +0 -202
  62. package/.docs/docs/observability/tracing/exporters/otel.md +0 -479
  63. package/.docs/docs/observability/tracing/exporters/posthog.md +0 -148
  64. package/.docs/docs/observability/tracing/exporters/sentry.md +0 -208
  65. package/.docs/docs/observability/tracing/overview.md +0 -1114
  66. package/.docs/docs/observability/tracing/processors/sensitive-data-filter.md +0 -303
  67. package/.docs/docs/rag/chunking-and-embedding.md +0 -183
  68. package/.docs/docs/rag/graph-rag.md +0 -215
  69. package/.docs/docs/rag/overview.md +0 -72
  70. package/.docs/docs/rag/retrieval.md +0 -521
  71. package/.docs/docs/rag/vector-databases.md +0 -648
  72. package/.docs/docs/server/auth/auth0.md +0 -222
  73. package/.docs/docs/server/auth/better-auth.md +0 -203
  74. package/.docs/docs/server/auth/clerk.md +0 -132
  75. package/.docs/docs/server/auth/composite-auth.md +0 -234
  76. package/.docs/docs/server/auth/custom-auth-provider.md +0 -513
  77. package/.docs/docs/server/auth/firebase.md +0 -272
  78. package/.docs/docs/server/auth/jwt.md +0 -110
  79. package/.docs/docs/server/auth/simple-auth.md +0 -178
  80. package/.docs/docs/server/auth/supabase.md +0 -117
  81. package/.docs/docs/server/auth/workos.md +0 -190
  82. package/.docs/docs/server/auth.md +0 -38
  83. package/.docs/docs/server/custom-adapters.md +0 -374
  84. package/.docs/docs/server/custom-api-routes.md +0 -267
  85. package/.docs/docs/server/mastra-client.md +0 -243
  86. package/.docs/docs/server/mastra-server.md +0 -71
  87. package/.docs/docs/server/middleware.md +0 -228
  88. package/.docs/docs/server/request-context.md +0 -478
  89. package/.docs/docs/server/server-adapters.md +0 -547
  90. package/.docs/docs/streaming/events.md +0 -247
  91. package/.docs/docs/streaming/overview.md +0 -181
  92. package/.docs/docs/streaming/tool-streaming.md +0 -178
  93. package/.docs/docs/streaming/workflow-streaming.md +0 -109
  94. package/.docs/docs/voice/overview.md +0 -979
  95. package/.docs/docs/voice/speech-to-speech.md +0 -103
  96. package/.docs/docs/voice/speech-to-text.md +0 -80
  97. package/.docs/docs/voice/text-to-speech.md +0 -84
  98. package/.docs/docs/workflows/agents-and-tools.md +0 -170
  99. package/.docs/docs/workflows/control-flow.md +0 -823
  100. package/.docs/docs/workflows/error-handling.md +0 -360
  101. package/.docs/docs/workflows/human-in-the-loop.md +0 -213
  102. package/.docs/docs/workflows/overview.md +0 -372
  103. package/.docs/docs/workflows/snapshots.md +0 -238
  104. package/.docs/docs/workflows/suspend-and-resume.md +0 -205
  105. package/.docs/docs/workflows/time-travel.md +0 -309
  106. package/.docs/docs/workflows/workflow-state.md +0 -181
  107. package/.docs/docs/workspace/filesystem.md +0 -162
  108. package/.docs/docs/workspace/overview.md +0 -239
  109. package/.docs/docs/workspace/sandbox.md +0 -63
  110. package/.docs/docs/workspace/search.md +0 -219
  111. package/.docs/docs/workspace/skills.md +0 -126
  112. package/.docs/guides/agent-frameworks/ai-sdk.md +0 -140
  113. package/.docs/guides/build-your-ui/ai-sdk-ui.md +0 -1463
  114. package/.docs/guides/build-your-ui/assistant-ui.md +0 -156
  115. package/.docs/guides/build-your-ui/copilotkit.md +0 -292
  116. package/.docs/guides/deployment/amazon-ec2.md +0 -130
  117. package/.docs/guides/deployment/aws-lambda.md +0 -248
  118. package/.docs/guides/deployment/azure-app-services.md +0 -114
  119. package/.docs/guides/deployment/cloudflare.md +0 -99
  120. package/.docs/guides/deployment/digital-ocean.md +0 -168
  121. package/.docs/guides/deployment/inngest.md +0 -685
  122. package/.docs/guides/deployment/netlify.md +0 -77
  123. package/.docs/guides/deployment/vercel.md +0 -101
  124. package/.docs/guides/getting-started/astro.md +0 -408
  125. package/.docs/guides/getting-started/electron.md +0 -504
  126. package/.docs/guides/getting-started/express.md +0 -251
  127. package/.docs/guides/getting-started/hono.md +0 -191
  128. package/.docs/guides/getting-started/next-js.md +0 -355
  129. package/.docs/guides/getting-started/nuxt.md +0 -476
  130. package/.docs/guides/getting-started/quickstart.md +0 -67
  131. package/.docs/guides/getting-started/sveltekit.md +0 -300
  132. package/.docs/guides/getting-started/vite-react.md +0 -439
  133. package/.docs/guides/guide/ai-recruiter.md +0 -227
  134. package/.docs/guides/guide/chef-michel.md +0 -215
  135. package/.docs/guides/guide/code-review-bot.md +0 -221
  136. package/.docs/guides/guide/dev-assistant.md +0 -304
  137. package/.docs/guides/guide/docs-manager.md +0 -238
  138. package/.docs/guides/guide/github-actions-pr-description.md +0 -236
  139. package/.docs/guides/guide/notes-mcp-server.md +0 -425
  140. package/.docs/guides/guide/research-assistant.md +0 -349
  141. package/.docs/guides/guide/stock-agent.md +0 -134
  142. package/.docs/guides/guide/web-search.md +0 -326
  143. package/.docs/guides/guide/whatsapp-chat-bot.md +0 -416
  144. package/.docs/guides/index.md +0 -3
  145. package/.docs/guides/migrations/agentnetwork.md +0 -101
  146. package/.docs/guides/migrations/ai-sdk-v4-to-v5.md +0 -112
  147. package/.docs/guides/migrations/upgrade-to-v1/agent.md +0 -404
  148. package/.docs/guides/migrations/upgrade-to-v1/cli.md +0 -57
  149. package/.docs/guides/migrations/upgrade-to-v1/client.md +0 -337
  150. package/.docs/guides/migrations/upgrade-to-v1/deployment.md +0 -37
  151. package/.docs/guides/migrations/upgrade-to-v1/evals.md +0 -239
  152. package/.docs/guides/migrations/upgrade-to-v1/mastra.md +0 -143
  153. package/.docs/guides/migrations/upgrade-to-v1/mcp.md +0 -97
  154. package/.docs/guides/migrations/upgrade-to-v1/memory.md +0 -285
  155. package/.docs/guides/migrations/upgrade-to-v1/overview.md +0 -119
  156. package/.docs/guides/migrations/upgrade-to-v1/processors.md +0 -68
  157. package/.docs/guides/migrations/upgrade-to-v1/rag.md +0 -42
  158. package/.docs/guides/migrations/upgrade-to-v1/storage.md +0 -553
  159. package/.docs/guides/migrations/upgrade-to-v1/tools.md +0 -180
  160. package/.docs/guides/migrations/upgrade-to-v1/tracing.md +0 -417
  161. package/.docs/guides/migrations/upgrade-to-v1/vectors.md +0 -87
  162. package/.docs/guides/migrations/upgrade-to-v1/voice.md +0 -30
  163. package/.docs/guides/migrations/upgrade-to-v1/workflows.md +0 -341
  164. package/.docs/guides/migrations/vnext-to-standard-apis.md +0 -364
  165. package/.docs/models/embeddings.md +0 -161
  166. package/.docs/models/gateways/azure-openai.md +0 -128
  167. package/.docs/models/gateways/custom-gateways.md +0 -545
  168. package/.docs/models/gateways/netlify.md +0 -88
  169. package/.docs/models/gateways/openrouter.md +0 -219
  170. package/.docs/models/gateways/vercel.md +0 -225
  171. package/.docs/models/gateways.md +0 -14
  172. package/.docs/models/index.md +0 -286
  173. package/.docs/models/providers/302ai.md +0 -134
  174. package/.docs/models/providers/abacus.md +0 -125
  175. package/.docs/models/providers/agentrouter.md +0 -90
  176. package/.docs/models/providers/aihubmix.md +0 -107
  177. package/.docs/models/providers/alibaba-cn.md +0 -135
  178. package/.docs/models/providers/alibaba.md +0 -111
  179. package/.docs/models/providers/amazon-bedrock.md +0 -33
  180. package/.docs/models/providers/anthropic.md +0 -153
  181. package/.docs/models/providers/azure.md +0 -33
  182. package/.docs/models/providers/bailing.md +0 -72
  183. package/.docs/models/providers/baseten.md +0 -77
  184. package/.docs/models/providers/berget.md +0 -78
  185. package/.docs/models/providers/cerebras.md +0 -101
  186. package/.docs/models/providers/chutes.md +0 -136
  187. package/.docs/models/providers/cloudflare-ai-gateway.md +0 -33
  188. package/.docs/models/providers/cloudflare-workers-ai.md +0 -109
  189. package/.docs/models/providers/cohere.md +0 -33
  190. package/.docs/models/providers/cortecs.md +0 -91
  191. package/.docs/models/providers/deepinfra.md +0 -112
  192. package/.docs/models/providers/deepseek.md +0 -88
  193. package/.docs/models/providers/fastrouter.md +0 -84
  194. package/.docs/models/providers/fireworks-ai.md +0 -89
  195. package/.docs/models/providers/firmware.md +0 -85
  196. package/.docs/models/providers/friendli.md +0 -78
  197. package/.docs/models/providers/github-models.md +0 -125
  198. package/.docs/models/providers/google-vertex.md +0 -33
  199. package/.docs/models/providers/google.md +0 -159
  200. package/.docs/models/providers/groq.md +0 -107
  201. package/.docs/models/providers/helicone.md +0 -161
  202. package/.docs/models/providers/huggingface.md +0 -90
  203. package/.docs/models/providers/iflowcn.md +0 -84
  204. package/.docs/models/providers/inception.md +0 -72
  205. package/.docs/models/providers/inference.md +0 -79
  206. package/.docs/models/providers/io-intelligence.md +0 -87
  207. package/.docs/models/providers/io-net.md +0 -87
  208. package/.docs/models/providers/jiekou.md +0 -131
  209. package/.docs/models/providers/kilo.md +0 -333
  210. package/.docs/models/providers/kimi-for-coding.md +0 -100
  211. package/.docs/models/providers/kuae-cloud-coding-plan.md +0 -71
  212. package/.docs/models/providers/llama.md +0 -77
  213. package/.docs/models/providers/lmstudio.md +0 -73
  214. package/.docs/models/providers/lucidquery.md +0 -72
  215. package/.docs/models/providers/minimax-cn-coding-plan.md +0 -102
  216. package/.docs/models/providers/minimax-cn.md +0 -102
  217. package/.docs/models/providers/minimax-coding-plan.md +0 -102
  218. package/.docs/models/providers/minimax.md +0 -104
  219. package/.docs/models/providers/mistral.md +0 -124
  220. package/.docs/models/providers/moark.md +0 -72
  221. package/.docs/models/providers/modelscope.md +0 -77
  222. package/.docs/models/providers/moonshotai-cn.md +0 -76
  223. package/.docs/models/providers/moonshotai.md +0 -76
  224. package/.docs/models/providers/morph.md +0 -73
  225. package/.docs/models/providers/nano-gpt.md +0 -103
  226. package/.docs/models/providers/nebius.md +0 -116
  227. package/.docs/models/providers/nova.md +0 -72
  228. package/.docs/models/providers/novita-ai.md +0 -154
  229. package/.docs/models/providers/nvidia.md +0 -141
  230. package/.docs/models/providers/ollama-cloud.md +0 -103
  231. package/.docs/models/providers/ollama.md +0 -33
  232. package/.docs/models/providers/openai.md +0 -193
  233. package/.docs/models/providers/opencode.md +0 -100
  234. package/.docs/models/providers/ovhcloud.md +0 -83
  235. package/.docs/models/providers/perplexity.md +0 -100
  236. package/.docs/models/providers/poe.md +0 -183
  237. package/.docs/models/providers/privatemode-ai.md +0 -75
  238. package/.docs/models/providers/requesty.md +0 -90
  239. package/.docs/models/providers/scaleway.md +0 -84
  240. package/.docs/models/providers/siliconflow-cn.md +0 -138
  241. package/.docs/models/providers/siliconflow.md +0 -140
  242. package/.docs/models/providers/stackit.md +0 -78
  243. package/.docs/models/providers/stepfun.md +0 -73
  244. package/.docs/models/providers/submodel.md +0 -79
  245. package/.docs/models/providers/synthetic.md +0 -96
  246. package/.docs/models/providers/togetherai.md +0 -115
  247. package/.docs/models/providers/upstage.md +0 -73
  248. package/.docs/models/providers/venice.md +0 -95
  249. package/.docs/models/providers/vivgrid.md +0 -106
  250. package/.docs/models/providers/vultr.md +0 -75
  251. package/.docs/models/providers/wandb.md +0 -80
  252. package/.docs/models/providers/xai.md +0 -141
  253. package/.docs/models/providers/xiaomi.md +0 -71
  254. package/.docs/models/providers/zai-coding-plan.md +0 -80
  255. package/.docs/models/providers/zai.md +0 -79
  256. package/.docs/models/providers/zenmux.md +0 -161
  257. package/.docs/models/providers/zhipuai-coding-plan.md +0 -79
  258. package/.docs/models/providers/zhipuai.md +0 -79
  259. package/.docs/models/providers.md +0 -81
  260. package/.docs/reference/agents/agent.md +0 -142
  261. package/.docs/reference/agents/generate.md +0 -174
  262. package/.docs/reference/agents/generateLegacy.md +0 -176
  263. package/.docs/reference/agents/getDefaultGenerateOptions.md +0 -36
  264. package/.docs/reference/agents/getDefaultOptions.md +0 -34
  265. package/.docs/reference/agents/getDefaultStreamOptions.md +0 -36
  266. package/.docs/reference/agents/getDescription.md +0 -21
  267. package/.docs/reference/agents/getInstructions.md +0 -34
  268. package/.docs/reference/agents/getLLM.md +0 -37
  269. package/.docs/reference/agents/getMemory.md +0 -34
  270. package/.docs/reference/agents/getModel.md +0 -34
  271. package/.docs/reference/agents/getTools.md +0 -29
  272. package/.docs/reference/agents/getVoice.md +0 -34
  273. package/.docs/reference/agents/listAgents.md +0 -35
  274. package/.docs/reference/agents/listScorers.md +0 -34
  275. package/.docs/reference/agents/listTools.md +0 -34
  276. package/.docs/reference/agents/listWorkflows.md +0 -34
  277. package/.docs/reference/agents/network.md +0 -134
  278. package/.docs/reference/ai-sdk/chat-route.md +0 -82
  279. package/.docs/reference/ai-sdk/handle-chat-stream.md +0 -53
  280. package/.docs/reference/ai-sdk/handle-network-stream.md +0 -37
  281. package/.docs/reference/ai-sdk/handle-workflow-stream.md +0 -55
  282. package/.docs/reference/ai-sdk/network-route.md +0 -74
  283. package/.docs/reference/ai-sdk/to-ai-sdk-stream.md +0 -232
  284. package/.docs/reference/ai-sdk/to-ai-sdk-v4-messages.md +0 -79
  285. package/.docs/reference/ai-sdk/to-ai-sdk-v5-messages.md +0 -73
  286. package/.docs/reference/ai-sdk/with-mastra.md +0 -59
  287. package/.docs/reference/ai-sdk/workflow-route.md +0 -79
  288. package/.docs/reference/auth/auth0.md +0 -73
  289. package/.docs/reference/auth/better-auth.md +0 -71
  290. package/.docs/reference/auth/clerk.md +0 -36
  291. package/.docs/reference/auth/firebase.md +0 -80
  292. package/.docs/reference/auth/jwt.md +0 -26
  293. package/.docs/reference/auth/supabase.md +0 -33
  294. package/.docs/reference/auth/workos.md +0 -84
  295. package/.docs/reference/cli/create-mastra.md +0 -137
  296. package/.docs/reference/cli/mastra.md +0 -336
  297. package/.docs/reference/client-js/agents.md +0 -438
  298. package/.docs/reference/client-js/error-handling.md +0 -16
  299. package/.docs/reference/client-js/logs.md +0 -24
  300. package/.docs/reference/client-js/mastra-client.md +0 -63
  301. package/.docs/reference/client-js/memory.md +0 -225
  302. package/.docs/reference/client-js/observability.md +0 -72
  303. package/.docs/reference/client-js/telemetry.md +0 -20
  304. package/.docs/reference/client-js/tools.md +0 -44
  305. package/.docs/reference/client-js/vectors.md +0 -79
  306. package/.docs/reference/client-js/workflows.md +0 -199
  307. package/.docs/reference/configuration.md +0 -749
  308. package/.docs/reference/core/addGateway.md +0 -42
  309. package/.docs/reference/core/getAgent.md +0 -21
  310. package/.docs/reference/core/getAgentById.md +0 -21
  311. package/.docs/reference/core/getDeployer.md +0 -22
  312. package/.docs/reference/core/getGateway.md +0 -38
  313. package/.docs/reference/core/getGatewayById.md +0 -41
  314. package/.docs/reference/core/getLogger.md +0 -22
  315. package/.docs/reference/core/getMCPServer.md +0 -45
  316. package/.docs/reference/core/getMCPServerById.md +0 -53
  317. package/.docs/reference/core/getMemory.md +0 -50
  318. package/.docs/reference/core/getScorer.md +0 -54
  319. package/.docs/reference/core/getScorerById.md +0 -54
  320. package/.docs/reference/core/getServer.md +0 -22
  321. package/.docs/reference/core/getStorage.md +0 -22
  322. package/.docs/reference/core/getStoredAgentById.md +0 -89
  323. package/.docs/reference/core/getTelemetry.md +0 -22
  324. package/.docs/reference/core/getVector.md +0 -22
  325. package/.docs/reference/core/getWorkflow.md +0 -40
  326. package/.docs/reference/core/listAgents.md +0 -21
  327. package/.docs/reference/core/listGateways.md +0 -40
  328. package/.docs/reference/core/listLogs.md +0 -38
  329. package/.docs/reference/core/listLogsByRunId.md +0 -36
  330. package/.docs/reference/core/listMCPServers.md +0 -51
  331. package/.docs/reference/core/listMemory.md +0 -56
  332. package/.docs/reference/core/listScorers.md +0 -29
  333. package/.docs/reference/core/listStoredAgents.md +0 -93
  334. package/.docs/reference/core/listVectors.md +0 -22
  335. package/.docs/reference/core/listWorkflows.md +0 -21
  336. package/.docs/reference/core/mastra-class.md +0 -66
  337. package/.docs/reference/core/mastra-model-gateway.md +0 -153
  338. package/.docs/reference/core/setLogger.md +0 -26
  339. package/.docs/reference/core/setStorage.md +0 -27
  340. package/.docs/reference/datasets/addItem.md +0 -35
  341. package/.docs/reference/datasets/addItems.md +0 -33
  342. package/.docs/reference/datasets/compareExperiments.md +0 -48
  343. package/.docs/reference/datasets/create.md +0 -49
  344. package/.docs/reference/datasets/dataset.md +0 -78
  345. package/.docs/reference/datasets/datasets-manager.md +0 -84
  346. package/.docs/reference/datasets/delete.md +0 -23
  347. package/.docs/reference/datasets/deleteExperiment.md +0 -25
  348. package/.docs/reference/datasets/deleteItem.md +0 -25
  349. package/.docs/reference/datasets/deleteItems.md +0 -27
  350. package/.docs/reference/datasets/get.md +0 -29
  351. package/.docs/reference/datasets/getDetails.md +0 -45
  352. package/.docs/reference/datasets/getExperiment.md +0 -28
  353. package/.docs/reference/datasets/getItem.md +0 -31
  354. package/.docs/reference/datasets/getItemHistory.md +0 -29
  355. package/.docs/reference/datasets/list.md +0 -29
  356. package/.docs/reference/datasets/listExperimentResults.md +0 -37
  357. package/.docs/reference/datasets/listExperiments.md +0 -31
  358. package/.docs/reference/datasets/listItems.md +0 -44
  359. package/.docs/reference/datasets/listVersions.md +0 -31
  360. package/.docs/reference/datasets/startExperiment.md +0 -60
  361. package/.docs/reference/datasets/startExperimentAsync.md +0 -41
  362. package/.docs/reference/datasets/update.md +0 -46
  363. package/.docs/reference/datasets/updateItem.md +0 -36
  364. package/.docs/reference/deployer/cloudflare.md +0 -79
  365. package/.docs/reference/deployer/netlify.md +0 -82
  366. package/.docs/reference/deployer/vercel.md +0 -91
  367. package/.docs/reference/deployer.md +0 -100
  368. package/.docs/reference/evals/answer-relevancy.md +0 -105
  369. package/.docs/reference/evals/answer-similarity.md +0 -99
  370. package/.docs/reference/evals/bias.md +0 -120
  371. package/.docs/reference/evals/completeness.md +0 -137
  372. package/.docs/reference/evals/content-similarity.md +0 -101
  373. package/.docs/reference/evals/context-precision.md +0 -196
  374. package/.docs/reference/evals/context-relevance.md +0 -536
  375. package/.docs/reference/evals/create-scorer.md +0 -270
  376. package/.docs/reference/evals/faithfulness.md +0 -114
  377. package/.docs/reference/evals/hallucination.md +0 -220
  378. package/.docs/reference/evals/keyword-coverage.md +0 -128
  379. package/.docs/reference/evals/mastra-scorer.md +0 -123
  380. package/.docs/reference/evals/noise-sensitivity.md +0 -685
  381. package/.docs/reference/evals/prompt-alignment.md +0 -619
  382. package/.docs/reference/evals/run-evals.md +0 -138
  383. package/.docs/reference/evals/scorer-utils.md +0 -330
  384. package/.docs/reference/evals/textual-difference.md +0 -113
  385. package/.docs/reference/evals/tone-consistency.md +0 -119
  386. package/.docs/reference/evals/tool-call-accuracy.md +0 -533
  387. package/.docs/reference/evals/toxicity.md +0 -123
  388. package/.docs/reference/harness/harness-class.md +0 -645
  389. package/.docs/reference/index.md +0 -276
  390. package/.docs/reference/logging/pino-logger.md +0 -117
  391. package/.docs/reference/memory/clone-utilities.md +0 -199
  392. package/.docs/reference/memory/cloneThread.md +0 -130
  393. package/.docs/reference/memory/createThread.md +0 -68
  394. package/.docs/reference/memory/deleteMessages.md +0 -40
  395. package/.docs/reference/memory/getThreadById.md +0 -24
  396. package/.docs/reference/memory/listThreads.md +0 -145
  397. package/.docs/reference/memory/memory-class.md +0 -147
  398. package/.docs/reference/memory/observational-memory.md +0 -565
  399. package/.docs/reference/memory/recall.md +0 -91
  400. package/.docs/reference/observability/tracing/bridges/otel.md +0 -131
  401. package/.docs/reference/observability/tracing/configuration.md +0 -178
  402. package/.docs/reference/observability/tracing/exporters/arize.md +0 -141
  403. package/.docs/reference/observability/tracing/exporters/braintrust.md +0 -93
  404. package/.docs/reference/observability/tracing/exporters/cloud-exporter.md +0 -163
  405. package/.docs/reference/observability/tracing/exporters/console-exporter.md +0 -138
  406. package/.docs/reference/observability/tracing/exporters/datadog.md +0 -116
  407. package/.docs/reference/observability/tracing/exporters/default-exporter.md +0 -174
  408. package/.docs/reference/observability/tracing/exporters/laminar.md +0 -78
  409. package/.docs/reference/observability/tracing/exporters/langfuse.md +0 -134
  410. package/.docs/reference/observability/tracing/exporters/langsmith.md +0 -110
  411. package/.docs/reference/observability/tracing/exporters/otel.md +0 -199
  412. package/.docs/reference/observability/tracing/exporters/posthog.md +0 -92
  413. package/.docs/reference/observability/tracing/exporters/sentry.md +0 -184
  414. package/.docs/reference/observability/tracing/instances.md +0 -109
  415. package/.docs/reference/observability/tracing/interfaces.md +0 -749
  416. package/.docs/reference/observability/tracing/processors/sensitive-data-filter.md +0 -144
  417. package/.docs/reference/observability/tracing/spans.md +0 -224
  418. package/.docs/reference/processors/batch-parts-processor.md +0 -61
  419. package/.docs/reference/processors/language-detector.md +0 -81
  420. package/.docs/reference/processors/message-history-processor.md +0 -85
  421. package/.docs/reference/processors/moderation-processor.md +0 -104
  422. package/.docs/reference/processors/pii-detector.md +0 -107
  423. package/.docs/reference/processors/processor-interface.md +0 -525
  424. package/.docs/reference/processors/prompt-injection-detector.md +0 -71
  425. package/.docs/reference/processors/semantic-recall-processor.md +0 -123
  426. package/.docs/reference/processors/system-prompt-scrubber.md +0 -80
  427. package/.docs/reference/processors/token-limiter-processor.md +0 -113
  428. package/.docs/reference/processors/tool-call-filter.md +0 -85
  429. package/.docs/reference/processors/tool-search-processor.md +0 -113
  430. package/.docs/reference/processors/unicode-normalizer.md +0 -62
  431. package/.docs/reference/processors/working-memory-processor.md +0 -154
  432. package/.docs/reference/rag/chunk.md +0 -221
  433. package/.docs/reference/rag/database-config.md +0 -264
  434. package/.docs/reference/rag/document.md +0 -114
  435. package/.docs/reference/rag/embeddings.md +0 -92
  436. package/.docs/reference/rag/extract-params.md +0 -168
  437. package/.docs/reference/rag/graph-rag.md +0 -111
  438. package/.docs/reference/rag/metadata-filters.md +0 -216
  439. package/.docs/reference/rag/rerank.md +0 -80
  440. package/.docs/reference/rag/rerankWithScorer.md +0 -80
  441. package/.docs/reference/server/create-route.md +0 -260
  442. package/.docs/reference/server/express-adapter.md +0 -176
  443. package/.docs/reference/server/fastify-adapter.md +0 -90
  444. package/.docs/reference/server/hono-adapter.md +0 -162
  445. package/.docs/reference/server/koa-adapter.md +0 -127
  446. package/.docs/reference/server/mastra-server.md +0 -298
  447. package/.docs/reference/server/register-api-route.md +0 -249
  448. package/.docs/reference/server/routes.md +0 -306
  449. package/.docs/reference/storage/cloudflare-d1.md +0 -218
  450. package/.docs/reference/storage/cloudflare.md +0 -88
  451. package/.docs/reference/storage/composite.md +0 -235
  452. package/.docs/reference/storage/convex.md +0 -161
  453. package/.docs/reference/storage/dynamodb.md +0 -282
  454. package/.docs/reference/storage/lance.md +0 -131
  455. package/.docs/reference/storage/libsql.md +0 -135
  456. package/.docs/reference/storage/mongodb.md +0 -262
  457. package/.docs/reference/storage/mssql.md +0 -155
  458. package/.docs/reference/storage/overview.md +0 -121
  459. package/.docs/reference/storage/postgresql.md +0 -529
  460. package/.docs/reference/storage/upstash.md +0 -160
  461. package/.docs/reference/streaming/ChunkType.md +0 -292
  462. package/.docs/reference/streaming/agents/MastraModelOutput.md +0 -182
  463. package/.docs/reference/streaming/agents/stream.md +0 -212
  464. package/.docs/reference/streaming/agents/streamLegacy.md +0 -142
  465. package/.docs/reference/streaming/workflows/observeStream.md +0 -42
  466. package/.docs/reference/streaming/workflows/resumeStream.md +0 -61
  467. package/.docs/reference/streaming/workflows/stream.md +0 -88
  468. package/.docs/reference/streaming/workflows/timeTravelStream.md +0 -142
  469. package/.docs/reference/templates/overview.md +0 -194
  470. package/.docs/reference/tools/create-tool.md +0 -237
  471. package/.docs/reference/tools/document-chunker-tool.md +0 -89
  472. package/.docs/reference/tools/graph-rag-tool.md +0 -185
  473. package/.docs/reference/tools/mcp-client.md +0 -962
  474. package/.docs/reference/tools/mcp-server.md +0 -1275
  475. package/.docs/reference/tools/vector-query-tool.md +0 -459
  476. package/.docs/reference/vectors/astra.md +0 -121
  477. package/.docs/reference/vectors/chroma.md +0 -267
  478. package/.docs/reference/vectors/convex.md +0 -303
  479. package/.docs/reference/vectors/couchbase.md +0 -226
  480. package/.docs/reference/vectors/duckdb.md +0 -318
  481. package/.docs/reference/vectors/elasticsearch.md +0 -189
  482. package/.docs/reference/vectors/lance.md +0 -220
  483. package/.docs/reference/vectors/libsql.md +0 -305
  484. package/.docs/reference/vectors/mongodb.md +0 -295
  485. package/.docs/reference/vectors/opensearch.md +0 -99
  486. package/.docs/reference/vectors/pg.md +0 -408
  487. package/.docs/reference/vectors/pinecone.md +0 -168
  488. package/.docs/reference/vectors/qdrant.md +0 -222
  489. package/.docs/reference/vectors/s3vectors.md +0 -277
  490. package/.docs/reference/vectors/turbopuffer.md +0 -157
  491. package/.docs/reference/vectors/upstash.md +0 -294
  492. package/.docs/reference/vectors/vectorize.md +0 -147
  493. package/.docs/reference/voice/azure.md +0 -148
  494. package/.docs/reference/voice/cloudflare.md +0 -83
  495. package/.docs/reference/voice/composite-voice.md +0 -121
  496. package/.docs/reference/voice/deepgram.md +0 -79
  497. package/.docs/reference/voice/elevenlabs.md +0 -98
  498. package/.docs/reference/voice/google-gemini-live.md +0 -378
  499. package/.docs/reference/voice/google.md +0 -228
  500. package/.docs/reference/voice/mastra-voice.md +0 -313
  501. package/.docs/reference/voice/murf.md +0 -122
  502. package/.docs/reference/voice/openai-realtime.md +0 -203
  503. package/.docs/reference/voice/openai.md +0 -88
  504. package/.docs/reference/voice/playai.md +0 -80
  505. package/.docs/reference/voice/sarvam.md +0 -126
  506. package/.docs/reference/voice/speechify.md +0 -75
  507. package/.docs/reference/voice/voice.addInstructions.md +0 -56
  508. package/.docs/reference/voice/voice.addTools.md +0 -67
  509. package/.docs/reference/voice/voice.answer.md +0 -54
  510. package/.docs/reference/voice/voice.close.md +0 -51
  511. package/.docs/reference/voice/voice.connect.md +0 -94
  512. package/.docs/reference/voice/voice.events.md +0 -37
  513. package/.docs/reference/voice/voice.getSpeakers.md +0 -129
  514. package/.docs/reference/voice/voice.listen.md +0 -164
  515. package/.docs/reference/voice/voice.off.md +0 -54
  516. package/.docs/reference/voice/voice.on.md +0 -111
  517. package/.docs/reference/voice/voice.send.md +0 -65
  518. package/.docs/reference/voice/voice.speak.md +0 -157
  519. package/.docs/reference/voice/voice.updateConfig.md +0 -60
  520. package/.docs/reference/workflows/run-methods/cancel.md +0 -86
  521. package/.docs/reference/workflows/run-methods/restart.md +0 -33
  522. package/.docs/reference/workflows/run-methods/resume.md +0 -59
  523. package/.docs/reference/workflows/run-methods/start.md +0 -58
  524. package/.docs/reference/workflows/run-methods/startAsync.md +0 -67
  525. package/.docs/reference/workflows/run-methods/timeTravel.md +0 -142
  526. package/.docs/reference/workflows/run.md +0 -59
  527. package/.docs/reference/workflows/step.md +0 -119
  528. package/.docs/reference/workflows/workflow-methods/branch.md +0 -25
  529. package/.docs/reference/workflows/workflow-methods/commit.md +0 -17
  530. package/.docs/reference/workflows/workflow-methods/create-run.md +0 -63
  531. package/.docs/reference/workflows/workflow-methods/dountil.md +0 -25
  532. package/.docs/reference/workflows/workflow-methods/dowhile.md +0 -25
  533. package/.docs/reference/workflows/workflow-methods/foreach.md +0 -118
  534. package/.docs/reference/workflows/workflow-methods/map.md +0 -93
  535. package/.docs/reference/workflows/workflow-methods/parallel.md +0 -21
  536. package/.docs/reference/workflows/workflow-methods/sleep.md +0 -35
  537. package/.docs/reference/workflows/workflow-methods/sleepUntil.md +0 -35
  538. package/.docs/reference/workflows/workflow-methods/then.md +0 -21
  539. package/.docs/reference/workflows/workflow.md +0 -157
  540. package/.docs/reference/workspace/e2b-sandbox.md +0 -288
  541. package/.docs/reference/workspace/filesystem.md +0 -202
  542. package/.docs/reference/workspace/gcs-filesystem.md +0 -170
  543. package/.docs/reference/workspace/local-filesystem.md +0 -327
  544. package/.docs/reference/workspace/local-sandbox.md +0 -285
  545. package/.docs/reference/workspace/s3-filesystem.md +0 -169
  546. package/.docs/reference/workspace/sandbox.md +0 -81
  547. package/.docs/reference/workspace/workspace-class.md +0 -226
@@ -1,1463 +0,0 @@
1
- # Using AI SDK UI
2
-
3
- [AI SDK UI](https://sdk.vercel.ai) is a library of React utilities and components for building AI-powered interfaces. In this guide, you'll learn how to use `@mastra/ai-sdk` to convert Mastra's output to AI SDK-compatible formats, enabling you to use its hooks and components in your frontend.
4
-
5
- > **Note:** Migrating from AI SDK v4 to v5? See the [migration guide](https://mastra.ai/guides/migrations/ai-sdk-v4-to-v5).
6
-
7
- > **Tip:** Want to see more examples? Visit Mastra's [**UI Dojo**](https://ui-dojo.mastra.ai/) or the [Next.js quickstart guide](https://mastra.ai/guides/getting-started/next-js).
8
-
9
- ## Getting Started
10
-
11
- Use Mastra and AI SDK UI together by installing the `@mastra/ai-sdk` package. `@mastra/ai-sdk` provides custom API routes and utilities for streaming Mastra agents in AI SDK-compatible formats. This includes chat, workflow, and network route handlers, along with utilities and exported types for UI integrations.
12
-
13
- `@mastra/ai-sdk` integrates with AI SDK UI's three main hooks: [`useChat()`](https://ai-sdk.dev/docs/ai-sdk-ui/chatbot), [`useCompletion()`](https://ai-sdk.dev/docs/ai-sdk-ui/completion), and [`useObject()`](https://ai-sdk.dev/docs/ai-sdk-ui/object-generation).
14
-
15
- Install the required packages to get started:
16
-
17
- **npm**:
18
-
19
- ```bash
20
- npm install @mastra/ai-sdk@latest @ai-sdk/react ai
21
- ```
22
-
23
- **pnpm**:
24
-
25
- ```bash
26
- pnpm add @mastra/ai-sdk@latest @ai-sdk/react ai
27
- ```
28
-
29
- **Yarn**:
30
-
31
- ```bash
32
- yarn add @mastra/ai-sdk@latest @ai-sdk/react ai
33
- ```
34
-
35
- **Bun**:
36
-
37
- ```bash
38
- bun add @mastra/ai-sdk@latest @ai-sdk/react ai
39
- ```
40
-
41
- You're now ready to follow the integration guides and recipes below!
42
-
43
- ## Integration Guides
44
-
45
- Typically, you'll set up API routes that stream Mastra content in AI SDK-compatible format, and then use those routes in AI SDK UI hooks like `useChat()`. Below you'll find two main approaches to achieve this:
46
-
47
- - [Mastra's server](#mastras-server)
48
- - [Framework-agnostic](#framework-agnostic)
49
-
50
- Once you have your API routes set up, you can use them in the [`useChat()`](#usechat) hook.
51
-
52
- ### Mastra's server
53
-
54
- Run Mastra as a standalone server and connect your frontend (e.g. using Vite + React) to its API endpoints. You'll be using Mastra's [custom API routes](https://mastra.ai/docs/server/custom-api-routes) feature for this.
55
-
56
- > **Info:** Mastra's [**UI Dojo**](https://ui-dojo.mastra.ai/) is an example of this setup.
57
-
58
- You can use [`chatRoute()`](https://mastra.ai/reference/ai-sdk/chat-route), [`workflowRoute()`](https://mastra.ai/reference/ai-sdk/workflow-route), and [`networkRoute()`](https://mastra.ai/reference/ai-sdk/network-route) to create API routes that stream Mastra content in AI SDK-compatible format. Once implemented, you can use these API routes in [`useChat()`](#usechat).
59
-
60
- **chatRoute()**:
61
-
62
- This example shows how to set up a chat route at the `/chat` endpoint that uses an agent with the ID `weatherAgent`.
63
-
64
- ```typescript
65
- import { Mastra } from "@mastra/core";
66
- import { chatRoute } from "@mastra/ai-sdk";
67
-
68
- export const mastra = new Mastra({
69
- server: {
70
- apiRoutes: [
71
- chatRoute({
72
- path: "/chat",
73
- agent: "weatherAgent",
74
- }),
75
- ],
76
- },
77
- });
78
- ```
79
-
80
- You can also use dynamic agent routing, see the [`chatRoute()` reference documentation](https://mastra.ai/reference/ai-sdk/chat-route) for more details.
81
-
82
- **workflowRoute()**:
83
-
84
- This example shows how to set up a workflow route at the `/workflow` endpoint that uses a workflow with the ID `weatherWorkflow`.
85
-
86
- ```typescript
87
- import { Mastra } from "@mastra/core";
88
- import { workflowRoute } from "@mastra/ai-sdk";
89
-
90
- export const mastra = new Mastra({
91
- server: {
92
- apiRoutes: [
93
- workflowRoute({
94
- path: "/workflow",
95
- workflow: "weatherWorkflow",
96
- }),
97
- ],
98
- },
99
- });
100
- ```
101
-
102
- You can also use dynamic workflow routing, see the [`workflowRoute()` reference documentation](https://mastra.ai/reference/ai-sdk/workflow-route) for more details.
103
-
104
- > **Agent streaming in workflows:** When a workflow step pipes an agent's stream to the workflow writer (e.g., `await response.fullStream.pipeTo(writer)`), the agent's text chunks and tool calls are forwarded to the UI stream in real time, even when the agent runs inside workflow steps.
105
- >
106
- > See [Workflow Streaming](https://mastra.ai/docs/streaming/workflow-streaming) for more details.
107
-
108
- **networkRoute()**:
109
-
110
- This example shows how to set up a network route at the `/network` endpoint that uses an agent with the ID `weatherAgent`.
111
-
112
- ```typescript
113
- import { Mastra } from "@mastra/core";
114
- import { networkRoute } from "@mastra/ai-sdk";
115
-
116
- export const mastra = new Mastra({
117
- server: {
118
- apiRoutes: [
119
- networkRoute({
120
- path: "/network",
121
- agent: "weatherAgent",
122
- }),
123
- ],
124
- },
125
- });
126
- ```
127
-
128
- You can also use dynamic network routing, see the [`networkRoute()` reference documentation](https://mastra.ai/reference/ai-sdk/network-route) for more details.
129
-
130
- ### Framework-agnostic
131
-
132
- If you don't want to run Mastra's server and instead use frameworks like Next.js or Express, you can use the [`handleChatStream()`](https://mastra.ai/reference/ai-sdk/handle-chat-stream), [`handleWorkflowStream()`](https://mastra.ai/reference/ai-sdk/handle-workflow-stream), and [`handleNetworkStream()`](https://mastra.ai/reference/ai-sdk/handle-network-stream) functions in your own API route handlers.
133
-
134
- They return a `ReadableStream` that you can wrap with [`createUIMessageStreamResponse()`](https://ai-sdk.dev/docs/reference/ai-sdk-ui/create-ui-message-stream-response).
135
-
136
- The examples below show you how to use them with Next.js App Router.
137
-
138
- **handleChatStream()**:
139
-
140
- This example shows how to set up a chat route at the `/chat` endpoint that uses an agent with the ID `weatherAgent`.
141
-
142
- ```typescript
143
- import { handleChatStream } from '@mastra/ai-sdk';
144
- import { createUIMessageStreamResponse } from 'ai';
145
- import { mastra } from '@/src/mastra';
146
-
147
- export async function POST(req: Request) {
148
- const params = await req.json();
149
- const stream = await handleChatStream({
150
- mastra,
151
- agentId: 'weatherAgent',
152
- params,
153
- });
154
- return createUIMessageStreamResponse({ stream });
155
- }
156
- ```
157
-
158
- **handleWorkflowStream()**:
159
-
160
- This example shows how to set up a workflow route at the `/workflow` endpoint that uses a workflow with the ID `weatherWorkflow`.
161
-
162
- ```typescript
163
- import { handleWorkflowStream } from '@mastra/ai-sdk';
164
- import { createUIMessageStreamResponse } from 'ai';
165
- import { mastra } from '@/src/mastra';
166
-
167
- export async function POST(req: Request) {
168
- const params = await req.json();
169
- const stream = await handleWorkflowStream({
170
- mastra,
171
- workflowId: 'weatherWorkflow',
172
- params,
173
- });
174
- return createUIMessageStreamResponse({ stream });
175
- }
176
- ```
177
-
178
- **handleNetworkStream()**:
179
-
180
- This example shows how to set up a network route at the `/network` endpoint that uses an agent with the ID `routingAgent`.
181
-
182
- ```typescript
183
- import { handleNetworkStream } from '@mastra/ai-sdk';
184
- import { createUIMessageStreamResponse } from 'ai';
185
- import { mastra } from '@/src/mastra';
186
-
187
- export async function POST(req: Request) {
188
- const params = await req.json();
189
- const stream = await handleNetworkStream({
190
- mastra,
191
- agentId: 'routingAgent',
192
- params,
193
- });
194
- return createUIMessageStreamResponse({ stream });
195
- }
196
- ```
197
-
198
- ### `useChat()`
199
-
200
- Whether you created API routes through [Mastra's server](#mastras-server) or used a [framework of your choice](#framework-agnostic), you can now use the API endpoints in the `useChat()` hook.
201
-
202
- Assuming you set up a route at `/chat` that uses a weather agent, you can ask it questions as seen below. It's important that you set the correct `api` URL.
203
-
204
- ```ts
205
- import { useChat } from "@ai-sdk/react";
206
- import { useState } from "react";
207
- import { DefaultChatTransport } from "ai";
208
-
209
- export default function Chat() {
210
- const [inputValue, setInputValue] = useState("")
211
- const { messages, sendMessage } = useChat({
212
- transport: new DefaultChatTransport({
213
- api: "http://localhost:4111/chat",
214
- }),
215
- });
216
-
217
- const handleFormSubmit = (e: React.FormEvent) => {
218
- e.preventDefault();
219
- sendMessage({ text: inputValue });
220
- };
221
-
222
- return (
223
- <div>
224
- <pre>{JSON.stringify(messages, null, 2)}</pre>
225
- <form onSubmit={handleFormSubmit}>
226
- <input value={inputValue} onChange={e => setInputValue(e.target.value)} placeholder="Name of the city" />
227
- </form>
228
- </div>
229
- );
230
- }
231
- ```
232
-
233
- Use [`prepareSendMessagesRequest`](https://ai-sdk.dev/docs/reference/ai-sdk-ui/use-chat#transport.default-chat-transport.prepare-send-messages-request) to customize the request sent to the chat route, for example to pass additional configuration to the agent.
234
-
235
- ### `useCompletion()`
236
-
237
- The `useCompletion()` hook handles single-turn completions between your frontend and a Mastra agent, allowing you to send a prompt and receive a streamed response over HTTP.
238
-
239
- Your frontend could look like this:
240
-
241
- ```typescript
242
- import { useCompletion } from '@ai-sdk/react';
243
-
244
- export default function Page() {
245
- const { completion, input, handleInputChange, handleSubmit } = useCompletion({
246
- api: '/api/completion',
247
- });
248
-
249
- return (
250
- <form onSubmit={handleSubmit}>
251
- <input
252
- name="prompt"
253
- value={input}
254
- onChange={handleInputChange}
255
- id="input"
256
- />
257
- <button type="submit">Submit</button>
258
- <div>{completion}</div>
259
- </form>
260
- );
261
- }
262
- ```
263
-
264
- Below are two approaches to implementing the backend:
265
-
266
- **Mastra Server**:
267
-
268
- ```ts
269
- import { Mastra } from '@mastra/core/mastra';
270
- import { registerApiRoute } from '@mastra/core/server';
271
- import { handleChatStream } from '@mastra/ai-sdk';
272
- import { createUIMessageStreamResponse } from 'ai';
273
-
274
- export const mastra = new Mastra({
275
- server: {
276
- apiRoutes: [
277
- registerApiRoute('/completion', {
278
- method: 'POST',
279
- handler: async (c) => {
280
- const { prompt } = await c.req.json();
281
- const mastra = c.get('mastra');
282
- const stream = await handleChatStream({
283
- mastra,
284
- agentId: 'weatherAgent',
285
- params: {
286
- messages: [
287
- {
288
- id: "1",
289
- role: 'user',
290
- parts: [
291
- {
292
- type: 'text',
293
- text: prompt
294
- }
295
- ]
296
- }
297
- ],
298
- }
299
- })
300
-
301
- return createUIMessageStreamResponse({ stream });
302
- }
303
- })
304
- ]
305
- }
306
- });
307
- ```
308
-
309
- **Next.js**:
310
-
311
- ```ts
312
- import { handleChatStream } from '@mastra/ai-sdk';
313
- import { createUIMessageStreamResponse } from 'ai';
314
- import { mastra } from '@/src/mastra';
315
-
316
- // Allow streaming responses up to 30 seconds
317
- export const maxDuration = 30;
318
-
319
- export async function POST(req: Request) {
320
- const { prompt }: { prompt: string } = await req.json();
321
-
322
- const stream = await handleChatStream({
323
- mastra,
324
- agentId: 'weatherAgent',
325
- params: {
326
- messages: [
327
- {
328
- id: "1",
329
- role: 'user',
330
- parts: [
331
- {
332
- type: 'text',
333
- text: prompt
334
- }
335
- ]
336
- }
337
- ],
338
- },
339
- });
340
- return createUIMessageStreamResponse({ stream });
341
- }
342
- ```
343
-
344
- ## Custom UI
345
-
346
- Custom UI (also known as Generative UI) allows you to render custom React components based on data streamed from Mastra. Instead of displaying raw text or JSON, you can create visual components for tool outputs, workflow progress, agent network execution, and custom events.
347
-
348
- Use Custom UI when you want to:
349
-
350
- - Render tool outputs as visual components (e.g., a weather card instead of JSON)
351
- - Display workflow step progress with status indicators
352
- - Visualize agent network execution with step-by-step updates
353
- - Show progress indicators or status updates during long-running operations
354
-
355
- ### Data part types
356
-
357
- Mastra streams data to the frontend as "parts" within messages. Each part has a `type` that determines how to render it. The `@mastra/ai-sdk` package transforms Mastra streams into AI SDK-compatible [UI Message DataParts](https://ai-sdk.dev/docs/reference/ai-sdk-core/ui-message#datauipart).
358
-
359
- | Data Part Type | Source | Description |
360
- | -------------------- | ----------------------- | ---------------------------------------------------------------------------------- |
361
- | `tool-{toolKey}` | AI SDK built-in | Tool invocation with states: `input-available`, `output-available`, `output-error` |
362
- | `data-workflow` | `workflowRoute()` | Workflow execution with step inputs, outputs, and status |
363
- | `data-network` | `networkRoute()` | Agent network execution with ordered steps and outputs |
364
- | `data-tool-agent` | Nested agent in tool | Agent output streamed from within a tool's `execute()` |
365
- | `data-tool-workflow` | Nested workflow in tool | Workflow output streamed from within a tool's `execute()` |
366
- | `data-tool-network` | Nested network in tool | Network output streamed from within a tool's `execute()` |
367
- | `data-{custom}` | `writer.custom()` | Custom events for progress indicators, status updates, etc. |
368
-
369
- ### Rendering tool outputs
370
-
371
- AI SDK automatically creates `tool-{toolKey}` parts when an agent calls a tool. These parts include the tool's state and output, which you can use to render custom components.
372
-
373
- The tool part cycles through states:
374
-
375
- - `input-streaming`: Tool input is being streamed (when tool call streaming is enabled)
376
- - `input-available`: Tool has been called with complete input, waiting for execution
377
- - `output-available`: Tool execution completed with output
378
- - `output-error`: Tool execution failed
379
-
380
- Here's an example of rendering a weather tool's output as a custom `WeatherCard` component.
381
-
382
- **Backend**:
383
-
384
- Define a tool with an `outputSchema` so the frontend knows the shape of the data to render.
385
-
386
- ```typescript
387
- import { createTool } from "@mastra/core/tools";
388
- import { z } from "zod";
389
-
390
- export const weatherTool = createTool({
391
- id: "get-weather",
392
- description: "Get current weather for a location",
393
- inputSchema: z.object({
394
- location: z.string().describe("The location to get the weather for"),
395
- }),
396
- outputSchema: z.object({
397
- temperature: z.number(),
398
- feelsLike: z.number(),
399
- humidity: z.number(),
400
- windSpeed: z.number(),
401
- conditions: z.string(),
402
- location: z.string(),
403
- }),
404
- execute: async (inputData) => {
405
- const response = await fetch(
406
- `https://api.weatherapi.com/v1/current.json?key=${process.env.WEATHER_API_KEY}&q=${inputData.location}`
407
- );
408
- const data = await response.json();
409
- return {
410
- temperature: data.current.temp_c,
411
- feelsLike: data.current.feelslike_c,
412
- humidity: data.current.humidity,
413
- windSpeed: data.current.wind_kph,
414
- conditions: data.current.condition.text,
415
- location: data.location.name,
416
- };
417
- },
418
- });
419
- ```
420
-
421
- **Frontend**:
422
-
423
- Check for `tool-{toolKey}` parts in the message and render a custom component based on the tool's state and output.
424
-
425
- ```typescript
426
- import { useChat } from "@ai-sdk/react";
427
- import { DefaultChatTransport } from "ai";
428
- import { WeatherCard } from "./weather-card";
429
- import { Loader } from "./loader";
430
-
431
- export function Chat() {
432
- const { messages, sendMessage } = useChat({
433
- transport: new DefaultChatTransport({
434
- api: "http://localhost:4111/chat/weatherAgent",
435
- }),
436
- });
437
-
438
- return (
439
- <div>
440
- {messages.map((message) => (
441
- <div key={message.id}>
442
- {message.parts.map((part, index) => {
443
- // Handle user text messages
444
- if (part.type === "text" && message.role === "user") {
445
- return <p key={index}>{part.text}</p>;
446
- }
447
-
448
- // Handle weather tool output
449
- if (part.type === "tool-weatherTool") {
450
- switch (part.state) {
451
- case "input-available":
452
- return <Loader key={index} />;
453
- case "output-available":
454
- return <WeatherCard key={index} {...part.output} />;
455
- case "output-error":
456
- return <div key={index}>Error: {part.errorText}</div>;
457
- default:
458
- return null;
459
- }
460
- }
461
-
462
- return null;
463
- })}
464
- </div>
465
- ))}
466
- </div>
467
- );
468
- }
469
- ```
470
-
471
- > **Tip:** The tool part type follows the pattern `tool-{toolKey}`, where `toolKey` is the key used when registering the tool with the agent. For example, if you register tools as `tools: { weatherTool }`, the part type will be `tool-weatherTool`.
472
-
473
- ### Rendering workflow data
474
-
475
- When using `workflowRoute()` or `handleWorkflowStream()`, Mastra emits `data-workflow` parts that contain the workflow's execution state, including step statuses and outputs.
476
-
477
- **Backend**:
478
-
479
- Define a workflow with multiple steps that will emit `data-workflow` parts as it executes.
480
-
481
- ```typescript
482
- import { createStep, createWorkflow } from "@mastra/core/workflows";
483
- import { z } from "zod";
484
-
485
- const fetchWeather = createStep({
486
- id: "fetch-weather",
487
- inputSchema: z.object({
488
- location: z.string(),
489
- }),
490
- outputSchema: z.object({
491
- temperature: z.number(),
492
- conditions: z.string(),
493
- }),
494
- execute: async ({ inputData }) => {
495
- // Fetch weather data...
496
- return { temperature: 22, conditions: "Sunny" };
497
- },
498
- });
499
-
500
- const planActivities = createStep({
501
- id: "plan-activities",
502
- inputSchema: z.object({
503
- temperature: z.number(),
504
- conditions: z.string(),
505
- }),
506
- outputSchema: z.object({
507
- activities: z.string(),
508
- }),
509
- execute: async ({ inputData, mastra }) => {
510
- const agent = mastra?.getAgent("activityAgent");
511
- const response = await agent?.generate(
512
- `Suggest activities for ${inputData.conditions} weather at ${inputData.temperature}°C`
513
- );
514
- return { activities: response?.text || "" };
515
- },
516
- });
517
-
518
- export const activitiesWorkflow = createWorkflow({
519
- id: "activities-workflow",
520
- inputSchema: z.object({
521
- location: z.string(),
522
- }),
523
- outputSchema: z.object({
524
- activities: z.string(),
525
- }),
526
- })
527
- .then(fetchWeather)
528
- .then(planActivities);
529
-
530
- activitiesWorkflow.commit();
531
- ```
532
-
533
- Register the workflow with Mastra and expose it via `workflowRoute()` to stream workflow events to the frontend.
534
-
535
- ```typescript
536
- import { Mastra } from "@mastra/core";
537
- import { workflowRoute } from "@mastra/ai-sdk";
538
-
539
- export const mastra = new Mastra({
540
- workflows: { activitiesWorkflow },
541
- server: {
542
- apiRoutes: [
543
- workflowRoute({
544
- path: "/workflow/activitiesWorkflow",
545
- workflow: "activitiesWorkflow",
546
- }),
547
- ],
548
- },
549
- });
550
- ```
551
-
552
- **Frontend**:
553
-
554
- Check for `data-workflow` parts and render each step's status and output using the `WorkflowDataPart` type for type safety.
555
-
556
- ```typescript
557
- import { useChat } from "@ai-sdk/react";
558
- import { DefaultChatTransport } from "ai";
559
- import type { WorkflowDataPart } from "@mastra/ai-sdk";
560
-
561
- type WorkflowData = WorkflowDataPart["data"];
562
- type StepStatus = "running" | "success" | "failed" | "suspended" | "waiting";
563
-
564
- function StepIndicator({ name, status, output }: {
565
- name: string;
566
- status: StepStatus;
567
- output: unknown;
568
- }) {
569
- return (
570
- <div className="step">
571
- <div className="step-header">
572
- <span>{name}</span>
573
- <span className={`status status-${status}`}>{status}</span>
574
- </div>
575
- {status === "success" && output && (
576
- <pre>{JSON.stringify(output, null, 2)}</pre>
577
- )}
578
- </div>
579
- );
580
- }
581
-
582
- export function WorkflowChat() {
583
- const { messages, sendMessage, status } = useChat({
584
- transport: new DefaultChatTransport({
585
- api: "http://localhost:4111/workflow/activitiesWorkflow",
586
- prepareSendMessagesRequest: ({ messages }) => ({
587
- body: {
588
- inputData: {
589
- location: messages[messages.length - 1]?.parts[0]?.text,
590
- },
591
- },
592
- }),
593
- }),
594
- });
595
-
596
- return (
597
- <div>
598
- {messages.map((message) => (
599
- <div key={message.id}>
600
- {message.parts.map((part, index) => {
601
- if (part.type === "data-workflow") {
602
- const workflowData = part.data as WorkflowData;
603
- const steps = Object.values(workflowData.steps);
604
-
605
- return (
606
- <div key={index} className="workflow-progress">
607
- <h3>Workflow: {workflowData.name}</h3>
608
- <p>Status: {workflowData.status}</p>
609
- {steps.map((step) => (
610
- <StepIndicator
611
- key={step.name}
612
- name={step.name}
613
- status={step.status}
614
- output={step.output}
615
- />
616
- ))}
617
- </div>
618
- );
619
- }
620
- return null;
621
- })}
622
- </div>
623
- ))}
624
- </div>
625
- );
626
- }
627
- ```
628
-
629
- For more details on workflow streaming, see [Workflow Streaming](https://mastra.ai/docs/streaming/workflow-streaming).
630
-
631
- ### Rendering network data
632
-
633
- When using `networkRoute()` or `handleNetworkStream()`, Mastra emits `data-network` parts that contain the agent network's execution state, including which agents were called and their outputs.
634
-
635
- **Backend**:
636
-
637
- Register agents with Mastra and expose the routing agent via `networkRoute()` to stream network execution events to the frontend.
638
-
639
- ```typescript
640
- import { Mastra } from "@mastra/core";
641
- import { networkRoute } from "@mastra/ai-sdk";
642
-
643
- export const mastra = new Mastra({
644
- agents: { routingAgent, researchAgent, weatherAgent },
645
- server: {
646
- apiRoutes: [
647
- networkRoute({
648
- path: "/network",
649
- agent: "routingAgent",
650
- }),
651
- ],
652
- },
653
- });
654
- ```
655
-
656
- **Frontend**:
657
-
658
- Check for `data-network` parts and render each agent's execution step using the `NetworkDataPart` type for type safety.
659
-
660
- ```typescript
661
- import { useChat } from "@ai-sdk/react";
662
- import { DefaultChatTransport } from "ai";
663
- import type { NetworkDataPart } from "@mastra/ai-sdk";
664
-
665
- type NetworkData = NetworkDataPart["data"];
666
-
667
- function AgentStep({ step }: { step: NetworkData["steps"][number] }) {
668
- return (
669
- <div className="agent-step">
670
- <div className="step-header">
671
- <span className="agent-name">{step.name}</span>
672
- <span className={`status status-${step.status}`}>{step.status}</span>
673
- </div>
674
- {step.input && (
675
- <div className="step-input">
676
- <strong>Input:</strong>
677
- <pre>{JSON.stringify(step.input, null, 2)}</pre>
678
- </div>
679
- )}
680
- {step.output && (
681
- <div className="step-output">
682
- <strong>Output:</strong>
683
- <pre>{typeof step.output === "string" ? step.output : JSON.stringify(step.output, null, 2)}</pre>
684
- </div>
685
- )}
686
- </div>
687
- );
688
- }
689
-
690
- export function NetworkChat() {
691
- const { messages, sendMessage, status } = useChat({
692
- transport: new DefaultChatTransport({
693
- api: "http://localhost:4111/network",
694
- }),
695
- });
696
-
697
- return (
698
- <div>
699
- {messages.map((message) => (
700
- <div key={message.id}>
701
- {message.parts.map((part, index) => {
702
- if (part.type === "data-network") {
703
- const networkData = part.data as NetworkData;
704
-
705
- return (
706
- <div key={index} className="network-execution">
707
- <div className="network-header">
708
- <h3>Agent Network: {networkData.name}</h3>
709
- <span className={`status status-${networkData.status}`}>
710
- {networkData.status}
711
- </span>
712
- </div>
713
- <div className="network-steps">
714
- {networkData.steps.map((step, stepIndex) => (
715
- <AgentStep key={stepIndex} step={step} />
716
- ))}
717
- </div>
718
- </div>
719
- );
720
- }
721
- return null;
722
- })}
723
- </div>
724
- ))}
725
- </div>
726
- );
727
- }
728
- ```
729
-
730
- For more details on agent networks, see [Agent Networks](https://mastra.ai/docs/agents/networks).
731
-
732
- ### Custom events
733
-
734
- Use `writer.custom()` within a tool's `execute()` function to emit custom data parts. This is useful for progress indicators, status updates, or any custom UI updates during tool execution.
735
-
736
- Custom event types must start with `data-` to be recognized as data parts.
737
-
738
- > **Warning:** You must `await` the `writer.custom()` call, otherwise you may encounter a `WritableStream is locked` error.
739
-
740
- **Backend**:
741
-
742
- Use `writer.custom()` inside the tool's `execute()` function to emit custom `data-` prefixed events at different stages of execution.
743
-
744
- ```typescript
745
- import { createTool } from "@mastra/core/tools";
746
- import { z } from "zod";
747
-
748
- export const taskTool = createTool({
749
- id: "process-task",
750
- description: "Process a task with progress updates",
751
- inputSchema: z.object({
752
- task: z.string().describe("The task to process"),
753
- }),
754
- outputSchema: z.object({
755
- result: z.string(),
756
- status: z.string(),
757
- }),
758
- execute: async (inputData, context) => {
759
- const { task } = inputData;
760
-
761
- // Emit "in progress" custom event
762
- await context?.writer?.custom({
763
- type: "data-tool-progress",
764
- data: {
765
- status: "in-progress",
766
- message: "Gathering information...",
767
- },
768
- });
769
-
770
- // Simulate work
771
- await new Promise((resolve) => setTimeout(resolve, 3000));
772
-
773
- // Emit "done" custom event
774
- await context?.writer?.custom({
775
- type: "data-tool-progress",
776
- data: {
777
- status: "done",
778
- message: `Successfully processed "${task}"`,
779
- },
780
- });
781
-
782
- return {
783
- result: `Task "${task}" has been completed successfully!`,
784
- status: "completed",
785
- };
786
- },
787
- });
788
- ```
789
-
790
- **Frontend**:
791
-
792
- Filter message parts for your custom event type and render a progress indicator that updates as new events arrive.
793
-
794
- ```typescript
795
- import { useChat } from "@ai-sdk/react";
796
- import { DefaultChatTransport } from "ai";
797
- import { useMemo } from "react";
798
-
799
- type ProgressData = {
800
- status: "in-progress" | "done";
801
- message: string;
802
- };
803
-
804
- function ProgressIndicator({ progress }: { progress: ProgressData }) {
805
- return (
806
- <div className="progress-indicator">
807
- {progress.status === "in-progress" ? (
808
- <span className="spinner" />
809
- ) : (
810
- <span className="check-icon" />
811
- )}
812
- <span className={`status-${progress.status}`}>{progress.message}</span>
813
- </div>
814
- );
815
- }
816
-
817
- export function TaskChat() {
818
- const { messages, sendMessage } = useChat({
819
- transport: new DefaultChatTransport({
820
- api: "http://localhost:4111/chat/taskAgent",
821
- }),
822
- });
823
-
824
- // Extract the latest progress event from messages
825
- const latestProgress = useMemo(() => {
826
- const allProgressParts: ProgressData[] = [];
827
- messages.forEach((message) => {
828
- message.parts.forEach((part) => {
829
- if (part.type === "data-tool-progress") {
830
- allProgressParts.push(part.data as ProgressData);
831
- }
832
- });
833
- });
834
- return allProgressParts[allProgressParts.length - 1];
835
- }, [messages]);
836
-
837
- return (
838
- <div>
839
- {latestProgress && <ProgressIndicator progress={latestProgress} />}
840
- {messages.map((message) => (
841
- <div key={message.id}>
842
- {message.parts.map((part, index) => {
843
- if (part.type === "text") {
844
- return <p key={index}>{part.text}</p>;
845
- }
846
- return null;
847
- })}
848
- </div>
849
- ))}
850
- </div>
851
- );
852
- }
853
- ```
854
-
855
- ### Tool streaming
856
-
857
- Tools can also stream data using `context.writer.write()` for lower-level control, or pipe an agent's stream directly to the tool's writer. For more details, see [Tool Streaming](https://mastra.ai/docs/streaming/tool-streaming).
858
-
859
- ### Examples
860
-
861
- For live examples of Custom UI patterns, visit [Mastra's UI Dojo](https://ui-dojo.mastra.ai/). The repository includes implementations for:
862
-
863
- - [Generative UIs](https://github.com/mastra-ai/ui-dojo/blob/main/src/pages/ai-sdk/generative-user-interfaces.tsx) - Custom components for tool outputs
864
- - [Workflows](https://github.com/mastra-ai/ui-dojo/blob/main/src/pages/ai-sdk/workflow.tsx) - Workflow step visualization
865
- - [Agent Networks](https://github.com/mastra-ai/ui-dojo/blob/main/src/pages/ai-sdk/network.tsx) - Network execution display
866
- - [Custom Events](https://github.com/mastra-ai/ui-dojo/blob/main/src/pages/ai-sdk/generative-user-interfaces-with-custom-events.tsx) - Progress indicators with custom events
867
-
868
- ## Recipes
869
-
870
- ### Stream transformations
871
-
872
- To manually transform Mastra's streams to AI SDK-compatible format, use the [`toAISdkStream()`](https://mastra.ai/reference/ai-sdk/to-ai-sdk-stream) utility. See the [examples](https://mastra.ai/reference/ai-sdk/to-ai-sdk-stream) for concrete usage patterns.
873
-
874
- ### Loading historical messages
875
-
876
- When loading messages from Mastra's memory to display in a chat UI, use [`toAISdkV5Messages()`](https://mastra.ai/reference/ai-sdk/to-ai-sdk-v5-messages) or [`toAISdkV4Messages()`](https://mastra.ai/reference/ai-sdk/to-ai-sdk-v4-messages) to convert them to the appropriate AI SDK format for `useChat()`'s `initialMessages`.
877
-
878
- ### Passing additional data
879
-
880
- [`sendMessage()`](https://ai-sdk.dev/docs/reference/ai-sdk-ui/use-chat#send-message) allows you to pass additional data from the frontend to Mastra. This data can then be used on the server as [`RequestContext`](https://mastra.ai/docs/server/request-context).
881
-
882
- Here's an example of the frontend code:
883
-
884
- ```typescript
885
- import { useChat } from "@ai-sdk/react";
886
- import { useState } from "react";
887
- import { DefaultChatTransport } from 'ai';
888
-
889
- export function ChatAdditional() {
890
- const [inputValue, setInputValue] = useState('')
891
- const { messages, sendMessage } = useChat({
892
- transport: new DefaultChatTransport({
893
- api: 'http://localhost:4111/chat-extra',
894
- }),
895
- });
896
-
897
- const handleFormSubmit = (e: React.FormEvent) => {
898
- e.preventDefault();
899
- sendMessage({ text: inputValue }, {
900
- body: {
901
- data: {
902
- userId: "user123",
903
- preferences: {
904
- language: "en",
905
- temperature: "celsius"
906
- }
907
- }
908
- }
909
- });
910
- };
911
-
912
- return (
913
- <div>
914
- <pre>{JSON.stringify(messages, null, 2)}</pre>
915
- <form onSubmit={handleFormSubmit}>
916
- <input value={inputValue} onChange={e => setInputValue(e.target.value)} placeholder="Name of the city" />
917
- </form>
918
- </div>
919
- );
920
- }
921
- ```
922
-
923
- Two examples on how to implement the backend portion of it.
924
-
925
- **Mastra Server**:
926
-
927
- Add a `chatRoute()` to your Mastra configuration like shown above. Then, add a server-level middleware:
928
-
929
- ```typescript
930
- import { Mastra } from "@mastra/core";
931
-
932
- export const mastra = new Mastra({
933
- server: {
934
- middleware: [
935
- async (c, next) => {
936
- const requestContext = c.get("requestContext");
937
-
938
- if (c.req.method === "POST") {
939
- const clonedReq = c.req.raw.clone();
940
- const body = await clonedReq.json();
941
-
942
- if (body?.data) {
943
- for (const [key, value] of Object.entries(body.data)) {
944
- requestContext.set(key, value);
945
- }
946
- }
947
- }
948
- await next();
949
- },
950
- ],
951
- },
952
- });
953
- ```
954
-
955
- > **Info:** You can access this data in your tools via the `requestContext` parameter. See the [Request Context documentation](https://mastra.ai/docs/server/request-context) for more details.
956
-
957
- **Next.js**:
958
-
959
- ```typescript
960
- import { handleChatStream } from '@mastra/ai-sdk';
961
- import { RequestContext } from "@mastra/core/request-context";
962
- import { createUIMessageStreamResponse } from 'ai';
963
- import { mastra } from '@/src/mastra';
964
-
965
- export async function POST(req: Request) {
966
- const { messages, data } = await req.json();
967
-
968
- const requestContext = new RequestContext();
969
-
970
- if (data) {
971
- for (const [key, value] of Object.entries(data)) {
972
- requestContext.set(key, value);
973
- }
974
- }
975
-
976
- const stream = await handleChatStream({
977
- mastra,
978
- agentId: 'weatherAgent',
979
- params: {
980
- messages,
981
- requestContext,
982
- },
983
- });
984
- return createUIMessageStreamResponse({ stream });
985
- }
986
- ```
987
-
988
- ### Workflow suspend/resume with user approval
989
-
990
- Workflows can suspend execution and wait for user input before continuing. This is useful for approval flows, confirmations, or any human-in-the-loop scenario.
991
-
992
- The workflow uses:
993
-
994
- - `suspendSchema` / `resumeSchema` - Define the data structure for suspend payload and resume input
995
- - `suspend()` - Pauses the workflow and sends the suspend payload to the UI
996
- - `resumeData` - Contains the user's response when the workflow resumes
997
- - `bail()` - Exits the workflow early (e.g., when user rejects)
998
-
999
- **Backend**:
1000
-
1001
- Create a workflow step that suspends for approval. The step checks `resumeData` to determine if it's resuming, and calls `suspend()` on first execution.
1002
-
1003
- ```typescript
1004
- import { createStep, createWorkflow } from "@mastra/core/workflows";
1005
- import { z } from "zod";
1006
-
1007
- const requestApproval = createStep({
1008
- id: "request-approval",
1009
- inputSchema: z.object({ requestId: z.string(), summary: z.string() }),
1010
- outputSchema: z.object({
1011
- approved: z.boolean(),
1012
- requestId: z.string(),
1013
- approvedBy: z.string().optional(),
1014
- }),
1015
- resumeSchema: z.object({
1016
- approved: z.boolean(),
1017
- approverName: z.string().optional(),
1018
- }),
1019
- suspendSchema: z.object({
1020
- message: z.string(),
1021
- requestId: z.string(),
1022
- }),
1023
- execute: async ({ inputData, resumeData, suspend, bail }) => {
1024
- // User rejected - bail out
1025
- if (resumeData?.approved === false) {
1026
- return bail({ message: "Request rejected" });
1027
- }
1028
- // User approved - continue
1029
- if (resumeData?.approved) {
1030
- return {
1031
- approved: true,
1032
- requestId: inputData.requestId,
1033
- approvedBy: resumeData.approverName || "User",
1034
- };
1035
- }
1036
- // First execution - suspend and wait
1037
- return await suspend({
1038
- message: `Please approve: ${inputData.summary}`,
1039
- requestId: inputData.requestId,
1040
- });
1041
- },
1042
- });
1043
-
1044
- export const approvalWorkflow = createWorkflow({
1045
- id: "approval-workflow",
1046
- inputSchema: z.object({ requestId: z.string(), summary: z.string() }),
1047
- outputSchema: z.object({
1048
- approved: z.boolean(),
1049
- requestId: z.string(),
1050
- approvedBy: z.string().optional(),
1051
- }),
1052
- })
1053
- .then(requestApproval);
1054
-
1055
- approvalWorkflow.commit();
1056
- ```
1057
-
1058
- Register the workflow. Storage is required for suspend/resume to persist state.
1059
-
1060
- ```typescript
1061
- import { Mastra } from "@mastra/core";
1062
- import { workflowRoute } from "@mastra/ai-sdk";
1063
- import { LibSQLStore } from "@mastra/libsql";
1064
-
1065
- export const mastra = new Mastra({
1066
- workflows: { approvalWorkflow },
1067
- storage: new LibSQLStore({
1068
- url: "file:../mastra.db",
1069
- }),
1070
- server: {
1071
- apiRoutes: [
1072
- workflowRoute({ path: "/workflow/approvalWorkflow", workflow: "approvalWorkflow" }),
1073
- ],
1074
- },
1075
- });
1076
- ```
1077
-
1078
- **Frontend**:
1079
-
1080
- Detect when the workflow is suspended and send resume data with `runId`, `step`, and `resumeData`.
1081
-
1082
- ```typescript
1083
- import { useChat } from "@ai-sdk/react";
1084
- import { DefaultChatTransport } from "ai";
1085
- import { useMemo, useState } from "react";
1086
- import type { WorkflowDataPart } from "@mastra/ai-sdk";
1087
-
1088
- type WorkflowData = WorkflowDataPart["data"];
1089
-
1090
- export function ApprovalWorkflow() {
1091
- const [requestId, setRequestId] = useState("");
1092
- const [summary, setSummary] = useState("");
1093
-
1094
- const { messages, sendMessage, setMessages, status } = useChat({
1095
- transport: new DefaultChatTransport({
1096
- api: "http://localhost:4111/workflow/approvalWorkflow",
1097
- prepareSendMessagesRequest: ({ messages }) => {
1098
- const lastMessage = messages[messages.length - 1];
1099
- const text = lastMessage.parts.find((p) => p.type === "text")?.text;
1100
- const metadata = lastMessage.metadata as Record<string, string>;
1101
-
1102
- // Resuming: send runId, step, and resumeData
1103
- if (text === "Approve" || text === "Reject") {
1104
- return {
1105
- body: {
1106
- runId: metadata.runId,
1107
- step: "request-approval",
1108
- resumeData: { approved: text === "Approve" },
1109
- },
1110
- };
1111
- }
1112
- // Starting: send inputData
1113
- return {
1114
- body: { inputData: { requestId: metadata.requestId, summary: metadata.summary } },
1115
- };
1116
- },
1117
- }),
1118
- });
1119
-
1120
- // Find suspended workflow
1121
- const suspended = useMemo(() => {
1122
- for (const m of messages) {
1123
- for (const p of m.parts) {
1124
- if (p.type === "data-workflow" && (p.data as WorkflowData).status === "suspended") {
1125
- return { data: p.data as WorkflowData, runId: p.id };
1126
- }
1127
- }
1128
- }
1129
- return null;
1130
- }, [messages]);
1131
-
1132
- const handleApprove = () => {
1133
- setMessages([]);
1134
- sendMessage({ text: "Approve", metadata: { runId: suspended?.runId } });
1135
- };
1136
-
1137
- const handleReject = () => {
1138
- setMessages([]);
1139
- sendMessage({ text: "Reject", metadata: { runId: suspended?.runId } });
1140
- };
1141
-
1142
- return (
1143
- <div>
1144
- {!suspended ? (
1145
- <form onSubmit={(e) => {
1146
- e.preventDefault();
1147
- setMessages([]);
1148
- sendMessage({ text: "Start", metadata: { requestId, summary } });
1149
- }}>
1150
- <input value={requestId} onChange={(e) => setRequestId(e.target.value)} placeholder="Request ID" />
1151
- <input value={summary} onChange={(e) => setSummary(e.target.value)} placeholder="Summary" />
1152
- <button type="submit" disabled={status !== "ready"}>Submit</button>
1153
- </form>
1154
- ) : (
1155
- <div>
1156
- <p>{(suspended.data.steps["request-approval"]?.suspendPayload as { message: string })?.message}</p>
1157
- <button onClick={handleApprove}>Approve</button>
1158
- <button onClick={handleReject}>Reject</button>
1159
- </div>
1160
- )}
1161
- </div>
1162
- );
1163
- }
1164
- ```
1165
-
1166
- Key points:
1167
-
1168
- - The suspend payload is accessible via `step.suspendPayload`
1169
- - To resume, send `runId`, `step` (the step ID), and `resumeData` in the request body
1170
- - Storage must be configured for suspend/resume to persist workflow state
1171
-
1172
- For a complete implementation, see the [workflow-suspend-resume example](https://github.com/mastra-ai/ui-dojo/blob/main/src/pages/ai-sdk/workflow-suspend-resume.tsx) in UI Dojo.
1173
-
1174
- ### Nested agent streams in tools
1175
-
1176
- Tools can call agents internally and stream the agent's output back to the UI. This creates `data-tool-agent` parts that can be rendered alongside the tool's final output.
1177
-
1178
- The pattern uses:
1179
-
1180
- - `context.mastra.getAgent()` - Get an agent instance from within a tool
1181
- - `agent.stream()` - Stream the agent's response
1182
- - `stream.fullStream.pipeTo(context.writer)` - Pipe the agent's stream to the tool's writer
1183
-
1184
- **Backend**:
1185
-
1186
- Create a tool that calls an agent and pipes its stream to the tool's writer.
1187
-
1188
- ```typescript
1189
- import { createTool } from "@mastra/core/tools";
1190
- import { z } from "zod";
1191
-
1192
- export const nestedAgentTool = createTool({
1193
- id: "nested-agent-stream",
1194
- description: "Analyze weather using a nested agent",
1195
- inputSchema: z.object({
1196
- city: z.string().describe("The city to analyze"),
1197
- }),
1198
- outputSchema: z.object({
1199
- summary: z.string(),
1200
- }),
1201
- execute: async (inputData, context) => {
1202
- const agent = context?.mastra?.getAgent("weatherAgent");
1203
- if (!agent) {
1204
- return { summary: "Weather agent not available" };
1205
- }
1206
-
1207
- const stream = await agent.stream(
1208
- `Analyze the weather in ${inputData.city} and provide a summary.`
1209
- );
1210
-
1211
- // Pipe the agent's stream to emit data-tool-agent parts
1212
- await stream.fullStream.pipeTo(context!.writer!);
1213
-
1214
- return { summary: (await stream.text) ?? "No summary available" };
1215
- },
1216
- });
1217
- ```
1218
-
1219
- Create an agent that uses this tool.
1220
-
1221
- ```typescript
1222
- import { Agent } from "@mastra/core/agent";
1223
- import { nestedAgentTool } from "../tools/nested-agent-tool";
1224
-
1225
- export const forecastAgent = new Agent({
1226
- id: "forecast-agent",
1227
- instructions: "Use the nested-agent-stream tool when asked about weather.",
1228
- model: "openai/gpt-4o-mini",
1229
- tools: { nestedAgentTool },
1230
- });
1231
- ```
1232
-
1233
- **Frontend**:
1234
-
1235
- Handle `data-tool-agent` parts to display the nested agent's streamed output.
1236
-
1237
- ```typescript
1238
- import { useChat } from "@ai-sdk/react";
1239
- import { DefaultChatTransport } from "ai";
1240
- import { useState } from "react";
1241
- import type { AgentDataPart } from "@mastra/ai-sdk";
1242
-
1243
- export function NestedAgentChat() {
1244
- const [input, setInput] = useState("");
1245
- const { messages, sendMessage, status } = useChat({
1246
- transport: new DefaultChatTransport({
1247
- api: "http://localhost:4111/chat/forecastAgent",
1248
- }),
1249
- });
1250
-
1251
- return (
1252
- <div>
1253
- <form onSubmit={(e) => {
1254
- e.preventDefault();
1255
- sendMessage({ text: input });
1256
- setInput("");
1257
- }}>
1258
- <input value={input} onChange={(e) => setInput(e.target.value)} placeholder="Enter a city" />
1259
- <button type="submit" disabled={status !== "ready"}>Get Forecast</button>
1260
- </form>
1261
-
1262
- {messages.map((message) => (
1263
- <div key={message.id}>
1264
- {message.parts.map((part, index) => {
1265
- if (part.type === "text") {
1266
- return <p key={index}>{part.text}</p>;
1267
- }
1268
- if (part.type === "data-tool-agent") {
1269
- const { id, data } = part as AgentDataPart;
1270
- return (
1271
- <div key={index} className="nested-agent">
1272
- <strong>Nested Agent: {id}</strong>
1273
- {data.text && <p>{data.text}</p>}
1274
- </div>
1275
- );
1276
- }
1277
- return null;
1278
- })}
1279
- </div>
1280
- ))}
1281
- </div>
1282
- );
1283
- }
1284
- ```
1285
-
1286
- Key points:
1287
-
1288
- - Piping `fullStream` to `context.writer` creates `data-tool-agent` parts
1289
- - The `AgentDataPart` has `id` (on the part) and `data.text` (the agent's streamed text)
1290
- - The tool still returns its own output after the stream completes
1291
-
1292
- For a complete implementation, see the [tool-nested-streams example](https://github.com/mastra-ai/ui-dojo/blob/main/src/pages/ai-sdk/tool-nested-streams.tsx) in UI Dojo.
1293
-
1294
- ### Streaming agent text from workflow steps
1295
-
1296
- Workflow steps can stream an agent's text output in real-time by piping the agent's stream to the step's `writer`. This lets users see the agent "thinking" while the workflow executes, rather than waiting for the step to complete.
1297
-
1298
- The pattern uses:
1299
-
1300
- - `writer` in workflow step - Pipe the agent's `fullStream` to the step's writer
1301
- - `text` and `data-workflow` parts - The frontend receives streaming text alongside step progress
1302
-
1303
- **Backend**:
1304
-
1305
- Create a workflow step that streams an agent's response by piping to the step's `writer`.
1306
-
1307
- ```typescript
1308
- import { createStep, createWorkflow } from "@mastra/core/workflows";
1309
- import { z } from "zod";
1310
- import { weatherAgent } from "../agents/weather-agent";
1311
-
1312
- const analyzeWeather = createStep({
1313
- id: "analyze-weather",
1314
- inputSchema: z.object({ location: z.string() }),
1315
- outputSchema: z.object({ analysis: z.string(), location: z.string() }),
1316
- execute: async ({ inputData, writer }) => {
1317
- const response = await weatherAgent.stream(
1318
- `Analyze the weather in ${inputData.location} and provide insights.`
1319
- );
1320
-
1321
- // Pipe agent stream to step writer for real-time text streaming
1322
- await response.fullStream.pipeTo(writer);
1323
-
1324
- return {
1325
- analysis: await response.text,
1326
- location: inputData.location,
1327
- };
1328
- },
1329
- });
1330
-
1331
- const calculateScore = createStep({
1332
- id: "calculate-score",
1333
- inputSchema: z.object({ analysis: z.string(), location: z.string() }),
1334
- outputSchema: z.object({ score: z.number(), summary: z.string() }),
1335
- execute: async ({ inputData }) => {
1336
- const score = inputData.analysis.includes("sunny") ? 85 : 50;
1337
- return { score, summary: `Comfort score for ${inputData.location}: ${score}/100` };
1338
- },
1339
- });
1340
-
1341
- export const weatherWorkflow = createWorkflow({
1342
- id: "weather-workflow",
1343
- inputSchema: z.object({ location: z.string() }),
1344
- outputSchema: z.object({ score: z.number(), summary: z.string() }),
1345
- })
1346
- .then(analyzeWeather)
1347
- .then(calculateScore);
1348
-
1349
- weatherWorkflow.commit();
1350
- ```
1351
-
1352
- Register the workflow with a `workflowRoute()`. Text streaming is enabled by default.
1353
-
1354
- ```typescript
1355
- import { Mastra } from "@mastra/core";
1356
- import { workflowRoute } from "@mastra/ai-sdk";
1357
-
1358
- export const mastra = new Mastra({
1359
- agents: { weatherAgent },
1360
- workflows: { weatherWorkflow },
1361
- server: {
1362
- apiRoutes: [
1363
- workflowRoute({ path: "/workflow/weather", workflow: "weatherWorkflow" }),
1364
- ],
1365
- },
1366
- });
1367
- ```
1368
-
1369
- **Frontend**:
1370
-
1371
- Render both `text` parts (streaming agent output) and `data-workflow` parts (step progress).
1372
-
1373
- ```typescript
1374
- import { useChat } from "@ai-sdk/react";
1375
- import { DefaultChatTransport } from "ai";
1376
- import { useState } from "react";
1377
- import type { WorkflowDataPart } from "@mastra/ai-sdk";
1378
-
1379
- type WorkflowData = WorkflowDataPart["data"];
1380
-
1381
- export function WeatherWorkflow() {
1382
- const [location, setLocation] = useState("");
1383
- const { messages, sendMessage, status } = useChat({
1384
- transport: new DefaultChatTransport({
1385
- api: "http://localhost:4111/workflow/weather",
1386
- prepareSendMessagesRequest: ({ messages }) => ({
1387
- body: {
1388
- inputData: {
1389
- location: messages[messages.length - 1].parts.find((p) => p.type === "text")?.text,
1390
- },
1391
- },
1392
- }),
1393
- }),
1394
- });
1395
-
1396
- return (
1397
- <div>
1398
- <form onSubmit={(e) => {
1399
- e.preventDefault();
1400
- sendMessage({ text: location });
1401
- setLocation("");
1402
- }}>
1403
- <input value={location} onChange={(e) => setLocation(e.target.value)} placeholder="Enter city" />
1404
- <button type="submit" disabled={status !== "ready"}>Analyze</button>
1405
- </form>
1406
-
1407
- {messages.map((message) => (
1408
- <div key={message.id}>
1409
- {message.parts.map((part, index) => {
1410
- // Streaming agent text
1411
- if (part.type === "text" && message.role === "assistant") {
1412
- return (
1413
- <div key={index}>
1414
- {status === "streaming" && <p><em>Agent analyzing...</em></p>}
1415
- <p>{part.text}</p>
1416
- </div>
1417
- );
1418
- }
1419
- // Workflow step progress
1420
- if (part.type === "data-workflow") {
1421
- const workflow = part.data as WorkflowData;
1422
- return (
1423
- <div key={index}>
1424
- {Object.entries(workflow.steps).map(([stepId, step]) => (
1425
- <div key={stepId}>
1426
- <strong>{stepId}</strong>: {step.status}
1427
- </div>
1428
- ))}
1429
- </div>
1430
- );
1431
- }
1432
- return null;
1433
- })}
1434
- </div>
1435
- ))}
1436
- </div>
1437
- );
1438
- }
1439
- ```
1440
-
1441
- Key points:
1442
-
1443
- - The step's `writer` is available in the `execute` function (not via `context`)
1444
- - `includeTextStreamParts` defaults to `true` on `workflowRoute()`, so text streams by default
1445
- - Text parts stream in real-time while `data-workflow` parts update with step status
1446
-
1447
- For a complete implementation, see the [workflow-agent-text-stream example](https://github.com/mastra-ai/ui-dojo/blob/main/src/pages/ai-sdk/workflow-agent-text-stream.tsx) in UI Dojo.
1448
-
1449
- ### Multi-stage progress with branching workflows
1450
-
1451
- For workflows with conditional branching (e.g., express vs standard shipping), you can track progress across different branches by including a identifier in your custom events.
1452
-
1453
- The UI Dojo example uses a `stage` field in the event data to identify which branch is executing (e.g., `"validation"`, `"standard-processing"`, `"express-processing"`). The frontend groups events by this field to show a pipeline-style progress UI.
1454
-
1455
- See the [branching-workflow.ts](https://github.com/mastra-ai/ui-dojo/blob/main/src/mastra/workflows/branching-workflow.ts) (backend) and [workflow-custom-events.tsx](https://github.com/mastra-ai/ui-dojo/blob/main/src/pages/ai-sdk/workflow-custom-events.tsx) (frontend) in UI Dojo.
1456
-
1457
- ### Progress indicators in agent networks
1458
-
1459
- When using agent networks, you can emit custom progress events from tools used by subagents to show which agent is currently active.
1460
-
1461
- The UI Dojo example includes a `stage` field in the event data to identify which subagent is running (e.g., `"report-generation"`, `"report-review"`). The frontend groups events by this field and displays the latest status for each.
1462
-
1463
- See the [report-generation-tool.ts](https://github.com/mastra-ai/ui-dojo/blob/main/src/mastra/tools/report-generation-tool.ts) (backend) and [agent-network-custom-events.tsx](https://github.com/mastra-ai/ui-dojo/blob/main/src/pages/ai-sdk/agent-network-custom-events.tsx) (frontend) in UI Dojo.