Generated banner for Migrating Claude Agent SDK To Pydantic AI
Generated logo for Migrating Claude Agent SDK To Pydantic AI

Migrating Claude Agent SDK To Pydantic AI

PydanticOfficialPublished by Pydantic

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

From the author

Migrate Python applications from the Claude Agent SDK to Pydantic AI and, only when needed, Pydantic AI Harness. Use when source code imports `claude_agent_sdk` or relies on Claude Code's agent loop, sessions, built-in tools, hooks, permissions, skills, or subagents. Do not use for the Anthropic Messages SDK or Claude Managed Agents.
— the description by Pydantic

AutoGineer summary

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

This skill provides a systematic approach to migrating existing Python applications that rely on the Claude Agent SDK to the Pydantic AI framework. It emphasizes preserving observable application behavior rather than replicating internal SDK implementation details. The process involves tracing existing agent contracts, mapping them to Pydantic AI core features or Pydantic AI Harness capabilities, and validating the migration through focused testing of request/response boundaries.

What it does

  • Provides a step-by-step methodology for tracing and characterizing existing Claude Agent SDK behavior.
  • Maps Claude Agent SDK concepts like tools, hooks, and sessions to Pydantic AI equivalents.
  • Defines criteria for when to use Pydantic AI core versus Pydantic AI Harness.
  • Establishes high-risk gates for handling approvals, hooks, and streaming.
  • Outlines a testing strategy to ensure parity at the application's public boundary.
  • Guides the removal of legacy SDK dependencies after successful verification.

When to use it

  • When your Python application imports claude_agent_sdk.
  • When you need to move away from Claude Code's agent loop or session management.
  • When you want to leverage Pydantic AI for typed dependencies, tools, and agent orchestration.
  • When you need to maintain existing application infrastructure while updating the underlying agent runtime.

Advantages

  • Focuses on observable outcomes rather than internal implementation parity.
  • Provides clear guidance on handling complex features like approvals and state persistence.
  • Encourages a modular migration approach by targeting the smallest complete caller path.
  • Includes specific verification steps to ensure application stability during the transition.

Usage examples

“How do I start migrating my Claude Agent SDK implementation to Pydantic AI?”
The agent will guide you through tracing your current implementation, establishing a baseline characterization test, and identifying the core Pydantic AI components needed to replace your existing Claude SDK logic.
“How should I handle tool approvals during the migration?”
The agent will explain how to map Claude's allowed_tools logic to Pydantic AI's approval mechanisms, ensuring that authorization and audit trails remain owned by your application.

Install

  1. Download the skill as a ZIP:

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

    mkdir -p .agents/skills && unzip migrating-claude-agent-sdk-to-pydantic-ai.zip -d .agents/skills

Documentation by Pydantic

Migrate Claude Agent SDK to Pydantic AI

Preserve observable behavior, not the Claude Code process or API shape. 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 Claude Agent SDK, bundled Claude Code CLI, Pydantic AI, and Harness versions.

  2. Trace one real request from query() or ClaudeSDKClient through prompts, tools, events, results, state, persistence, approvals, and side effects that callers use. Establish a focused baseline or characterization test.

  3. Separate these source contracts when present:

    • fresh query() calls, live ClaudeSDKClient continuation, disk/external-store resume, transcript forks, and file rewind;

    • tool availability, automatic approval, policy callbacks, and OS/container isolation;

    • completed messages, raw token deltas, lifecycle events, and terminal results;

    • conversation history, workflow checkpoints, model-owned plans, long-term memory, and workspace state;

    • model-directed subagents from application-owned loops, queues, retries, and schedulers.

  4. Record each observed contract, its owner, semantic difference, and executable proof. An unobserved Claude Code 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 model calls, the agent loop, typed dependencies, tools, outputs, normalized messages, generic hooks, streaming, MCP, approvals, usage limits, instrumentation, and durable-runtime integrations.

  • Harness: add pydantic-ai-harness only for observed reusable policy such as coding filesystem/shell tools, repository context, planning, memory, model-directed subagents, model-agnostic context management, or Agent Skills. Harness capabilities compose through the core agent loop; Harness is not a second runtime.

  • Application: retain authentication, service clients, databases, queues, schedulers, deployment, product state, session lookup, tenant policy, and existing transports 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 create a lookalike ClaudeSDKClient or emulate Claude transcript files 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 the caller expects structure, and application-owned storage of result.all_messages() when later turns need context. Preserve the existing public request/response/event boundary with a small adapter while callers migrate.

