Files
gabrielvidalandClaude Opus 5.5 319560f8d9 feat(plugins): live plugins add their own ai-agent CLI commands and MCP tools
A plugin declares `commands` in plugin.json — each one names a declared
action, with a summary, its args and how to print the answer — and gets
`ai-agent plugin <id> <command> …` and, opt-in (`"mcp": true`), the MCP
tool `plugin_<id>_<command>`. Core no longer names any plugin
(Gabriel's form ai-agent-cli-and-mcp-for-live-plugins_fevcts: manifest
commands, namespaced under `plugin`, MCP opt-in, guests by their grants).

- backend/plugins/commands.py: validation (names, typed args, positional
  order, output text|rows, ≤ 64-char tool names, no commands for a plugin
  named like a core verb) and the caller's catalogue; GET
  /api/plugins/commands (plugins.use — a guest's CLI and AI-app connection
  see the plugins granted to them, never an ownerOnly action). Not in the
  approval fingerprint: a command only reaches an action the plugin already
  declares, through the same route. The consent card lists them.
- cli/plugin_commands.py: the per-plugin argparse parser, table/text
  printing, `ai-agent plugin commands`, `ai-agent plugin call ID ACTION`
  (any action, raw), and the MCP tool specs. readOnly actions go by GET
  ?payload=, so read-only MCP connections work.
- cli/mcp_tools.py: tools/list appends the plugin tools (read group when
  readOnly, run otherwise; none on a worker-bound connection);
  tools/call runs them.
- Removed the hard-coded plugin surfaces: `ai-agent plans|memories|goals`,
  MCP browse plans|goals|memories, read_document, work_on_goal (goals is
  not used — Gabriel). Plans and memories come back as their plugins'
  commands. This also fixes read-only MCP connections, which got "this
  connection is read-only" on plans and memories since they moved to
  plugins (the CLI POSTed). `ai-agent plans` now says where its commands are.
- openapi.json + orval regenerated, authz golden matrix (+1 route), docs
  (plugins.md "Commands", mcp.md, CLAUDE.md, create-plugin skill).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 23:17:09 +01:00

227 lines
9.1 KiB
Python

"""``ai-agent plugin`` subcommands: validate, ls, install, reload, enable,
disable, uninstall, test, catalog, promote, grant, secret — and a live
plugin's own commands: ``ai-agent plugin commands`` lists them,
``ai-agent plugin <id> <command> …`` runs one, ``ai-agent plugin call <id>
<action>`` any declared action raw (``plugin_commands.py``).
Runs against the hub's ``/api/plugins/*`` endpoints — works for both the owner
and (via the hub broker) guests with ``cli.use``.
"""
from __future__ import annotations
import argparse
import json
import pathlib
import sys
from typing import Callable
VERBS = ("ls", "validate", "install", "reload", "enable", "disable", "uninstall", "test",
"promote", "unpromote", "catalog", "grant", "secret", "commands", "call")
def is_plugin_command(argv: list[str]) -> bool:
"""``ai-agent plugin <id> …`` with ``<id>`` not one of :data:`VERBS`: a
plugin's own command (``plugin_commands.run_cli``)."""
return (len(argv) >= 2 and argv[0] == "plugin" and argv[1] not in VERBS
and argv[1] != "help" and not argv[1].startswith("-"))
def add_parser(sub) -> argparse.ArgumentParser:
pl = sub.add_parser(
"plugin",
help="live plugins: ls | validate | install | reload | enable | disable | uninstall | "
"test | promote | catalog | grant | secret | commands | call — or a plugin's own "
"command: ai-agent plugin <id> <command> …",
epilog="A plugin's own commands (its plugin.json `commands`): `ai-agent plugin "
"commands` lists them, `ai-agent plugin <id> <command> …` runs one "
"(`ai-agent plugin <id> --help`).")
pl.add_argument("action", nargs="?", default="ls", choices=VERBS)
pl.add_argument("target", nargs="?", help="plugin id, local folder path, or git URL")
pl.add_argument("extra", nargs="?", help="grant: guest uid · secret: secret key name · "
"call: the action")
pl.add_argument("--payload", default=None,
help="call: the action's JSON payload (- = stdin)")
pl.add_argument("--get", action="store_true",
help="call: by GET (a readOnly action; what a read-only caller may use)")
pl.add_argument("--catalog", dest="from_catalog", action="store_true",
help="install: install by catalog id")
pl.add_argument("--as", dest="as_uid", default="",
help="install: operator installs on behalf of guest uid")
pl.add_argument("--approve", action="store_true",
help="reload: approve widened capabilities")
pl.add_argument("--purge", action="store_true",
help="uninstall: also delete stored secrets and data")
pl.add_argument("--no-guests", action="store_true",
help="promote: owner-only catalog entry")
pl.add_argument("--refresh", action="store_true",
help="validate: git pull before validating")
pl.add_argument("--off", action="store_true",
help="grant: revoke/disable managed plugin for guest")
pl.add_argument("--budget", type=float, default=None,
help="grant: per-plugin monthly USD cap for guest")
pl.add_argument("--config", dest="grant_config", default="",
help="grant: JSON object of grantFields config")
pl.add_argument("--no-verify", action="store_true",
help="secret: skip proxy.inspect check when saving")
pl.add_argument("--json", action="store_true")
return pl
def _resolve_target(target: str | None) -> str:
if not target:
return ""
if "://" in target or target.startswith("git@"):
return target
p = pathlib.Path(target).expanduser()
return str(p.resolve()) if p.exists() else target
def run(a, api_call: Callable) -> int:
act = a.action
if act == "ls":
data = api_call("GET", "/api/plugins")
if a.json:
print(json.dumps(data, indent=2))
return 0
installed = data.get("installed") or []
if not installed:
print("No plugins installed.")
for p in installed:
state = "needs-approval" if p.get("needsApproval") else ("on" if p.get("enabled") else "off")
sk = f"skill:{p['skillName']}" if p.get("skillName") else "-"
print(f"{p['id']:<20} {state:<14} v{p.get('version','?'):<8} {sk:<18} {p.get('name','')}")
return 0
if act == "catalog":
data = api_call("GET", "/api/plugins")
cat = data.get("catalog") or []
if a.json:
print(json.dumps(cat, indent=2))
return 0
if not cat:
print("Hub plugin catalog is empty.")
for c in cat:
guests = "guests" if c.get("guestsAllowed") else "owner-only"
print(f"{c['id']:<20} v{c.get('version','?'):<8} {guests:<11} {c.get('name','')}")
return 0
if not a.target:
print(f"ai-agent plugin {act}: target required", file=sys.stderr)
return 2
if act == "validate":
src = _resolve_target(a.target)
res = api_call("POST", "/api/plugins/validate", {"source": src, "refresh": bool(a.refresh)})
if a.json:
print(json.dumps(res, indent=2))
return 0
mf = res["manifest"]
print(f"OK: {mf['id']} ({mf['name']} v{mf['version']}) fingerprint={res['fingerprint']}")
for c in res.get("capabilities") or []:
mark = "!" if c.get("privileged") else "·"
print(f" {mark} {c['label']}")
return 0
if act == "install":
body: dict = {"approve": True}
if a.from_catalog:
body["catalogId"] = a.target
else:
body["source"] = _resolve_target(a.target)
if getattr(a, "as_uid", ""):
body["asUid"] = a.as_uid
res = api_call("POST", "/api/plugins/install", body)
if a.json:
print(json.dumps(res, indent=2))
return 0
who_s = f" for {a.as_uid}" if getattr(a, "as_uid", "") else ""
print(f"Installed {res['id']} ({res['name']} v{res['version']}){who_s} — live.")
return 0
if act == "reload":
res = api_call("POST", f"/api/plugins/{a.target}/reload", {"approve": bool(a.approve)})
if a.json:
print(json.dumps(res, indent=2))
return 0
note = " (needs re-approval: pass --approve)" if res.get("needsApproval") else " — live"
print(f"Reloaded {res['id']} v{res['version']}{note}.")
return 0
if act in ("enable", "disable"):
res = api_call("PUT", f"/api/plugins/{a.target}", {"enabled": act == "enable"})
if a.json:
print(json.dumps(res, indent=2))
return 0
print(f"{res['id']}: {'enabled' if res['enabled'] else 'disabled'}.")
return 0
if act == "uninstall":
q = "?purge=true" if a.purge else ""
res = api_call("DELETE", f"/api/plugins/{a.target}{q}")
if a.json:
print(json.dumps(res, indent=2))
return 0
print(f"Uninstalled {a.target}.")
return 0
if act == "test":
res = api_call("POST", f"/api/plugins/{a.target}/test", {})
print(json.dumps(res, indent=2))
return 0
if act == "promote":
src = _resolve_target(a.target)
res = api_call("POST", "/api/plugins/catalog",
{"source": src, "guestsAllowed": not a.no_guests})
if a.json:
print(json.dumps(res, indent=2))
return 0
print(f"Promoted {res['id']} to hub catalog.")
return 0
if act == "unpromote":
res = api_call("DELETE", f"/api/plugins/catalog/{a.target}")
if a.json:
print(json.dumps(res, indent=2))
return 0
print(f"Removed {a.target} from hub catalog.")
return 0
if act == "grant":
if not a.extra:
print("ai-agent plugin grant <pid> <uid> [--off] [--budget N] [--config JSON]", file=sys.stderr)
return 2
body = {"enabled": not bool(a.off)}
if a.budget is not None:
body["monthlyBudgetUsd"] = a.budget
if a.grant_config:
body["config"] = json.loads(a.grant_config)
res = api_call("PUT", f"/api/plugins/managed/grants/{a.extra}/{a.target}", body)
if a.json:
print(json.dumps(res, indent=2))
return 0
state = "granted" if res["grant"]["enabled"] else "revoked"
print(f"{a.target} → {a.extra}: {state}.")
return 0
if act == "secret":
if not a.extra:
print("ai-agent plugin secret <pid> <key> [--no-verify] (reads secret from stdin)", file=sys.stderr)
return 2
val = sys.stdin.read().strip()
if not val:
print("ai-agent plugin secret: empty secret on stdin", file=sys.stderr)
return 2
res = api_call("PUT", f"/api/plugins/{a.target}/secrets/{a.extra}",
{"value": val, "verify": not bool(a.no_verify)})
if a.json:
print(json.dumps(res, indent=2))
return 0
print(f"Stored secret {a.target}/{a.extra} (length {len(val)}).")
return 0
return 2