Migrating Claude Agent SDK To Pydantic AI
PydanticOfficialPublished by Pydantic
- Skill
- Workflow
- Software development
- MIT
- No issues found
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
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/pydantic/migrating-claude-agent-sdk-to-pydantic-ai/downloadUnzip 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
Read repository instructions, dependencies, tests, and the runtime entrypoint. Record the installed Claude Agent SDK, bundled Claude Code CLI, Pydantic AI, and Harness versions.
Trace one real request from
query()orClaudeSDKClientthrough prompts, tools, events, results, state, persistence, approvals, and side effects that callers use. Establish a focused baseline or characterization test.Separate these source contracts when present:
fresh
query()calls, liveClaudeSDKClientcontinuation, 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.
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.Agentfor 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-harnessonly 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
ClaudeSDKClientor 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_toolsin the Claude Agent SDK means auto-approval, not exclusive availability and not isolation. Map availability, approval, policy, and sandboxing independently.Pydantic AI
message_historyexplicitly replays normalized messages.conversation_idcorrelates 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 nestswrap_*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
SubAgentsonly for model-directed delegation. Keep deterministic orchestration and verification loops in application code.Harness
Skillssupplies on-demandSKILL.mdinstructions; 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
ModalSandboxwhere 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
Preserve the supported caller boundary and replace only the agent-owned internals.
Start core-only. Add the narrowest Harness capabilities only after a source contract requires them.
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.
For resume, durability, approvals, concurrent tools, or external effects, test interruption/restart, lineage, authorization, and idempotency at the exact boundary promised by the source.
Remove
claude-agent-sdkonly 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
- ATTRIBUTION.mdAdded by AutoGineer899 B
- LICENSELicence file added by AutoGineer1.1 KiB
- SKILL.md6.3 KiB
- agents/openai.yaml341 B
- references/RESEARCH-AND-MAPPING.md7.6 KiB
- references/VERIFICATION-AND-CUTOVER.md4.4 KiB
references/RESEARCH-AND-MAPPING.md
Research and concept mapping
Use this reference conditionally after tracing the source path. It is a decision guide, not a requirement to reproduce every Claude Code feature.
Primary documentation
Inspect the installed versions before migrating because the Claude Agent SDK, Pydantic AI, and Harness continue to evolve.
Claude Agent SDK: Python reference, agent loop, and sessions.
Pydantic AI: agents, message history, hooks, and deferred tools.
Pydantic AI Harness: overview, shell execution, subagents, and step persistence.
The source SDK launches a bundled Claude Code process, passes configuration through CLI flags and a control protocol, and parses stream-JSON frames into Python message classes. That subprocess architecture is not a caller contract by itself. Preserve configured behavior, ordered outputs/events, errors, state, and external effects.
Ownership map
| Observed Claude Agent SDK behavior | Target owner and likely seam | Focused proof |
|---|---|---|
query() model/tool loop and ResultMessage.result | Core: Agent.run() / run_sync(), AgentRunResult.output | Assert caller output, errors, required usage data, and side effects without preserving the subprocess envelope. |
ClaudeAgentOptions.system_prompt, model, thinking, limits | Core: instructions, model/provider settings, UsageLimits(request_limit=..., cost_limit=...); Harness: SpendLimits only for observed cross-run spend policy | Assert that limit exhaustion raises UsageLimitExceeded and translate it if callers expect a Claude result subtype. Core cost limits are best-effort, depend on available pricing, and may be checked after a billed response; retain provider/application spend controls when the source promises a hard cap. |
Custom @tool and in-process SDK MCP server | Core: @agent.tool, @agent.tool_plain, Tool, toolsets; MCP only for protocol interoperability | Assert schema validation, retry/error behavior, concurrency, output content, and side effects. |
Built-in Read/Write/Edit/Glob/Grep/Bash | Harness: FileSystem, Shell, RepoContext, or Coder; Application/infrastructure: ModalSandbox or existing isolation | Assert file/process outcomes, path escape resistance, command containment, and output limits. |
| Built-in web tools | Core: WebSearch and WebFetch capabilities, backed by WebSearchTool and WebFetchTool where the provider supports them; otherwise retain the application integration | Assert result shape, citations/events consumed by callers, credentials, and egress policy. |
| External MCP servers | Core: MCPToolset, load_mcp_toolsets() | Assert discovery, collisions/prefixes, transport, credentials, errors, lifecycle, and any required live control. |
allowed_tools, disallowed_tools, permission modes, can_use_tool | Core: tool preparation; requires_approval or ApprovalRequiredToolset to gate the tool; resolve inline with HandleDeferredToolCalls, or return DeferredToolRequests and resume a later run with DeferredToolResults; optional Harness policy; Application: authorization/UI/audit | Assert availability and each pre-effect allow, deny, or ask outcome independently, including source callback precedence. |
Structured output_format and structured_output | Core: typed output_type, Pydantic models, output validators and modes | Assert validated values and invalid-output retry exhaustion; do not silently parse fallback text. |
| Completed assistant/tool/result messages | Core: normalized messages and agent stream events; Application: retained event adapter | Compare a stable-field golden trace and include trailing source events. |
Raw partial StreamEvents | Core: run_stream(), run_stream_events(), event_stream_handler, or agent.iter() according to consumer intent | Assert reconstruction, order, terminal detection, no duplicate final text, and cancellation. |
| Live multi-turn client | Core: repeated Agent.run(..., message_history=...); Application: connection/UI loop | Assert next-turn context plus observed mid-run input or interrupt behavior. |
Disk resume, SessionStore, transcript list/read/rename/tag | Core: serialized normalized messages; Application: storage, indexing, tenancy, metadata | Round-trip through the real store and continue in a fresh process. |
| Session fork/truncating resume | Application + Core: copy validated history and start a correlated conversation; optional Harness: StepPersistence for settled snapshots | Assert branch point, source immutability, new lineage, tool-call pairing, and side-effect safety. |
| File checkpoint rewind | Application/infrastructure: VCS, overlay, snapshot, or workspace owner | Assert filesystem state independently of message history; otherwise record a tested gap. |
| Hooks and matchers | Core: Hooks or a custom capability; Application: audit/integration effects | Golden-test firing, stable inputs, decisions, mutation, errors, ordering, retry, and streaming behavior. |
Model-directed AgentDefinition subagents | Harness: SubAgents; Core: agent-as-tool for a fixed handoff | Assert task-only input, isolated history, dependencies, budgets, handback, events, and recursion policy. |
| Agent Skills | Harness: Skills | Assert SKILL.md discovery/loading and test any resources, scripts, or setting-source behavior separately. |
| Local plugins | Decompose used skills, agents, hooks, commands, and MCP servers across Core, Harness, and Application | Assert each used feature; record packaging or namespace parity as a gap only when caller-visible. |
| Planning/task tracking | Harness: Planning only for an observed model-owned plan | Assert persistence and tenant/session keys only when required. |
| Cross-run model memory | Harness: Memory for its notebook semantics; otherwise retain application storage/retrieval | Assert restart, namespace isolation, concurrency, and bounded injection. |
| Compaction/context management | Core: history processors/provider compaction; optional Harness: compaction, output limits, conversation search | Assert retained facts, tool pairing, thresholds, cache behavior, and retrieval of omitted history. |
| Interrupts and cancellation | Core: cancellation token/task cancellation; Application: transport semantics | Assert stopped work, terminal shape, cleanup, and next-turn continuation. |
| Durable restart/replay | Core: durable runtime integration; optional Harness durability capabilities | Kill and restart at each promised boundary; assert external effects are idempotent. |
| Cost, usage, rate-limit and telemetry events | Core: run usage and OTel; optional Harness: spend policy; Application: billing and retained adapters | Assert required metrics, event/trace mapping, and privacy settings; do not treat estimated cost as billing. |
| HTTP, WebSocket, queues, deployment and auth | Application/infrastructure | Exercise the retained production boundary, including tenancy, scheduling, secrets, scaling, and isolation. |
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