diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 69b32d1..ef8ea0d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,7 +10,8 @@ permissions: jobs: test: - runs-on: ubuntu-latest + # ubuntu-latest (26.04) has no Python 3.9 build; 24.04 still has every version the SDK supports. + runs-on: ubuntu-24.04 strategy: fail-fast: false matrix: diff --git a/README.md b/README.md index 256a36b..430940b 100644 --- a/README.md +++ b/README.md @@ -212,8 +212,12 @@ methods raise `drums.NotFound`. Concepts: [runs and evaluations](https://docs.dr ## MCP -Drums publishes one MCP server with 34 tools: the workspace (computers, snapshots, tasks, runs, API keys, audit log) -and the desktop itself (GUI, screenshot, shell, files, verify, fork, reset). Two ways to reach it: +Drums publishes one MCP server with 36 tools: the workspace (computers, snapshots, tasks, task sets, runs, API keys, +audit log) and the desktop itself (GUI, screenshot, shell, files, verify, fork, reset). `create_computer` and +`load_task` take your own tasks too: `task` (a whole task document, as an object or a JSON string), `task_set_id` + +`task_id` (a task of a set registered in the console or with `POST /v1/task-sets`; `list_task_sets` and +`get_task_set` find them), or `task_id` alone (an OSWorld task). `verify` on a computer with no task says so. Two ways +to reach it: | Transport | Where it runs | Address | |---|---|---| diff --git a/drums/mcp.py b/drums/mcp.py index 7630b48..2cdf3a5 100644 --- a/drums/mcp.py +++ b/drums/mcp.py @@ -31,7 +31,7 @@ import urllib.parse from . import Client, Env, __version__, connect -from .errors import DrumsError, InsecureTransport, NotFound +from .errors import BadRequest, DrumsError, InsecureTransport, NotFound from .hybrid import HybridTools PROTOCOL = "2025-06-18" @@ -139,6 +139,23 @@ def _check(v, schema: dict, label: str): return None +NO_TASK = "no task loaded on this computer: use load_task (task, task_set_id + task_id, or task_id), or create_computer with a task" + + +def coerce_json_objects(schema: dict, args: dict) -> None: + """Some MCP clients send an object argument as a JSON string: for a property whose schema is an object, a string + that parses to a JSON object is replaced by that object before validation (as the gateway's server does).""" + for k, s in (schema.get("properties") or {}).items(): + v = args.get(k) + if isinstance(s, dict) and s.get("type") == "object" and isinstance(v, str) and v.lstrip().startswith("{"): + try: + parsed = json.loads(v) + except ValueError: + continue + if isinstance(parsed, dict): + args[k] = parsed + + def validate(schema: dict, args) -> str | None: """The first schema violation of a tool's arguments, naming the field; None when they are fine.""" if not isinstance(args, dict): @@ -221,12 +238,22 @@ def _gateway(self, method: str, path: str, body=None, headers=None): raise def _task_doc(self, args: dict, required: bool): + """`task` (a whole document), `task_set_id` + `task_id` (a task of a registered set), or `task_id` alone (an + OSWorld task from the host's checkout). The same rules and messages as the gateway's server.""" if isinstance(args.get("task"), dict): return args["task"] + if args.get("task_set_id"): + if not args.get("task_id"): + raise ToolError("task_set_id needs task_id: the id of a task in that set (get_task_set lists them)") + q = urllib.parse.quote + try: + return self._gateway("GET", f"/v1/task-sets/{q(str(args['task_set_id']))}/tasks/{q(str(args['task_id']), safe='')}") + except NotFound as e: + raise ToolError(f"{e.message}: task_set_id {args['task_set_id']}, task_id {args['task_id']}") from None if args.get("task_id"): return self._api("GET", f"/v1/tasks/{urllib.parse.quote(str(args['task_id']))}") if required: - raise ToolError("one of task_id or task is required") + raise ToolError("one of task (a task document), task_set_id + task_id, or task_id (an OSWorld task) is required") return None def _checkpoints(self) -> list: @@ -280,6 +307,13 @@ def list_tasks(self, a): def get_task(self, a): return self._api("GET", f"/v1/tasks/{urllib.parse.quote(a['task_id'])}") + def list_task_sets(self, a): + r = self._gateway("GET", "/v1/task-sets" + _q(limit=a.get("limit") or 50)) + return {"task_sets": _rows(r, "task_sets"), "next": r.get("next_cursor") if isinstance(r, dict) else None} + + def get_task_set(self, a): + return self._gateway("GET", f"/v1/task-sets/{urllib.parse.quote(a['task_set_id'])}") + def _list_runs(self, a, kind=None): return self._gateway("GET", "/v1/runs" + _q(kind=kind, status=a.get("status"), limit=a.get("limit") or 50)) @@ -320,7 +354,20 @@ def read_audit_log(self, a): # desktop tools ------------------------------------------------------------------------------------------------------ def verify(self, a): - r = self._env(a["computer_id"]).verify(strict=False) + env = self._env(a["computer_id"]) + try: + r = env.verify(strict=False) + except BadRequest as e: + # drumsd answers 400 to a verify with no task (or a task without an OSWorld checker): say which (A-08) + if e.status != 400: + raise + try: + rec = env.refresh() + except DrumsError: + raise e from None + if not isinstance(rec.get("task"), dict): + raise ToolError(NO_TASK) from None + raise ToolError("the loaded task has no checker this host can run (it is not an OSWorld-format task with an evaluator)") from None return {"score": r.score, "valid": r.valid, "trusted": r.trusted, "audit_flags": r.audit_flags, "checker_error": r.checker_error} def fork(self, a): @@ -360,6 +407,8 @@ def call(self, name: str, args) -> list: args["computer_id"] = self.default_computer_id if tool.get("destructive") and not (isinstance(args, dict) and args.get("confirm") is True): raise ToolError(f"refused: pass confirm: true to {name}") + if isinstance(args, dict): + coerce_json_objects(tool["inputSchema"], args) problem = validate(tool["inputSchema"], args) if problem: raise ToolError(problem) diff --git a/drums/mcp_tools.json b/drums/mcp_tools.json index 50bcff9..f5b7533 100644 --- a/drums/mcp_tools.json +++ b/drums/mcp_tools.json @@ -27,13 +27,14 @@ "name": "create_computer", "layer": "workspace", "scope": "computers:write", - "description": "Start a new isolated desktop (computer) from a template or a snapshot, optionally with a task loaded. Returns the computer record; its `id` is the computer_id every desktop tool takes. The desktop is ready when state is `ready` and validity is `valid`.", + "description": "Start a new isolated desktop (computer) from a template or a snapshot, optionally with a task loaded. The task is one of: `task` (a whole task document, for tasks you wrote or generated), `task_set_id` + `task_id` (a task of a set registered in the console or with POST /v1/task-sets; see list_task_sets), or `task_id` alone (an OSWorld task from list_tasks). Returns the computer record; its `id` is the computer_id every desktop tool takes. The desktop is ready when state is `ready` and validity is `valid`.", "inputSchema": { "type": "object", "properties": { "template": { "type": "string", "description": "A template checkpoint from list_templates (for example osworld-ubuntu) or a snapshot id from list_snapshots.", "minLength": 1, "maxLength": 200 }, - "task_id": { "type": "string", "description": "A task id from list_tasks to load into the desktop at start (its setup runs before the episode).", "maxLength": 200 }, - "task": { "type": "object", "description": "A full task document (OSWorld format) instead of task_id.", "additionalProperties": true }, + "task_id": { "type": "string", "description": "With task_set_id: a task id of that set. Alone: an OSWorld task id from list_tasks. Its setup runs before the episode.", "maxLength": 200 }, + "task_set_id": { "type": "string", "description": "A registered task set from list_task_sets; with task_id, the task to load from it.", "pattern": "^[0-9a-fA-F-]{36}$" }, + "task": { "type": "object", "description": "A whole task document (OSWorld format: id, instruction, config, evaluator, ...) instead of task_id.", "additionalProperties": true }, "ttl_s": { "type": "integer", "description": "Lifetime in seconds; the computer is closed when it expires (0 or absent: the workspace default).", "minimum": 0, "maximum": 2592000 }, "setup": { "type": "boolean", "description": "Run the task's setup (default true when a task is given)." } }, @@ -133,17 +134,41 @@ "additionalProperties": false } }, + { + "name": "list_task_sets", + "layer": "workspace", + "scope": "computers:read", + "description": "List the task sets this workspace can use: the ones it registered (console Tasks page, POST /v1/task-sets, the drums-verifiers task factory) and the platform sets, with id, name, task_count and validation. get_task_set lists a set's task ids.", + "inputSchema": { + "type": "object", + "properties": { "limit": { "type": "integer", "minimum": 1, "maximum": 200, "default": 50 } }, + "additionalProperties": false + } + }, + { + "name": "get_task_set", + "layer": "workspace", + "scope": "computers:read", + "description": "One task set with its items (task_id, instruction, related_apps). Pass its id as task_set_id and an item's task_id to create_computer or load_task to run that task.", + "inputSchema": { + "type": "object", + "properties": { "task_set_id": { "type": "string", "pattern": "^[0-9a-fA-F-]{36}$" } }, + "required": ["task_set_id"], + "additionalProperties": false + } + }, { "name": "load_task", "layer": "desktop", "scope": "computers:write", - "description": "Load a task into a running computer (runs its setup and starts a new episode). After this, `verify` scores the desktop against this task's checker.", + "description": "Load a task into a running computer (runs its setup and starts a new episode): `task` (a whole task document), `task_set_id` + `task_id` (a task of a registered set), or `task_id` alone (an OSWorld task). After this, `verify` scores the desktop against this task's checker.", "inputSchema": { "type": "object", "properties": { "computer_id": { "type": "string", "minLength": 1, "maxLength": 64 }, - "task_id": { "type": "string", "maxLength": 200 }, - "task": { "type": "object", "additionalProperties": true } + "task_id": { "type": "string", "description": "With task_set_id: a task id of that set. Alone: an OSWorld task id from list_tasks.", "maxLength": 200 }, + "task_set_id": { "type": "string", "description": "A registered task set from list_task_sets; with task_id, the task to load from it.", "pattern": "^[0-9a-fA-F-]{36}$" }, + "task": { "type": "object", "description": "A whole task document (OSWorld format) instead of task_id.", "additionalProperties": true } }, "required": ["computer_id"], "additionalProperties": false @@ -442,7 +467,7 @@ "name": "verify", "layer": "desktop", "scope": "computers:write", - "description": "Score the desktop's current state with the loaded task's checker: score (0..1), valid (every gate of the episode passed), trusted, audit flags.", + "description": "Score the desktop's current state with the loaded task's checker: score (0..1), valid (every gate of the episode passed), trusted, audit flags. On a computer with no task loaded it says so: load one with load_task first.", "inputSchema": { "type": "object", "properties": { "computer_id": { "type": "string", "minLength": 1, "maxLength": 64 } }, diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 806ab8a..5b32894 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -15,6 +15,7 @@ from drums import mcp # noqa: E402 TOKEN = "k" * 43 +TS_ID = "0b5c2a52-77a0-4c0e-9a39-0a7a0f3c1d10" HERE = os.path.dirname(os.path.abspath(__file__)) TOOLS_JSON = mcp.TOOLS_PATH # the installed package's copy, so the test also proves the wheel ships it @@ -56,7 +57,7 @@ def _route(self, method, body): u = urllib.parse.urlsplit(self.path) path, q = u.path, dict(urllib.parse.parse_qsl(u.query)) parts = path.strip("/").split("/") - gateway_only = len(parts) >= 2 and parts[1] in ("runs", "api-keys", "audit") + gateway_only = len(parts) >= 2 and parts[1] in ("runs", "api-keys", "audit", "task-sets") if gateway_only and FakeGateway.no_runs: return self._send(404) # axum's default: no body at all # ---- slots @@ -69,6 +70,10 @@ def _route(self, method, body): return self._send(201, computer(7, checkpoint=body.get("checkpoint"), task=body.get("task"))) if path.startswith("/v1/slots/"): cid = parts[2] + if cid == "bare" and len(parts) == 3 and method == "GET": + return self._send(200, computer(1, task=None)) + if cid == "bare" and parts[3:] == ["verify"]: + return self._send(400, {"error": "drumsd rejected the request", "code": "invalid_request"}) if cid == "missing": return self._send(404, {"error": f"no env {cid} on this drumsd", "code": "not_found"}) if len(parts) == 3 and method == "GET": @@ -105,6 +110,18 @@ def _route(self, method, body): return self._send(200, rows) if path.startswith("/v1/tasks/"): return self._send(200, {"id": parts[2], "domain": "chrome", "instruction": "open a tab", "config": [], "evaluator": {"func": "x"}}) + # ---- task sets + if path == "/v1/task-sets" and method == "GET": + return self._send(200, {"items": [{"id": TS_ID, "name": "factory", "task_count": 2}], "next_cursor": None}) + if path == f"/v1/task-sets/{TS_ID}" and method == "GET": + return self._send(200, {"id": TS_ID, "name": "factory", "items": [{"task_id": "f-1"}, {"task_id": "f-2"}]}) + if path.startswith(f"/v1/task-sets/{TS_ID}/tasks/") and method == "GET": + tid = urllib.parse.unquote(parts[4]) + if tid not in ("f-1", "f-2"): + return self._send(404, {"error": "no such task in this set", "code": "not_found"}) + return self._send(200, {"id": tid, "instruction": "make a folder", "config": [], "evaluator": {"func": "drums_verifier"}}) + if path.startswith("/v1/task-sets/"): + return self._send(404, {"error": "no such task set", "code": "not_found"}) # ---- runs if path == "/v1/runs" and method == "GET": return self._send(200, {"items": [{"id": "r1", "kind": q.get("kind") or "scripted_test", "status": q.get("status") or "queued"}], "next_cursor": None}) @@ -183,7 +200,7 @@ def test_tools_list_equals_mcp_tools_json_in_order_with_annotations(self): with open(TOOLS_JSON) as f: want = json.load(f)["tools"] got = self.rpc(self.srv, "tools/list")["result"]["tools"] - self.assertEqual(len(got), 34) + self.assertEqual(len(got), 36) self.assertEqual([t["name"] for t in got], [t["name"] for t in want]) for g, w in zip(got, want): self.assertEqual(g["description"], w["description"]) @@ -207,7 +224,7 @@ def test_initialize_and_tools_list_send_nothing_and_the_transport_rule_holds_for # initialize and tools/list are answered from mcp_tools.json: no request reaches the gateway srv = mcp.Server(drums.Client("https://beta.drums.run/gw", TOKEN)) self.assertEqual(self.rpc(srv, "initialize")["result"]["serverInfo"]["name"], "drums") - self.assertEqual(len(self.rpc(srv, "tools/list")["result"]["tools"]), 34) + self.assertEqual(len(self.rpc(srv, "tools/list")["result"]["tools"]), 36) self.assertEqual(FakeGateway.calls, []) # the Server never gets a client that would send the token over plain http off loopback with self.assertRaises(drums.InsecureTransport) as cm: @@ -397,7 +414,37 @@ def test_desktop_tools_over_the_api(self): self.assertEqual(self.last()[2], {"task": {"id": "inline"}}) res, out = self.tool("load_task", {"computer_id": "c1"}) self.assertTrue(res["isError"]) - self.assertIn("task_id or task", out) + self.assertIn("one of task (a task document), task_set_id + task_id, or task_id", out) + + def test_custom_tasks_by_task_set_and_as_a_json_string(self): + res, out = self.tool("list_task_sets", {}) + self.assertEqual(out["task_sets"][0]["id"], TS_ID) + res, out = self.tool("get_task_set", {"task_set_id": TS_ID}) + self.assertEqual([i["task_id"] for i in out["items"]], ["f-1", "f-2"]) + res, out = self.tool("create_computer", {"template": "osworld-ubuntu", "task_set_id": TS_ID, "task_id": "f-2"}) + self.assertFalse(res["isError"], out) + self.assertEqual(FakeGateway.calls[-2][:2], ("GET", f"/v1/task-sets/{TS_ID}/tasks/f-2")) + self.assertEqual(self.last()[2]["task"]["id"], "f-2") + self.assertEqual(self.last()[2]["task"]["evaluator"], {"func": "drums_verifier"}) + res, out = self.tool("load_task", {"computer_id": "c1", "task_set_id": TS_ID, "task_id": "f-1"}) + self.assertEqual(self.last()[2]["task"]["id"], "f-1") + res, out = self.tool("create_computer", {"template": "osworld-ubuntu", "task_set_id": TS_ID, "task_id": "nope"}) + self.assertTrue(res["isError"]) + self.assertIn("no such task in this set", out) + res, out = self.tool("create_computer", {"template": "osworld-ubuntu", "task_set_id": TS_ID}) + self.assertIn("task_set_id needs task_id", out) + res, out = self.tool("create_computer", {"template": "osworld-ubuntu", "task": json.dumps({"id": "as-string", "instruction": "x"})}) + self.assertFalse(res["isError"], out) + self.assertEqual(self.last()[2]["task"], {"id": "as-string", "instruction": "x"}) + res, out = self.tool("create_computer", {"template": "osworld-ubuntu", "task": "not json"}) + self.assertTrue(res["isError"]) + + def test_verify_without_a_task_says_so(self): + res, out = self.tool("verify", {"computer_id": "bare"}) + self.assertTrue(res["isError"]) + self.assertEqual(out, mcp.NO_TASK) + res, out = self.tool("verify", {"computer_id": "c1"}) + self.assertFalse(res["isError"]) # safety ----------------------------------------------------------------------------------------------------------- def test_destructive_tools_refuse_without_confirm_before_any_request(self): diff --git a/tests/test_transport.py b/tests/test_transport.py index 5e1540d..13bec83 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -150,16 +150,16 @@ def test_loopback_http_and_https_start_the_server(self): self.assertEqual(rc, 0, (url, err)) self.assertEqual(err, "", url) reply = json.loads(out) - self.assertEqual(len(reply["result"]["tools"]), 34, url) # tools/list needs no gateway + self.assertEqual(len(reply["result"]["tools"]), 36, url) # tools/list needs no gateway self.assertNotIn(SECRET, out) def test_opt_in_flag_and_env_allow_plain_http(self): rc, out, err = run_cli(["mcp", "--url", "http://example.com", "--allow-insecure-http"], {"DRUMS_TOKEN": SECRET}, stdin=LIST_TOOLS) self.assertEqual(rc, 0, err) - self.assertEqual(len(json.loads(out)["result"]["tools"]), 34) + self.assertEqual(len(json.loads(out)["result"]["tools"]), 36) rc, out, err = run_cli(["mcp", "--url", "http://example.com"], {"DRUMS_TOKEN": SECRET, "DRUMS_ALLOW_INSECURE_HTTP": "1"}, stdin=LIST_TOOLS) self.assertEqual(rc, 0, err) - self.assertEqual(len(json.loads(out)["result"]["tools"]), 34) + self.assertEqual(len(json.loads(out)["result"]["tools"]), 36) self.assertNotIn(SECRET, out + err) def test_no_token_plain_http_is_not_refused(self):