Halve `import pydantic_ai` time by loading `pydantic_ai.mcp` only when an `MCP` capability needs it
import pydantic_ai spent about half its time loading MCP support that most programs never use. pydantic_ai/capabilities/mcp.py imported pydantic_ai.mcp at module level, so import pydantic_ai (through agent ā capabilities._deferred_capability_loader ā capabilities) loaded fastmcp and mcp too.
The MCP capability now imports MCPToolset only where it builds one, as _build_local already did, and imports the names under TYPE_CHECKING otherwise.
Import time: python -X importtime -c "import pydantic_ai", cumulative for pydantic_ai, 5 runs each on Python 3.14:
| Median | |
|---|---|
| Before | 818ms |
| After | 406ms |
The time saved applies to every program and every test that starts a fresh interpreter.
Behavior:
- Unchanged:
MCP(url, native=True, local=False)still never importsmcp, andMCP(url).get_toolset()still imports it when called.AgentSpecschema generation is unaffected, becauseMCP.from_spec's type hints don't mentionMCPToolset.- The missing-extra error from
_build_localis unchanged.
- One edge case gets a clearer error: passing a non-toolset object such as a
Pathaslocal=without themcpextra used to fail with aTypeErrorfrom instantiatingAny. It now raises theImportErrorthat says to install the fastmcp client. pydantic_ai.capabilities.mcp.MCPToolset/MCPToolsetClientare no longer runtime attributes of that private module.
Regression guard: the existing fresh-interpreter check in tests/test_httpx2_sdk_readiness.py::test_core_runs_without_httpx now also fails if pydantic_ai.mcp, mcp or fastmcp is loaded. I confirmed it fails with the old eager import put back.
Checklist
- No breaking changes in accordance with the version policy.
- Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver.
- PR title is fit for the release changelog.
š¤ Generated with Claude Code