Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "drums",
"description": "Isolated desktops for computer-use agents: start a computer from a template, act with GUI, shell and files, verify against a task checker, fork and reset, and read run results, all through the Drums MCP server.",
"version": "0.3.0",
"author": { "name": "Drums Labs" }
}
9 changes: 9 additions & 0 deletions .mcp.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"mcpServers": {
"drums": {
"command": "drums",
"args": ["mcp"],
"env": { "DRUMS_URL": "${DRUMS_URL}", "DRUMS_TOKEN": "${DRUMS_TOKEN}" }
}
}
}
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,23 @@
All notable changes to the `drums` Python SDK. The SDK talks to drumsd over its HTTP API; the drumsd version each
SDK version was built against is noted where it matters.

## 0.3.0 - unreleased (after 0.2.5 is on PyPI)

The MCP server and the `drums` command. The hosted MCP endpoint on the gateway (`<gateway URL>/mcp`) is live already;
this release adds the local server and the client methods for the new gateway routes.

- `drums mcp` (the same as `python -m drums.mcp`): a stdio MCP server with the 34 workspace and desktop tools of
`drums/mcp_tools.json`, the list the gateway serves. `--env <computer id>` binds the desktop tools to one computer;
`--print-config claude|claude-local|cursor|codex` prints the matching client snippet with a placeholder key.
Destructive tools (`destroy_computer`, `delete_snapshot`, `revoke_api_key`) are refused unless `confirm` is true,
before any request is sent.
- `drums` console script (`drums mcp`, `drums version`); `mcp_tools.json` ships in the wheel.
- `Client.runs`, `create_run`, `run`, `api_keys`, `create_api_key`, `revoke_api_key`, `audit` for the gateway's
`/v1/runs`, `/v1/api-keys` and `/v1/audit` routes; `call()` takes extra headers.
- The repository is a Claude Code plugin (`.claude-plugin/plugin.json`, `.mcp.json`, the `drums-workflow` skill).
- `drums.hybrid` `write_file` sends chunks of 8000 base64 characters (the gateway caps a step argument at 8192);
`gui` code is at most 16384 characters.

## 0.2.5 - first release on PyPI

