fix(cli): register module in sys.module during _import_server so it can find itself - #3374
Conversation
|
Thanks for the contribution. This repository only keeps pull requests open when they're linked to an issue that a maintainer has assigned to the author — CONTRIBUTING.md explains why and how we work. This PR has been closed for now because its description doesn't yet link an open issue in this repository (with If there isn't an issue for this yet, please open one — a clear description of the problem is genuinely the most useful thing for us. Then add There's no need to open a new PR — this one will be reopened. While it's closed, please push any updates as new commits rather than force-pushing, since GitHub can't reopen a PR whose branch has been rewritten. Maintainers: reopening this PR, removing the |
Bug
_import_server()loads a server file viaimportlib.util.module_from_spec()exec_module(), but never registers the resulting module insys.modulesbefore 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.modulesbefore running its code, specifically so the module can look itself up via
sys.modules[__name__]while it's still executing. The official importlibdocs 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_serverskips it, which breaks anything that relies onsys.modules[cls.__module__]at class-definition time — most notably@dataclassresolving string type annotations (viafrom __future__ import annotations, or even just a manually-quoted forward reference).Repro