The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): settings MCP reload is serialized, borrow-aware, one schema reader
Tekniumfe78f95bbb29
diff --git a/hermes_cli/agent_plugins.py b/hermes_cli/agent_plugins.pyindex 73192ca32bc..f983c39060c 100644--- a/hermes_cli/agent_plugins.py+++ b/hermes_cli/agent_plugins.py@@ -490,6 +490,15 @@ def load_agent_plugin(plugin_root: Path, data_root: Path) -> AgentPluginPackage:)+def manifest_config_schema(manifest: Any) -> Any:+ """Raw ``extensions.com.nousresearch.hermes.config_schema`` of a parsed ``plugin.json`` (Agent+ Plugins v1 forbids unknown top-level fields), else ``None``. Unvalidated: the settings form+ filters it, the loader and ``plugins validate`` report what is malformed."""+ extensions = manifest.get("extensions") if isinstance(manifest, dict) else None+ hermes = extensions.get(_HERMES_EXTENSION) if isinstance(extensions, dict) else None+ return hermes.get("config_schema") if isinstance(hermes, dict) else None++def read_agent_plugin_manifest(plugin_root: Path) -> tuple[dict, tuple[AgentPluginDiagnostic, ...]]:"""Validate only root ``plugin.json`` without discovering components."""_root, manifest, diagnostics = _validate_root(plugin_root)diff --git a/hermes_cli/plugin_validate.py b/hermes_cli/plugin_validate.pyindex def36b10594..916a4834789 100644--- a/hermes_cli/plugin_validate.py+++ b/hermes_cli/plugin_validate.py@@ -661,8 +661,8 @@ def _validate_portable_plugin(report: ValidationReport, plugin_dir: Path) -> Valbool(name),"name present" if name else "plugin.json missing required 'name'",)- hermes_ext = manifest.get("extensions", {}).get("com.nousresearch.hermes", {})- _check_config_spec(report, {"config_schema": hermes_ext.get("config_schema")})+ from hermes_cli.agent_plugins import manifest_config_schema+ _check_config_spec(report, {"config_schema": manifest_config_schema(manifest)})for server_name, config in package.mcp_servers.items():if config.get("trust") == "untrusted":report.add(f"server trust: {server_name}", True,diff --git a/hermes_cli/plugins_manifest.py b/hermes_cli/plugins_manifest.pyindex f866cde44ac..95419c36c6b 100644--- a/hermes_cli/plugins_manifest.py+++ b/hermes_cli/plugins_manifest.py@@ -126,6 +126,26 @@ def _manifest_int(raw: object, key: str, warn: str, fallback: Optional[int]) ->return fallback+def _config_schema_entries(key: str, raw: Any) -> dict[str, Any]:+ """``config_schema`` (key -> {type?, default?, description?, ...}) keeping only mapping entries;+ warns on what it drops or cannot type-check. Shared by ``plugin.yaml`` and ``plugin.json``."""+ schema: dict[str, Any] = {}+ for skey, spec in (raw if isinstance(raw, Mapping) else {}).items():+ if not isinstance(spec, Mapping):+ logger.warning(+ "Plugin %s: config_schema entry %r must be a mapping (e.g. {type: str}); skipping", key, skey)+ continue+ stype = spec.get("type")+ if stype is not None and str(stype).lower() not in _CONFIG_SCHEMA_TYPES:+ logger.warning(+ "Plugin %s: config_schema key %r declares unknown type %r "+ "(known: %s); type check will be skipped for it",+ key, skey, stype, ", ".join(sorted(_CONFIG_SCHEMA_TYPES)),+ )+ schema[str(skey)] = dict(spec)+ return schema++def _parse_manifest_v2_fields(data: Mapping, key: str) -> dict[str, Any]:"""Validate/normalize manifest v2 fields into PluginManifest kwargs (warnings, never failures).@@ -153,22 +173,7 @@ def _parse_manifest_v2_fields(data: Mapping, key: str) -> dict[str, Any]:lambda item: item.strip() if isinstance(item, str) and item.strip() else None,"Plugin %s: python_dependencies entry %r must be a non-empty requirement string; skipping",)- # config_schema — mapping of key -> {type?, default?, description?, required?}.- schema: dict[str, Any] = {}- raw_schema = _manifest_field_of_type(data, key, "config_schema", Mapping, "a mapping")- for skey, spec in (raw_schema or {}).items():- if not isinstance(spec, Mapping):- logger.warning(- "Plugin %s: config_schema entry %r must be a mapping (e.g. {type: str}); skipping", key, skey)- continue- stype = spec.get("type")- if stype is not None and str(stype).lower() not in _CONFIG_SCHEMA_TYPES:- logger.warning(- "Plugin %s: config_schema key %r declares unknown type %r "- "(known: %s); type check will be skipped for it",- key, skey, stype, ", ".join(sorted(_CONFIG_SCHEMA_TYPES)),- )- schema[str(skey)] = dict(spec)+ schema = _config_schema_entries(key, _manifest_field_of_type(data, key, "config_schema", Mapping, "a mapping"))tags = [str(t) for t in (_manifest_field_of_type(data, key, "tags", list, "a list") or [])]# Forward compat: unknown fields warn (never fail); v1 manifests only at debug.unknown = sorted(set(data.keys()) - _KNOWN_MANIFEST_FIELDS)@@ -488,19 +493,16 @@ def requires_hermes_error(manifest: PluginManifest) -> Optional[str]:def portable_plugin_manifest(child: Path, source: str, prefix: str) -> PluginManifest:"""Build the manifest for a portable Agent Plugin directory (``plugin.json``); diagnostics warn."""- from hermes_cli.agent_plugins import read_agent_plugin_manifest+ from hermes_cli.agent_plugins import manifest_config_schema, read_agent_plugin_manifestdata, diagnostics = read_agent_plugin_manifest(child)for diagnostic in diagnostics:logger.warning("Agent Plugin '%s': %s", child, diagnostic.message)key = f"{prefix}/{child.name}" if prefix else data["name"]- hermes = data.get("extensions", {}).get("com.nousresearch.hermes", {})- schema = hermes.get("config_schema") if isinstance(hermes, Mapping) else Nonereturn PluginManifest(name=data["name"], version=data.get("version", ""), description=data.get("description", ""),author=_display_author(data.get("author", "")), source=source, path=str(child), key=key,portable=True, skill_namespace=_portable_skill_namespace(key),- config_schema={str(k): dict(v) for k, v in schema.items() if isinstance(v, Mapping)}- if isinstance(schema, Mapping) else {},+ config_schema=_config_schema_entries(key, manifest_config_schema(data)),)diff --git a/hermes_cli/plugins_settings.py b/hermes_cli/plugins_settings.pyindex d392785a6d0..3230d303468 100644--- a/hermes_cli/plugins_settings.py+++ b/hermes_cli/plugins_settings.py@@ -49,7 +49,7 @@ def _manifest_config_schema(plugin_dir: Optional[Path]) -> Mapping[str, Mapping[data = fast_safe_load(manifest.read_text(encoding="utf-8-sig")) or {}raw = data.get("config_schema") if isinstance(data, Mapping) else Noneelse:- raw = portable_config_schema(Path(plugin_dir))+ raw = _portable_config_schema(Path(plugin_dir))except Exception as exc: # unreadable manifest: no settings surface, never a failed listlogger.debug("plugin settings: cannot read the manifest in %s: %s", plugin_dir, exc)return {}@@ -57,17 +57,14 @@ def _manifest_config_schema(plugin_dir: Optional[Path]) -> Mapping[str, Mapping[return {}return {str(k): v for k, v in raw.items() if isinstance(v, Mapping)}--def portable_config_schema(plugin_dir: Path) -> Any:- """Raw ``extensions.com.nousresearch.hermes.config_schema`` of a ``plugin.json``, else ``None``."""- manifest = plugin_dir / "plugin.json"- if not manifest.is_file():+def _portable_config_schema(plugin_dir: Path) -> Any:+ portable = plugin_dir / "plugin.json"+ if not portable.is_file():return Noneimport json- data = json.loads(manifest.read_text(encoding="utf-8-sig"))- extensions = data.get("extensions") if isinstance(data, Mapping) else None- hermes = extensions.get("com.nousresearch.hermes") if isinstance(extensions, Mapping) else None- return hermes.get("config_schema") if isinstance(hermes, Mapping) else None+ from hermes_cli.agent_plugins import manifest_config_schema+ return manifest_config_schema(json.loads(portable.read_text(encoding="utf-8-sig")))+def secret_env_name(plugin_id: str, key: str, spec: Mapping[str, Any]) -> str:diff --git a/tests/tools/test_mcp_restart_on_new_inputs.py b/tests/tools/test_mcp_restart_on_new_inputs.pyindex 3c1d1a771f2..999f4e14584 100644--- a/tests/tools/test_mcp_restart_on_new_inputs.py+++ b/tests/tools/test_mcp_restart_on_new_inputs.py@@ -6,7 +6,6 @@ import jsonimport osimport sysimport textwrap-import timeimport pytest@@ -30,7 +29,7 @@ def _pid_of(core, name):@pytest.mark.no_isolate[email protected](sys.platform == "win32", reason="sh launcher")[email protected]("posix")def test_restart_only_when_resolved_launch_inputs_change(monkeypatch, tmp_path):pytest.importorskip("mcp.server.mcpserver")home = tmp_path / "home"@@ -70,10 +69,8 @@ def test_restart_only_when_resolved_launch_inputs_change(monkeypatch, tmp_path):save_env_value("DEMO_KEY", "second") # what the settings form's secret save doesassert disc.restart_mcp_servers_with_new_inputs({"envecho"}) == ["envecho"]- deadline = time.monotonic() + 30- while _core._servers.get("envecho") is None or _pid_of(_core, "envecho") in (None, session):- assert time.monotonic() < deadline, "server did not reconnect"- time.sleep(0.2)+ # Returns only once reconnected, so a later save compares against THIS connection's inputs.+ assert _pid_of(_core, "envecho") not in (None, session)assert _core._servers["envecho"]._resolved_identity != firstassert os.environ["DEMO_KEY"] == "second"finally:diff --git a/tools/mcp_tool_discovery.py b/tools/mcp_tool_discovery.pyindex 46ce572f351..3eb3657d997 100644--- a/tools/mcp_tool_discovery.py+++ b/tools/mcp_tool_discovery.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport asyncioimport logging+import threadingimport timefrom contextlib import contextmanagerfrom pathlib import Path@@ -755,32 +756,48 @@ def mcp_servers_awaiting_connect() -> list[str]:return _awaiting_connect(_enabled_config_names(), _core._mcp_registry_scope())+# One settings-driven reconnect at a time (see restart_mcp_servers_with_new_inputs).+_RESTART_LOCK = threading.Lock()++def restart_mcp_servers_with_new_inputs(names: set[str]) -> list[str]:"""Reconnect each live server in *names* whose resolved launch inputs (stdio command/env/cwd,HTTP url/headers) no longer hash to what it connected with, e.g. after a plugin settings formsaved a new ``${VAR}`` its ``env`` passes through. A server whose inputs did not change keeps- its connection. Returns the names restarted."""- scope = _core._mcp_registry_scope()- with _owner_secret_scope():- servers = _config._load_mcp_config()- changed = []- for name in sorted(names):- config = servers.get(name)- with _core._lock:- server = _core._servers.get(_server_key(name, scope, current=False))- recorded = getattr(server, "_resolved_identity", None)- if config is None or recorded is None or not mcp_server_enabled(config):- continue- # Render as the connect path does (plugin servers join the config after load's render pass).- if _registration._adopter_identity_digest(name, _config._interpolate_env_vars(config)) != recorded:- changed.append(name)- if changed:+ its connection. Returns the names restarted.++ Serialized: a second save waits for the first reconnect, then compares against what THAT one+ connected with, so a newer key is never lost to an older in-flight start. A connection this+ profile only borrows (same inputs as another profile's) is left running for its owner; this+ profile just detaches and connects its own."""+ with _RESTART_LOCK:+ scope = _core._mcp_registry_scope()+ owned, borrowed = [], []+ with _owner_secret_scope():+ servers = _config._load_mcp_config()+ for name in sorted(names):+ config = servers.get(name)+ with _core._lock:+ key = _resolve_server_key(name, scope, current=False)+ server = _core._servers.get(key)+ recorded = getattr(server, "_resolved_identity", None)+ if config is None or recorded is None or not mcp_server_enabled(config):+ continue+ # Render as the connect path does (plugin servers join the config after load's render pass).+ if _registration._adopter_identity_digest(name, _config._interpolate_env_vars(config)) != recorded:+ (owned if key == _server_key(name, scope, current=False) else borrowed).append((name, key))+ if not owned and not borrowed:+ return []+ changed = sorted(name for name, _key in owned + borrowed)logger.info("MCP server(s) %s: launch inputs changed; reconnecting", ", ".join(changed))- _lifecycle.shutdown_mcp_servers(scope=scope, names=set(changed))+ if owned:+ _lifecycle.shutdown_mcp_servers(scope=scope, names={name for name, _key in owned})+ for _name, key in borrowed:+ _registration._remove_server_scope(key, scope)for name in changed:_clear_connect_failure(name)discover_mcp_tools()- return changed+ return changeddef _forget_lazy_server(key) -> None:diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.pyindex 54dc851aaa5..6b37fc3e18c 100644--- a/tui_gateway/methods_tools.py+++ b/tui_gateway/methods_tools.py@@ -1826,13 +1826,10 @@ def _plugins_settings(rid, params):if plugin_dir and pc._is_portable_plugin_dir(plugin_dir):servers = _portable_server_names(Path(str(plugin_dir)), canonical)if servers:- import contextvars- import threading+ from agent.memory_provider import spawn_context_thread # keeps this request's profile scopediscovery = _tools_mod("tools.mcp_tool_discovery")- # copy_context: the worker must run under THIS request's profile scope, not the process's.- ctx = contextvars.copy_context()- threading.Thread(target=ctx.run, args=(discovery.restart_mcp_servers_with_new_inputs, servers),- name=f"plugin-settings-mcp-{canonical}", daemon=True).start()+ spawn_context_thread(discovery.restart_mcp_servers_with_new_inputs, args=(servers,),+ name=f"plugin-settings-mcp-{canonical}").start()return _ok(rid, {"ok": True, "name": canonical, "written": written, "plugin": row})