mastra

mastra-ai活跃维护 有专家点评

用 TypeScript 快速搭建 AI 应用和智能体的现代框架,内置工作流、对话机器人和评测能力,省去自己拼装 LLM 调用链的麻烦。

Mastra is the modern TypeScript framework for AI-powered applications and agents.

@mastra/[email protected]发布于 2026-11-04 10:59 UTC29,457star +59 / 7 天3,089fork同步于 2026-11-11 05:21 UTC

专家点评

上手难度:进阶更新于 2026-11-11

TypeScript 里把 agent、工作流和 eval 串成一套的框架,替代自己用 AI SDK 拼装编排层

适用场景

  • 需要人工审批环节的 agent 流程:工作流可以挂起、等审批后恢复,这类 suspend/resume 语义自己用 AI SDK 手写要维护一套状态机,Mastra 直接给到图原语
  • 多 provider 切换或做模型对比:统一接口接 40+ provider,换模型只改配置;自己封装的话每接一家都要重写一遍 tool-call 和流式解析
  • 需要把 agent 行为纳入回归测试:内置 evals 和可观测性,跑完能对比;否则得自己搭 trace 采集加评分管线
  • Next.js/Node 项目里做对话式功能:和 React/Next 生态贴合,不用为了 agent 编排再引入一套 Python 服务

踩坑

  • 在 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 提炼,执行前请确认
npm create mastra@latest
硬件要求按 README 说明

README 未说明

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

TypeScript 框架,用来构建 AI 应用与智能体,从原型一路做到生产

用 TypeScript 快速搭建 AI 应用和智能体的现代框架,内置工作流、对话机器人和评测能力,省去自己拼装 LLM 调用链的麻烦。

核心能力

  • 通过统一接口接入 40+ 模型提供商
  • 构建会用工具、自主推理迭代的 Agent
  • 用 .then/.branch/.parallel 编排图式工作流
  • 支持挂起工作流等待人工审批后恢复
  • 内置 evals 与可观测性做持续评估调优

容易踩的坑

