mcp_tool_node_abi.py 4.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """Stdio MCP servers whose native addon was built for a different Node.js (#124264).
  2. Hermes runs every stdio MCP server on its own managed Node, never the user's. A server whose
  3. ``.node`` addon was compiled under another Node (typically through the ``~/.npm/_npx`` cache the
  4. user's ``npx`` shares with ours) dies at startup with ``NODE_MODULE_VERSION`` /
  5. ``ERR_DLOPEN_FAILED`` and only its stderr says so. This module turns that stderr into an error that
  6. names the remedy: rebuild the server under Hermes's Node.
  7. """
  8. import os
  9. import re
  10. import shlex
  11. from pathlib import Path
  12. from typing import Optional
  13. _ABI_MARKERS = ("NODE_MODULE_VERSION", "ERR_DLOPEN_FAILED")
  14. _MODULE_PATH = re.compile(r"'([^'\n]+?\.node)'|(\S+?\.node):")
  15. _ABI_VERSIONS = re.compile(r"using\s+NODE_MODULE_VERSION (\d+)\..*?requires\s+NODE_MODULE_VERSION (\d+)", re.DOTALL)
  16. class NodeAbiMismatchError(RuntimeError):
  17. """A stdio server's native addon does not load under Hermes's Node. Permanent: every retry
  18. loads the same binary, so the server parks until the user rebuilds it."""
  19. def _managed(name: str) -> tuple[Optional[Path], str]:
  20. """``(binary, version)`` of Hermes's own node/npm, or ``(None, "")`` when PM has none."""
  21. try:
  22. from pm import installed_package
  23. installed = installed_package(name)
  24. except Exception:
  25. return None, ""
  26. return (installed.binary, installed.version) if installed and installed.binary else (None, "")
  27. def _package_of(module_path: str) -> tuple[Optional[Path], str]:
  28. """``(project root, package name)`` owning *module_path*: the directory above its innermost
  29. ``node_modules`` and the (possibly scoped) package under it."""
  30. parts = Path(module_path).parts
  31. marks = [i for i, part in enumerate(parts) if part == "node_modules"]
  32. if not marks or marks[-1] + 1 >= len(parts):
  33. return None, ""
  34. at = marks[-1]
  35. package = parts[at + 1]
  36. if package.startswith("@") and at + 2 < len(parts):
  37. package = f"{package}/{parts[at + 2]}"
  38. return Path(*parts[:at]), package
  39. def _remedy(root: Optional[Path], package: str, node: Path, npm: Path) -> str:
  40. """The fix in the host shell's syntax: delete an npx cache entry (Hermes's npx reinstalls it on the
  41. next start) or rebuild with Hermes's npm, Hermes's Node first on PATH because npm's shebang and its
  42. lifecycle scripts both run the first ``node`` there."""
  43. windows = os.name == "nt"
  44. q = (lambda p: "'" + str(p).replace("'", "''") + "'") if windows else (lambda p: shlex.quote(str(p)))
  45. target = f" {q(package)} --prefix {q(root)}" if root is not None else ""
  46. if windows:
  47. rebuild = f"$env:Path = {q(str(node.parent) + ';')} + $env:Path; & {q(npm)} rebuild{target}"
  48. else:
  49. rebuild = f"PATH={q(node.parent)}:\"$PATH\" {q(npm)} rebuild{target}"
  50. if root is None:
  51. return f"in the server's package directory run {rebuild}"
  52. if root.parent.name != "_npx":
  53. return rebuild
  54. delete = f"Remove-Item -Recurse -Force {q(root)}" if windows else f"rm -rf {q(root)}"
  55. return f"{delete} (Hermes reinstalls it on the next start), or {rebuild}"
  56. def node_abi_error(server_name: str, stderr_text: str) -> Optional[NodeAbiMismatchError]:
  57. """The remedy-naming error for a server whose stderr shows a native-addon load failure, else None."""
  58. if not stderr_text or not any(marker in stderr_text for marker in _ABI_MARKERS):
  59. return None
  60. found = _MODULE_PATH.search(stderr_text)
  61. module = (found.group(1) or found.group(2)) if found else ""
  62. versions = _ABI_VERSIONS.search(stderr_text)
  63. node, node_version = _managed("node")
  64. npm, _ = _managed("npm")
  65. ours = f"Hermes's Node {node_version}".strip() if node_version else "Hermes's Node"
  66. built = (f"NODE_MODULE_VERSION {versions.group(1)}; {ours} needs {versions.group(2)}" if versions
  67. else f"it does not load under {ours}")
  68. # Diagnosis first: the startup banner keeps only the first ~120 characters.
  69. head = (f"native addon built for a different Node.js ({built}): {module or 'see logs/mcp-stderr.log'}. "
  70. "Hermes runs MCP servers on its own Node; rebuild the server under it")
  71. if node is None or npm is None:
  72. return NodeAbiMismatchError(f"{head}: install Hermes's Node with `hermes pm install npm`, then run "
  73. f"`hermes mcp test {server_name}`")
  74. root, package = _package_of(module) if module else (None, "")
  75. return NodeAbiMismatchError(f"{head}: {_remedy(root, package, node, npm)}")