Files
ai-agent/cli/test_mcp_tools.py
gabrielvidalandClaude Opus 5.5 f038c4fa20 feat(cli): ai-agent new --handoff-from and MCP handoff_from go — the Handoff plugin's commands replace them
The plugin-commands mechanism is live (299c27e7): the Handoff plugin declares
its own CLI commands and MCP tools (ai-agent plugin handoff start|link|links|
models; plugin_handoff_start/_link/_links), so the core's inert --handoff-from
flag and start_conversation.handoff_from leave, with their tests.

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

245 lines
13 KiB
Python

"""The `ai-agent` CLI as MCP tools (mcp_tools.py) and the JSON-RPC layer
(mcp_server.py): what each tool sends to the hub, what a connection may list
and call. ``python3 -m unittest test_mcp_tools`` from ``cli/``."""
import unittest
import ai_agent
import mcp_server
import mcp_tools
SID = "aaaaaaaa-1111-4111-8111-111111111111"
class Hub:
"""Records calls; answers from ``routes`` ("METHOD path" → value)."""
def __init__(self, routes=None):
self.routes = routes or {}
self.calls = []
def call(self, method, path, body=None, query=None, timeout=30):
self.calls.append((method, path, body, query))
out = self.routes.get(f"{method} {path}")
if isinstance(out, Exception):
raise out
return out if out is not None else {}
def get(self, path, **query):
return self.call("GET", path, query=query)
def post(self, path, body, timeout=60):
return self.call("POST", path, body)
def ctx(hub, **kw):
return mcp_tools.Ctx(hub=hub, view_url="https://app.test", **kw)
def rpc(c, method, params=None):
return mcp_server.handle({"jsonrpc": "2.0", "id": 7, "method": method,
"params": params or {}}, c)
class Tools(unittest.TestCase):
def test_every_tool_has_a_schema_and_honest_hints(self):
for t in mcp_tools.TOOLS.values():
d = t.describe()
self.assertEqual(d["inputSchema"]["type"], "object")
self.assertTrue(set(t.required) <= set(t.params), t.name)
self.assertIn(t.group, mcp_tools.GROUPS)
if t.read_only:
self.assertFalse(t.destructive, t.name)
def test_a_read_connection_lists_and_calls_read_tools_only(self):
c = ctx(Hub(), scope="read")
names = {t["name"] for t in rpc(c, "tools/list")["result"]["tools"]}
self.assertIn("get_conversation", names)
self.assertNotIn("start_conversation", names)
out = rpc(c, "tools/call", {"name": "start_conversation", "arguments": {"prompt": "x"}})
self.assertEqual(out["error"]["code"], mcp_server.INVALID_PARAMS)
def test_a_guest_gets_their_tools_and_kinds_only(self):
c = ctx(Hub({"GET /api/cron": {"jobs": []}}), guest=True)
names = {t["name"] for t in rpc(c, "tools/list")["result"]["tools"]}
self.assertFalse(names & {"run_agent", "schedule_conversation"})
out = rpc(c, "tools/call", {"name": "browse", "arguments": {"kind": "cron"}})
self.assertTrue(out["result"]["isError"])
def test_bad_arguments_are_the_models_to_read(self):
c = ctx(Hub())
out = rpc(c, "tools/call", {"name": "get_conversation", "arguments": {"nope": 1}})
self.assertTrue(out["result"]["isError"])
self.assertIn("unknown argument", out["result"]["content"][0]["text"])
out = rpc(c, "tools/call", {"name": "get_conversation", "arguments": {}})
self.assertIn("missing argument", out["result"]["content"][0]["text"])
def test_a_hub_error_is_a_tool_error_not_a_crash(self):
hub = Hub({"GET /api/conversations": ai_agent.HubError(503, "down")})
out = rpc(ctx(hub), "tools/call", {"name": "list_conversations", "arguments": {}})
self.assertTrue(out["result"]["isError"])
self.assertIn("down", out["result"]["content"][0]["text"])
# ── live plugins' tools (plugin.json `commands` with "mcp": true) ───────
CMDS = {"commands": [
{"plugin": "plans", "pluginName": "Plans", "name": "ls", "summary": "Every plan",
"description": "", "action": "index", "readOnly": True, "args": [],
"output": {"rows": "plans", "columns": ["slug", "status"]}, "mcp": True,
"tool": "plugin_plans_ls"},
{"plugin": "plans", "pluginName": "Plans", "name": "show", "summary": "One plan's markdown",
"description": "", "action": "get", "readOnly": True,
"args": [{"name": "slug", "type": "string", "required": True, "positional": True,
"help": "Its slug."}],
"output": {"text": "content"}, "mcp": True, "tool": "plugin_plans_show"},
{"plugin": "plans", "pluginName": "Plans", "name": "set-status", "summary": "Set a status",
"description": "", "action": "set_status", "readOnly": False,
"args": [{"name": "slug", "type": "string", "required": True, "positional": True},
{"name": "status", "type": "string", "required": True, "positional": True}],
"output": None, "mcp": True, "destructive": False, "tool": "plugin_plans_set-status"},
{"plugin": "plans", "pluginName": "Plans", "name": "secret", "summary": "Not a tool",
"description": "", "action": "list", "readOnly": True, "args": [], "output": None,
"mcp": False, "tool": None},
]}
def _names(self, c):
return {t["name"] for t in rpc(c, "tools/list")["result"]["tools"]}
def test_plugin_tools_are_listed_only_when_opted_in(self):
names = self._names(ctx(Hub({"GET /api/plugins/commands": self.CMDS})))
self.assertTrue({"plugin_plans_ls", "plugin_plans_show", "plugin_plans_set-status"} <= names)
self.assertNotIn("plugin_plans_secret", names)
self.assertIn("list_conversations", names)
tools = {t["name"]: t for t in rpc(ctx(Hub({"GET /api/plugins/commands": self.CMDS})),
"tools/list")["result"]["tools"]}
show = tools["plugin_plans_show"]
self.assertEqual(show["inputSchema"]["required"], ["slug"])
self.assertTrue(show["annotations"]["readOnlyHint"])
self.assertIn("query", tools["plugin_plans_ls"]["inputSchema"]["properties"])
self.assertFalse(tools["plugin_plans_set-status"]["annotations"]["readOnlyHint"])
def test_a_read_connection_gets_the_read_only_plugin_tools_by_get(self):
hub = Hub({"GET /api/plugins/commands": self.CMDS,
"GET /api/plugins/plans/actions/get": {"slug": "p1", "content": "# One"}})
c = ctx(hub, scope="read")
names = self._names(c)
self.assertIn("plugin_plans_show", names)
self.assertNotIn("plugin_plans_set-status", names)
out = rpc(c, "tools/call", {"name": "plugin_plans_show", "arguments": {"slug": "p1"}})
self.assertEqual(out["result"]["content"][0]["text"], "# One")
self.assertEqual(hub.calls[-1][0], "GET")
self.assertEqual(hub.calls[-1][3], {"payload": '{"slug":"p1"}'})
out = rpc(c, "tools/call", {"name": "plugin_plans_set-status",
"arguments": {"slug": "p1", "status": "done"}})
self.assertEqual(out["error"]["code"], mcp_server.INVALID_PARAMS)
def test_plugin_rows_come_as_json_lines_filtered_by_query(self):
hub = Hub({"GET /api/plugins/commands": self.CMDS,
"GET /api/plugins/plans/actions/index": {"plans": [
{"slug": "p1", "status": "done", "title": "One", "estCost": 2},
{"slug": "p2", "status": "proposed", "title": "Two"}]}})
out = rpc(ctx(hub), "tools/call", {"name": "plugin_plans_ls", "arguments": {"query": "done"}})
self.assertEqual(out["result"]["content"][0]["text"], '{"slug": "p1", "status": "done"}')
self.assertEqual(hub.calls[-1][3], {"payload": ""})
def test_a_writing_plugin_tool_posts_its_arguments(self):
hub = Hub({"GET /api/plugins/commands": self.CMDS,
"POST /api/plugins/plans/actions/set_status": {"ok": True}})
out = rpc(ctx(hub), "tools/call", {"name": "plugin_plans_set-status",
"arguments": {"slug": "p1", "status": "done"}})
self.assertEqual(out["result"]["content"][0]["text"], '{"ok": true}')
self.assertEqual(hub.calls[-1][:3], ("POST", "/api/plugins/plans/actions/set_status",
{"slug": "p1", "status": "done"}))
out = rpc(ctx(hub), "tools/call", {"name": "plugin_plans_set-status",
"arguments": {"slug": "p1", "nope": 1}})
self.assertTrue(out["result"]["isError"])
self.assertIn("unknown argument", out["result"]["content"][0]["text"])
def test_a_plugin_thats_off_says_so(self):
hub = Hub({"GET /api/plugins/commands": self.CMDS,
"GET /api/plugins/plans/actions/index":
ai_agent.HubError(404, "plugin 'plans' not active")})
out = rpc(ctx(hub), "tools/call", {"name": "plugin_plans_ls", "arguments": {}})
self.assertTrue(out["result"]["isError"])
self.assertIn("Plans plugin isn't installed", out["result"]["content"][0]["text"])
def test_no_plugin_tools_without_the_group_on_a_worker_or_when_the_hub_cant_list(self):
names = self._names(ctx(Hub({"GET /api/plugins/commands": self.CMDS}),
groups=frozenset({"read"})))
self.assertIn("plugin_plans_ls", names)
self.assertNotIn("plugin_plans_set-status", names)
hub = Hub({"GET /api/plugins/commands": self.CMDS})
self.assertFalse({n for n in self._names(ctx(hub, worker="w1")) if n.startswith("plugin_")})
self.assertFalse(any(c[1] == "/api/plugins/commands" for c in hub.calls))
down = Hub({"GET /api/plugins/commands": ai_agent.HubError(503, "down")})
self.assertIn("list_conversations", self._names(ctx(down)))
def test_plans_memories_and_goals_left_the_core_tools(self):
names = self._names(ctx(Hub()))
self.assertFalse(names & {"read_document", "work_on_goal"})
self.assertFalse({"plans", "goals", "memories"} & set(mcp_tools.BROWSE_KINDS))
def test_start_sends_the_spawn_and_stamps_it(self):
hub = Hub({"POST /api/spawn": {"sessionId": SID}})
seen = []
c = ctx(hub, on_spawn=seen.append)
out = rpc(c, "tools/call", {"name": "start_conversation",
"arguments": {"prompt": "fix it", "cwd": "/x"}})
self.assertFalse(out["result"]["isError"])
_, path, body, _ = hub.calls[-1]
self.assertEqual((path, body["prompt"], body["cwd"]), ("/api/spawn", "fix it", "/x"))
self.assertEqual(seen, [SID])
self.assertIn(SID, out["result"]["content"][0]["text"])
def test_schedule_takes_in_or_at_not_both(self):
hub = Hub({"POST /api/scheduled": {"id": "sch_1"}})
c = ctx(hub)
out = rpc(c, "tools/call", {"name": "schedule_conversation",
"arguments": {"prompt": "later", "in": "2h"}})
self.assertFalse(out["result"]["isError"], out)
self.assertIn("shouldStartAt", hub.calls[-1][2])
out = rpc(c, "tools/call", {"name": "schedule_conversation",
"arguments": {"prompt": "x", "in": "2h", "at": "10:00"}})
self.assertTrue(out["result"]["isError"])
def test_waits_are_capped_by_the_server(self):
seen = []
orig = ai_agent.wait_done
ai_agent.wait_done = lambda hub, sid, timeout, since=None: seen.append(timeout)
self.addCleanup(setattr, ai_agent, "wait_done", orig)
hub = Hub({"GET /api/conversations": {"conversations": [{"id": "x", "sessionId": SID}]}})
out = rpc(ctx(hub, max_wait_s=20), "tools/call",
{"name": "wait_for_conversation", "arguments": {"id": SID, "timeout_seconds": 999}})
self.assertEqual(seen, [20])
self.assertIn("still running", out["result"]["content"][0]["text"])
def test_wait_takes_a_conversation_uid(self):
"""Its own id looks like a session id; waiting on it as one never ends."""
uid = "019a4f2e-7c11-7a3b-9c2d-0e1f2a3b4c5d"
seen = []
orig = ai_agent.wait_done
ai_agent.wait_done = lambda hub, sid, timeout, since=None: seen.append(sid)
self.addCleanup(setattr, ai_agent, "wait_done", orig)
hub = Hub({"GET /api/conversations": {"conversations": []},
"GET /api/conversation-summary": {"id": uid, "sessionId": SID}})
rpc(ctx(hub), "tools/call", {"name": "wait_for_conversation", "arguments": {"id": uid}})
self.assertEqual(seen, [SID])
class Protocol(unittest.TestCase):
def test_initialize_negotiates_the_version(self):
r = rpc(ctx(Hub()), "initialize", {"protocolVersion": "2025-03-26"})["result"]
self.assertEqual(r["protocolVersion"], "2025-03-26")
self.assertEqual(rpc(ctx(Hub()), "initialize", {"protocolVersion": "1999"})["result"]
["protocolVersion"], mcp_server.PROTOCOL_VERSIONS[0])
self.assertIn("tools", r["capabilities"])
def test_notifications_get_no_answer_and_unknown_methods_an_error(self):
c = ctx(Hub())
self.assertIsNone(mcp_server.handle({"jsonrpc": "2.0", "method": "notifications/initialized"}, c))
self.assertEqual(rpc(c, "sampling/whatever")["error"]["code"], mcp_server.METHOD_NOT_FOUND)
self.assertEqual(mcp_server.handle_body([], c)["error"]["code"], mcp_server.INVALID_REQUEST)
if __name__ == "__main__":
unittest.main()