33471c77fd
The wire schemas load on the first message per protocol version and the pydantic validators build on first use, which keeps imports fast but puts a one-time bill on a process's first messages. A long-running host that would rather pay that at startup than on its first request had only a DIY recipe of model_rebuild() loops. mcp_types.methods.warm(version=None, *, everything=False) is the supported version: with no argument it builds the version-independent set (the exported mcp_types models, the JSON-RPC envelopes and the routing union adapters, ~50 ms); with a version it also imports that version's wire package and builds the routing surface a connection at that version uses (so its first messages then build nothing); everything=True covers every known version. Model classes are always completed before the adapters that reference them, so no schema is generated twice, and repeat calls are no-ops. It returns a small WarmReport for logging and is re-exported as mcp.warm. Nothing in the SDK calls it. The import-cost docs recipe now uses it.
15 lines
662 B
Python
15 lines
662 B
Python
"""Prewarm the SDK's deferred startup work in a host's startup hook.
|
|
|
|
Imports stay fast because the heavy pieces load on first use: a protocol
|
|
version's wire schemas load on the first message parsed for that version, and
|
|
each pydantic model builds its validator the first time it is used. A host that
|
|
would rather pay that once, before serving traffic, calls `mcp.warm()`.
|
|
"""
|
|
|
|
import mcp
|
|
|
|
# Build the deferred validators now: the version-independent set, plus the
|
|
# routing surface of each protocol version this host will serve.
|
|
report = mcp.warm("2025-11-25")
|
|
print(f"prewarmed {report.models} models and {report.adapters} adapters in {report.elapsed_ms} ms")
|