migrating-mastra-to-pydantic-ai

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.

Install
npx skills add 'https://github.com/pydantic/pydantic-ai/tree/main/pydantic_ai_slim/pydantic_ai/.agents/skills/migrating-mastra-to-pydantic-ai'
Download bundle ↓
main · 9e9fdc4Scanned 2026-09-17

Contributors

GitHub-linked commit authors for this SKILL.md at the saved revision. Co-authors and history before file renames are not included.

File history ↗

references/RESEARCH-AND-MAPPING.md

references/RESEARCH-AND-MAPPING.mdBrowse 4 files
View on GitHub
← Back to SKILL.md

Research and concept mapping

Use this reference conditionally after tracing the source path. It is a decision guide, not a requirement to reproduce the entire Mastra platform.

Primary documentation

Inspect installed versions before migrating because Mastra, Pydantic AI, and Harness continue to evolve.

Mastra is a TypeScript framework and Pydantic AI is Python. Capture each existing transport or storage boundary with language-neutral fixtures and keep its field names, using Pydantic aliases where needed.

Ownership map

Observed Mastra behaviorTarget owner and likely seamFocused proof
Agent.generate() and response text, toolCalls, toolResults, steps, or usageCore: Agent.run() / run_sync(), AgentRunResult; Application: response adapterAssert caller-visible output, required trajectory fields, usage, errors, and side effects.
Agent.stream(), textStream, object, and fullStreamCore: run_stream(), run_stream_events(), event_stream_handler, or iter(); Application: event adapterAssert reconstruction, order, terminal detection, trailing events, cancellation, and no duplicate final output.
Agent instructions, model, maxSteps, and call optionsCore: instructions, model/provider settings, UsageLimits; Application: configuration mappingConstruct every configured provider branch and assert step-limit behavior without assuming identical defaults.
RequestContext and dynamic configuration functionsCore: typed deps_type, RunContext.deps, dynamic instructions/tool preparation; Application: authenticated context constructionInspect tool schemas and prove that tenant identity, credentials, and services cannot be model-selected.
createTool() with Zod/JSON schemas and execute()Core: typed functions, Tool, Tool.from_schema, function toolsetsAssert schema, return shape, retry/error behavior, timeout, concurrency, approval, and effects.
structuredOutput.schema, response.objectCore: Pydantic output type and explicit NativeOutput, ToolOutput, or PromptedOutput when transport mattersAssert valid output and invalid-output behavior; preserve a second structuring-model pass explicitly if the source uses one.
Input/output processors and processor workflowsCore: history processors, output validators, Hooks; Harness: InputGuardrail, OutputGuardrail, or ToolGuardrail for matching block/replace/retry policy; Application: public error/event adapterGolden-test firing point, mutation, order, tripwire/error shape, retries, persistence, and streaming.
Memory thread/resource message historyCore: normalized messages; Application: existing store, ownership, indexing, retention, and record migrationAssert the selected cutover strategy against real records, continue in a fresh process, and reject cross-tenant access.
Semantic recall across messages/threadsApplication: existing vector/retrieval service behind typed dependencies or a toolAssert scope, ranking/filtering, context placement, limits, and behavior when retrieval fails.
Working memoryHarness: Memory only when a model-owned Markdown notebook fits; otherwise Application: retain structured profile storageAssert schema/format, update ownership, namespace isolation, bounded injection, restart, and concurrency.
Observational memoryApplication: retain observation/reflection service; optionally combine explicit retrieval with core history processingAssert when raw history is replaced, facts retained, background failure behavior, and fresh-process continuation. Do not label generic compaction equivalent.
createWorkflow().then() fixed stepsApplication: plain typed async functions; pydantic_graph when explicit graph inspection adds valueAssert step inputs/outputs, order, error propagation, and public terminal status.
.branch(), .parallel(), .foreach(), loops, nested workflowsApplication: explicit Python control flow; Graph: pydantic_graph for typed branches/joinsAssert chosen branch, join shape, source ordering, concurrency limit, cancellation, partial failure, and retry.
Workflow stateSchema, state, setStateApplication/Graph: separate typed workflow state from dependencies and messagesSerialize and resume state independently; assert updates, versioning, and nested-flow propagation actually used. Graph state alone does not provide persisted snapshots.
Workflow suspend(), resume(), snapshots, time travelApplication or underlying durable engine: workflow state, branch progress, snapshots, and resume correlation; Core durable integration: agent model, tool, and MCP operations inside that workflow onlyKill and restart at each promised boundary; assert resume payload validation, step identity, lineage, branch progress, and exactly-once effects.
Durable or evented agentsHarness: StepPersistence for continuable agent snapshots; Core: Temporal, DBOS, or Prefect integration for durable executionKill and restart during model, tool, and external-effect boundaries; assert continuation, replay behavior, and idempotency.
Tool requireApproval, request-wide approval, tool suspensionCore: requires_approval, ApprovalRequired, or ApprovalRequiredToolset to gate the tool; resolve inline with HandleDeferredToolCalls, or return DeferredToolRequests and resume a later run with DeferredToolResults; Application: auth, policy, UI, audit, persistenceExercise deny and approve; bind the decision to call ID and validated arguments; assert zero effects before resolution and after denial, and exactly one after approval.
Registered subagents / supervisor delegationHarness: SubAgents; Core: agent-as-tool or programmatic handoff when fixedAssert task-only input, isolated history, dependency and budget propagation, result handback, cancellation, errors, events, and recursion policy.
Agent Skills and workspace skillsHarness: Skills for SKILL.md instructions; FileSystem or an Application tool for references/resources; Application: dynamic selection and scriptsAssert configured-root discovery, loading, request-scoped selection, and every used reference, resource, or script separately. Harness does not automatically scan .agents or .claude.
MCP clientsCore: MCPToolsetAssert discovery, name collisions, transport, credentials, errors, lifecycle, and approvals.
MCP servers exposing tools or agentsApplication: MCP Python SDK around the migrated public boundaryAssert advertised schemas, transport lifecycle, auth, errors, and client compatibility.
Scorers, datasets, and experimentsEvals (pydantic_evals): cases, datasets, evaluators; Application: live sampling, scheduling, and score storageAdd the separate pydantic-evals dependency, compare the same dataset and essential metrics, and separately prove sampling, trace correlation, and persistence when retained.
OpenTelemetry and Mastra observabilityCore: instrumentation/OpenTelemetry; optional Logfire; Application: existing backend and trace/event adaptersAssert trace correlation, content/privacy policy, required spans, logs, feedback, retention, and dashboards before switching.
Mastra registry, server, client SDK, Studio, auth, storage adapters, queues, schedules, and deploymentApplication/infrastructureExercise the retained public endpoint or job boundary, including auth, tenancy, configuration, secrets, scaling, and failure behavior.
Mastra Code, filesystem/shell/browser, and workspace sandboxesHarness: Coder, FileSystem, Shell, browser capabilities, or ModalSandbox; Application: existing isolationAssert tools and workspace effects. Treat command allowlists as policy, not isolation; test the real sandbox for untrusted execution.
Realtime voiceCore: realtime agent/session APIs where the provider and media contract fit; otherwise retain the integrationTest media formats, interruption, event ordering, tool calls, session lifetime, and transport errors.
Referenced from SKILL.md