main moved cron jobs into the cron-jobs plugin (#37) and retired the core Send later doors for the scheduled-conversations plugin's commands (#36), both touching the core MCP files this branch moves into the hub-mcp plugin. - The MCP stays out of core: backend/mcpserver/, cli/mcp_tools.py, cli/mcp_server.py, their tests and business/aiApps/ stay deleted (main's edits to them — no schedule group, no cron / schedule tools — are the plugin's to apply). - Cron and Send later follow main: backend/cron/routes.py gone (its by-name worker pick is runs.start's at fire time now), no ai-agent later / scheduled / unschedule — so a worker's narrowed CLI drops them from its command lists (workers/cli.py) and schedules nothing; Full reaches the plugin's commands. - authz: neither runs.schedule nor mcp.connect. - Settings: neither Scheduled jobs nor AI apps in the registry; both old addresses redirect to their plugin's page. - Regenerated openapi.json, src/generated, rolesCatalog.json, matrix.golden.txt and telemetry features.json. - cli/test_library_surface.py: parse_when left with `ai-agent later`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
323 lines
14 KiB
Python
323 lines
14 KiB
Python
"""Live plugins' commands in the ``ai-agent`` CLI and the MCP server.
|
|
|
|
A plugin declares ``commands`` in its ``plugin.json`` (backend
|
|
``plugins/commands.py``: each one names an action of the plugin, with a
|
|
summary, its arguments and how to print the answer). The hub lists the ones
|
|
active for the caller at ``GET /api/plugins/commands``; this module turns them
|
|
into
|
|
|
|
* ``ai-agent plugin <id> <command> …`` — an argparse parser built per call
|
|
(:func:`run_cli`), ``ai-agent plugin commands`` lists them all, and
|
|
``ai-agent plugin call <id> <action>`` reaches any action raw;
|
|
* MCP tools ``plugin_<id>_<command>`` for the commands marked ``mcp``
|
|
(:func:`tool_specs`, :func:`call_tool` — used by the ``hub-mcp`` plugin's
|
|
``mcp_tools.py``, which imports this module from ``AIA_CLI_DIR``).
|
|
|
|
A ``readOnly`` action is called by GET (``?payload=``), so a read-scoped MCP
|
|
connection, whose hub refuses every other method, can use it. Core knows no
|
|
plugin by name. Stdlib only, like the CLI.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import sys
|
|
import urllib.parse
|
|
from typing import Any
|
|
|
|
import ai_agent as aa # the running CLI itself (ai_agent.py aliases __main__)
|
|
|
|
CATALOGUE = "/api/plugins/commands"
|
|
# The hub's GET payload cap (plugins/routes.py _READ_PAYLOAD_MAX).
|
|
READ_PAYLOAD_MAX = 8 * 1024
|
|
|
|
|
|
# ── the hub side ─────────────────────────────────────────────────────────────
|
|
def catalogue(hub) -> list[dict]:
|
|
"""Every command of the plugins active for this caller."""
|
|
try:
|
|
return hub.get(CATALOGUE).get("commands") or []
|
|
except aa.HubError as e:
|
|
# an older hub: 404, or its app shell's HTML for an unknown GET
|
|
if e.code in (404, 405) or (e.code == 0 and "not JSON" in (e.detail or "")):
|
|
raise aa.HubError(e.code, "this hub has no plugin commands yet (update the ai-agent)") from None
|
|
raise
|
|
|
|
|
|
def _action_path(pid: str, action: str) -> str:
|
|
return (f"/api/plugins/{urllib.parse.quote(pid, safe='')}/actions/"
|
|
f"{urllib.parse.quote(action, safe='')}")
|
|
|
|
|
|
def invoke(hub, cmd: dict, payload: dict, timeout: float = 120) -> Any:
|
|
"""Run ``cmd``'s action with ``payload`` as this caller."""
|
|
path = _action_path(cmd["plugin"], cmd["action"])
|
|
try:
|
|
if cmd.get("readOnly"):
|
|
raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":")) if payload else ""
|
|
if len(raw) > READ_PAYLOAD_MAX:
|
|
raise aa.HubError(413, "arguments too long for a read")
|
|
return hub.call("GET", path, query={"payload": raw}, timeout=timeout)
|
|
return hub.call("POST", path, payload, timeout=timeout)
|
|
except aa.HubError as e:
|
|
if e.code == 404 and "not active" in (e.detail or ""):
|
|
raise aa.HubError(404, f"the {cmd.get('pluginName') or cmd['plugin']} plugin isn't "
|
|
f"installed or is off for you (Settings → Plugins)") from None
|
|
raise
|
|
|
|
|
|
def payload_from(cmd: dict, values: dict) -> dict:
|
|
"""The action's payload: each declared argument given, else its default."""
|
|
out: dict = {}
|
|
for a in cmd.get("args") or []:
|
|
v = values.get(a["name"])
|
|
if v is None or v == []:
|
|
if "default" in a and a["default"] is not None:
|
|
out[a["name"]] = a["default"]
|
|
continue
|
|
out[a["name"]] = v
|
|
return out
|
|
|
|
|
|
HERE = "."
|
|
|
|
|
|
def resolve_conversations(hub, cmd: dict, payload: dict, *, here: bool) -> dict:
|
|
"""``payload`` with each ``conversation`` argument turned into a session
|
|
id (:func:`ai_agent.resolve` — an id, a prefix, a viewer link). ``.`` is
|
|
the calling run's own session when ``here`` (the CLI), refused otherwise
|
|
(the MCP: no run behind the call)."""
|
|
out = dict(payload)
|
|
for a in cmd.get("args") or []:
|
|
v = out.get(a["name"])
|
|
if not a.get("conversation") or not isinstance(v, str) or not v.strip():
|
|
continue
|
|
if v.strip() == HERE:
|
|
if not here:
|
|
raise aa.HubError(400, f"{a['name']}: '.' (this conversation) only works from a "
|
|
f"run's ai-agent CLI — give the conversation's id")
|
|
sid = aa.resolve_session_id(guess=False)
|
|
if not sid:
|
|
raise aa.HubError(400, f"{a['name']}: '.' — no session id for this conversation "
|
|
f"($CLAUDE_SESSION_ID is unset)")
|
|
out[a["name"]] = sid
|
|
else:
|
|
out[a["name"]] = aa.resolve(hub, v)["sessionId"]
|
|
return out
|
|
|
|
|
|
# ── printing ─────────────────────────────────────────────────────────────────
|
|
def _cell(v: Any) -> str:
|
|
if v is None:
|
|
return ""
|
|
if isinstance(v, bool):
|
|
return "yes" if v else ""
|
|
if isinstance(v, (list, tuple)):
|
|
return ", ".join(c for c in (_cell(x) for x in v) if c)
|
|
if isinstance(v, dict):
|
|
return json.dumps(v, ensure_ascii=False, default=str)
|
|
return " ".join(str(v).split())
|
|
|
|
|
|
def _rows_of(cmd: dict, result: Any) -> list | None:
|
|
out = cmd.get("output") or {}
|
|
if not out.get("rows"):
|
|
return None
|
|
rows = result.get(out["rows"]) if isinstance(result, dict) else result
|
|
return rows if isinstance(rows, list) else []
|
|
|
|
|
|
def table(rows: list, cols: list[str], width: int = 44, last: int = 100) -> str:
|
|
cells = [[_cell(r.get(c)) if isinstance(r, dict) else _cell(r) for c in cols] for r in rows]
|
|
widths = [min(max((len(row[i]) for row in cells), default=0), width) for i in range(len(cols))]
|
|
lines = []
|
|
for row in cells:
|
|
parts = []
|
|
for i, v in enumerate(row):
|
|
if i == len(cols) - 1:
|
|
parts.append(v if len(v) <= last else v[:last - 1] + "…")
|
|
else:
|
|
parts.append((v if len(v) <= widths[i] else v[:widths[i] - 1] + "…").ljust(widths[i]))
|
|
lines.append(" ".join(parts).rstrip())
|
|
return "\n".join(lines)
|
|
|
|
|
|
def render_cli(cmd: dict, result: Any) -> str:
|
|
out = cmd.get("output") or {}
|
|
if out.get("text"):
|
|
v = result.get(out["text"]) if isinstance(result, dict) else result
|
|
return v if isinstance(v, str) else json.dumps(v, ensure_ascii=False, indent=2, default=str)
|
|
rows = _rows_of(cmd, result)
|
|
if rows is not None:
|
|
return table(rows, out["columns"]) if rows else "Nothing."
|
|
return json.dumps(result, ensure_ascii=False, indent=2, default=str)
|
|
|
|
|
|
def render_mcp(cmd: dict, result: Any, query: str | None = None) -> str:
|
|
"""Compact text for a model: the text field, one JSON row per line (only
|
|
the declared columns, filtered by ``query``'s words) or the JSON answer."""
|
|
out = cmd.get("output") or {}
|
|
if out.get("text"):
|
|
v = result.get(out["text"]) if isinstance(result, dict) else result
|
|
text = v if isinstance(v, str) else json.dumps(v, ensure_ascii=False, default=str)
|
|
return text or "(empty)"
|
|
rows = _rows_of(cmd, result)
|
|
if rows is not None:
|
|
keep = [{c: r.get(c) for c in out["columns"]} if isinstance(r, dict) else r for r in rows]
|
|
words = [w.casefold() for w in (query or "").split()]
|
|
lines = [json.dumps(r, ensure_ascii=False, default=str) for r in keep]
|
|
if words:
|
|
lines = [ln for ln in lines if all(w in ln.casefold() for w in words)]
|
|
return "\n".join(lines) or "Nothing matches."
|
|
return json.dumps(result, ensure_ascii=False, default=str)
|
|
|
|
|
|
# ── the CLI: ai-agent plugin <id> <command> … ───────────────────────────────
|
|
def _usage(a: dict) -> str:
|
|
n = "ID|." if a.get("conversation") else a["name"].upper()
|
|
if a["positional"]:
|
|
s = f"{n}…" if a["type"] == "array" else n
|
|
return s if a["required"] else f"[{s}]"
|
|
flag = "--" + a["name"].replace("_", "-")
|
|
if a["type"] == "boolean":
|
|
return f"[--no-{flag[2:]}]" if a.get("default") is True else f"[{flag}]"
|
|
s = f"{flag} {n}"
|
|
return s if a["required"] else f"[{s}]"
|
|
|
|
|
|
def usage_line(cmd: dict) -> str:
|
|
return " ".join([cmd["name"], *(_usage(a) for a in cmd.get("args") or [])])
|
|
|
|
|
|
def build_parser(pid: str, cmds: list[dict]) -> argparse.ArgumentParser:
|
|
name = cmds[0].get("pluginName") or pid if cmds else pid
|
|
p = argparse.ArgumentParser(prog=f"ai-agent plugin {pid}",
|
|
description=f"The {name} plugin's commands (from its plugin.json).")
|
|
sub = p.add_subparsers(dest="_command", metavar="COMMAND")
|
|
for c in cmds:
|
|
sp = sub.add_parser(c["name"], help=c["summary"],
|
|
description=c.get("description") or c["summary"])
|
|
for a in c.get("args") or []:
|
|
kw: dict = {"help": a.get("help") or None}
|
|
if a["type"] in ("integer", "number"):
|
|
kw["type"] = int if a["type"] == "integer" else float
|
|
if a.get("enum"):
|
|
kw["choices"] = a["enum"]
|
|
if a["positional"]:
|
|
if a["type"] == "array":
|
|
kw["nargs"] = "+" if a["required"] else "*"
|
|
elif not a["required"]:
|
|
kw["nargs"] = "?"
|
|
sp.add_argument(a["name"], metavar=a["name"].upper(), **kw)
|
|
continue
|
|
flag = "--" + a["name"].replace("_", "-")
|
|
if a["type"] == "boolean":
|
|
kw.pop("type", None)
|
|
if a.get("default") is True:
|
|
sp.add_argument("--no-" + flag[2:], dest=a["name"], action="store_false",
|
|
default=None, help=kw["help"])
|
|
else:
|
|
sp.add_argument(flag, dest=a["name"], action="store_true", default=None,
|
|
help=kw["help"])
|
|
elif a["type"] == "array":
|
|
sp.add_argument(flag, dest=a["name"], action="append", metavar=a["name"].upper(),
|
|
**kw)
|
|
else:
|
|
sp.add_argument(flag, dest=a["name"], metavar=a["name"].upper(),
|
|
required=a["required"], **kw)
|
|
sp.add_argument("--json", action="store_true", help="print the action's raw JSON answer")
|
|
return p
|
|
|
|
|
|
def run_cli(argv: list[str], hub) -> int:
|
|
"""``ai-agent plugin <id> [<command> …]``."""
|
|
pid, rest = argv[0], argv[1:]
|
|
cmds = [c for c in catalogue(hub) if c.get("plugin") == pid]
|
|
if not cmds:
|
|
raise aa.HubError(404, f"no active plugin {pid!r} with commands for you — "
|
|
f"`ai-agent plugin commands` lists them")
|
|
p = build_parser(pid, cmds)
|
|
ns = p.parse_args(rest)
|
|
if not ns._command:
|
|
p.print_help()
|
|
return 0
|
|
cmd = next(c for c in cmds if c["name"] == ns._command)
|
|
payload = resolve_conversations(hub, cmd, payload_from(cmd, vars(ns)), here=True)
|
|
res = invoke(hub, cmd, payload)
|
|
print(json.dumps(res, ensure_ascii=False, default=str) if ns.json else render_cli(cmd, res))
|
|
return 0
|
|
|
|
|
|
def list_cli(hub, as_json: bool) -> int:
|
|
"""``ai-agent plugin commands``."""
|
|
cmds = catalogue(hub)
|
|
if as_json:
|
|
print(json.dumps(cmds, ensure_ascii=False, indent=2))
|
|
return 0
|
|
if not cmds:
|
|
print("No active plugin declares commands.")
|
|
return 0
|
|
rows = [{"cmd": f"{c['plugin']} {usage_line(c)}", "summary": c["summary"],
|
|
"mcp": f"(MCP {c['tool']})" if c.get("tool") else ""} for c in cmds]
|
|
print(table(rows, ["cmd", "summary", "mcp"], width=48, last=40))
|
|
print("\nRun one as `ai-agent plugin <id> <command> …` (--help on any of them).")
|
|
return 0
|
|
|
|
|
|
def call_cli(hub, pid: str, action: str, payload_text: str | None, read: bool) -> int:
|
|
"""``ai-agent plugin call <id> <action> [--payload JSON|-] [--get]`` — any
|
|
declared action, raw JSON in and out."""
|
|
text = sys.stdin.read() if payload_text == "-" else (payload_text or "")
|
|
try:
|
|
payload = json.loads(text) if text.strip() else {}
|
|
except ValueError:
|
|
raise aa.HubError(0, "--payload must be JSON") from None
|
|
if not isinstance(payload, dict):
|
|
raise aa.HubError(0, "--payload must be a JSON object")
|
|
res = invoke(hub, {"plugin": pid, "action": action, "readOnly": read}, payload)
|
|
print(json.dumps(res, ensure_ascii=False, indent=2, default=str))
|
|
return 0
|
|
|
|
|
|
# ── the MCP server: plugin_<id>_<command> tools ──────────────────────────────
|
|
def input_schema(cmd: dict) -> dict:
|
|
props: dict = {}
|
|
for a in cmd.get("args") or []:
|
|
s: dict = {"type": a["type"]}
|
|
if a["type"] == "array":
|
|
s["items"] = {"type": "string"}
|
|
if a.get("enum"):
|
|
s["enum"] = a["enum"]
|
|
desc = a.get("help") or a["name"]
|
|
if a.get("conversation"):
|
|
desc += " (a conversation: its session id, a prefix of it, its id or its viewer link)"
|
|
if "default" in a and a["default"] is not None:
|
|
desc += f" (default {json.dumps(a['default'], ensure_ascii=False)})"
|
|
s["description"] = desc
|
|
props[a["name"]] = s
|
|
if (cmd.get("output") or {}).get("rows"):
|
|
props["query"] = {"type": "string", "description": "Words a row must contain (optional)."}
|
|
return {"type": "object", "properties": props,
|
|
"required": [a["name"] for a in cmd.get("args") or [] if a["required"]],
|
|
"additionalProperties": False}
|
|
|
|
|
|
def describe(cmd: dict) -> dict:
|
|
title = f"{cmd.get('pluginName') or cmd['plugin']}: {cmd['summary']}"[:100]
|
|
text = (cmd.get("description") or cmd["summary"]).strip()
|
|
text += f"\n\n(From the {cmd.get('pluginName') or cmd['plugin']} plugin.)"
|
|
ro = bool(cmd.get("readOnly"))
|
|
return {"name": cmd["tool"], "title": title, "description": text,
|
|
"inputSchema": input_schema(cmd),
|
|
"annotations": {"title": title, "readOnlyHint": ro,
|
|
"destructiveHint": bool(cmd.get("destructive")) and not ro,
|
|
"idempotentHint": ro, "openWorldHint": not ro}}
|
|
|
|
|
|
def call_tool(hub, cmd: dict, args: dict) -> str:
|
|
args = dict(args or {})
|
|
query = args.pop("query", None) if (cmd.get("output") or {}).get("rows") else None
|
|
payload = resolve_conversations(hub, cmd, payload_from(cmd, args), here=False)
|
|
return render_mcp(cmd, invoke(hub, cmd, payload), query)
|