Halve `import pydantic_ai` time by loading `pydantic_ai.mcp` only when an `MCP` capability needs it

Merged
DO
2mo ago
+9-7

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
Before818ms
After406ms

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 imports mcp, and MCP(url).get_toolset() still imports it when called.
    • AgentSpec schema generation is unaffected, because MCP.from_spec's type hints don't mention MCPToolset.
    • The missing-extra error from _build_local is unchanged.
  • One edge case gets a clearer error: passing a non-toolset object such as a Path as local= without the mcp extra used to fail with a TypeError from instantiating Any. It now raises the ImportError that says to install the fastmcp client.
  • pydantic_ai.capabilities.mcp.MCPToolset / MCPToolsetClient are 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