NerdlyBuilds

Python 3.15's Lazy Imports Can Make an MCP Server Forget Its Tools

Lazy imports cut an MCP server's startup from 1.6 seconds to 0.6. The global switch also broke pandas and made every tool vanish. Tested results inside.

·7 min read

Illustration: a small robot at a workshop bench in front of a nearly empty pegboard wall, beside a stack of closed boxes with one glowing as it opens

A local MCP server has an unusual startup problem. With the stdio transport, the client launches your server as a subprocess, so every import at the top of the file is a bill paid each time that process starts. A server that pulls in pandas and an LLM client just to answer a health check pays the whole bill anyway.

Python 3.15, released on 9 October, adds a real fix: a lazy keyword for imports, plus a global switch that makes nearly every import lazy without touching your code. I tried both on a small MCP server. The keyword took time-to-ready from 1,625 ms to 580 ms. The global switch was even faster, and it broke the server in ways that didn’t show up at startup: a tool that failed on every call, and on a second server, a tool list that came back empty with no error at all.

This guide covers the speedup, the five ways it went sideways, and a small test file that catches them.

Tested with: Python 3.15.2, mcp 2.3.0, pandas 3.1.0, anthropic 2.4.0, pytest 9.2.0, uv 0.13.7, on Ubuntu 24.04 with 2 CPU cores, 3 November 2026. Your milliseconds will differ. The ratios are the useful part.

Setup

uv python install 3.15.2
mkdir lazy-mcp && cd lazy-mcp
uv venv --python 3.15.2 .venv && . .venv/bin/activate
uv pip install "mcp==2.3.0" "pandas==3.1.0" "anthropic==2.4.0" "pytest==9.2.0"

Before changing anything, find out where the time goes. This little script is worth stealing:

import time
t0 = time.perf_counter()
import mcp.server
t1 = time.perf_counter()
import pandas
t2 = time.perf_counter()
import anthropic
t3 = time.perf_counter()
print(f'mcp.server {(t1-t0)*1000:.0f} ms | pandas {(t2-t1)*1000:.0f} ms | anthropic {(t3-t2)*1000:.0f} ms')
mcp.server 558 ms | pandas 197 ms | anthropic 878 ms

The surprise is the LLM client: it costs more than twice what pandas does. python -X importtime gives you the same answer one module at a time if you want to dig further.

The server, and the one-word change

Here’s the test subject, a small print-log server in the style of the one from the SQLite MCP guide. One tool is free, one needs pandas, and one needs the Anthropic client.

# server_eager.py
import anthropic
import pandas as pd

from mcp.server import MCPServer

mcp = MCPServer("print-log")


@mcp.tool()
def ping() -> str:
    """Cheap health check."""
    return "pong"


@mcp.tool()
def spool_stats(grams: list[float]) -> dict:
    """Summarize filament used per print."""
    s = pd.Series(grams)
    return {"total": float(s.sum()), "mean": float(s.mean())}


@mcp.tool()
def draft_note(text: str) -> str:
    """Build (but don't send) a request for a print-failure note."""
    client = anthropic.Anthropic(api_key="not-a-real-key")
    return f"{type(client).__name__} ready for: {text}"


if __name__ == "__main__":
    mcp.run()

server_lazy.py is the same file with two words added:

lazy import anthropic
lazy import pandas as pd

Nothing else changes. The name binds to a proxy, and the real import runs the first time that name gets used. I also made server_local.py, the old-fashioned version with the imports inside the tool functions, because that trick has worked for years and deserves a fair race.

This harness spawns each server over real stdio and times three things: how long until tools/list answers, a ping, and the first call that needs pandas.

# measure.py
import asyncio
import statistics
import sys
import time

from mcp import StdioServerParameters
from mcp.client import Client


async def once(script, env):
    params = StdioServerParameters(command=sys.executable, args=[script], env=env)
    t0 = time.perf_counter()
    async with Client(params) as client:
        await client.list_tools()
        t1 = time.perf_counter()
        await client.call_tool("ping", {})
        t2 = time.perf_counter()
        result = await client.call_tool("spool_stats", {"grams": [38.5, 112.0]})
        t3 = time.perf_counter()
    return t1 - t0, t2 - t1, t3 - t2, result.is_error


async def main():
    runs = int(sys.argv[1])
    cases = [
        ("eager", "server_eager.py", None),
        ("lazy keyword", "server_lazy.py", None),
        ("function-local", "server_local.py", None),
        ("env var = all", "server_eager.py", {"PYTHON_LAZY_IMPORTS": "all"}),
    ]
    print(f"{'case':15}{'ready ms':>10}{'ping ms':>9}{'pandas ms':>11}  failed")
    for name, script, env in cases:
        rows = [await once(script, env) for _ in range(runs)]
        ready, ping, pandas = (statistics.median(r[i] for r in rows) * 1000 for i in range(3))
        failed = sum(r[3] for r in rows)
        print(f"{name:15}{ready:10.0f}{ping:9.1f}{pandas:11.1f}  {failed}/{runs}")