Apply high-risk gates

  • allowed_tools in the Claude Agent SDK means auto-approval, not exclusive availability and not isolation. Map availability, approval, policy, and sandboxing independently.

  • Pydantic AI message_history explicitly replays normalized messages. conversation_id correlates runs; it is not a Claude session-resume token. Prove restart and fork behavior rather than renaming IDs.

  • Pydantic AI approval defers a validated tool call. The application still owns authenticated authorization, identity, and audit, and the protected effect must not run before approval.

  • Map hooks by firing point, inputs, ordering, mutation, blocking, and error behavior. Claude hook matchers may run concurrently. Pydantic AI runs before_* hooks in capability order, after_* hooks in reverse order, and nests wrap_* hooks with the first capability outermost. Require a golden trace for any hook-visible contract.

  • Map consumer intent for streaming. Pydantic AI output streaming, run-event streaming, and graph iteration are different surfaces; none promises the Claude SDK message taxonomy.

  • Use Harness SubAgents only for model-directed delegation. Keep deterministic orchestration and verification loops in application code.

  • Harness Skills supplies on-demand SKILL.md instructions; verify resources and scripts separately instead of assuming Claude Code skill or plugin loading parity.

  • Harness command controls are best-effort policy, not an OS security boundary. For untrusted execution, use ModalSandbox where it fits or retain application-owned container, VM, or sandbox isolation.

  • File rewind, Claude Code prompt presets, plugin packaging, raw stream-event identity, and dynamic MCP control are gaps unless the migrated caller actually needs them and a public target seam is proven.

Implement and prove one vertical slice

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

  2. Start core-only. Add the narrowest Harness capabilities only after a source contract requires them.

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

  4. For resume, durability, approvals, concurrent tools, or external effects, test interruption/restart, lineage, authorization, and idempotency at the exact boundary promised by the source.

  5. Remove claude-agent-sdk only after no retained path imports it, spawns Claude Code, reads its transcripts, or consumes its event/result types.

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, Harness, or GapWhat will not remain identicalBaseline and focused target test

Evidence states are preserved, accepted change, application-owned, tested gap, or unverified. Do not call unverified equivalent.

Match testing to the slice

Ordinary core agent
  • Characterize the public request and result.

  • Use TestModel or FunctionModel to prove prompt, 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.

Stateful or branching agent
  • Serialize the first result's normalized messages through the application's real store and load them in a fresh process for the next run.

  • Test branch point, branch independence, conversation_id/run_id semantics, incomplete tool-call history, retention, tenant authorization, and store failures that callers can observe.

  • If the source resumes in-flight work, kill and restart at each promised boundary. Select a durable runtime deliberately and assert that an external effect is not duplicated.

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

  • Exercise deny, approve, and argument override where supported.

  • 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 side effect before resolution, zero after denial, and exactly one after approval.

  • Exercise the application's authenticated identity, policy lookup, and audit trail. A local yes/no callback is not authorization proof.

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

  • Test text reconstruction, tool start/result order, hook order and mutations, 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, and recursion limits.

Coding and shell agents
  • Use a disposable workspace. Exercise normal reads/edits/search/commands plus .., absolute paths, escaping symlinks, denied/protected files, output limits, timeouts, background cleanup, environment stripping, and working-directory behavior.

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

  • If rollback is promised, verify filesystem or VCS state independently of conversation history.

Dependency and cutover checks

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

  2. Run the original characterization tests and focused target tests. Test sync, async, callback, and streaming forms only where callers use them.

  3. Search imports, factories, configuration, transcript readers, event/result adapters, and deployment scripts for retained Claude Agent SDK dependencies.

  4. Remove claude-agent-sdk, Claude Code subprocess setup, and Claude transcript assumptions only when no retained path needs them.

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

Completion criterion

Cut over only when each ledger row has a non-unverified evidence state, the original supported boundary passes, requested gaps are resolved or explicitly accepted, 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-claude-agent-sdk-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.

Download ZIP

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