The first version published on PyPI, as `drums-sdk` (`pip install drums-sdk`; the import name stays `drums`). Versions 0.2.0 to 0.2.4 shipped as wheels sent with invites.
Expand Down
96 changes: 95 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ for an invalid episode instead of returning a reward.
([guide](https://console.drums.run/docs/guides/group-rollouts-with-fork))
- Run a policy over many tasks: [Evaluate on OSWorld](https://console.drums.run/docs/guides/evaluate-on-osworld)
- `drums.aio` is the asyncio variant of the same calls; `drums.hybrid` adds shell, file and app-API tools over one
desktop; `python -m drums.mcp` serves them to an agent over MCP (stdio).
desktop; `drums mcp` serves the whole workflow to an agent over MCP (stdio), see [MCP server](#mcp-server).
- Every method: [Python SDK reference](https://console.drums.run/docs/reference/python-sdk).
Every endpoint: [HTTP API](https://console.drums.run/docs/reference/http-api).
If something fails: [Errors](https://console.drums.run/docs/reference/errors).
Expand All @@ -99,6 +99,100 @@ for an invalid episode instead of returning a reward.
- **Errors.** Every failure is a typed exception under `drums.DrumsError` carrying the server's status, message and
body; errors about a desktop carry its record and gate report.

## MCP server

`drums mcp` (the same as `python -m drums.mcp`) is an MCP server on stdio that gives an agent the whole workflow:
start a computer, act in it, verify against a task checker, fork and reset it, and read run results. It talks to
the Drums gateway (or a plain drumsd for the desktop tools) at `DRUMS_URL` with `DRUMS_TOKEN`.

```
drums mcp # all tools; desktop tools take computer_id
drums mcp --env <computer_id> # desktop tools default to this computer
drums mcp --create [--task FILE] # create one computer, bind it, close it on exit
drums mcp --print-config claude|claude-local|cursor|codex
```

The same tool list is served remotely by the gateway at `<GATEWAY_URL>/mcp` (MCP Streamable HTTP, authenticated
with a workspace API key; Drums MCP uses API keys, not OAuth). Replace `<GATEWAY_URL>` with your workspace's gateway
URL and `drums_sk_...` with a key from the console.

Claude Code, remote:

```
claude mcp add --transport http drums <GATEWAY_URL>/mcp --header "Authorization: Bearer drums_sk_..."
```

Claude Code, local (this package):

```
claude mcp add drums -e DRUMS_URL=<GATEWAY_URL> -e DRUMS_TOKEN=drums_sk_... -- drums mcp
```

Cursor (`~/.cursor/mcp.json` or `.cursor/mcp.json`):

```json
{"mcpServers": {"drums": {"url": "<GATEWAY_URL>/mcp", "headers": {"Authorization": "Bearer drums_sk_..."}}}}
```

Codex (`~/.codex/config.toml`):

```toml
[mcp_servers.drums]
command = "drums"
args = ["mcp"]
env = { DRUMS_URL = "<GATEWAY_URL>", DRUMS_TOKEN = "drums_sk_..." }
```

This repository is also a Claude Code plugin (`.claude-plugin/plugin.json`, `.mcp.json`, and the
`drums-workflow` skill under `skills/`), which installs the server and a skill that teaches the loop below.

### Tools

Workspace tools (the gateway's HTTP API; `*` needs the Drums gateway and answers "not available on this server"
against a plain drumsd):

| tool | what it does |
|---|---|
| `list_templates` | base desktop images a computer can start from |
| `list_computers`, `get_computer` | the workspace's computers: state, validity, task |
| `create_computer` | a new computer from a template or snapshot, optionally with a task |
| `destroy_computer` | close a computer for good (destructive) |
| `list_snapshots`, `create_snapshot`, `delete_snapshot` | saved desktop states (delete is destructive) |
| `list_tasks`, `get_task` | the verified computer-use tasks on the host |
| `list_runs`, `create_run`, `get_run` * | runs: submit a RunSpec, read status, counts and events |
| `list_evaluations`, `create_evaluation`, `get_evaluation` * | runs with kind `evaluation` |
| `list_api_keys`, `create_api_key`, `revoke_api_key` * | API keys (metadata only; revoke is destructive) |
| `read_audit_log` * | who did what, newest first; MCP calls appear as `mcp.<tool>` |

Desktop tools (each takes `computer_id`):

| tool | what it does |
|---|---|
| `gui` | pyautogui code in the desktop (1920x1080) |
| `screenshot` | a PNG of the desktop (image content) |
| `shell` | a bash command as the desktop user (no root, no internet) |
| `read_file`, `write_file`, `list_dir` | the desktop's files (`~` is `/home/user`) |
| `office_convert`, `spreadsheet_read` | LibreOffice conversions and sheet reads |
| `browser_tabs`, `browser_open` | Chrome tabs through its DevTools port (1337) |
| `load_task` | load a task into a running computer (setup runs, a new episode starts) |
| `verify` | score the desktop with the task's checker: score, valid, trusted, audit flags |
| `fork` | n children that continue from this exact state; the parent keeps running |
| `reset` | back to the clean template state; the task's setup runs again |

The canonical list with every input schema is `drums/mcp_tools.json`; `tools/list` returns exactly it, in order.

### Safety

- `destroy_computer`, `delete_snapshot` and `revoke_api_key` are refused unless `confirm` is `true`, before any
request is sent. Agents should tell the user before passing it.
- Arguments are checked against the tool's schema before anything is sent; a violation is a tool error naming the
field. A tool failure is always a tool result with `isError`, never a protocol error.
- `--print-config` prints placeholders (`<GATEWAY_URL>` when no URL is known, always `drums_sk_...`), never a key.
- The token comes from `DRUMS_TOKEN`, else the file `DRUMS_TOKEN_FILE`, else `/etc/drums/token`; it is never
printed or written by the server.
- Keys are workspace-scoped on the gateway: a key never sees another workspace's computers.
- `create_api_key` returns the plaintext key once; nothing stores it.

## Development

```bash
Expand Down
49 changes: 45 additions & 4 deletions drums/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
EnvGone, ForkError, GateFailed, GuestError, InvalidEpisode, NotFound, NotQuiescent, Overloaded, RestoreFailed, TaskSetupFailed,
TaskUnsupported)

__version__ = "0.2.5"
__version__ = "0.3.0"
DEFAULT_URL = os.environ.get("DRUMS_URL") or os.environ.get("DRUMSD_URL") or "http://127.0.0.1:7070"
DEFAULT_IMAGE = "osworld-ubuntu"

Expand Down Expand Up @@ -168,11 +168,12 @@ def __exit__(self, *exc):
self.close()

# transport --------------------------------------------------------------------------------------------------------
def call(self, method: str, path: str, body=None, raw: bool = False, timeout: float | None = None):
def call(self, method: str, path: str, body=None, raw: bool = False, timeout: float | None = None, headers: dict | None = None):
"""One request. GETs are retried while drumsd is unreachable (up to retry_s: a restarting drumsd comes back and
reconciles); other methods are never retried, since their outcome is unknown after a dropped connection."""
reconciles); other methods are never retried, since their outcome is unknown after a dropped connection.
`headers` are added to the request (e.g. Idempotency-Key)."""
data = None if body is None else json.dumps(body).encode()
headers = {"Content-Type": "application/json"}
headers = {"Content-Type": "application/json", **(headers or {})}
if self.token:
headers["Authorization"] = f"Bearer {self.token}"
deadline = time.monotonic() + (self.retry_s if method == "GET" else 0.0)
Expand Down Expand Up @@ -266,6 +267,46 @@ def env_records(self, include_destroyed: bool = False, page_size: int = 500):
if not after:
return

# gateway: runs, API keys, audit log ---------------------------------------------------------------------------------
# These routes exist on the Drums gateway only; a plain drumsd answers 404 (NotFound).
def runs(self, kind: str | None = None, status: str | None = None, limit: int = 50) -> dict:
"""The workspace's runs, newest first (GET /v1/runs): {"items": [run rows], "next_cursor"}. `kind` filters
(e.g. "evaluation"), `status` too (queued, running, completed, failed, cancelled)."""
q = {k: v for k, v in (("kind", kind), ("status", status), ("limit", limit)) if v is not None}
return self.call("GET", "/v1/runs?" + urllib.parse.urlencode(q))

def create_run(self, spec: dict, idempotency_key: str | None = None) -> dict:
"""Submit a RunSpec (POST /v1/runs): {"run_id", "operation_id", "status", "created"}. With `idempotency_key`
(the Idempotency-Key header) the same key with the same spec returns the same run."""
headers = {"Idempotency-Key": idempotency_key} if idempotency_key else None
return self.call("POST", "/v1/runs", spec, headers=headers)

def run(self, run_id: str) -> dict:
"""One run (GET /v1/runs/{id}): its row, the attempts summary and the last events."""
return self.call("GET", f"/v1/runs/{urllib.parse.quote(str(run_id))}")

def api_keys(self) -> dict:
"""The workspace's API keys, metadata only (GET /v1/api-keys): {"items": [{id, name, prefix, scopes, ...}]}."""
return self.call("GET", "/v1/api-keys")

def create_api_key(self, name: str, scopes: list, expires_in_days: int | None = None) -> dict:
"""A new API key (POST /v1/api-keys): {"id", "prefix", "key", "expires_at"}. `key` is the plaintext, shown
once; the scopes cannot exceed this client's own."""
body = {"name": name, "scopes": list(scopes)}
if expires_in_days is not None:
body["expires_in_days"] = expires_in_days
return self.call("POST", "/v1/api-keys", body)

def revoke_api_key(self, key_id: str) -> dict:
"""Revoke an API key (DELETE /v1/api-keys/{id}): {"id", "revoked_at"}. A key cannot revoke itself."""
return self.call("DELETE", f"/v1/api-keys/{urllib.parse.quote(str(key_id))}")

def audit(self, action: str | None = None, limit: int = 50, cursor: str | None = None) -> dict:
"""The workspace's audit log, newest first (GET /v1/audit): {"items": [events], "next_cursor"}. `action`
filters by prefix (e.g. "mcp", "computer.create")."""
q = {k: v for k, v in (("action", action), ("limit", limit), ("cursor", cursor)) if v is not None}
return self.call("GET", "/v1/audit?" + urllib.parse.urlencode(q))

def _task(self, task):
if task is None or isinstance(task, dict):
return task
Expand Down
66 changes: 66 additions & 0 deletions drums/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""The `drums` command.

drums mcp [--env ID] [--url URL] [--create] [--task FILE] # the MCP server on stdio (== python -m drums.mcp)
drums mcp --print-config claude|claude-local|cursor|codex # a client config snippet (placeholders, never a key)
drums version
"""
from __future__ import annotations

import argparse
import os
import sys

from . import __version__

PLACEHOLDER_URL = "<GATEWAY_URL>"
PLACEHOLDER_KEY = "drums_sk_..."
CLIENTS = ("claude", "claude-local", "cursor", "codex")


def gateway_url(url: str | None = None) -> str:
"""--url, else $DRUMS_URL, else the placeholder <GATEWAY_URL>. Never a token."""
u = (url or os.environ.get("DRUMS_URL") or "").strip().rstrip("/")
return u or PLACEHOLDER_URL


def print_config(client: str, url: str | None = None) -> str:
"""The config snippet for one MCP client. The key is always the placeholder `drums_sk_...`: paste your own."""
g = gateway_url(url)
if client == "claude":
return (f'claude mcp add --transport http drums {g}/mcp --header "Authorization: Bearer {PLACEHOLDER_KEY}"\n')
if client == "claude-local":
return f"claude mcp add drums -e DRUMS_URL={g} -e DRUMS_TOKEN={PLACEHOLDER_KEY} -- drums mcp\n"
if client == "cursor":
return ('{"mcpServers": {"drums": {"url": "' + g + '/mcp", "headers": {"Authorization": "Bearer ' + PLACEHOLDER_KEY + '"}}}}\n')
if client == "codex":
return ("[mcp_servers.drums]\n"
'command = "drums"\n'
'args = ["mcp"]\n'
'env = { DRUMS_URL = "' + g + '", DRUMS_TOKEN = "' + PLACEHOLDER_KEY + '" }\n')
raise ValueError(f"unknown client {client!r}; one of {', '.join(CLIENTS)}")


def build_parser() -> argparse.ArgumentParser:
from .mcp import add_arguments
ap = argparse.ArgumentParser(prog="drums", description="Drums: isolated desktops for computer-use agents.")
sub = ap.add_subparsers(dest="command", metavar="command")
add_arguments(sub.add_parser("mcp", help="run the MCP server on stdio (or print a client config with --print-config)"))
sub.add_parser("version", help="print the SDK version")
return ap


def main(argv=None) -> int:
ap = build_parser()
a = ap.parse_args(sys.argv[1:] if argv is None else argv)
if a.command == "version":
sys.stdout.write(f"drums {__version__}\n")
return 0
if a.command == "mcp":
from .mcp import run
return run(a)
ap.print_help()
return 2


if __name__ == "__main__":
sys.exit(main())
2 changes: 1 addition & 1 deletion drums/hybrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@

HOME = "/home/user"
MAX_READ = 2 * 1024 * 1024
CHUNK = 60_000
CHUNK = 8_000 # one argv chunk: the gateway caps each step command argument at 8192 chars (contracts drumsActionSchema)
SOFFICE = ["soffice", "-env:UserInstallation=file:///tmp/drums-hybrid-lo", "--headless", "--norestore"]


Expand Down
Loading
Loading