migrating-claude-agent-sdk-to-pydantic-ai

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.

Install
npx skills add 'https://github.com/pydantic/pydantic-ai/tree/main/pydantic_ai_slim/pydantic_ai/.agents/skills/migrating-claude-agent-sdk-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 every Claude Code feature.

Primary documentation

Inspect the installed versions before migrating because the Claude Agent SDK, Pydantic AI, and Harness continue to evolve.

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 behaviorTarget owner and likely seamFocused proof
query() model/tool loop and ResultMessage.resultCore: Agent.run() / run_sync(), AgentRunResult.outputAssert caller output, errors, required usage data, and side effects without preserving the subprocess envelope.
ClaudeAgentOptions.system_prompt, model, thinking, limitsCore: instructions, model/provider settings, UsageLimits(request_limit=..., cost_limit=...); Harness: SpendLimits only for observed cross-run spend policyAssert 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 serverCore: @agent.tool, @agent.tool_plain, Tool, toolsets; MCP only for protocol interoperabilityAssert schema validation, retry/error behavior, concurrency, output content, and side effects.
Built-in Read/Write/Edit/Glob/Grep/BashHarness: FileSystem, Shell, RepoContext, or Coder; Application/infrastructure: ModalSandbox or existing isolationAssert file/process outcomes, path escape resistance, command containment, and output limits.
Built-in web toolsCore: WebSearch and WebFetch capabilities, backed by WebSearchTool and WebFetchTool where the provider supports them; otherwise retain the application integrationAssert result shape, citations/events consumed by callers, credentials, and egress policy.
External MCP serversCore: 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_toolCore: 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/auditAssert availability and each pre-effect allow, deny, or ask outcome independently, including source callback precedence.
Structured output_format and structured_outputCore: typed output_type, Pydantic models, output validators and modesAssert validated values and invalid-output retry exhaustion; do not silently parse fallback text.
Completed assistant/tool/result messagesCore: normalized messages and agent stream events; Application: retained event adapterCompare a stable-field golden trace and include trailing source events.
Raw partial StreamEventsCore: run_stream(), run_stream_events(), event_stream_handler, or agent.iter() according to consumer intentAssert reconstruction, order, terminal detection, no duplicate final text, and cancellation.
Live multi-turn clientCore: repeated Agent.run(..., message_history=...); Application: connection/UI loopAssert next-turn context plus observed mid-run input or interrupt behavior.
Disk resume, SessionStore, transcript list/read/rename/tagCore: serialized normalized messages; Application: storage, indexing, tenancy, metadataRound-trip through the real store and continue in a fresh process.
Session fork/truncating resumeApplication + Core: copy validated history and start a correlated conversation; optional Harness: StepPersistence for settled snapshotsAssert branch point, source immutability, new lineage, tool-call pairing, and side-effect safety.
File checkpoint rewindApplication/infrastructure: VCS, overlay, snapshot, or workspace ownerAssert filesystem state independently of message history; otherwise record a tested gap.
Hooks and matchersCore: Hooks or a custom capability; Application: audit/integration effectsGolden-test firing, stable inputs, decisions, mutation, errors, ordering, retry, and streaming behavior.
Model-directed AgentDefinition subagentsHarness: SubAgents; Core: agent-as-tool for a fixed handoffAssert task-only input, isolated history, dependencies, budgets, handback, events, and recursion policy.
Agent SkillsHarness: SkillsAssert SKILL.md discovery/loading and test any resources, scripts, or setting-source behavior separately.
Local pluginsDecompose used skills, agents, hooks, commands, and MCP servers across Core, Harness, and ApplicationAssert each used feature; record packaging or namespace parity as a gap only when caller-visible.
Planning/task trackingHarness: Planning only for an observed model-owned planAssert persistence and tenant/session keys only when required.
Cross-run model memoryHarness: Memory for its notebook semantics; otherwise retain application storage/retrievalAssert restart, namespace isolation, concurrency, and bounded injection.
Compaction/context managementCore: history processors/provider compaction; optional Harness: compaction, output limits, conversation searchAssert retained facts, tool pairing, thresholds, cache behavior, and retrieval of omitted history.
Interrupts and cancellationCore: cancellation token/task cancellation; Application: transport semanticsAssert stopped work, terminal shape, cleanup, and next-turn continuation.
Durable restart/replayCore: durable runtime integration; optional Harness durability capabilitiesKill and restart at each promised boundary; assert external effects are idempotent.
Cost, usage, rate-limit and telemetry eventsCore: run usage and OTel; optional Harness: spend policy; Application: billing and retained adaptersAssert required metrics, event/trace mapping, and privacy settings; do not treat estimated cost as billing.
HTTP, WebSocket, queues, deployment and authApplication/infrastructureExercise the retained production boundary, including tenancy, scheduling, secrets, scaling, and isolation.
Referenced from SKILL.md