{"record":{"id":"a95f4a696d051e6e","repo":"PrefectHQ/fastmcp","slug":"failed-to-execute-module-file-path-e","errorCode":null,"errorMessage":"Failed to execute module {file_path}: {e}","messagePattern":"Failed to execute module (.+?): (.+?)","errorType":"exception","errorClass":"ImportError","httpStatus":null,"severity":"error","filePath":"fastmcp_slim/fastmcp/server/providers/filesystem_discovery.py","lineNumber":276,"sourceCode":"                existing.__loader__ = spec.loader\n                existing.__file__ = str(file_path)\n                try:\n                    spec.loader.exec_module(existing)\n                except Exception as e:\n                    raise ImportError(\n                        f\"Failed to reload module {file_path}: {e}\"\n                    ) from e\n                return existing\n\n            module = importlib.util.module_from_spec(spec)\n            sys.modules[module_name] = module\n\n            try:\n                spec.loader.exec_module(module)\n            except Exception as e:\n                # Clean up sys.modules on failure\n                sys.modules.pop(module_name, None)\n                raise ImportError(f\"Failed to execute module {file_path}: {e}\") from e\n\n            return module\n        finally:\n            if path_added:\n                with contextlib.suppress(ValueError):\n                    sys.path.remove(parent_dir)\n\n\ndef extract_components(module: ModuleType) -> list[FastMCPComponent]:\n    \"\"\"Extract all MCP components from a module.\n\n    Scans all module attributes for instances of Tool, Resource,\n    ResourceTemplate, or Prompt objects created by standalone decorators,\n    or functions decorated with @tool/@resource/@prompt that have __fastmcp__ metadata.\n\n    Args:\n        module: The imported module to scan.\n","sourceCodeStart":258,"sourceCodeEnd":294,"githubUrl":"https://github.com/PrefectHQ/fastmcp/blob/1f021142978e0861cd910c8df4e8074bc7cf3978/fastmcp_slim/fastmcp/server/providers/filesystem_discovery.py#L258-L294","documentation":"First-time import path: after building the module from the spec, `spec.loader.exec_module(module)` raised. FastMCP pops the half-initialized module from sys.modules (so retries start clean) and wraps any exception in this ImportError.","triggerScenarios":"Executing a plugin file for the first time where module-level code raises anything: SyntaxError, ImportError, NameError, or a runtime error at import time.","commonSituations":"Newly added tool files with syntax errors; dependencies missing in the deployment env; module-level `open()`/network calls failing; Python version incompatibilities in the plugin.","solutions":["Read the chained cause for the real exception and fix the plugin file","Run `python -m py_compile plugin.py` to catch syntax errors early","Move side-effectful code out of module scope into functions or `if __name__ == '__main__':`","Install missing dependencies; since sys.modules is cleaned up, simply retry discovery after fixing"],"exampleFix":"// before\n# plugin.py\ncfg = open('/etc/missing.conf').read()  # FileNotFoundError at import\n// after\n# plugin.py\ndef load_cfg():\n    return open('/etc/missing.conf').read()","handlingStrategy":"try-catch","validationCode":"import py_compile; py_compile.compile(str(path), doraise=True)","typeGuard":null,"tryCatchPattern":"try:\n    mod = provider.import_module_from_file(path)\nexcept ImportError as e:\n    log.error('exec of %s failed: %s', path, e.__cause__)\n    # sys.modules is cleaned up; safe to retry after fixing the file","preventionTips":["Run py_compile or a lint pass on plugins before dropping them into the watched dir","Keep imports minimal and declare dependencies","Defer side effects (I/O, network) out of module scope"],"tags":["python","import","module-loading","plugin-discovery"],"backgroundTag":"module-exec-failed","analyzedSha":"1f021142978e0861cd910c8df4e8074bc7cf3978","analyzedAt":"2026-08-29T14:31:16.082Z","schemaVersion":2},"datasetVersion":"2026-08-29T17:17:51.833Z"}