Skip to content

The agent that grows with you

feat(plugins): portable plugins get the Settings > Plugins form, live

Teknium2d35f6184baa
diff --git a/apps/desktop/src/store/agent-plugins.test.ts b/apps/desktop/src/store/agent-plugins.test.ts
index 3e3e4069394..b1576ce9eb9 100644
--- a/apps/desktop/src/store/agent-plugins.test.ts
+++ b/apps/desktop/src/store/agent-plugins.test.ts
@@ -118,6 +118,25 @@ describe('saveAgentPluginSettings (#46600, #87934)', () => {
expect($agentPlugins.get()[0].settings_schema).toEqual([])
})
+ // The backend's settings save is what announces `plugin.<id>.settings.changed`; a new API key alone
+ // is the change a plugin's Desktop half most needs to hear about.
+ it('still makes the settings call when only a secret changed', async () => {
+ $agentPluginsProfile.set('workbot')
+ const request = vi.fn(async () => ({ ok: true, plugin: row({ key: 'demo', source: 'user' }) }))
+
+ await saveAgentPluginSettings(request as never, {
+ failMessage: 'fail',
+ key: 'demo',
+ profile: 'workbot',
+ secrets: { DEMO_API_KEY: 'sk-2' },
+ values: {},
+ writeSecret: vi.fn(async () => ({ ok: true }))
+ })
+
+ expect(request).toHaveBeenCalledWith('plugins.manage', { action: 'settings', key: 'demo', profile: 'workbot', values: {} })
+ expect(JSON.stringify(request.mock.calls)).not.toContain('sk-2')
+ })
+
// The list is shared across profiles: a save that lands after the list moved
// to another profile must neither patch that list nor refetch over it.
it('leaves a list loaded for another profile alone', async () => {
diff --git a/apps/desktop/src/store/agent-plugins.ts b/apps/desktop/src/store/agent-plugins.ts
index 3dd96e0365e..41a048a3bd5 100644
--- a/apps/desktop/src/store/agent-plugins.ts
+++ b/apps/desktop/src/store/agent-plugins.ts
@@ -476,8 +476,12 @@ export async function saveAgentPluginSettings(
}
}
+ // A secret-only save still makes the (empty) settings call: the backend's save is what tells a
+ // Desktop half `plugin.<id>.settings.changed`, and a new API key is the change it most needs.
+ const wroteSecret = Object.values(opts.secrets).some(Boolean)
+
const result =
- Object.keys(opts.values).length > 0
+ Object.keys(opts.values).length > 0 || wroteSecret
? await request<{ ok?: boolean; plugin?: AgentPluginRow | null }>(
'plugins.manage',
withProfile({ action: 'settings', key: opts.key, values: opts.values }, opts.profile)
diff --git a/hermes_cli/plugin_validate.py b/hermes_cli/plugin_validate.py
index 1f18c048365..def36b10594 100644
--- a/hermes_cli/plugin_validate.py
+++ b/hermes_cli/plugin_validate.py
@@ -661,6 +661,8 @@ def _validate_portable_plugin(report: ValidationReport, plugin_dir: Path) -> Val
bool(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")})
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.py
index 3b643fbdce3..f866cde44ac 100644
--- a/hermes_cli/plugins_manifest.py
+++ b/hermes_cli/plugins_manifest.py
@@ -493,10 +493,14 @@ def portable_plugin_manifest(child: Path, source: str, prefix: str) -> PluginMan
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 None
return 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 {},
)
diff --git a/hermes_cli/plugins_settings.py b/hermes_cli/plugins_settings.py
index 4c5350be0bb..d392785a6d0 100644
--- a/hermes_cli/plugins_settings.py
+++ b/hermes_cli/plugins_settings.py
@@ -36,25 +36,40 @@ _ENV_NAME_CLEAN_RE = re.compile(r"[^A-Z0-9]+")
def _manifest_config_schema(plugin_dir: Optional[Path]) -> Mapping[str, Mapping[str, Any]]:
- """``config_schema`` mapping from ``<plugin_dir>/plugin.yaml``; ``{}`` when absent or malformed
- (the loader already warned about malformed entries at load time)."""
+ """``config_schema`` from ``<plugin_dir>/plugin.yaml``, or for a portable package from
+ ``plugin.json`` ``extensions.com.nousresearch.hermes.config_schema`` (Agent Plugins v1 forbids
+ unknown top-level fields, so Hermes-specific keys live in the vendor namespace); ``{}`` when
+ absent or malformed (the loader already warned about malformed entries at load time)."""
if plugin_dir is None:
return {}
manifest = Path(plugin_dir) / "plugin.yaml"
- if not manifest.is_file():
- return {}
try:
- from utils import fast_safe_load
- data = fast_safe_load(manifest.read_text(encoding="utf-8-sig")) or {}
+ if manifest.is_file():
+ from utils import fast_safe_load
+ data = fast_safe_load(manifest.read_text(encoding="utf-8-sig")) or {}
+ raw = data.get("config_schema") if isinstance(data, Mapping) else None
+ else:
+ raw = portable_config_schema(Path(plugin_dir))
except Exception as exc: # unreadable manifest: no settings surface, never a failed list
- logger.debug("plugin settings: cannot read %s: %s", manifest, exc)
+ logger.debug("plugin settings: cannot read the manifest in %s: %s", plugin_dir, exc)
return {}
- raw = data.get("config_schema") if isinstance(data, Mapping) else None
if not isinstance(raw, 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():
+ return None
+ import 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
+
+
def secret_env_name(plugin_id: str, key: str, spec: Mapping[str, Any]) -> str:
"""``.env`` variable a ``type: secret`` field is stored under: the manifest's ``env:`` or
``<PLUGIN_ID>_<KEY>`` upper-snaked (``image_gen/fal`` + ``api_key`` → ``IMAGE_GEN_FAL_API_KEY``)."""
diff --git a/tests/tools/test_mcp_restart_on_new_inputs.py b/tests/tools/test_mcp_restart_on_new_inputs.py
new file mode 100644
index 00000000000..3c1d1a771f2
--- /dev/null
+++ b/tests/tools/test_mcp_restart_on_new_inputs.py
@@ -0,0 +1,82 @@
+"""A plugin settings save reconnects only the MCP servers whose resolved launch inputs changed:
+a new ``${VAR}`` value the server's ``env`` passes through restarts it with that value; a save that
+changes nothing it launches with leaves the live connection alone. Real stdio child, real config."""
+
+import json
+import os
+import sys
+import textwrap
+import time
+
+import pytest
+
+SERVER = textwrap.dedent('''\
+ import os
+ from mcp.server.mcpserver import MCPServer
+ app = MCPServer("envecho")
+
+ @app.tool()
+ def key() -> str:
+ return os.environ.get("DEMO_KEY", "")
+
+ app.run()
+''')
+
+
+def _pid_of(core, name):
+ srv = core._servers.get(name)
+ session = getattr(srv, "session", None)
+ return id(session) if session is not None else None
+
+
[email protected](sys.platform == "win32", reason="sh launcher")
+def test_restart_only_when_resolved_launch_inputs_change(monkeypatch, tmp_path):
+ pytest.importorskip("mcp.server.mcpserver")
+ home = tmp_path / "home"
+ home.mkdir()
+ # A portable plugin's server: it joins the config AFTER load's ${VAR} render pass, the case where
+ # an unrendered recompute reads every save as "changed".
+ plugin = home / "plugins" / "envecho"
+ plugin.mkdir(parents=True)
+ (plugin / "server.py").write_text(SERVER, encoding="utf-8")
+ launcher = plugin / "run.sh" # portable commands are bare or ./-relative: wrap this interpreter
+ launcher.write_text(f'#!/bin/sh\nexec "{sys.executable}" "$(dirname "$0")/server.py"\n', encoding="utf-8")
+ launcher.chmod(0o755)
+ (plugin / "plugin.json").write_text(json.dumps({
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name": "envecho"}), encoding="utf-8")
+ (plugin / "mcp.json").write_text(json.dumps({
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json", "mcpServers": {"envecho": {
+ "type": "stdio", "command": "./run.sh", "cwd": "${PLUGIN_ROOT}",
+ "env": {"DEMO_KEY": "${DEMO_KEY}"}}}}), encoding="utf-8")
+ (home / "config.yaml").write_text("plugins:\n enabled: [envecho]\n", encoding="utf-8")
+ (home / ".env").write_text("DEMO_KEY=first\n", encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setenv("DEMO_KEY", "first")
+
+ from hermes_cli.config import save_env_value
+ from tools import mcp_tool_discovery as disc
+ from tools import mcp_tool_loop as _loop
+ from tools.mcp_tool_common import _core
+
+ try:
+ disc.discover_mcp_tools()
+ first = _core._servers["envecho"]._resolved_identity
+ session = _pid_of(_core, "envecho")
+ assert first and session
+
+ assert disc.restart_mcp_servers_with_new_inputs({"envecho"}) == [] # nothing it launches with moved
+ assert _pid_of(_core, "envecho") == session
+
+ save_env_value("DEMO_KEY", "second") # what the settings form's secret save does
+ assert 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)
+ assert _core._servers["envecho"]._resolved_identity != first
+ assert os.environ["DEMO_KEY"] == "second"
+ finally:
+ from tools.mcp_tool_lifecycle import shutdown_mcp_servers
+ shutdown_mcp_servers()
+ _loop._stop_mcp_loop()
diff --git a/tests/tui_gateway/test_plugins_manage_settings.py b/tests/tui_gateway/test_plugins_manage_settings.py
index 8a274e5e70c..55a27d9cf02 100644
--- a/tests/tui_gateway/test_plugins_manage_settings.py
+++ b/tests/tui_gateway/test_plugins_manage_settings.py
@@ -64,3 +64,38 @@ def test_settings_writes_the_plugin_namespace_and_refuses_secrets_and_bad_types(
for values in ({"api_key": "leak"}, {"retries": "two"}, {"mode": "reckless"}, {"unknown": 1}):
assert _manage(action="settings", key="demo-plugin", values=values)["error"]["code"] == 4021
assert "api_key" not in (plugins_home / "config.yaml").read_text(encoding="utf-8")
+
+
+PORTABLE_MANIFEST = """\
+{
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
+ "name": "portable-demo",
+ "version": "1.0.0",
+ "extensions": {"com.nousresearch.hermes": {"config_schema": {
+ "show_chip": {"type": "bool", "default": true},
+ "api_key": {"type": "secret", "env": "PORTABLE_DEMO_KEY"}
+ }}}
+}
+"""
+
+
+def test_portable_plugin_json_schema_lists_and_saves_like_a_native_one(plugins_home, monkeypatch):
+ """Agent Plugins v1 forbids unknown top-level fields, so a portable package declares its form under
+ ``extensions.com.nousresearch.hermes.config_schema``; it must get the same list + save path, and a
+ save tells the plugin's Desktop half (``plugin.<id>.settings.changed``) so it applies without polling."""
+ sent = []
+ monkeypatch.setattr(server, "_broadcast_global_event", lambda name, payload: sent.append((name, payload)))
+ (plugins_home / "plugins" / "portable-demo").mkdir()
+ (plugins_home / "plugins" / "portable-demo" / "plugin.json").write_text(PORTABLE_MANIFEST, encoding="utf-8")
+
+ rows = _manage(action="list")["result"]["plugins"]
+ fields = {f["key"]: f for f in next(r for r in rows if r["key"] == "portable-demo")["settings_schema"]}
+ assert fields["show_chip"]["type"] == "boolean" and fields["show_chip"]["value"] is True
+ assert fields["api_key"]["type"] == "secret" and fields["api_key"]["env"] == "PORTABLE_DEMO_KEY"
+
+ resp = _manage(action="settings", key="portable-demo", values={"show_chip": False})
+ assert resp["result"]["written"] == ["show_chip"]
+ from hermes_cli.config import load_config_readonly
+ assert load_config_readonly()["plugins"]["entries"]["portable-demo"]["settings"] == {"show_chip": False}
+ assert sent == [("plugin.portable-demo.settings.changed", {"written": ["show_chip"]})]
+ assert _manage(action="settings", key="portable-demo", values={"api_key": "leak"})["error"]["code"] == 4021
diff --git a/tools/mcp_tool_discovery.py b/tools/mcp_tool_discovery.py
index 118527c2298..46ce572f351 100644
--- a/tools/mcp_tool_discovery.py
+++ b/tools/mcp_tool_discovery.py
@@ -755,6 +755,34 @@ def mcp_servers_awaiting_connect() -> list[str]:
return _awaiting_connect(_enabled_config_names(), _core._mcp_registry_scope())
+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 form
+ saved 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:
+ logger.info("MCP server(s) %s: launch inputs changed; reconnecting", ", ".join(changed))
+ _lifecycle.shutdown_mcp_servers(scope=scope, names=set(changed))
+ for name in changed:
+ _clear_connect_failure(name)
+ discover_mcp_tools()
+ return changed
+
+
def _forget_lazy_server(key) -> None:
"""Drop a schema-cache (lazy) registration whose config entry is gone: its cached tools would
otherwise stay callable and spawn the server on first use."""
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index a5cd314117c..54dc851aaa5 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -1817,9 +1817,31 @@ def _plugins_settings(rid, params):
except (ValueError, PermissionError) as e:
return _err(rid, 4021, str(e))
row = next((r for r in _plugin_rows() if r["key"] == canonical), None)
+ # A Desktop half applies its own preferences (a status-bar chip on/off) without polling.
+ events = _tools_mod("hermes_cli.plugin_events")
+ if events._PLUGIN_ID_RE.match(canonical): # category keys (``image_gen/fal``) form no event name
+ events.broadcast_plugin_event(canonical, "settings.changed", {"written": written})
+ # A secret the form just stored may feed the plugin's MCP server env (``${MESHY_API_KEY}``): bounce
+ # only servers whose resolved launch inputs changed, off the RPC thread (an npx start takes seconds).
+ 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
+ discovery = _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()
return _ok(rid, {"ok": True, "name": canonical, "written": written, "plugin": row})
+def _portable_server_names(plugin_dir: Path, key: str) -> set[str]:
+ package = _tools_mod("hermes_cli.agent_plugins").load_agent_plugin(plugin_dir, plugin_dir)
+ name_for = _tools_mod("hermes_cli.plugins_manifest").portable_mcp_server_name
+ return {name_for(key, server) for server in package.mcp_servers}
+
+
def _plugins_onboarding(rid, params):
"""Catalog plugins curated for the onboarding card that this OS runs, each with its app state."""
return _ok(rid, {"onboarding": _tools_mod("hermes_cli.plugin_catalog_presence").onboarding_entries()})
diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.md
index dc1c04fcf05..47e5ac56975 100644
--- a/website/docs/developer-guide/plugins/index.md
+++ b/website/docs/developer-guide/plugins/index.md
@@ -975,6 +975,35 @@ Never read `.env`, `auth.json` or another tool's credential files yourself (cata
The `plugins.manage settings` action refuses secret keys and any value whose type
or `choices` disagree with the schema.
+**Portable packages (`plugin.json`)** declare the same schema under the Hermes
+vendor namespace, since Agent Plugins v1 rejects unknown top-level fields:
+
+```json
+{
+ "extensions": {
+ "com.nousresearch.hermes": {
+ "config_schema": {
+ "api_key": { "type": "secret", "env": "MY_PLUGIN_API_KEY" },
+ "show_chip": { "type": "bool", "default": true, "label": "Show the status-bar chip" }
+ }
+ }
+ }
+}
+```
+
+A secret whose `env` names a variable your `mcp.json` passes through
+(`"env": { "MY_PLUGIN_API_KEY": "${MY_PLUGIN_API_KEY}" }`) reaches the MCP server
+right away: after a save, Hermes reconnects the plugin's servers whose resolved
+launch inputs changed (a new key does, a toggle does not), so the form is also
+where users set the server's key.
+
+**React to a save without polling.** Every save broadcasts
+`plugin.<id>.settings.changed` (payload `{ written: [...keys] }`; a secret-only
+save sends an empty list), so a Desktop half re-reads its preferences at once:
+`ctx.onEvent('plugin.my-plugin.settings.changed', reload)`. Read the values from
+your own `plugin_api.py` with `load_config_readonly()` from `hermes_cli.config`
+(`plugins.entries.<id>.settings`), falling back to the schema defaults.
+
## Step 6: Test it
Start Hermes: