К основному содержанию
скилл CX Codex

migrating-mastra-to-pydantic-ai — скилл миграции Mastra на Pydantic AI

Скилл переносит TypeScript-приложения на Mastra в Python с Pydantic AI. Пригодится, когда код импортирует @mastra/* или использует агентов, инструменты и воркфлоу Mastra.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add pydantic/skills --skill migrating-mastra-to-pydantic-ai -a claude-code
Открыть на GitHub

Что делает migrating-mastra-to-pydantic-ai

Скилл задаёт правила миграции: сохранять наблюдаемое поведение, а не объектную модель Mastra. Сначала он требует прочитать инструкции репозитория, зависимости, тесты и точку входа, записать версии Mastra, Pydantic AI и Harness. Затем проследить один реальный запрос от публичной точки входа через инструменты, процессоры, память и побочные эффекты.

Миграция идёт одним вертикальным срезом: сохраняется граница вызова, заменяются только внутренности, которыми владеет агент. Для агентного цикла берётся pydantic_ai.Agent, для явных типизированных узлов — pydantic_graph. Harness подключается только при реальной нужде: память-блокнот, планирование, субагенты по указанию модели, guardrails.

Высокорисковые места описаны отдельно: RequestContext Mastra — это доверенный контекст запуска, его нельзя передавать модели как вход. Воркфлоу Mastra — детерминированный код, его не переносят в промпт агента. Аппрув приостанавливает проверенное действие, но не аутентифицирует того, кто одобряет. Из-за этих правил миграция Mastra Studio, серверных адаптеров и точной совместимости снапшотов остаётся за рамками скилла — их меняют осознанно, а не приравнивают к порту агента.

Версии Mastra, Pydantic AI и Harness нужно записать до начала работы — без них скилл не сможет корректно сопоставить контракты.

Какие задачи решает

  • перенести агентов Mastra на pydantic_ai.Agent без потери наблюдаемого поведения
  • заменить воркфлоу Mastra на обычный Python или pydantic_graph
  • разделить RequestContext на доверенные зависимости и модельные параметры
  • сохранить границу HTTP, задачи или UI с текущими именами полей
  • понять, когда Harness действительно нужен, а когда можно без него

Примеры запросов агенту

  • перенеси этот Mastra-агент на Pydantic AI, сохранив поведение вызовов
  • проследи один запрос от точки входа и покажи, какие контракты нужно сохранить
  • этот воркфлоу Mastra — перепиши на plain Python или pydantic_graph, но не в промпт

Как установить migrating-mastra-to-pydantic-ai

1Через Skills CLI (Vercel)

npx skills add pydantic/skills --skill migrating-mastra-to-pydantic-ai -a claude-code

2Вручную: положить файлы

~/.claude/skills/migrating-mastra-to-pydantic-ai/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/migrating-mastra-to-pydantic-ai/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о migrating-mastra-to-pydantic-ai

Как установить migrating-mastra-to-pydantic-ai в Claude Code?

Выполни npx skills add pydantic/skills --skill migrating-mastra-to-pydantic-ai -a claude-code. Скилл появится в ~/.claude/skills/migrating-mastra-to-pydantic-ai/SKILL.md.

Что делает скилл migrating-mastra-to-pydantic-ai?

Он переносит TypeScript-приложения на Mastra в Python с Pydantic AI, сохраняя наблюдаемое поведение. Скилл не копирует объектную модель Mastra и не воспроизводит её реестр или серверные адаптеры.

Когда нужен Pydantic AI Harness, а когда нет?

Harness добавляется только для реально используемых возможностей: память-блокнот, планирование, субагенты по указанию модели, Agent Skills, guardrails, стратегии компактизации. Он не заменяет движок воркфлоу и не является вторым рантаймом.

Исходный текст

SKILL.md · MIT
---
name: migrating-mastra-to-pydantic-ai
description: 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.
---

# 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](references/RESEARCH-AND-MAPPING.md) for the detected source features. Read [Verification and cutover](references/VERIFICATION-AND-CUTOVER.md) 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](references/VERIFICATION-AND-CUTOVER.md). Label evidence from fakes, recordings, and live providers accurately.

© pydantic · MIT · pydantic/skills

Похожие скиллы

Все скиллы по теме «Настройка агента: память, контекст, субагенты» →
mastra-hono agent-skills Скилл для сборки ИИ-агентов, инструментов и воркфлоу на Mastra v1 Beta с API-серверами на Hono. Пригодится, когда пишете агентную логику на TypeScript. CX Codex +1 373установок mastra Mastra Скилл помогает разрабатывать на Mastra, сверяясь с актуальной документацией. Пригодится для настройки TypeScript-проекта, проверки API и разбора ошибок. CX Codex +1 83 000установок mastra-factory Mastra Скилл для работы с Mastra Factory через CLI: смотрит статус, очередь, проекты и сессии, а по разрешению запускает операции. CX Codex +1 4 500установок migrating-workflow-v4-to-v5 Vercel Inc. Переводит приложение с Workflow SDK 4.x на 5.0: подсказывает, какие зависимости поднять и какие вызовы переписать. CX Codex +1 310установок agentic-development alinaqi Скилл для сборки автономных ИИ-агентов на Pydantic AI (Python) и Claude Agent SDK (Node.js). Пригодится, когда агент должен выполнять многошаговые задачи с инструментами. CX Codex +1 406установок migrating-ai-sdk-to-common-ai astronomer Переводит Airflow-проекты с airflow-ai-sdk на официальный провайдер apache-airflow-providers-common-ai 0.4.0+. Пригодится, когда LLM-декораторы и конфигурация моделей переезжают на соединения. CX Codex +1 348установок

Из того же набора12

pydantic Скилл для работы с Pydantic: подсказывает, как описывать модели, ограничения полей и валидаторы, когда агенту нужно разобрать внешние данные. CX Codex +1 2 200установок logfire-query Выполняет SQL-запросы к телеметрии Logfire прямо через агента. Скилл нужен для поиска медленных спанов, группировки исключений и расчёта метрик. CX Codex +1 1 900установок logfire-ui Открывает экраны Logfire, трейсы и живой просмотр в браузере без предварительных запросов к телеметрии. CX Codex +1 1 600установок logfire-setup Разбирает широкий запрос «настрой мне Logfire» и отправляет агента к нужному специалисту: инструментация приложения, инфраструктура, evals, фронтенд, Gateway. CX Codex +1 555установок logfire-evals Прогоняет офлайн-оценки Python и Node.js, разбирает отчёты в Logfire и перенаправляет существующие наборы Braintrust. CX Codex +1 554установок migrating-langchain-to-pydantic-ai Скилл для переноса Python-приложений с LangChain, LangGraph и Deep Agents на Pydantic AI. Пригодится, когда нужно сохранить поведение, а не форму фреймворка. CX Codex +1 314установок migrating-vercel-ai-sdk-and-eve-to-pydantic-ai Переводит приложения на TypeScript Vercel AI SDK или Eve на Python с Pydantic AI. Полезен, когда нужно сохранить поведение, а не API исходника. CX Codex +1 306установок migrating-claude-agent-sdk-to-pydantic-ai Скилл ведёт миграцию Python-приложения с Claude Agent SDK на Pydantic AI. Нужен, когда в коде есть импорт claude_agent_sdk. CX Codex +1 308установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой