fix(cli): register module in sys.module during _import_server so it can find itself
Bug
_import_server() loads a server file via importlib.util.module_from_spec()
exec_module(), but never registers the resulting module insys.modules
before executing it:
https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/cli/cli.py#L140-L141
Python's own import machinery always inserts a module into sys.modules
before running its code, specifically so the module can look itself up via
sys.modules[__name__] while it's still executing. The official importlib
docs include exactly this step in their reference recipe for loading a file
directly: https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
_import_server skips it, which breaks anything that relies on
sys.modules[cls.__module__] at class-definition time — most notably
@dataclass resolving string type annotations (via from __future__ import annotations, or even just a manually-quoted forward reference).
Repro
# server.py
from __future__ import annotations
from dataclasses import dataclass
from mcp.server import MCPServer
@dataclass
class AppContext:
value: str
mcp = MCPServer("repro")
-----------------------------------------------------------------------------
$ mcp dev server.py
...
File ".../dataclasses.py", line 757, in _is_type
ns = sys.modules.get(cls.__module__).__dict__
AttributeError: 'NoneType' object has no attribute '__dict__'
----------------------------------------------------------------------------
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module # so the module can find itself (dataclasses, pickle, etc.)
spec.loader.exec_module(module)