Generated banner for Migrating Mastra To Pydantic AI
Generated logo for Migrating Mastra To Pydantic AI

Migrating Mastra To Pydantic AI

PydanticOfficialPublished by Pydantic

  • Skill
  • Workflow
  • Software development
  • MIT
  • No issues found

From the author

Migrate TypeScript Mastra applications to Python with Pydantic AI and, only when needed, Pydantic AI Harness. Use when source code imports `@mastra/*` or relies on Mastra agents, tools, workflows, memory, processors, streaming, approvals, skills, or subagents.
— the description by Pydantic

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured methodology for migrating Mastra-based TypeScript applications to Pydantic AI. It emphasizes preserving observable behavior over internal object models, focusing on tracing source contracts, selecting the appropriate Pydantic AI components (Core, Graph, or Harness), and validating the migration through focused vertical slices. The approach prioritizes application-owned infrastructure and explicit handling of state, memory, and workflow persistence.

What it does

  • Provides a step-by-step process to trace and characterize existing Mastra application contracts.
  • Maps Mastra concepts to Pydantic AI Core, Graph, and Harness components.
  • Offers guidance on handling complex features like memory, workflows, and approvals.
  • Defines a testing strategy using contract ledgers to ensure parity.
  • Advises on managing application-level infrastructure like authentication and databases during migration.
  • Includes instructions for verifying cutover and managing semantic changes.

When to use it

  • When you need to migrate an existing Mastra application to Pydantic AI.
  • When you need to ensure that application behavior remains consistent after switching frameworks.
  • When you need to determine which Pydantic AI components are necessary for specific Mastra features.
  • When you need a structured way to test and verify the migration of agentic workflows.

Advantages

  • Focuses on observable behavior rather than rigid code translation.
  • Promotes a modular approach by migrating one vertical slice at a time.
  • Provides clear decision-making criteria for choosing between Core, Graph, and Harness.
  • Emphasizes robust testing and contract verification to minimize regression risks.
  • Encourages keeping application infrastructure separate from agent logic.

Usage examples

“How do I migrate a Mastra agent that uses memory and tools to Pydantic AI?”
The agent will guide you to trace the agent's current request/response contract, map the memory and tools to Pydantic AI's message history and Tool definitions, and implement a vertical slice test to verify parity.
“Should I use Pydantic Graph for my Mastra workflow?”
The agent will help you evaluate if your workflow requires explicit typed nodes and branches (Pydantic Graph) or if it can be simplified into plain async Python code.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/pydantic/migrating-mastra-to-pydantic-ai/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip migrating-mastra-to-pydantic-ai.zip -d .agents/skills

Documentation by Pydantic

Migrate Mastra to Pydantic AI

Preserve observable behavior, not TypeScript or Mastra's object model. Migrate the smallest complete caller path and keep application infrastructure in place.

Trace the source before choosing a target

  1. Read repository instructions, dependencies, tests, and the runtime entrypoint. Record the installed Mastra, Pydantic AI, and Harness versions.

  2. Trace one real request from its public entrypoint, whether an Agent.generate() / Agent.stream() call or a workflow run, through the tools, processors, memory, events, results, state, and side effects that callers use. Establish a focused baseline or characterization test.

  3. Separate these source contracts when present:

    • request context, model-chosen tool input, workflow input/output, and shared workflow state;

    • conversation messages, semantic recall, working or observational memory, workflow snapshots, and model-owned plans;

    • final text or objects, token deltas, lifecycle events, tripwires, and terminal workflow status;

    • tool approval, authenticated authorization, and process or sandbox isolation;

    • deterministic workflows, agent-selected delegation, queues, schedules, and durable execution.

  4. Record each observed contract, its owner, semantic difference, and executable proof. An unused Mastra feature is not migration scope.

Read Research and concept mapping for the detected source features. Read Verification and cutover before implementation.

Choose the smallest target

  • Core: use pydantic_ai.Agent for the agent loop, typed dependencies, tools, outputs, normalized messages, generic hooks, streaming, MCP clients, approvals, usage limits, instrumentation, realtime, and durable-runtime integrations.

  • Graph: use pydantic_graph only when explicit typed nodes, branches, and joins remain useful; use plain async Python for simple fixed control flow.

  • Harness: add pydantic-ai-harness only for observed reusable policy such as memory notebooks, planning, model-directed subagents, Agent Skills, coding tools, guardrails, model-agnostic compaction strategies, or step persistence. Harness capabilities compose through the core agent loop; Harness is not a workflow engine or second runtime.

  • Evals: add the separate pydantic-evals package for observed datasets, cases, and evaluators.

  • Application: retain authentication, databases, vector search, queues, schedulers, deployment, product state, API/UI transports, session lookup, and tenant policy unless the requested slice includes them.

  • Gap: name behavior that no supported public seam preserves, explain its impact, and test a bounded adapter. Do not reproduce the Mastra registry, server, storage schema, or event taxonomy merely to hide a difference.

The normal migration is one reusable Agent, application services supplied through typed dependencies, ordinary Pydantic AI tools, a typed output when callers expect structure, and application-owned storage of result.all_messages() for later turns. Preserve an existing HTTP, job, or UI boundary with a small adapter and its current field names. If the Mastra call is only in-process, migrate its nearest caller in the same slice or explicitly agree on a new application-owned service boundary; do not add a transport by default.

Apply high-risk gates

  • Mastra RequestContext is trusted run context, not model input. Map authenticated identity and services to typed dependencies; expose only model-chosen values as tool parameters.

  • Mastra memory combines distinct behaviors. Map thread messages to serialized Pydantic AI message history, keep semantic retrieval behind an application service or tool, and use Harness Memory only when its model-owned notebook semantics preserve the observed working-memory contract. For existing Mastra records, explicitly choose and test one-time conversion, a read-through adapter, or starting fresh as an accepted change. Do not treat message history, a notebook, or Harness StepPersistence as a workflow snapshot.

  • A Mastra workflow is deterministic application control flow. Use plain Python or pydantic_graph; do not move .branch(), .parallel(), .foreach(), loops, or suspend conditions into an agent prompt. Preserve concurrency, aggregation, failure, and cancellation semantics explicitly.

  • Mastra workflow suspension persists a resumable snapshot. Keep branch and workflow-state persistence in the application or underlying durable engine and prove restart at the promised step. Pydantic AI durable integrations make agent model, tool, and MCP operations durable inside that workflow; they do not own its surrounding control flow. Deferred tools preserve agent tool calls, not arbitrary workflow state.

  • Map processors by firing point, input/output mutation, tripwire behavior, ordering, streaming visibility, and persistence. Use the narrowest of core history processors, output validators, hooks, Harness input/output/tool guardrails, a custom capability, or an application adapter, and golden-test any caller-visible event or error.

  • Approval pauses a validated action; it does not authenticate the approver. Keep identity, authorization, audit, correlation, and idempotency in the application, and prove the effect does not run before approval.

  • Map consumer intent for streaming. Pydantic AI output streaming, run-event streaming, UI adapters, and graph iteration are different surfaces; none promises Mastra's fullStream chunk taxonomy.

  • Use Harness SubAgents only for model-directed delegation. Keep deterministic fan-out, aggregation, retries, and scorer-driven verification loops in application or graph code.

  • Mastra Agent Skills may include references and dynamic resolution. Harness Skills loads on-demand SKILL.md instructions only and does not automatically scan .agents or .claude; use Harness FileSystem or an application tool for required references, and test per-request selection separately.

  • Mastra Studio, server adapters, storage providers, deployment targets, logs, trace storage, and live-eval scheduling are product infrastructure. Retain or replace them deliberately rather than treating the agent port as equivalent.

  • Mastra durable agents, workflow time travel, exact snapshot compatibility, observational-memory compaction, and exact raw event identity are gaps unless a supported target seam is proven for the observed caller.