asyncio.run(main())

Run with python measure.py 15 2>/dev/null:

case             ready ms  ping ms  pandas ms  failed
eager                1625      2.8        2.5  0/15
lazy keyword          580      2.8      184.7  0/15
function-local        564      2.8      195.9  0/15
env var = all         441      2.7       66.4  15/15

Bar chart of median times: eager is ready in 1,625 ms with a 2.5 ms first pandas call; the lazy keyword is ready in 580 ms with a 185 ms first pandas call; function-local imports are ready in 564 ms with a 196 ms first call; the all mode is ready in 441 ms but the pandas tool failed in all 15 runs

Three things stand out. Startup dropped 64% with two words. The bill for pandas came due on its first call, right on schedule, since laziness moves the cost and doesn’t remove it. And lazy is no faster than a function-local import. What it buys you is tidiness: your imports stay at the top of the file where people look for them.

There’s also a floor. MCPServer runs at module level, so mcp.server has to load at startup whatever you do. That’s most of the remaining 580 ms.

Then there’s that last row.

Trap 1: the global switch breaks real libraries

PYTHON_LAZY_IMPORTS=all looks like a free upgrade, and it won the startup race. You’d put it in your client’s env block and forget about it. But every run failed on the pandas call, even though the server started and listed all three tools. Here’s the short version of what was on stderr:

python -X lazy_imports=all -c "import pandas as pd; pd.Series([1.0])"
ImportError: numpy._core.multiarray failed to import

The Anthropic client fails too, for a different reason:

AttributeError: 'lazy_import' object has no attribute '__module__' and no __dict__ for setting new attributes.

That one comes from a package __init__.py that loops over its names and sets __module__ on each. Under all, some of those names are still proxies, and proxies don’t allow it. Neither library did anything wrong. all changes rules they were written under, and the sys docs pitch the global mode at advanced users for a reason. A filter that kept numpy and pandas eager fixed pandas and left the Anthropic failure in place, so I’d stop there and use the keyword, which only affects the imports you marked.

Trap 2: tools that register on import disappear

Split your tools across files and you probably have this shape:

# server.py
from app import mcp
import tools_cost   # noqa: F401  (registers tools)
import tools_maint  # noqa: F401  (registers tools)

if __name__ == "__main__":
    mcp.run()

Each tools_*.py file does from app import mcp and decorates its functions with @mcp.tool(). Those imports exist only for their side effects, and nothing ever touches the names, so a lazy import never fires. This small client prints the tool names and takes env vars as arguments:

# list_tools.py
import asyncio, sys

from mcp import StdioServerParameters
from mcp.client import Client


async def main():
    env = dict(a.split("=", 1) for a in sys.argv[2:])
    params = StdioServerParameters(command=sys.executable, args=[sys.argv[1]], env=env)
    async with Client(params) as client:
        tools = await client.list_tools()
        print("tools:", [t.name for t in tools.tools])


asyncio.run(main())
python list_tools.py server.py
python list_tools.py server.py PYTHON_LAZY_IMPORTS=all
tools: ['spool_cost', 'nozzle_due']
tools: []

No error and no warning, just a healthy server with nothing to offer. The fix is to make registration explicit, which is what the PEP recommends too:

# tools_cost.py
def spool_cost(grams: float, price_per_kg: float) -> float:
    """Filament cost for one print."""
    return round(grams / 1000 * price_per_kg, 2)


def register(mcp):
    mcp.add_tool(spool_cost)

Call tools_cost.register(mcp) from server.py, and the same command lists both tools, with or without all.

Trap 3: a type in a tool signature undoes everything

lazy from anthropic.types import Usage


@mcp.tool()
def last_usage() -> Usage:
    """Token usage from the last note we drafted."""
    return Usage(input_tokens=0, output_tokens=0)

The SDK reads your annotations at decoration time to build the tool’s schema, and that resolves the lazy name. This server was ready in 1,475 ms, nearly back to eager. Adding from __future__ import annotations didn’t help, since anthropic still landed in sys.modules at startup. Return a plain dict or your own Pydantic model at the boundary.

Trap 4: a missing dependency stops failing fast

With a normal import, a package missing from server_missing_eager.py kills the process, and the client reports Connection closed before any work starts. Swap in lazy import filament_oracle and the server starts and lists its tool, then fails on use:

tools: ['predict']
isError: True | content: Error executing tool predict

That generic message is all the model sees. The real cause, lazy import of 'filament_oracle' raised an exception during resolution, goes to the server’s stderr. So a broken install now looks like a flaky tool.

Trap 5: the first async call stalls the server

Sync tools run on a worker thread in SDK v2, but async def tools run on the event loop, so an import triggered there blocks everything. I started a first pandas call and sent a ping 10 ms later, nine runs each:

spool_stats_async: ping during first call 185.6 ms
spool_stats_sync: ping during first call 18.1 ms

If that matters, warm the imports on a thread after startup:

# server_warm.py
def _warm() -> None:
    # Touching a name reifies the lazy import.
    pd.Series
    anthropic.Anthropic


@asynccontextmanager
async def lifespan(server) -> AsyncIterator[None]:
    async with anyio.create_task_group() as tg:
        tg.start_soon(anyio.to_thread.run_sync, _warm)
        yield
        tg.cancel_scope.cancel()


mcp = MCPServer("print-log", lifespan=lifespan)

With a 2-second pause before the first pandas call, that call fell from 201.8 ms to 5.0 ms, and ready time only went from 583 ms to 604 ms. An agent that connects fast and calls slowly gets most of both worlds.

A test file that catches all of this

Each of these traps looks fine at a glance, so they belong in CI. This covers the three that matter most: deferred modules stay deferred, every lazy import resolves, and the tools are really there.

# test_startup.py
import asyncio
import subprocess
import sys

from mcp import StdioServerParameters
from mcp.client import Client

SERVER = "server_lazy.py"
DEFERRED = ("pandas", "anthropic")
EXPECTED_TOOLS = {"ping", "spool_stats", "draft_note"}


def run_python(code):
    return subprocess.run(
        [sys.executable, "-c", code], capture_output=True, text=True, timeout=60
    )


def test_heavy_modules_stay_deferred():
    result = run_python(
        "import runpy, sys\n"
        f"runpy.run_path({SERVER!r}, run_name='check')\n"
        f"print([m for m in {DEFERRED!r} if m in sys.modules])"
    )
    assert result.returncode == 0, result.stderr
    assert result.stdout.strip() == "[]"


def test_every_lazy_import_resolves():
    result = run_python(
        "import runpy, sys\n"
        "sys.set_lazy_imports_filter(lambda *args: False)\n"
        f"runpy.run_path({SERVER!r}, run_name='check')"
    )
    assert result.returncode == 0, result.stderr


def test_all_tools_are_registered():
    async def names():
        params = StdioServerParameters(command=sys.executable, args=[SERVER])
        async with Client(params) as client:
            return {t.name for t in (await client.list_tools()).tools}

    assert asyncio.run(names()) == EXPECTED_TOOLS

The result was 3 passed on server_lazy.py. Pointed at the broken servers, it failed where it should: test_every_lazy_import_resolves on the missing dependency and test_heavy_modules_stay_deferred on the annotation case.

What went wrong when I tested it

  • uv offered only a beta. uv 0.11.32 listed 3.15.0b4 as the newest build. Upgrading to 0.13.7 made 3.15.2 appear.
  • The PEP’s none mode isn’t there. The PEP describes a mode that turns off all lazy imports. On 3.15.2, -X lazy_imports=none dies with invalid value; expected 'all' or 'normal', and sys.set_lazy_imports("none") raises ValueError. A filter that returns False does the job, which is why the test uses one.
  • Exporting the variable did nothing. My first PYTHON_LAZY_IMPORTS=all python list_tools.py server.py still listed both tools. The SDK’s stdio client passes only a short allow-list of environment variables to the child process, so the setting has to go in env. It also made my client lazy, which proved nothing.
  • My warm-up looked useless at first. Calling the tool straight after tools/list still took 188 ms, because the warm-up hadn’t finished and the call waited for it. The 2-second pause showed it was working.
  • The first timing pass lied. Before the disk cache warmed up, the anthropic import took 1,746 ms against about 870 ms afterward. Run the server a few times first.
  • lazy isn’t allowed everywhere. Inside try it’s a SyntaxError, so the classic optional-dependency pattern stays eager. Under all, imports inside try stay eager too, which I confirmed.

When to use this, and when not to

Decision guide asking, in order, whether an import has side effects, runs at module level, appears in a tool signature, is first used in an async tool, or is slow and needed by only some tools, with the matching choice for each

Use the keyword on heavy dependencies that only some tools need. Server startup is the clearest win, since a client that launches several servers pays for each one.

Skip it if your server sits on Streamable HTTP and runs for weeks. One second at boot won’t matter, and you’d rather learn about a bad deploy right away. For local MCP work, also ask whether a lighter dependency would do. Removing an import beats deferring it.

Avoid PYTHON_LAZY_IMPORTS=all for now, at least on a stack like this one. A clean startup there proves very little.

Supporting older Pythons? __lazy_modules__ = ["wave"] at the top of a module gave a lazy import on 3.15 and an ordinary one on 3.13, with no syntax error on either.

If you’re building up a local agent setup, startup time is one piece of it, and The Brain in the Basement covers the model side.

Sources

How this was made: researched and drafted with AI assistance, with every code sample run and tested before publishing, then reviewed by Colby.

Get an email when I publish something new