The rest of the host side of the mcp-servers plugin (spec §4.4–4.7):
- ui.slots[].where "machine.detail" (a machine page's Tools tab) and
ui.pages[].nav "none" (routable, in no nav — an OAuth callback page).
- provides machine.attention (plugins/machine_attention.py): the owner's
providers answer {items: [{machine, key, title, detail?, tone}]};
GET /api/machines/attention (owner, lab.read) serves them with pluginId,
cached 30 s. A provider's non-read-only action, webhook, scheduled job,
or an install / enable / disable / uninstall drops the cache and
publishes SSE machine-attention.
- carryover.mcp_servers: once the plugin is installed and enabled for the
owner (at start, or right after its install / enable), the core's old
/data/mcp-servers.json servers and the lab's and workers' ticks go to
the plugin's _private/servers.json / overrides.json (accounts as
claude:<id>, mode direct), merged under the plugin's own, then a
.carried-over marker; the old file stays.
- A purged uninstall also drops the plugin's relay file.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
149 lines
5.0 KiB
Python
149 lines
5.0 KiB
Python
"""What waits for the owner on each of his machines, from live plugins
|
|
(``provides: {"machine.attention": "<action>"}``, 2026-11-26 — the
|
|
``mcp-servers`` plugin's "2 MCP servers need a sign-in").
|
|
|
|
Each provider's action runs as the owner (stdin ``{"trigger":
|
|
"machine.attention"}``) and answers ``{"items": [{machine, key, title,
|
|
detail?, tone: "warn"|"error"}]}``; ``GET /api/machines/attention`` (owner,
|
|
``lab.read``) serves every provider's, ``pluginId`` added, cached
|
|
:data:`TTL_SECS`. The machine page's *Needs you* strip draws each item of its
|
|
machine (*Open* → the Tools tab, scrolled to ``#plugin-slot-<pluginId>``) and
|
|
a worker card's Setup checklist one row per provider.
|
|
|
|
:func:`touched` drops the cache and publishes SSE ``{"type":
|
|
"machine-attention"}`` when a provider ran an action that may change
|
|
something (not one marked ``readOnly``), a webhook or a scheduled job, or was
|
|
installed, enabled, disabled or uninstalled.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import re
|
|
import threading
|
|
import time
|
|
from typing import Any
|
|
|
|
from plugins.store import OWNER_UID
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
PROVIDES = "machine.attention"
|
|
TTL_SECS = 30.0
|
|
TONES = ("warn", "error")
|
|
MAX_ITEMS = 200
|
|
_MACHINE_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
|
|
|
|
_lock = threading.Lock()
|
|
_cache: tuple[float, list[dict[str, Any]]] | None = None
|
|
|
|
|
|
def invalidate() -> None:
|
|
global _cache
|
|
with _lock:
|
|
_cache = None
|
|
|
|
|
|
def provides(rec: dict[str, Any] | None) -> bool:
|
|
return PROVIDES in (((rec or {}).get("manifest") or {}).get("provides") or {})
|
|
|
|
|
|
def touched(deps, rec: dict[str, Any] | None, *, action: str | None = None) -> None:
|
|
"""The plugin ``rec`` ran something: when it provides machine attention
|
|
(and ``action``, if named, isn't read-only), drop the cache and tell the
|
|
app to refetch."""
|
|
if not provides(rec):
|
|
return
|
|
if action:
|
|
act = (((rec or {}).get("manifest") or {}).get("actions") or {}).get(action) or {}
|
|
if act.get("readOnly"):
|
|
return
|
|
changed()
|
|
try:
|
|
deps.hub.publish({"type": "machine-attention"})
|
|
except Exception: # noqa: BLE001 — no hub (tests)
|
|
pass
|
|
|
|
|
|
def changed() -> None:
|
|
"""A provider came or went (install, enable, disable, uninstall)."""
|
|
invalidate()
|
|
|
|
|
|
def _providers(deps) -> list[tuple[dict[str, Any], str]]:
|
|
from plugins.waiting import _providers_for
|
|
try:
|
|
found = _providers_for(deps, OWNER_UID, PROVIDES)
|
|
except Exception: # noqa: BLE001 — no plugin store (tests, early boot)
|
|
return []
|
|
out = []
|
|
for rec, _grant in found:
|
|
mf = rec.get("manifest") or {}
|
|
act = (mf.get("provides") or {}).get(PROVIDES)
|
|
if act in (mf.get("actions") or {}):
|
|
out.append((rec, act))
|
|
return out
|
|
|
|
|
|
def has_provider(deps) -> bool:
|
|
return bool(_providers(deps))
|
|
|
|
|
|
def _text(v: Any, n: int) -> str | None:
|
|
if not isinstance(v, (str, int, float)) or isinstance(v, bool):
|
|
return None
|
|
s = re.sub(r"\s+", " ", str(v)).strip()
|
|
return s[:n] or None
|
|
|
|
|
|
def normalize(pid: str, raw: Any) -> list[dict[str, Any]]:
|
|
"""A provider's answer → its valid items (``pluginId`` added)."""
|
|
items = raw.get("items") if isinstance(raw, dict) else None
|
|
out: list[dict[str, Any]] = []
|
|
for it in items if isinstance(items, list) else []:
|
|
if not isinstance(it, dict):
|
|
continue
|
|
machine = _text(it.get("machine"), 64)
|
|
key, title = _text(it.get("key"), 120), _text(it.get("title"), 200)
|
|
if not machine or not _MACHINE_RE.match(machine) or not key or not title:
|
|
continue
|
|
row: dict[str, Any] = {"pluginId": pid, "machine": machine, "key": key, "title": title,
|
|
"tone": it.get("tone") if it.get("tone") in TONES else "warn"}
|
|
detail = _text(it.get("detail"), 400)
|
|
if detail:
|
|
row["detail"] = detail
|
|
out.append(row)
|
|
if len(out) >= MAX_ITEMS:
|
|
break
|
|
return out
|
|
|
|
|
|
def _fetch(deps) -> list[dict[str, Any]]:
|
|
from plugins.runner import run_script
|
|
out: list[dict[str, Any]] = []
|
|
for rec, action in _providers(deps):
|
|
act = (rec.get("manifest") or {}).get("actions", {}).get(action) or {}
|
|
try:
|
|
res = run_script(deps, deps.plugin_store, OWNER_UID, rec, act["script"],
|
|
payload={"trigger": PROVIDES},
|
|
timeout_sec=min(20, int(act.get("timeoutSec") or 20)))
|
|
except Exception as e: # noqa: BLE001 — a broken plugin never breaks the hub
|
|
log.warning("%s via %s failed: %s", PROVIDES, rec.get("id"), e)
|
|
continue
|
|
out.extend(normalize(rec["id"], res))
|
|
return out
|
|
|
|
|
|
def items(deps) -> list[dict[str, Any]]:
|
|
"""Every provider's items (copies), cached :data:`TTL_SECS`."""
|
|
global _cache
|
|
now = time.monotonic()
|
|
with _lock:
|
|
c = _cache
|
|
if c is not None and now - c[0] < TTL_SECS:
|
|
return [dict(x) for x in c[1]]
|
|
got = _fetch(deps)
|
|
with _lock:
|
|
_cache = (time.monotonic(), got)
|
|
return [dict(x) for x in got]
|