Files
ai-agent/backend/plugins/commands.py
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

249 lines
11 KiB
Python

"""``commands``: what a live plugin adds to the ``ai-agent`` CLI and to the
hub's MCP server.
A command is one of the plugin's declared actions with a name, a one-line
summary, its arguments and how to print the answer::
"commands": {
"ls": {"action": "index", "summary": "Every plan, newest first",
"output": {"rows": "plans", "columns": ["slug", "status", "title"]},
"mcp": true},
"show": {"action": "get", "summary": "One plan's markdown",
"args": [{"name": "slug", "positional": true, "required": true}],
"output": {"text": "content"}, "mcp": true}
}
* The CLI offers it as ``ai-agent plugin <id> <command> …`` (the CLI's
``plugin_commands.py``), namespaced under ``plugin`` so a plugin never
shadows a core command.
* With ``"mcp": true`` the MCP server offers it as the tool
``plugin_<id>_<command>`` — opt-in: an action is not a tool until its
plugin says so (a webhook handler, an ``inspect`` check never should be).
* Nothing new can run: a command only names an action the plugin already
declares, called through the same ``/api/plugins/{id}/actions/{action}``
route as the plugin's own pages — the caller's grants, ``ownerOnly`` and
``runAs`` apply unchanged. A ``readOnly`` action is called by GET, so a
read-scoped MCP connection can use it. So ``commands`` is not part of the
approval fingerprint.
``GET /api/plugins/commands`` lists the commands of the caller's active
plugins: the owner's installs; a guest's own installs plus the owner-managed
plugins granted to them. A non-owner never sees a command whose action is
``ownerOnly``.
"""
from __future__ import annotations
import re
from typing import Any
NAME_RE = re.compile(r"^[a-z][a-z0-9-]{0,31}$")
ARG_RE = re.compile(r"^[a-z][a-z0-9_]{0,31}$")
FIELD_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,47}$")
ARG_TYPES = frozenset({"string", "integer", "number", "boolean", "array"})
MAX_COMMANDS = 16
MAX_ARGS = 12
MAX_COLUMNS = 8
MAX_ENUM = 32
# MCP clients (Claude.ai, the Anthropic API) take ^[a-zA-Z0-9_-]{1,64}$.
TOOL_MAX = 64
# ``ai-agent plugin <verb>``: a plugin with one of these ids can't be reached
# as ``ai-agent plugin <id> …``, so it may not declare commands.
RESERVED_IDS = frozenset({
"ls", "validate", "install", "reload", "enable", "disable", "uninstall", "test",
"promote", "unpromote", "catalog", "grant", "secret", "commands", "call", "help"})
def tool_name(pid: str, name: str) -> str:
return f"plugin_{pid}_{name}"
def _arg(raw: Any, label: str, seen: set[str], errors: list[str]) -> dict[str, Any] | None:
if not isinstance(raw, dict):
errors.append(f"{label} must be an object")
return None
name = str(raw.get("name") or "")
if not ARG_RE.match(name) or name in seen or name in ("json", "query"):
errors.append(f"{label}.name invalid or duplicate (lower-case, a-z0-9_; "
f"not json or query)")
return None
seen.add(name)
typ = str(raw.get("type") or "string")
if typ not in ARG_TYPES:
errors.append(f"{label}.type must be one of {sorted(ARG_TYPES)}")
return None
out: dict[str, Any] = {"name": name, "type": typ,
"help": str(raw.get("help") or "")[:200],
"required": raw.get("required") is True,
"positional": raw.get("positional") is True}
if out["positional"] and typ == "boolean":
errors.append(f"{label}: a boolean can't be positional")
return None
if raw.get("enum") is not None:
enum = raw["enum"]
if (typ != "string" or not isinstance(enum, list) or not enum
or len(enum) > MAX_ENUM or not all(isinstance(e, str) and e for e in enum)):
errors.append(f"{label}.enum: a list of 1..{MAX_ENUM} strings, on a string arg")
return None
out["enum"] = list(dict.fromkeys(enum))
if "default" in raw:
d = raw["default"]
ok = {"string": isinstance(d, str), "integer": isinstance(d, int) and not isinstance(d, bool),
"number": isinstance(d, (int, float)) and not isinstance(d, bool),
"boolean": isinstance(d, bool),
"array": isinstance(d, list) and all(isinstance(e, str) for e in d)}[typ]
if not ok or out["required"]:
errors.append(f"{label}.default must be a {typ} (and the arg not required)")
return None
out["default"] = d
return out
def _output(raw: Any, label: str, errors: list[str]) -> dict[str, Any] | None:
if raw is None:
return None
if not isinstance(raw, dict):
errors.append(f"{label} must be an object")
return None
if raw.get("text") is not None:
if not FIELD_RE.match(str(raw["text"])):
errors.append(f"{label}.text must be a top-level field name")
return None
return {"text": str(raw["text"])}
if raw.get("rows") is not None:
cols = raw.get("columns") or []
if (not FIELD_RE.match(str(raw["rows"])) or not isinstance(cols, list)
or not 1 <= len(cols) <= MAX_COLUMNS
or not all(isinstance(c, str) and FIELD_RE.match(c) for c in cols)):
errors.append(f"{label}: rows names a top-level list field, columns 1..{MAX_COLUMNS} "
f"of its rows' field names")
return None
return {"rows": str(raw["rows"]), "columns": list(dict.fromkeys(cols))}
errors.append(f"{label} needs text or rows (or leave it out: the JSON answer)")
return None
def parse(raw: Any, pid: str, actions: dict[str, Any], errors: list[str]) -> dict[str, Any]:
"""The manifest's ``commands`` block, validated; ``{}`` when absent."""
if raw is None:
return {}
if not isinstance(raw, dict):
errors.append("commands must be an object")
return {}
if raw and pid in RESERVED_IDS:
errors.append(f"commands: a plugin named {pid!r} can't declare commands "
f"(`ai-agent plugin {pid}` is a core verb)")
return {}
if len(raw) > MAX_COMMANDS:
errors.append(f"commands: at most {MAX_COMMANDS}")
return {}
out: dict[str, Any] = {}
for name, spec in raw.items():
label = f"commands.{name}"
if not NAME_RE.match(str(name)):
errors.append(f"{label}: invalid name (lower-case, a-z0-9-, ≤ 32)")
continue
if not isinstance(spec, dict):
errors.append(f"{label} must be an object")
continue
act = spec.get("action")
if not isinstance(act, str) or act not in actions:
errors.append(f"{label}.action must name a declared action")
continue
summary = str(spec.get("summary") or "").strip()
if not summary:
errors.append(f"{label}.summary is required (the --help line and the MCP description)")
continue
args_raw = spec.get("args") or []
if not isinstance(args_raw, list) or len(args_raw) > MAX_ARGS:
errors.append(f"{label}.args: a list of at most {MAX_ARGS}")
continue
seen: set[str] = set()
args = [a for i, r in enumerate(args_raw)
if (a := _arg(r, f"{label}.args[{i}]", seen, errors))]
if len(args) != len(args_raw):
continue
pos = [a for a in args if a["positional"]]
first_opt = next((i for i, a in enumerate(pos) if not a["required"]), len(pos))
if any(a["required"] for a in pos[first_opt:]):
errors.append(f"{label}.args: a required positional can't follow an optional one")
continue
if any(a["type"] == "array" for a in pos[:-1]):
errors.append(f"{label}.args: only the last positional may be an array")
continue
output = _output(spec.get("output"), f"{label}.output", errors)
if spec.get("output") is not None and output is None:
continue
mcp = spec.get("mcp") is True
if mcp and len(tool_name(pid, str(name))) > TOOL_MAX:
errors.append(f"{label}: the MCP tool name {tool_name(pid, str(name))!r} is over "
f"{TOOL_MAX} characters — shorten the command name")
continue
out[str(name)] = {
"action": act,
"summary": summary[:200],
"description": str(spec.get("description") or "").strip()[:2000],
"args": args,
"output": output,
"mcp": mcp,
"destructive": spec.get("destructive") is True,
}
return out
def _rows(pid: str, mf: dict[str, Any], is_owner: bool) -> list[dict[str, Any]]:
acts = mf.get("actions") or {}
rows = []
for name, c in (mf.get("commands") or {}).items():
act = acts.get(c.get("action")) or {}
if not act or (act.get("ownerOnly") and not is_owner):
continue
rows.append({
"plugin": pid, "pluginName": mf.get("name") or pid, "name": name,
"summary": c.get("summary") or "", "description": c.get("description") or "",
"action": c["action"], "readOnly": bool(act.get("readOnly")),
"args": c.get("args") or [], "output": c.get("output"),
"mcp": bool(c.get("mcp")), "destructive": bool(c.get("destructive")),
"tool": tool_name(pid, name) if c.get("mcp") else None,
})
return rows
def commands_for(deps, caller) -> list[dict[str, Any]]:
"""The commands of every plugin active for ``caller``, by plugin id."""
from plugins.store import OWNER_UID # not at import: store → … → manifest → here
store = getattr(deps, "plugin_store", None)
if store is None:
return []
uid = OWNER_UID if caller.is_owner else caller.id
out: list[dict[str, Any]] = []
seen: set[str] = set()
for rec in store.active_declaring(uid, "commands"):
seen.add(rec["id"])
out += _rows(rec["id"], rec.get("manifest") or {}, caller.is_owner)
if uid != OWNER_UID:
for rec in store.active_declaring(OWNER_UID, "commands"):
mf = rec.get("manifest") or {}
if rec["id"] in seen or not mf.get("managed"):
continue
if store.effective_grant(uid, rec["id"], mf).get("enabled"):
out += _rows(rec["id"], mf, False)
return sorted(out, key=lambda r: (r["plugin"], r["name"]))
def summary_items(manifest: dict[str, Any]) -> list[dict[str, Any]]:
"""The "what it can access" rows of a plugin that declares commands."""
cmds = manifest.get("commands") or {}
if not cmds:
return []
pid = manifest.get("id") or "<id>"
names = ", ".join(f"`{n}`" for n in cmds)
items = [{"kind": "commands",
"label": f"Adds command(s) to the `ai-agent` CLI — `ai-agent plugin {pid} …`: {names}"}]
tools = [tool_name(pid, n) for n, c in cmds.items() if c.get("mcp")]
if tools:
items.append({"kind": "commands",
"label": "Offers MCP tool(s) to the AI apps you connect: "
+ ", ".join(f"`{t}`" for t in tools)})
return items