- 需要人工审批环节的 agent 流程:工作流可以挂起、等审批后恢复,这类 suspend/resume 语义自己用 AI SDK 手写要维护一套状态机,Mastra 直接给到图原语
- 多 provider 切换或做模型对比:统一接口接 40+ provider,换模型只改配置;自己封装的话每接一家都要重写一遍 tool-call 和流式解析
- 需要把 agent 行为纳入回归测试:内置 evals 和可观测性,跑完能对比;否则得自己搭 trace 采集加评分管线
- Next.js/Node 项目里做对话式功能:和 React/Next 生态贴合,不用为了 agent 编排再引入一套 Python 服务
mastra
mastra-ai活跃维护 有专家点评用 TypeScript 快速搭建 AI 应用和智能体的现代框架,内置工作流、对话机器人和评测能力,省去自己拼装 LLM 调用链的麻烦。
Mastra is the modern TypeScript framework for AI-powered applications and agents.
专家点评
上手难度:进阶更新于 2026-11-11TypeScript 里把 agent、工作流和 eval 串成一套的框架,替代自己用 AI SDK 拼装编排层
适用场景
踩坑
- 在 monorepo 里跑
mastra dev:issue 里依赖解析不正确的问题被反复提出且讨论量大,多包工作区要先验证 dev server 能否正确解析 workspace 依赖 - 部署到 Cloudflare Workers 这类有体积上限的平台:有 issue 报告升级后 bundle 体积回退十几 MB 直接阻塞部署,选这条路之前先量一下产物大小
- 依赖版本跟进:Zod v4 和 AI SDK v5 的支持都是以大 issue 形式推进的,说明底层依赖升级存在滞后窗口,锁版本时要留意
- 默认端口 4111、创建项目时必须先选 provider,本地多服务并存时容易撞端口
同类对比
要的是纯模型调用层而不想引入编排框架,直接用 Vercel AI SDK;要的是持久化、可重试的后台任务编排而非 agent 图,看 Trigger.dev 这类任务平台。
项目说明
由 README 自动翻译提炼TypeScript 框架,用来构建 AI 应用与智能体,从原型一路做到生产
用 TypeScript 快速搭建 AI 应用和智能体的现代框架,内置工作流、对话机器人和评测能力,省去自己拼装 LLM 调用链的麻烦。
核心能力
- 通过统一接口接入 40+ 模型提供商
- 构建会用工具、自主推理迭代的 Agent
- 用 .then/.branch/.parallel 编排图式工作流
- 支持挂起工作流等待人工审批后恢复
- 内置 evals 与可观测性做持续评估调优
容易踩的坑
需先选定模型提供商(openai/anthropic/google/xai)才能创建项目;开发服务器默认端口为 4111;ee/ 目录下功能生产使用需企业许可证
Highlights
Knowledge v2: page-tree model, richer tools, and server-side sync APIs
Knowledge is now a first-class page tree (pages/notes/pins) with major tool upgrades:
knowledge_list, line/section/grep-style reads inknowledge_read, list pinning (kind: 'list'), and a link index for counting/listing[[links]]. Apps can also sync external content via server APIs likeknowledge.upsertPage()/removePage()and note upserts, with optional vector/hybrid search and chunked embeddings for very long pages.Knowledge Explorer + read-only Knowledge HTTP/JS client APIs (and SSE change stream)
Mastra Server now offers opt-in read-only Knowledge routes (tree/page/graph/search/activity) plus an SSE events stream, with matching
listKnowledge()/getKnowledge()APIs in@mastra/client-js. These routes are scope-gated (and FGA-aware) and enable building Knowledge browsing UIs outside Studio, including link-count/link-edge endpoints when the store supports the link index.Durable agent continuity across API restarts (fencing + shared storage requirement)
Evented durable agents no longer stop when the API process shuts down: workers continue running, clean up, and free threads correctly, with improved run ownership isolation and safer cancellation semantics. To get true cross-process continuity you now need fencing-capable shared storage (e.g.
PostgresStorefrom@mastra/pg) plus shared pubsub/lease infrastructure.Background tasks + MCP: resumable “input required” flows that survive reloads
Suspended background tool calls can now be resumed after reload with persisted open-request metadata, concurrency-safe resume via
suspendedAt, and optional completion notifications that wake idle threads;@mastra/client-jsand@mastra/serveradd resume APIs. MCP also gains “answer task input from chat” behavior (suspends instead of failing when unhandled), plus richer tool results (images/audio/files) viaMCPServer.toolResult.Observability upgrades: streaming latency metrics + richer trace filtering
Trace/span aggregates now support
timeToFirstToken.*andtimeToFirstChunk.*so dashboards can chart streaming latency, gated by store capability. Advanced trace queries also gainrequestId,serviceName, andexperimentIdfilters across core and supported stores, with capabilities surfaced to clients and clearer 501s when a store is too old.Breaking Changes
@mastra/[email protected]: Steps now validateinputSchemaandrequestContextSchemabefore running (can fail runs that previously “succeeded” with wrong input); setvalidateInputs: falseto opt out.- Experimental memory changes:
experimental_subconsciousand Memoryknowledgeoption are removed (now throw); Knowledge must be attached to the Agent, and older Subconscious/Coordinator constructors now throw. knowledge.reindex()is removed; useupsertPage/note writes (andreindexLinks()for link indexing) instead.- Factory (
@mastra/[email protected]): removes work-item claiming APIs (claimKeyremoved; related methods/types removed) as part of allowing the same external item to exist in multiple projects.
Changelog
@mastra/[email protected]
Minor Changes
-
An agent's
scopesfunction can now narrow or replace a run's scopes. It receives the run's incoming scopes (from the call,defaultOptionsand request context) and returns the run's final set. A staticscopeslist is still added to the incoming scopes. The function must keep anyresource:orthread:scope it was given; dropping one throws. (#28353)const agent = new Agent({ id: 'support', name: 'Support', instructions: 'Answer support questions.', model, // Keep identity scopes, drop anything else the caller sent, and add the tenant's org. scopes: ({ scopes, requestContext }) => [ ...scopes.f
查看更新说明
Highlights
MCP Tasks (Storage-backed, restart-safe long-running execution)
@mastra/mcpadds experimental Mastra-storage-backed MCP tasks so long-running tools/agents/workflows can return immediately with a task, be polled/answered/cancelled across instances, and survive restarts with shared storage and unified tracing.Background Tasks for Non-Agent Owners (Retention, Concurrency, Queued Resume)
Mastra background tasks now support non-agent owners (e.g., MCP servers) with per-task
expiresAt/metadataretention, per-owner concurrency overrides, and{ onNoSlot: 'queue' }to queue resumes until capacity frees up (with storage adapters updated to persist the new fields).Observability: Outcomes/Stop Reasons + Model/Provider + TTFT Across Queries and Stores
Observability now records execution
outcome+ typedstopReason(and context), exportsmodel/provider, and measurestimeToFirstTokenMs(TTFT); these fields are queryable/groupable in clients/servers and supported by major stores (ClickHouse/DuckDB/Postgres), enabling better failure analysis and model/provider cost/perf breakdowns.Dashboards and Saved Views as Schemas + UI Rendering/Sharing
Core adds browser-safe schemas for custom dashboard definitions and saved observability list views, while
@mastra/playground-uiintroducesDashboardRendererplus first-class Saved Views for Traces/Spans/Threads/Logs (URL↔view helpers, view picker, and host-provided persistence).Agents + Workspaces: Authenticated Channel Attachments & Workspace File UX
Channel agents can now download authenticated binary attachments (e.g., Slack ZIP/DOCX) into
channel-attachments/with storage caps/policies, and text attachments (CSV/JSON/YAML/logs) are fetched and inlined as text; workspace write protection is now opt-in (viarequireReadBeforeWrite) to reduce falseStaleFileErrorfailures.Breaking Changes
@mastra/playground-ui: Metrics chart card API cleanup (e.g., removedChartCarddescription/summary, removed severalMetricsCard.*components, changed related table/legend APIs).@mastra/playground-ui: Removed fluid-hover utilities (useFluidHover,FluidHoverHighlight) andCommandList.highlightClassName.@mastra/core: Removed runtime-importable subpaths@mastra/core/network/vNextand@mastra/core/telemetry/otel-vendor(they pointed to files that no longer ship).@mastra/factory:defineBoard()andMastraFactoryboards/includeDefaultBoardsare deprecated in favor of stored boards APIs; code reading deprecated board fields (title/role/next) should move toname/runner.context/nextPhases.
Changelog
@mastra/[email protected]
Minor Changes
-
Added schemas for saved observability list views. Use
savedViewStateSchemato validate a saved traces, spans, threads or logs view: its filters, time range, sort, columns and page options. A service that only stores views can usesavedViewStateEnvelopeSchemainstead. It checks the version, the page and the 16 KiB size limit. Dashboards can reuse the filter shape throughfilterNodeSchema. It accepts any operator id, so new operators don't need a schema change. (#28715)import { savedViewStateSchema } from '@mastra/core/storage'; savedViewStateSchema.parse({ schemaVersion: 1, page: 'traces', filters: [{ fieldId: 'status', value: 'error' }], dateRange: { preset: 'last-24h' }, sort: { field: 'startedAt', direction: 'desc' }, }); -
Channel agents with a workspace can now open binary file attachments, such as ZIP and DOCX files, that need an authenticated download (for example Slack files). The file is downloaded through the adapter and saved under
channel-attachments/in the agent's workspace. The agent gets the workspace path instead of a private URL it can't open. (#28913)Th
查看更新说明
Highlights
End-user (per-resource) connections in
@mastra/connecttools({ resourceId })and newuserConnectRoutes()enable user-scoped OAuth connections so agents can safely use each end user’s accounts (in addition to global connections), with built-in caching and hard enforcement that one user’s connection can’t serve another user.In-chat “request connection” prompts for missing integrations
Resource-scoped tool resolution now includes a built-in
request_connectiontool that returns a structuredconnect-promptpayload (provider list + connection state) so chat UIs can render a connect card when the agent needs an unconnected provider.Span aggregation API + store support (ClickHouse/Postgres/DuckDB)
New
POST /observability/spans/aggregateplusaggregateSpans()in ClickHouse/Postgres/DuckDB enable fast grouped metrics over spans (counts, latency, error rate, tokens, cost) for agent runs, tools, workflows, and more—powering richer Metrics/observability experiences.Unified, persisted provider-error classification (better retries + better UX)
@mastra/core/erroraddsclassifyProviderError(and related helpers) and server streams now carry provider status/body/requestId/modelId/codes/reason so clients can show consistent, actionable error messages live and after reload; retry logic (StreamErrorRetryProcessor) now aligns with the same classification.Run status + durable execution control improvements
Thread subscriptions can opt into
withRunStatus: trueto receive orderedthread-run-statusoutcomes without closing the subscription, and clients can explicitly cancel durable runs viaagent.abortRun(runId)(disconnecting observers no longer aborts durable/evented execution by default).Breaking Changes
queryTraceThreads()thread rows no longer includemodelorprovider, andpage.limitis now capped at 100 (default 25); larger limits fail validation.@mastra/connectconnect-session creation response changed:POST /connect/:provider/sessionsnow returnslaunchUrl(server-side verified launch route) instead ofconnectUrl.@mastra/code-sdkno longer registers built-in subagents by default; you must passsubagents: [...builtinSubagents]to keep prior behavior.@mastra/playground-uiTracesExplorersorting API changed to a single{ field, direction }object (replacingsortDirection/onSortDirectionChange).
Changelog
@mastra/[email protected]
Minor Changes
-
Added
agentModeltodataset.startExperiment()anddataset.startExperimentAsync()so you can run an agent experiment against a different model without editing or versioning the agent. The model is passed with each call the experiment makes: the registered agent, its sub-agents and other experiments running at the same time keep their own models, and the agent version is picked the same way as withoutagentModel. (#28165)await dataset.startExperiment({ targetType: 'agent', targetId: 'support-agent', agentModel: 'anthropic/claude-haiku-5-5', scorers: ['accuracy'], });The experiment's
metadata.agentModeland each run's trace metadata record the model (for exampleanthropic/claude-haiku-5-5), so runs on different models can be told apart.agentModelworks only with agent targets and is rejected before an experiment record is created otherwise. -
Channel
formatErrornow receives the failed run's request context as a second argument, so the message posted to Slack, Discord, Teams or Telegram can link back to whatever the run belongs to. Formatters that take only the error keep working. When a stream fails with a raw provider payload instead of anError, the error passed toformatErrorkeeps that payload as itscause, so the formatter can still tell what failed. (#27811)channels: {
查看更新说明
Highlights
MCP Events (poll/stream/webhooks + Studio inspection)
Experimental MCP Events (SEP-3415 draft) let MCP servers publish event streams that clients can poll, keep a stream open for, or receive via signed webhooks. Core/server/client add inspection APIs so Studio can list event types, stream occurrences, and test-emit events under
mastra dev.Observability Upgrades: Span Aggregation + “Time to First Chunk” + Richer Trace/Span Querying
New
aggregateSpans()storage contract enables per-span analytics (e.g., p95 latency per tool, token/cost per agent) via thespan-aggregatefeature. Observability queries gaintimeToFirstChunkMsfields, filtering, and sorting, plus expanded trace-scope fields (rootentityId, rootname, rootspanType) and richerquerySpans()context/parent/root-entity filters (with updated store capabilities to detect support).Agent Controller Sessions Move to Session IDs (Multi-session per resource)
Sessions are now addressed by
sessionId(notresourceId + scope) across core, server, and client-js, enabling many sessions per resource while keepingresourceIdas the memory/thread owner key. New APIs includecontroller.getSession(sessionId), updatedcreateSession()/deleteSession()signatures, and server routes under/agent-controller/:controllerId/sessions/:sessionId/....Sandboxes Get a Native Filesystem API (Faster workspace operations)
WorkspaceSandboxcan expose an optionalfilesystemfor one-roundtrip reads/writes/listings instead of shelling out per operation. This lands across providers (e.g., E2B/PlatformSandbox) and is adopted bySandboxFilesystemin@mastra/code-sdkfor faster file operations.End-User Scoped Connect Integrations + Teams Channel
@mastra/connectadds per-resource (end-user) connection scoping for tools/credentials, preventing one user’s connections from serving another user’s requests, plususerConnectRoutes()to let authenticated end users connect their own accounts. Connect also adds Microsoft Teams as a supported channel.Breaking Changes
- Agent controller sessions are keyed by
sessionId(scope removed): core/controller APIs, server routes, and client-jscontroller.session()/session.create()signatures updated. - Thread-row query contract changed: use
timeRange.traces/timeRange.threadsinstead oftraces.timeRange. querySpans()contract changed: removedmodel/providerfilters and droppedcost,inputTruncated,outputTruncated,errorTruncatedfrom responses (requires updated storage adapters).- Channel
resolveResourceId/resolveThreadIdcontexts now requirerequestContext(tests/manual calls must pass it).
Changelog
@mastra/[email protected]
Minor Changes
-
Breaking: Agent controller sessions are now addressed by their session id. Many sessions can share one
resourceId, soresourceIdonly says whose threads and memory a session works on. (#27336)- Added
controller.getSession(sessionId). Removedcontroller.getSessionByResource(resourceId, scope). - Removed the
scopeoption fromcreateSession(). Give each session its ownidinstead. Whenidis omitted it defaults to theresourceId, so existing one-session-per-resource code keeps working. deleteSession()takes{ sessionId }, andgenerateThreadTitle()takes an optionalsessionId.- The controller request context exposes
sessionIdnext toresourceId.
// Before await controller.createSession({ resourceId: 'repo-1', scope: 'run-a' }); const session = await controller.getSessionByResource('repo-1', 'run-a'); await controller.deleteSession({ resourceId: 'repo-1', scope: 'run-a' }); // After await controller.createSession({ id: 'run-a', resourceId: 'repo-1' }); const session = await controller.getSession('run-a'); awa - Added
- Agent controller sessions are keyed by
查看更新说明
Highlights
Agent Scopes (multi-tenant identity + safer memory/thread routing)
Agents now support
scopes(<type>:<value>) passed per call, configured on the agent, or injected by trusted middleware viaMASTRA_SCOPES_KEY; Mastra merges all three. Memory can deriveresourceandthreadfromresource:/thread:scopes (with conflicts now returning HTTP 400), nested calls can choose their own thread, and resumed runs preserve their original scopes (no adding new ones).Trace Aggregation API (server + client + React)
Mastra adds trace aggregation end-to-end:
POST /observability/traces/aggregateis discoverable viaGET /observability/capabilities(traceAggregate), clients getmastraClient.aggregateTraces(), and React addsuseTraceAggregateAvailable(). Field discovery now returns anaggregateschema describing valid group-by dimensions and measures.Typed Signal Queueing for Agents (
queueSignal)You can now queue a typed signal behind the active run—without degrading it into a plain user message—via
Agent.queueSignal()/ session support and the new server routePOST /agents/:agentId/queue-signal. Runs triggered by a signal also record signal metadata on theAGENT_RUNspan for better traceability.Faster, more usable trace lists with stored input/output/error previews
Trace and span list APIs now return
outputPreviewanderrorPreview(and spans adderrorTruncated), backed by a shared preview format in@mastra/core/storage(buildPreview,PREVIEW_MAX_LENGTH). Stores (ClickHouse/Postgres/DuckDB) persist previews at write time soqueryTraces()/querySpans()no longer need to read full payloads—improving latency, memory use, and enabling UIs like Playground’s new Traces “Output” column.Better reliability for long-running & durable workflows
Workflow execution is more robust:
.foreach()failures now correctly fail the run (instead of hanging or corrupting output), durable agents are correctly honored inside workflow steps across engines, resume behavior preservessuspendDataafter crashes, and invalid resume data now throwsAGENT_RESUME_INVALID_DATAwithout consuming the suspended run.Breaking Changes
buildInputPreview()andINPUT_PREVIEW_MAX_LENGTHare deprecated in favor ofbuildPreview()andPREVIEW_MAX_LENGTH.- Factory sessions no longer have modes (Plan/Explore removed); thinking defaults and related config endpoints now use a single global default, and
PUT /web/config/thinkingrejectsmodeDefaults. - Factory credential behavior changed: cross-scope credential fallback is removed; custom credential providers must move from
orgFirstto explicitcredentialScope/ policy resolution.
Changelog
@mastra/[email protected]
Minor Changes
-
Added
scopesto agents: the addresses a run acts as, written as<type>:<value>(for exampleorg:acme,resource:user-123,thread:conversation-123). (#26593)Setting scopes. Pass them per call on
stream,generate,network,sendMessage,queueMessageandsendSignal, set them on the agent, or set them from trusted middleware with the newMASTRA_SCOPES_KEYrequest context key. Mastra combines all three. Read an agent's configured scopes withagent.getScopes().Memory. Memory reads its resource and thread from
resource:andthread:scopes, in addition tomemory.resource,memory.threadand the existing request context keys. If they name different values, the call throws a 400 error instead of silently picking one. Runs with no scopes from any source behave as before.const agent = new Agent({ id: 'support', model: 'openai/gpt-5-mini', memory: new Memory(), scopes: ({ requestContext }) => { // Set by your auth middleware. Request bodies can fill unreserved keys, so only read trusted ones. con
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
Mastra
Mastra is a framework for building AI-powered applications and agents with a modern TypeScript stack.
It includes everything you need to go from early prototypes to production-ready applications. Mastra integrates with frontend and backend frameworks like React, Next.js, and Node, or you can deploy it anywhere as a standalone server. It's the easiest way to build, tune, and scale reliable AI products.
Why Mastra?
Purpose-built for TypeScript and designed around established AI patterns, Mastra gives you everything you need to build great AI applications out-of-the-box.
Some highlights include:
-
Model routing: Connect to 40+ providers through one standard interface. Use models from OpenAI, Anthropic, Gemini, and more.
-
Agents: Build autonomous agents that use LLMs and tools to solve open-ended tasks. Agents reason about goals, decide which tools to use, and iterate internally until the model emits a final answer or an optional stopping condition is met.
-
Workflows: When you need explicit control over execution, use Mastra's graph-based workflow engine to orchestrate complex multi-step processes. Mastra workflows use an intuitive syntax for control flow (
.then(),.branch(),.parallel()). -
Human-in-the-loop: Suspend an agent or workflow and await user input or approval before resuming. Mastra uses storage to remember execution state, so you can pause indefinitely and resume where you left off.
-
Context management: Give your agents the right context at the right time. Provide conversation history, retrieve data from your sources (APIs, databases, files), and add human-like memory with Observational Memory so your agents behave coherently.
-
Integrations: Bundle agents and workflows into existing React, Next.js, or Node.js apps, or ship them as standalone endpoints. When building UIs, integrate with agentic libraries like Vercel's AI SDK UI and CopilotKit to bring your AI assistant to life on the web.
-
MCP servers: Author Model Context Protocol servers, exposing agents, tools, and other structured resources via the MCP interface. These can then be accessed by any system or agent that supports the protocol.
-
Production essentials: Shipping reliable agents takes ongoing insight, evaluation, and iteration. With built-in evals and observability, Mastra gives you the tools to observe, measure, and refine continuously.
Get started
The recommended way to get started with Mastra is by running the command below:
npm create mastra@latest
Follow the Installation guide for step-by-step setup with the CLI or a manual install.
If you're new to AI agents, check out our templates, course, and YouTube videos to start building with Mastra today.
Create a new Mastra project. Mastra is a framework for AI applications and agents on a modern TypeScript stack. Before running the command, ask these questions one at a time and wait for each answer unless it was already provided:
1. Project name? (default: "my-mastra-app")
2. Provider? (required; options: "openai", "anthropic", "google", "xai")
If the provider isn't supported, ask again and list the supported values.
Run: `npm create mastra@latest <project-name> -- --llm <provider>`
The command creates a default Mastra project, installs Mastra skills for detected coding assistants, and initializes Git when appropriate.
After creation, enter the project directory and start the dev server: `npx bgproc start -n <project-name> -w -- npm run dev`
Open Mastra Studio at `http://localhost:4111`. Studio is the interface for building, testing, and managing agents, workflows, and tools.
Also mention that the Mastra model router provides access to thousands of models: https://mastra.ai/models
Documentation
Visit our official documentation.
Build with AI
Learn how to make your agent a Mastra expert by following the Build with AI guide.
Contributing
Looking to contribute? Pull requests are limited to collaborators only. Therefore you can best help by creating high-quality issues with good reproductions and descriptions. Mastra will then verify your report and prioritize it accordingly.
If you want to run Mastra or its tests locally, refer to the development documentation
Support
We have an open community Discord. Come and say hello and let us know if you have any questions or need any help getting things running.
It's also super helpful if you leave the project a star here, at the top of the page
Licensing
This repository uses a dual-license model:
- Apache License 2.0: The core framework and the vast majority of this codebase is open source under Apache-2.0.
- Mastra Enterprise License: Code in any directory named
ee/(e.g.,packages/core/src/auth/ee/) is source-available under the Mastra Enterprise License. These features require a valid enterprise license for production use but can be freely used for development and testing.
See LICENSE.md for the full license mapping and ee/LICENSE for the enterprise license terms.
Security
We are committed to maintaining the security of this repo and of Mastra as a whole. If you discover a security finding we ask you to please responsibly disclose this to us at [email protected] and we will get back to you.