Implement and prove one vertical slice

  1. Preserve the supported caller boundary and replace only the agent-owned internals.

  2. Start core-only. Add pydantic_graph, Harness, Pydantic Evals, or a durable runtime only after a source contract requires it.

  3. Test inputs, typed outputs, errors, event order, tool arguments/results, processor decisions, state across turns, and side effects at that boundary. Use deterministic models and fake application services offline; add a focused recorded or live test only when provider behavior is the contract.

  4. For persistence, approvals, concurrent workflows, or external effects, test interruption and restart, lineage, authorization, failure aggregation, and idempotency at the exact boundary promised by Mastra.

  5. Remove @mastra/*, Mastra server setup, and Mastra storage or event adapters only after no retained path needs them.

Explain any consequential semantic change before implementing it: state the source behavior, target behavior, caller impact, recommended choice, and remaining risk.

Completion

Apply the completion criterion in Verification and cutover. Label evidence from fakes, recordings, and live providers accurately.

Files

references/VERIFICATION-AND-CUTOVER.md

Verification and cutover

Prove parity through the application's supported boundary. Do not require high-risk exercises for behavior the source does not use.

Build a contract ledger

For each traced source behavior, maintain one row:

Source lifecycleObservable contractOwnerTarget differenceEvidence
What initiates and completes itInputs, outputs, events, errors, ordering, state or effects callers observeApplication, Core, Graph, Harness, Evals, or GapWhat will not remain identicalBaseline and focused target test

Use the same evidence states as the LangChain migration skill:

StatusMeaning
verified-equivalentSource and target preserve the same observable contract in executable checks.
verified-adapterInternal semantics differ, but an adapter preserves the public contract in executable checks.
intentional-changeThe difference and impact were explained and explicitly accepted.
external-ownerA named application or infrastructure component preserves the contract, with evidence at that boundary.
not-applicableThe observed source path does not provide or consume this behavior.
unverifiedEvidence is incomplete or only a candidate design exists; do not call it equivalent.
blockedA required contract has no acceptable proved construction; do not cut over the slice.

Match testing to the slice

Ordinary agent or tool
  • Characterize the public request and result before rewriting TypeScript as Python.

  • Use TestModel or FunctionModel to prove prompts, dependency-backed tool calls, validated output, retry/error mapping, messages, and usage without network access.

  • Add a provider recording or live probe only when transport, native tools, structured-output mode, or provider deltas are part of the contract.

Memory and state
  • Choose and test how existing Mastra thread and working-memory records cross the cutover: one-time conversion, a read-through adapter, or starting fresh as an intentional-change. Serialize normalized target messages through the application's real store and load them in a fresh process for the next turn.

  • Test thread ownership, retention, incomplete tool calls, store errors, and tenant authorization.

  • Test semantic recall, working memory, observations, workflow state, and model-owned plans independently. Similar facts appearing in a prompt do not prove equivalent lifecycle or ownership.

Workflows and durability
  • Characterize branch selection, step inputs/outputs, joins, concurrency limits, ordering, partial failures, cancellation, retries, and terminal status that callers consume.

  • For suspend/resume or durable execution, kill and restart at each promised boundary. Assert persisted state and step identity, validate resume input, and prove that external effects are idempotent.

  • Keep deterministic workflow control in Python or pydantic_graph; use deterministic agents or fake services only within the steps that actually call them.

Approvals and protected effects
  • Assert the deferred call ID and validated arguments.

  • Exercise deny and approve, including any source decline reason exposed to the model or caller.

  • For inline resolution, assert the handler runs and the agent completes in one call. When the decision arrives later, assert the first run ends with DeferredToolRequests, persist that complete request or an equivalent pending-action record with category, validated arguments, and metadata, then assert a new run over the persisted messages with DeferredToolResults completes with the final output.

  • Assert no protected effect before resolution, zero after denial, and exactly one after approval.

  • Exercise authenticated identity, policy lookup, durable correlation, and audit trail. A local yes/no callback is not authorization proof.

Streaming, processors, and subagents
  • Record a source golden trace containing only event types and stable fields the caller consumes.

  • Test text/object reconstruction, tool start/result order, processor order and mutations, tripwires, terminal detection, trailing events, cancellation, retry, and parallel calls.

  • For subagents, test task-only input, separate history, result handback, dependencies, budget/cancellation/error propagation, event forwarding, approval propagation, and recursion limits.

Coding and sandboxed agents
  • Use a disposable workspace. Exercise ordinary reads, edits, searches, and commands plus .., absolute paths, escaping symlinks, denied or protected files, output limits, timeouts, cleanup, environment handling, and working-directory behavior.

  • Demonstrate that an allowlisted interpreter can start another command. If untrusted code is in scope, run containment tests inside the selected container, VM, or cloud sandbox.

Dependency and cutover checks

  1. Resolve the Python project from a clean environment against supported Pydantic AI and Harness versions. Prefer pydantic-ai-slim with only required extras when the dependency surface is bounded.

  2. Run the original Mastra characterization tests and focused target tests. Capture every existing HTTP/event, persisted-record, snapshot, or provider boundary with language-neutral fixtures and run them against both implementations. If the source is only in-process, migrate its caller in the slice or explicitly test the newly agreed application service boundary.

  3. Search imports, factories, configuration, memory and snapshot readers, event/result adapters, server routes, and deployment scripts for retained @mastra/* dependencies.

  4. Remove Mastra packages, Node build/runtime setup, and storage/event assumptions only when no retained path needs them.

  5. Report which checks used deterministic fakes, recordings, live providers, fresh-process restart tests, or real sandbox tests, and state any remaining limitation.

Completion criterion

Cut over only when every ledger row is verified, an accepted intentional-change, external-owner, or not-applicable; no required row is unverified or blocked; the supported boundary passes; dependencies resolve cleanly; and rollback remains possible.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Pydantic
Publisher
Pydantic (Official)
Source
pydantic/skills · skills/migrating-mastra-to-pydantic-ai · commit 98f591c
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Also distributed in
pydantic/skills

AutoGineer is not affiliated with or endorsed by Pydantic or Pydantic.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download migrating-mastra-to-pydantic-ai.zip