The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Portable plugins declare the application each MCP server needs; install refuses on an unsupported host (NS-942) (#119049)
Siddharth Balyanadefd996711f
diff --git a/hermes_cli/agent_plugins.py b/hermes_cli/agent_plugins.pyindex 01366b60113..fa258cbd094 100644--- a/hermes_cli/agent_plugins.py+++ b/hermes_cli/agent_plugins.py@@ -12,6 +12,35 @@ from typing import Any, Dict, Mapping, Tuplefrom urllib.parse import urlsplitfrom agent.skill_utils import yaml_load+from hermes_platform.declaration import Declaration, parse_declaration++_HERMES_EXTENSION = "com.nousresearch.hermes"+_LIVENESS: Dict[str, dict] = {}+++def liveness_for(server_name: str) -> dict | None:+ """Return a copy of the portable server's liveness declaration."""+ value = _LIVENESS.get(server_name)+ return dict(value) if value is not None else None+++def _set_liveness(server_name: str, value: object) -> None:+ if value is None:+ _LIVENESS.pop(server_name, None)+ elif isinstance(value, dict):+ _LIVENESS[server_name] = dict(value)+ else:+ raise AgentPluginError(f"server '{server_name}' liveness must be an object")+++def _clear_liveness(server_name: str) -> None:+ _LIVENESS.pop(server_name, None)+++@dataclass(frozen=True)+class AgentPluginServerDeclaration:+ declaration: Declaration+ liveness: dict | NonePLUGIN_SCHEMA_V1 = "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json"MCP_SCHEMA_V1 = "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"@@ -56,9 +85,45 @@ class AgentPluginPackage:manifest: Mapping[str, Any]skills: Tuple[AgentPluginSkill, ...]mcp_servers: Mapping[str, Dict[str, Any]]+ server_declarations: Mapping[str, AgentPluginServerDeclaration]diagnostics: Tuple[AgentPluginDiagnostic, ...]+def _server_declarations(+ manifest: Mapping[str, Any], mcp_servers: Mapping[str, Dict[str, Any]]+) -> Dict[str, AgentPluginServerDeclaration]:+ namespace = manifest.get("extensions", {}).get(_HERMES_EXTENSION, {})+ raw_servers = namespace.get("servers", {})+ if not isinstance(raw_servers, dict):+ raise AgentPluginError(f"extension '{_HERMES_EXTENSION}'.servers must be an object")+ declarations: Dict[str, AgentPluginServerDeclaration] = {}+ for name, raw in raw_servers.items():+ if name not in mcp_servers:+ raise AgentPluginError(f"server declaration '{name}' has no matching mcp.json server")+ if not isinstance(raw, dict):+ raise AgentPluginError(f"server declaration '{name}' must be an object")+ if "liveness" in raw and "app" not in raw and "requires" not in raw:+ raise AgentPluginError(f"server declaration '{name}' has liveness without app or requires")+ unknown = set(raw) - {"app", "requires", "liveness"}+ if unknown:+ raise AgentPluginError(f"server declaration '{name}' has unknown keys {sorted(unknown)}")+ try:+ declaration = parse_declaration(+ name, raw.get("app"), raw.get("requires"),+ where=f"plugin.json extension server {name!r}",+ )+ except ValueError as exc:+ raise AgentPluginError(str(exc)) from exc+ liveness = raw.get("liveness")+ if liveness is not None and not isinstance(liveness, dict):+ raise AgentPluginError(f"server declaration '{name}' liveness must be an object")+ declarations[name] = AgentPluginServerDeclaration(+ declaration=declaration,+ liveness=dict(liveness) if liveness is not None else None,+ )+ return declarations++def _inside(path: Path, root: Path) -> bool:try:return path.resolve(strict=False).is_relative_to(root.resolve(strict=True))@@ -359,11 +424,15 @@ def load_agent_plugin(plugin_root: Path, data_root: Path) -> AgentPluginPackage:"""Validate and translate one installed Agent Plugins v1 package."""root, manifest, diagnostics = _validate_root(plugin_root)resolved_data = Path(data_root).resolve(strict=False)- return AgentPluginPackage( # skills are discovered before MCP: diagnostics keep that order+ skills = _discover_skills(root, diagnostics)+ mcp_servers = _discover_mcp(root, resolved_data, diagnostics)+ return AgentPluginPackage(name=manifest["name"], version=manifest.get("version", ""),description=manifest.get("description", ""), root=root, data_root=resolved_data,- manifest=dict(manifest), skills=_discover_skills(root, diagnostics),- mcp_servers=_discover_mcp(root, resolved_data, diagnostics), diagnostics=tuple(diagnostics))+ manifest=dict(manifest), skills=skills, mcp_servers=mcp_servers,+ server_declarations=_server_declarations(manifest, mcp_servers),+ diagnostics=tuple(diagnostics),+ )def read_agent_plugin_manifest(plugin_root: Path) -> tuple[dict, tuple[AgentPluginDiagnostic, ...]]:diff --git a/hermes_cli/plugin_validate.py b/hermes_cli/plugin_validate.pyindex 47b5f0617ac..490c412099a 100644--- a/hermes_cli/plugin_validate.py+++ b/hermes_cli/plugin_validate.py@@ -592,15 +592,17 @@ def _validate_portable_plugin(report: ValidationReport, plugin_dir: Path) -> Valdiagnostics (schema shape, name, supported subset)."""try:- from hermes_cli.agent_plugins import read_agent_plugin_manifest+ from hermes_cli.agent_plugins import load_agent_plugin+ from hermes_platform.resolver.availability import availability- manifest, diagnostics = read_agent_plugin_manifest(plugin_dir)+ with tempfile.TemporaryDirectory() as data_root:+ package = load_agent_plugin(plugin_dir, Path(data_root))+ manifest = package.manifest+ diagnostics = package.diagnosticsexcept Exception as exc:report.add("portable manifest", False, f"plugin.json failed validation: {exc}")return report- # The portable reader raises on hard failures; surviving diagnostics are- # advisory (unsupported-subset notes etc.) — surface them as warnings.for diag in diagnostics:scope = getattr(diag, "scope", "")message = getattr(diag, "message", str(diag))@@ -613,6 +615,14 @@ def _validate_portable_plugin(report: ValidationReport, plugin_dir: Path) -> Valbool(name),"name present" if name else "plugin.json missing required 'name'",)+ for server_name, server_decl in package.server_declarations.items():+ result = availability(server_decl.declaration)+ detail = result.state+ if result.version:+ detail += f", version {result.version}"+ if result.path:+ detail += f", path {result.path}"+ report.add(f"server availability: {server_name}", True, detail)_check_security_scan(report, plugin_dir)check_desktop_surface(report, plugin_dir)return reportdiff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.pyindex a9bd2ad11f0..c4fdcaee76c 100644--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@ -698,6 +698,26 @@ def _ensure_tree_readable(root: Path, plugins_dir: Path) -> None:) from exc+def _refuse_unavailable_portable_plugin(plugin_name: str, tree: Path) -> None:+ if not (tree / "plugin.json").is_file():+ return+ from hermes_cli.agent_plugins import load_agent_plugin+ from hermes_platform.resolver.availability import availability++ try:+ package = load_agent_plugin(tree, tree.parent / ".hermes-install-data")+ except ValueError as exc:+ raise PluginOperationError(f"Plugin '{plugin_name}' is unavailable: {exc}.") from exc+ for server_name, server_decl in package.server_declarations.items():+ result = availability(server_decl.declaration)+ if result.offerable:+ continue+ found = f", found version {result.version}" if result.version else ""+ raise PluginOperationError(+ f"Plugin '{plugin_name}' server '{server_name}' is unavailable: {result.state}{found}."+ )++def _swap_in_plugin(tmp_target: Path, target: Path, backup: Path, old_metadata: dict, new_metadata: dict) -> None:"""Move the validated clone into place and persist metadata; on any failure restore theprevious tree (if one was replaced) and the previous metadata sidecar, then re-raise."""@@ -781,6 +801,7 @@ def _install_plugin_core(reviewed_pin=at_reviewed_pin)if python_deps:_refuse_conflicting_python_deps(tmp_target, plugin_name)+ _refuse_unavailable_portable_plugin(plugin_name, tmp_target)if before_swap is not None:before_swap(manifest, tmp_target)diff --git a/hermes_cli/plugins_cmd_catalog.py b/hermes_cli/plugins_cmd_catalog.pyindex d831b32d02a..f14c5363b71 100644--- a/hermes_cli/plugins_cmd_catalog.py+++ b/hermes_cli/plugins_cmd_catalog.py@@ -168,6 +168,28 @@ def removed_annotation(name: str, dir_path, removed_entries: List[RemovedEntry])# ── Catalog-aware install / update ───────────────────────────────────────────+_PLATFORM_ALIASES = {"windows": "win32", "macos": "darwin"}+++def normalized_platforms(platforms: List[str]) -> set[str]:+ """Return catalog platform names in host OS-family vocabulary."""+ return {_PLATFORM_ALIASES.get(value.lower(), value.lower()) for value in platforms}+++def _refuse_unsupported_catalog_platform(entry: PluginCatalogEntry) -> None:+ if not entry.platforms:+ return+ from hermes_cli.plugins_cmd import PluginOperationError+ from hermes_platform.host.facts import os_family++ current = os_family()+ if current not in normalized_platforms(entry.platforms):+ raise PluginOperationError(+ f"Plugin '{entry.name}' is unavailable on {current}; supported platforms: "+ f"{', '.join(entry.platforms)}."+ )++def install_catalog_entry(entry: PluginCatalogEntry, *, force: bool, ref: Optional[str] = None,allow_removed: bool = False, scan_decision_cb=None, python_deps: bool = True,before_swap=None) -> tuple:@@ -177,6 +199,7 @@ def install_catalog_entry(entry: PluginCatalogEntry, *, force: bool, ref: Optionfrom hermes_cli.plugins_cmd import _install_plugin_core, pinned_revisionif not allow_removed:raise_if_removed(entry.name, entry.repo)+ _refuse_unsupported_catalog_platform(entry)target, manifest, installed_name = _install_plugin_core(entry.install_identifier, force=force, ref=ref or entry.sha, scan_decision_cb=scan_decision_cb,reviewed_pin=entry.sha, python_deps=python_deps, allow_removed=allow_removed, before_swap=before_swap,diff --git a/hermes_cli/plugins_loader.py b/hermes_cli/plugins_loader.pyindex 0b7ea5acc4d..a710a53e200 100644--- a/hermes_cli/plugins_loader.py+++ b/hermes_cli/plugins_loader.py@@ -523,17 +523,41 @@ class PluginLoaderMixin:ctx.register_skill(skill.name, skill.skill_md, skill.description, skill.frontmatter)except Exception as exc:logger.warning("Agent Plugin '%s' skill '%s' skipped: %s", lookup_key, skill.name, exc)- for server_name, config in package.mcp_servers.items():- internal_name = f"{manifest.skill_namespace}__{server_name}"- if internal_name in self._portable_mcp_servers:- logger.warning("Agent Plugin '%s' MCP server collision: %s", lookup_key, internal_name)- continue- self._portable_mcp_servers[internal_name] = dict(config)- self._portable_mcp_server_plugins[internal_name] = lookup_key- loaded.enabled = True+ from hermes_cli.agent_plugins import _clear_liveness, _set_liveness+ from hermes_platform import declaration+ registered: list[str] = []+ try:+ for server_name, config in package.mcp_servers.items():+ internal_name = f"{manifest.skill_namespace}__{server_name}"+ if internal_name in self._portable_mcp_servers:+ logger.warning("Agent Plugin '%s' MCP server collision: %s", lookup_key, internal_name)+ continue+ self._portable_mcp_servers[internal_name] = dict(config)+ self._portable_mcp_server_plugins[internal_name] = lookup_key+ server_decl = package.server_declarations.get(server_name)+ if server_decl is not None:+ declaration.register(internal_name, server_decl.declaration)+ _set_liveness(internal_name, server_decl.liveness)+ registered.append(internal_name)+ for internal_name in registered:+ def release(name: str = internal_name) -> None:+ self._portable_mcp_servers.pop(name, None)+ self._portable_mcp_server_plugins.pop(name, None)+ declaration.unregister(name)+ _clear_liveness(name)++ self._track_registration(manifest, "portable_mcp", internal_name, release)+ loaded.enabled = True+ except BaseException:+ for internal_name in registered:+ self._portable_mcp_servers.pop(internal_name, None)+ self._portable_mcp_server_plugins.pop(internal_name, None)+ declaration.unregister(internal_name)+ _clear_liveness(internal_name)+ raiseexcept (Exception, SystemExit) as exc:loaded.error = _load_error_text(exc)- logger.warning("Failed to load Agent Plugin '%s': %s", lookup_key, loaded.error)+ logger.warning("Agent Plugin '%s' disabled: %s", lookup_key, loaded.error)self._plugins[lookup_key] = loadeddef _directory_module_name(self, manifest: PluginManifest) -> str:diff --git a/tests/hermes_cli/test_agent_plugins.py b/tests/hermes_cli/test_agent_plugins.pyindex 2c070faa5fa..797bb319d5c 100644--- a/tests/hermes_cli/test_agent_plugins.py+++ b/tests/hermes_cli/test_agent_plugins.py@@ -94,6 +94,59 @@ def test_rejects_invalid_manifests(tmp_path: Path, manifest: object) -> None:load_agent_plugin(tmp_path, tmp_path / "data")+def test_server_declaration_joins_mcp_and_preserves_liveness(tmp_path: Path) -> None:+ app = tmp_path / "example-app"+ app.write_text("", encoding="utf-8")+ _write_json(+ tmp_path / "plugin.json",+ _manifest(extensions={+ "com.nousresearch.hermes": {"servers": {"worker": {+ "app": {"darwin": {"presence": "executable", "location": str(app)}},+ "requires": {"app": True},+ "liveness": {"kind": "static"},+ }}}+ }),+ )+ _write_json(+ tmp_path / "mcp.json",+ {"$schema": MCP_SCHEMA_V1, "mcpServers": {"worker": {"type": "stdio", "command": "python"}}},+ )++ package = load_agent_plugin(tmp_path, tmp_path / "data")++ server = package.server_declarations["worker"]+ assert server.declaration.requires_app+ assert server.liveness == {"kind": "static"}+++def test_orphan_server_declaration_disables_package(tmp_path: Path) -> None:+ _write_json(+ tmp_path / "plugin.json",+ _manifest(extensions={+ "com.nousresearch.hermes": {"servers": {"orphan": {"requires": {"app": False}}}}+ }),+ )++ with pytest.raises(AgentPluginError, match="orphan.*no matching mcp.json server"):+ load_agent_plugin(tmp_path, tmp_path / "data")+++def test_liveness_without_declaration_disables_package(tmp_path: Path) -> None:+ _write_json(+ tmp_path / "plugin.json",+ _manifest(extensions={+ "com.nousresearch.hermes": {"servers": {"worker": {"liveness": {"kind": "static"}}}}+ }),+ )+ _write_json(+ tmp_path / "mcp.json",+ {"$schema": MCP_SCHEMA_V1, "mcpServers": {"worker": {"type": "stdio", "command": "python"}}},+ )++ with pytest.raises(AgentPluginError, match="liveness without app or requires"):+ load_agent_plugin(tmp_path, tmp_path / "data")++def test_unknown_fields_and_non_object_extensions_are_nonfatal(tmp_path: Path) -> None:_write_json(tmp_path / "plugin.json",diff --git a/tests/hermes_cli/test_plugin_validate.py b/tests/hermes_cli/test_plugin_validate.pyindex d9e1ef61d1f..9bfac96ae1c 100644--- a/tests/hermes_cli/test_plugin_validate.py+++ b/tests/hermes_cli/test_plugin_validate.py@@ -6,6 +6,7 @@ recording stub context.from __future__ import annotations+import jsonfrom pathlib import Pathimport yaml@@ -27,6 +28,48 @@ def _make_plugin(return d+def _portable_plugin(root: Path, servers: dict, declarations: dict) -> Path:+ from hermes_cli.agent_plugins import MCP_SCHEMA_V1, PLUGIN_SCHEMA_V1++ root.mkdir()+ (root / "plugin.json").write_text(json.dumps({+ "$schema": PLUGIN_SCHEMA_V1,+ "name": "example-plugin",+ "extensions": {"com.nousresearch.hermes": {"servers": declarations}},+ }), encoding="utf-8")+ (root / "mcp.json").write_text(json.dumps({+ "$schema": MCP_SCHEMA_V1,+ "mcpServers": servers,+ }), encoding="utf-8")+ return root+++def test_portable_validation_fails_orphan_and_reports_availability(tmp_path: Path) -> None:+ orphan = _portable_plugin(+ tmp_path / "orphan",+ {},+ {"worker": {"requires": {"app": False}}},+ )+ report = validate_plugin_dir(orphan)+ assert not report.ok+ assert any("no matching mcp.json server" in failure for failure in report.failures)++ app = tmp_path / "example-app"+ declared = _portable_plugin(+ tmp_path / "declared",+ {"worker": {"type": "stdio", "command": "python"}},+ {"worker": {+ "app": {"darwin": {"presence": "executable", "location": str(app)}},+ "requires": {"app": True},+ }},+ )+ report = validate_plugin_dir(declared)+ assert any(+ name == "server availability: worker" and ok and detail in {"missing_app", "unsupported_os"}+ for name, ok, detail in report.checks+ )++BASE_MANIFEST = {"name": "fixture-plugin","version": "1.0.0",diff --git a/tests/hermes_cli/test_plugins.py b/tests/hermes_cli/test_plugins.pyindex 2e9c5bc146d..c577ce436b6 100644--- a/tests/hermes_cli/test_plugins.py+++ b/tests/hermes_cli/test_plugins.py@@ -170,8 +170,18 @@ class TestPluginDiscovery:plugin = home / "plugins" / "portable"skill = plugin / "skills" / "summarize"skill.mkdir(parents=True)+ app = tmp_path / "example-app"+ app.write_text("", encoding="utf-8")(plugin / "plugin.json").write_text(- json.dumps({"$schema": PLUGIN_SCHEMA_V1, "name": "portable.test"})+ json.dumps({+ "$schema": PLUGIN_SCHEMA_V1,+ "name": "portable.test",+ "extensions": {"com.nousresearch.hermes": {"servers": {"worker": {+ "app": {"darwin": {"presence": "executable", "location": str(app)}},+ "requires": {"app": True},+ "liveness": {"kind": "static"},+ }}}},+ }))(skill / "SKILL.md").write_text("---\nname: summarize\ndescription: Summarize reports.\n---\nBody.\n"@@ -213,6 +223,15 @@ class TestPluginDiscovery:assert manager._plugins["portable.test"].enabled is Trueassert manager._plugins["native"].enabled is Trueassert manager._plugins["native"].module is not None+ internal_name = next(iter(manager.get_portable_mcp_servers()))+ from hermes_cli.agent_plugins import liveness_for+ from hermes_platform import declaration++ assert declaration.lookup(internal_name) is not None+ assert liveness_for(internal_name) == {"kind": "static"}+ manager.unload("portable.test")+ assert declaration.lookup(internal_name) is None+ assert liveness_for(internal_name) is Nonedef test_disabled_portable_plugin_registers_nothing(self, tmp_path, monkeypatch):from hermes_cli.agent_plugins import PLUGIN_SCHEMA_V1diff --git a/tests/hermes_cli/test_plugins_cmd.py b/tests/hermes_cli/test_plugins_cmd.pyindex 285dbf14cda..1c3bce1bb31 100644--- a/tests/hermes_cli/test_plugins_cmd.py+++ b/tests/hermes_cli/test_plugins_cmd.py@@ -2,6 +2,7 @@from __future__ import annotations+import jsonimport loggingimport osimport shutil@@ -15,6 +16,7 @@ from hermes_cli.plugins_cmd import (PluginOperationError,_copy_example_files,_read_manifest,+ _refuse_unavailable_portable_plugin,_repo_name_from_url,_resolve_git_executable,_resolve_git_url,@@ -23,6 +25,35 @@ from hermes_cli.plugins_cmd import ()+def _write_portable_app_plugin(root: Path, app: Path) -> None:+ from hermes_cli.agent_plugins import MCP_SCHEMA_V1, PLUGIN_SCHEMA_V1+ from hermes_platform.host.facts import os_family++ (root / "plugin.json").write_text(json.dumps({+ "$schema": PLUGIN_SCHEMA_V1,+ "name": "example-plugin",+ "extensions": {"com.nousresearch.hermes": {"servers": {"worker": {+ "app": {os_family(): {"presence": "executable", "location": str(app)}},+ "requires": {"app": True},+ }}}},+ }), encoding="utf-8")+ (root / "mcp.json").write_text(json.dumps({+ "$schema": MCP_SCHEMA_V1,+ "mcpServers": {"worker": {"type": "stdio", "command": "python"}},+ }), encoding="utf-8")+++def test_portable_install_gate_accepts_present_app_and_refuses_missing(tmp_path: Path) -> None:+ app = tmp_path / "example-app"+ app.write_text("", encoding="utf-8")+ _write_portable_app_plugin(tmp_path, app)++ _refuse_unavailable_portable_plugin("example-plugin", tmp_path)+ app.unlink()+ with pytest.raises(PluginOperationError, match="example-plugin.*worker.*missing_app"):+ _refuse_unavailable_portable_plugin("example-plugin", tmp_path)++# ── _sanitize_plugin_name ─────────────────────────────────────────────────diff --git a/tests/hermes_cli/test_plugins_cmd_catalog.py b/tests/hermes_cli/test_plugins_cmd_catalog.pyindex 7f6a5fdf777..3c860627d0c 100644--- a/tests/hermes_cli/test_plugins_cmd_catalog.py+++ b/tests/hermes_cli/test_plugins_cmd_catalog.py@@ -64,6 +64,18 @@ def _head(path: Path) -> str:return sp.run(["git", "rev-parse", "HEAD"], cwd=path, capture_output=True, text=True).stdout.strip()+def test_catalog_platform_mismatch_refuses_before_install(world, monkeypatch):+ entry = pc_cat.PluginCatalogEntry(+ name="cat-plugin", repo=world["repo"].as_uri(), sha=world["sha1"],+ description="d", maintainer="t", platforms=["windows"],+ )+ monkeypatch.setattr("hermes_platform.host.facts.os_family", lambda: "darwin")++ with pytest.raises(pc.PluginOperationError, match="cat-plugin.*darwin.*windows"):+ cat.install_catalog_entry(entry, force=False)+ assert not (world["plugins_dir"] / "cat-plugin").exists()++def test_catalog_name_installs_pinned_sha_with_sidecar_then_update_repins(world, monkeypatch):entry = pc_cat.get_live_catalog_entry("cat-plugin")assert entry is not None