需先选定模型提供商(openai/anthropic/google/xai)才能创建项目;开发服务器默认端口为 4111;ee/ 目录下功能生产使用需企业许可证

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本@mastra/[email protected]
  1. @mastra/[email protected]November 4, 2026最新正式版2026-11-04 · 2026-11-04 10:59 UTC

    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 in knowledge_read, list pinning (kind: 'list'), and a link index for counting/listing [[links]]. Apps can also sync external content via server APIs like knowledge.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. PostgresStore from @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-js and @mastra/server add resume APIs. MCP also gains “answer task input from chat” behavior (suspends instead of failing when unhandled), plus richer tool results (images/audio/files) via MCPServer.toolResult.

    Observability upgrades: streaming latency metrics + richer trace filtering

    Trace/span aggregates now support timeToFirstToken.* and timeToFirstChunk.* so dashboards can chart streaming latency, gated by store capability. Advanced trace queries also gain requestId, serviceName, and experimentId filters 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 validate inputSchema and requestContextSchema before running (can fail runs that previously “succeeded” with wrong input); set validateInputs: false to opt out.
    • Experimental memory changes: experimental_subconscious and Memory knowledge option are removed (now throw); Knowledge must be attached to the Agent, and older Subconscious/Coordinator constructors now throw.
    • knowledge.reindex() is removed; use upsertPage/note writes (and reindexLinks() for link indexing) instead.
    • Factory (@mastra/[email protected]): removes work-item claiming APIs (claimKey removed; 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 scopes function can now narrow or replace a run's scopes. It receives the run's incoming scopes (from the call, defaultOptions and request context) and returns the run's final set. A static scopes list is still added to the incoming scopes. The function must keep any resource: or thread: 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
      
  2. @mastra/[email protected]November 2, 20262026-11-02 · 2026-11-02 12:33 UTC
    查看更新说明

    Highlights

    MCP Tasks (Storage-backed, restart-safe long-running execution)

    @mastra/mcp adds 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/metadata retention, 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 + typed stopReason (and context), exports model/provider, and measures timeToFirstTokenMs (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-ui introduces DashboardRenderer plus 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 (via requireReadBeforeWrite) to reduce false StaleFileError failures.

    Breaking Changes

    • @mastra/playground-ui: Metrics chart card API cleanup (e.g., removed ChartCard description/summary, removed several MetricsCard.* components, changed related table/legend APIs).
    • @mastra/playground-ui: Removed fluid-hover utilities (useFluidHover, FluidHoverHighlight) and CommandList.highlightClassName.
    • @mastra/core: Removed runtime-importable subpaths @mastra/core/network/vNext and @mastra/core/telemetry/otel-vendor (they pointed to files that no longer ship).
    • @mastra/factory: defineBoard() and MastraFactory boards/includeDefaultBoards are deprecated in favor of stored boards APIs; code reading deprecated board fields (title/role/next) should move to name/runner.context/nextPhases.

    Changelog

    @mastra/[email protected]

    Minor Changes
    • Added schemas for saved observability list views. Use savedViewStateSchema to 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 use savedViewStateEnvelopeSchema instead. It checks the version, the page and the 16 KiB size limit. Dashboards can reuse the filter shape through filterNodeSchema. 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

  3. @mastra/[email protected]October 28, 20262026-10-28 · 2026-10-28 15:23 UTC
    查看更新说明

    Highlights

    End-user (per-resource) connections in @mastra/connect

    tools({ resourceId }) and new userConnectRoutes() 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_connection tool that returns a structured connect-prompt payload (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/aggregate plus aggregateSpans() 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/error adds classifyProviderError (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: true to receive ordered thread-run-status outcomes without closing the subscription, and clients can explicitly cancel durable runs via agent.abortRun(runId) (disconnecting observers no longer aborts durable/evented execution by default).

    Breaking Changes

    • queryTraceThreads() thread rows no longer include model or provider, and page.limit is now capped at 100 (default 25); larger limits fail validation.
    • @mastra/connect connect-session creation response changed: POST /connect/:provider/sessions now returns launchUrl (server-side verified launch route) instead of connectUrl.
    • @mastra/code-sdk no longer registers built-in subagents by default; you must pass subagents: [...builtinSubagents] to keep prior behavior.
    • @mastra/playground-ui TracesExplorer sorting API changed to a single { field, direction } object (replacing sortDirection / onSortDirectionChange).

    Changelog

    @mastra/[email protected]

    Minor Changes
    • Added agentModel to dataset.startExperiment() and dataset.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 without agentModel. (#28165)

      await dataset.startExperiment({
        targetType: 'agent',
        targetId: 'support-agent',
        agentModel: 'anthropic/claude-haiku-5-5',
        scorers: ['accuracy'],
      });
      

      The experiment's metadata.agentModel and each run's trace metadata record the model (for example anthropic/claude-haiku-5-5), so runs on different models can be told apart. agentModel works only with agent targets and is rejected before an experiment record is created otherwise.

    • Channel formatError now 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 an Error, the error passed to formatError keeps that payload as its cause, so the formatter can still tell what failed. (#27811)

      channels: {
      
  4. @mastra/[email protected]October 21, 20262026-10-21 · 2026-10-21 12:28 UTC
    查看更新说明

    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 the span-aggregate feature. Observability queries gain timeToFirstChunkMs fields, filtering, and sorting, plus expanded trace-scope fields (root entityId, root name, root spanType) and richer querySpans() 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 (not resourceId + scope) across core, server, and client-js, enabling many sessions per resource while keeping resourceId as the memory/thread owner key. New APIs include controller.getSession(sessionId), updated createSession()/deleteSession() signatures, and server routes under /agent-controller/:controllerId/sessions/:sessionId/....

    Sandboxes Get a Native Filesystem API (Faster workspace operations)

    WorkspaceSandbox can expose an optional filesystem for one-roundtrip reads/writes/listings instead of shelling out per operation. This lands across providers (e.g., E2B/PlatformSandbox) and is adopted by SandboxFilesystem in @mastra/code-sdk for faster file operations.

    End-User Scoped Connect Integrations + Teams Channel

    @mastra/connect adds per-resource (end-user) connection scoping for tools/credentials, preventing one user’s connections from serving another user’s requests, plus userConnectRoutes() 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-js controller.session()/session.create() signatures updated.
    • Thread-row query contract changed: use timeRange.traces / timeRange.threads instead of traces.timeRange.
    • querySpans() contract changed: removed model/provider filters and dropped cost, inputTruncated, outputTruncated, errorTruncated from responses (requires updated storage adapters).
    • Channel resolveResourceId / resolveThreadId contexts now require requestContext (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, so resourceId only says whose threads and memory a session works on. (#27336)

      • Added controller.getSession(sessionId). Removed controller.getSessionByResource(resourceId, scope).
      • Removed the scope option from createSession(). Give each session its own id instead. When id is omitted it defaults to the resourceId, so existing one-session-per-resource code keeps working.
      • deleteSession() takes { sessionId }, and generateThreadTitle() takes an optional sessionId.
      • The controller request context exposes sessionId next to resourceId.
      // 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
      
  5. @mastra/[email protected]October 15, 20262026-10-16 · 2026-10-16 08:13 UTC
    查看更新说明

    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 via MASTRA_SCOPES_KEY; Mastra merges all three. Memory can derive resource and thread from resource:/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/aggregate is discoverable via GET /observability/capabilities (traceAggregate), clients get mastraClient.aggregateTraces(), and React adds useTraceAggregateAvailable(). Field discovery now returns an aggregate schema 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 route POST /agents/:agentId/queue-signal. Runs triggered by a signal also record signal metadata on the AGENT_RUN span for better traceability.

    Faster, more usable trace lists with stored input/output/error previews

    Trace and span list APIs now return outputPreview and errorPreview (and spans add errorTruncated), backed by a shared preview format in @mastra/core/storage (buildPreview, PREVIEW_MAX_LENGTH). Stores (ClickHouse/Postgres/DuckDB) persist previews at write time so queryTraces()/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 preserves suspendData after crashes, and invalid resume data now throws AGENT_RESUME_INVALID_DATA without consuming the suspended run.

    Breaking Changes

    • buildInputPreview() and INPUT_PREVIEW_MAX_LENGTH are deprecated in favor of buildPreview() and PREVIEW_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/thinking rejects modeDefaults.
    • Factory credential behavior changed: cross-scope credential fallback is removed; custom credential providers must move from orgFirst to explicit credentialScope / policy resolution.

    Changelog

    @mastra/[email protected]

    Minor Changes
    • Added scopes to agents: the addresses a run acts as, written as <type>:<value> (for example org:acme, resource:user-123, thread:conversation-123). (#26593)

      Setting scopes. Pass them per call on stream, generate, network, sendMessage, queueMessage and sendSignal, set them on the agent, or set them from trusted middleware with the new MASTRA_SCOPES_KEY request context key. Mastra combines all three. Read an agent's configured scopes with agent.getScopes().

      Memory. Memory reads its resource and thread from resource: and thread: scopes, in addition to memory.resource, memory.thread and 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
      

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    Mastra

    npm version CodeQl GitHub Repo stars Discord Twitter Follow NPM Downloads Static Badge

    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.