pybot task: MCP server for the pybot tools; harness-neutral instructions
Browse filespybot_mcp.py serves the world's tools to the agent over MCP stdio, adds the
caller's clone to open_pr and run_bot as a patch, and checks itself with
--self-test. The instructions and CONTRIBUTING.md name the tools directly.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Files changed (6)
5 unmodified lines678910111210 unmodified lines232425262728295 unmodified lines```tasks/pybot-agent/ the Harbor task each agent runs in (one Trial per agent): instruction,task.toml, environment/Dockerfile (python:3.12 by digest), tests/test.shworld/ the shared world service (World API v1), one per runpybot.py the world: PRs, reviews, the merge queue, bot runs, world_statusrepository.py the world's bare git repository and the Hub client10 unmodified lines## The worldAgents clone the code dataset (`$PYBOT_REPO`) into `pybot` and never push to it. They workthrough the world's tools, which legion exposes as `world.*`:| tool | what it does ||---|---|5 unmodified lines67891011121310 unmodified lines24252627282930313233345 unmodified lines```tasks/pybot-agent/ the Harbor task each agent runs in (one Trial per agent): instruction,task.toml, environment/Dockerfile (python:3.12 by digest), tests/test.sh,pybot_mcp.py (the pybot tools as an MCP server; task.toml starts it)world/ the shared world service (World API v1), one per runpybot.py the world: PRs, reviews, the merge queue, bot runs, world_statusrepository.py the world's bare git repository and the Hub client10 unmodified lines## The worldAgents clone the code dataset (`$PYBOT_REPO`) into `pybot` and never push to it. They workthrough the pybot tools, which the task's MCP server `pybot_mcp.py` serves: it reads`WORLD_URL` and `WORLD_TOKEN`, lists the tools from `GET $WORLD_URL/manifest`, calls`POST $WORLD_URL/tools/<name>`, and adds the caller's clone to `open_pr` and `run_bot` as apatch against its merge-base with `origin/main` (at most 750 KB). Check it with`python3 tasks/pybot-agent/pybot_mcp.py --self-test`.| tool | what it does ||---|---|
1234# The agent's own container, the same image as task.toml's docker_image: the full Python 3.12# image already has git, curl and bash (Harbor's Pi installer and legion's tools need them), and# root is its default user (legion's tool setup and hf-sandbox need that).FROM python@sha256:14a4933e6cef421424f7a66d89a3f4eafcbd0d90e0a822251f298e05132dc7351234# The agent's own container, the same image as task.toml's docker_image: the full Python 3.12# image already has git, curl and bash (the agent installer and the pybot tools need them), and# root is its default user.FROM python@sha256:14a4933e6cef421424f7a66d89a3f4eafcbd0d90e0a822251f298e05132dc735
5 unmodified lines67891011121314155 unmodified lines- The code is the Hugging Face dataset named in `$PYBOT_REPO`. Clone it once into`pybot` in your working directory:`git clone "https://huggingface.co/datasets/$PYBOT_REPO" pybot`- Never push to it. Submit, review and merge through the world's tools:`legion-tool world.tools` lists them with their parameters, and`legion-tool world.call --json '{"tool": "<name>", "args": {...}}'` calls one as you.A tool that takes a clone path (open_pr's `path`, default `pybot`, relative to yourworking directory) uploads that clone from your container.- Talk to the other agents on the board with the board tools (`message_board.*`,`message_board_extra.*`).5 unmodified lines6789101112135 unmodified lines- The code is the Hugging Face dataset named in `$PYBOT_REPO`. Clone it once into`pybot` in your working directory:`git clone "https://huggingface.co/datasets/$PYBOT_REPO" pybot`- Never push to it. Submit, review and merge through the pybot tools (`open_pr`, `review_pr`,`merge_pr`, `list_prs`, `get_pr`, `run_bot`, ...); each tool lists its parameters.A tool that takes a clone path (open_pr's `path`, default `pybot`, relative to yourworking directory; run_bot's `ref_or_path`) uploads your changes in that clone.- Talk to the other agents with the message board tools.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376"""pybot's tools as an MCP server over stdio (stdlib only, Python 3.10+).
Reads WORLD_URL and WORLD_TOKEN. tools/list is GET $WORLD_URL/manifest; tools/call isPOST $WORLD_URL/tools/<name> with {"args": ...}. open_pr and run_bot get the caller's cloneadded as `workspace`: a binary patch against its merge-base with origin/main.`python3 pybot_mcp.py --self-test` runs the checks at the end of this file."""
import base64import jsonimport osimport subprocessimport sysimport tempfileimport threadingimport timeimport urllib.errorimport urllib.request
PROTOCOLS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05") # newest firstMAX_PATCH = 750_000 # raw bytes; base64 and JSON must stay under the world's 1 MiB body capMAX_BYTES, MAX_FILES = 128 << 20, 10000 # the world's caps on the resulting tree# tool -> (clone argument, its default, values that name a Hub ref instead of a clone)CLONE_ARGS = {"open_pr": ("path", "pybot", ()), "run_bot": ("ref_or_path", "main", ("main",))}RETRY_STATUS, TRIES, RETRY_BUDGET_S = (429, 503), 3, 60CALL_TIMEOUT_S = 360 # run_bot may take 300 s plus the upload# Never run a command the clone configured, or let its diff settings change the patch format.SAFE_GIT = ("-c", "core.fsmonitor=false", "-c", "diff.noprefix=false", "-c", "diff.mnemonicPrefix=false", "-c", "diff.relative=false")
_out = threading.Lock()
def log(msg): print(f"pybot_mcp: {msg}", file=sys.stderr, flush=True)
def send(msg): with _out: sys.stdout.write(json.dumps(msg) + "\n") sys.stdout.flush()
def redact(text): token = os.environ.get("WORLD_TOKEN", "") return text.replace(token, "[redacted]") if token else text
class ToolFailure(Exception): """A failure the model reads as the tool's result (isError true)."""
# ------------------------------------------------------------------ the clone
def _git(root, *args, env=None): p = subprocess.run(["git", *SAFE_GIT, "-C", root, *args], capture_output=True, env=env, timeout=120, check=False) if p.returncode: raise ToolFailure(f"git {args[0]} in {root} failed: " f"{p.stderr.decode(errors='replace').strip()[-300:]}") return p.stdout
def capture(path): """The clone at `path` (committed or not) as {"base_sha", "patch"} against its merge-base with origin/main. The world checks the base and the files; nothing here is trusted.""" if not os.path.isdir(path): raise ToolFailure(f"{path} is not a directory: clone the repository there first") root = _git(path, "rev-parse", "--show-toplevel").decode().strip() base = _git(root, "merge-base", "HEAD", "refs/remotes/origin/main").decode().strip() with tempfile.TemporaryDirectory() as tmp: # A private index of what the world gets: the clone's own index stays as it is. env = {**os.environ, "GIT_INDEX_FILE": os.path.join(tmp, "index")} _git(root, "read-tree", "HEAD", env=env) _git(root, "add", "--all", env=env) count, total = 0, 0 for entry in _git(root, "ls-files", "--stage", "-z", env=env).decode().split("\0"): if not entry: continue meta, name = entry.split("\t", 1) mode = meta.split()[0] if mode == "120000": raise ToolFailure(f"{name} is a symlink: the world takes regular files only; " "remove it or add it to .gitignore") if mode == "160000": raise ToolFailure(f"{name} is a nested git repository (e.g. a git worktree): " "move it out of the clone or add it to .gitignore") count += 1 total += os.lstat(os.path.join(root, name)).st_size if count > MAX_FILES or total > MAX_BYTES: raise ToolFailure("the clone is over 128 MiB or 10,000 files: remove large or " "generated files, or add them to .gitignore") diff = _git(root, "diff", "--cached", "--binary", "--full-index", "--find-renames", "--no-ext-diff", "--no-textconv", "--no-color", base, env=env) if len(diff) > MAX_PATCH: raise ToolFailure(f"your change is {len(diff):,} bytes as a patch, over the " f"{MAX_PATCH:,} byte limit: split the change; don't commit data or " "generated files") return {"base_sha": base, "patch": base64.b64encode(diff).decode("ascii")}
# ------------------------------------------------------------------ the world
def world(method, path, body=None, timeout=60): """(HTTP status, parsed JSON or None, raw body, Retry-After seconds or None).""" if not (os.environ.get("WORLD_URL") and os.environ.get("WORLD_TOKEN")): raise ToolFailure("WORLD_URL and WORLD_TOKEN must be set to reach the pybot world") url = os.environ["WORLD_URL"].rstrip("/") + path data = None if body is None else json.dumps(body).encode() req = urllib.request.Request(url, data=data, method=method, headers={ "X-World-Token": os.environ["WORLD_TOKEN"], "Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=timeout) as r: status, headers, raw = r.status, r.headers, r.read() except urllib.error.HTTPError as e: status, headers, raw = e.code, e.headers, e.read() except (urllib.error.URLError, OSError) as e: # its text may quote the URL, never the token raise ToolFailure(redact(f"the world is unreachable ({type(e).__name__}: {e})")) from None try: parsed = json.loads(raw) except ValueError: parsed = None retry = headers.get("Retry-After", "") if headers else "" return status, parsed, raw, (float(retry) if retry.isdigit() else None)
def _error(status, parsed, raw): error = parsed.get("error") if isinstance(parsed, dict) else None if isinstance(error, dict): retry = error.get("retry_after_s") return redact(f"{error.get('code')}: {error.get('message')}" + (f" (retry after {retry} s)" if retry else "")) return redact(f"the world answered HTTP {status}: {raw[:300].decode(errors='replace')}")
def result(method, path, body=None, timeout=60): """The world's result, after bounded waits on 429/503 and on errors with retry_after_s.""" deadline = time.monotonic() + RETRY_BUDGET_S for attempt in range(1, TRIES + 1): status, parsed, raw, retry = world(method, path, body, timeout) ok = 200 <= status < 300 and isinstance(parsed, dict) if ok and parsed.get("ok") is not False: return parsed.get("result") if "ok" in parsed else parsed error = parsed.get("error") if isinstance(parsed, dict) else None if isinstance(error, dict) and isinstance(error.get("retry_after_s"), (int, float)): retry = error["retry_after_s"] code = error.get("code") if isinstance(error, dict) else None # upstream_unreachable may be a timeout after the world acted: resending could repeat it retryable = (status in RETRY_STATUS or retry is not None) and code != "upstream_unreachable" wait = 1.0 if retry is None else max(0.0, float(retry)) if not retryable or attempt == TRIES or time.monotonic() + wait > deadline: raise ToolFailure(_error(status, parsed, raw)) log(f"{path}: busy (HTTP {status}, {code}), retry in {wait:.0f} s") time.sleep(wait)
def tools(): """The manifest's tools as MCP tools, without the `workspace` argument this file fills.""" out = [] for t in result("GET", "/manifest").get("tools", []): schema = json.loads(json.dumps(t.get("parameters") or {"type": "object"})) schema.get("properties", {}).pop("workspace", None) if "required" in schema: schema["required"] = [r for r in schema["required"] if r != "workspace"] out.append({"name": t["name"], "description": t.get("description", ""), "inputSchema": schema}) return out
def call(name, args): args = dict(args or {}) args.pop("workspace", None) # only this file captures it if name in CLONE_ARGS: arg, default, refs = CLONE_ARGS[name] local = str(args.get(arg, default)) if local not in refs and not local.startswith("pr:"): args["workspace"] = capture(local) return result("POST", f"/tools/{name}", {"args": args}, timeout=CALL_TIMEOUT_S)
# ------------------------------------------------------------------ MCP over stdio
def handle(msg): method, mid, params = msg.get("method"), msg.get("id"), msg.get("params") or {} if mid is None: # a notification (initialized, cancelled): nothing to answer return try: if method == "initialize": asked = params.get("protocolVersion") answer = {"protocolVersion": asked if asked in PROTOCOLS else PROTOCOLS[0], "capabilities": {"tools": {}}, "serverInfo": {"name": "pybot", "version": "1.0.0"}} elif method == "ping": answer = {} elif method == "tools/list": try: answer = {"tools": tools()} except ToolFailure as e: send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32603, "message": str(e)}}) return elif method == "tools/call": try: text, failed = json.dumps(call(params.get("name"), params.get("arguments"))), False except ToolFailure as e: text, failed = str(e), True answer = {"content": [{"type": "text", "text": redact(text)}], "isError": failed} else: send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": f"method not found: {method}"}}) return except Exception as e: # a bug here must not kill the server or leak the token log(redact(f"{method} failed: {type(e).__name__}: {e}")) send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32603, "message": redact(f"{type(e).__name__}: {e}")}}) return send({"jsonrpc": "2.0", "id": mid, "result": answer})
def serve(): for missing in [v for v in ("WORLD_URL", "WORLD_TOKEN") if not os.environ.get(v)]: log(f"{missing} is not set: every call will fail") for line in sys.stdin: if not line.strip(): continue try: msg = json.loads(line) except ValueError: send({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "parse error"}}) continue if not isinstance(msg, dict): send({"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "invalid request"}}) continue # Calls run concurrently: a 5-minute run_bot must not hold up ping or other tools. threading.Thread(target=handle, args=(msg,), daemon=True).start()
# ------------------------------------------------------------------ self-test
def self_test(): """Drives this file over stdio against a fake world. Needs git.""" import http.server
token, seen, script = "s3cret-token", [], [] # script: (status, headers, body) to send next
class World(http.server.BaseHTTPRequestHandler): def log_message(self, *a): pass
def _answer(self, status, body, headers=()): raw = json.dumps(body).encode() self.send_response(status) for k, v in headers: self.send_header(k, v) self.send_header("Content-Length", str(len(raw))) self.end_headers() self.wfile.write(raw)
def do_GET(self): assert self.headers["X-World-Token"] == token self._answer(200, {"name": "pybot", "tools": [ {"name": "open_pr", "description": "open", "parameters": { "type": "object", "required": ["title", "workspace"], "properties": {"path": {"type": "string"}, "title": {"type": "string"}, "workspace": {"type": "object"}}}}, {"name": "list_prs", "description": "list", "parameters": {"type": "object"}}]})
def do_POST(self): assert self.path.startswith("/world/tools/"), self.path assert self.headers["X-World-Token"] == token seen.append(json.loads(self.rfile.read(int(self.headers["Content-Length"])))) status, headers, body = script.pop(0) if script else (200, (), {"ok": True, "result": "done"}) self._answer(status, body, headers)
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), World) threading.Thread(target=server.serve_forever, daemon=True).start() with tempfile.TemporaryDirectory() as tmp: def git(cwd, *a): subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *a], cwd=cwd, check=True, capture_output=True) origin, clone = os.path.join(tmp, "origin"), os.path.join(tmp, "pybot") os.makedirs(origin) git(origin, "init", "-q", "-b", "main") with open(os.path.join(origin, "a.txt"), "w") as f: f.write("one\n") with open(os.path.join(origin, "b.bin"), "wb") as f: f.write(bytes(range(256))) git(origin, "add", ".") git(origin, "commit", "-qm", "base") git(tmp, "clone", "-q", origin, clone) with open(os.path.join(clone, "a.txt"), "a") as f: f.write("two\n") # committed below git(clone, "commit", "-qam", "change") with open(os.path.join(clone, "new.bin"), "wb") as f: f.write(bytes(range(255, -1, -1))) # untracked: still part of the upload
env = {**os.environ, "WORLD_URL": f"http://127.0.0.1:{server.server_port}/world", "WORLD_TOKEN": token} proc = subprocess.Popen([sys.executable, os.path.abspath(__file__)], cwd=tmp, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
def rpc(mid, method, params=None): proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": mid, "method": method, "params": params or {}}) + "\n") proc.stdin.flush() answer = json.loads(proc.stdout.readline()) assert answer["id"] == mid, answer return answer
def tool(mid, name, args): return rpc(mid, "tools/call", {"name": name, "arguments": args})["result"]
init = rpc(1, "initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "test", "version": "0"}})["result"] assert init["protocolVersion"] == "2025-06-18" and init["capabilities"] == {"tools": {}} proc.stdin.write('{"jsonrpc":"2.0","method":"notifications/initialized"}\n') assert rpc(2, "ping")["result"] == {} listed = {t["name"]: t for t in rpc(3, "tools/list")["result"]["tools"]} schema = listed["open_pr"]["inputSchema"] assert "workspace" not in schema["properties"] and schema["required"] == ["title"]
# open_pr: the patch applies to the base and reproduces the clone out = tool(4, "open_pr", {"title": "t"}) assert out == {"content": [{"type": "text", "text": '"done"'}], "isError": False}, out ws = seen[-1]["args"]["workspace"] check = os.path.join(tmp, "check") git(tmp, "clone", "-q", origin, check) assert ws["base_sha"] == subprocess.run(["git", "-C", check, "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip() with open(os.path.join(tmp, "p.diff"), "wb") as f: f.write(base64.b64decode(ws["patch"])) git(check, "apply", "--index", os.path.join(tmp, "p.diff")) for name in ("a.txt", "new.bin"): with open(os.path.join(check, name), "rb") as a, open(os.path.join(clone, name), "rb") as b: assert a.read() == b.read(), name
# run_bot on a Hub ref sends no workspace; list_prs passes through tool(5, "run_bot", {"ref_or_path": "pr:3", "lines": ["hi"]}) assert "workspace" not in seen[-1]["args"]
# 429 with Retry-After, then an envelope retry_after_s: retried, then success script[:] = [(429, [("Retry-After", "0")], {"error": {"code": 429}}), (200, (), {"ok": False, "error": {"code": "busy", "message": "slots", "retry_after_s": 0}})] n = len(seen) assert tool(6, "list_prs", {})["isError"] is False and len(seen) == n + 3
# a refusal without a retry hint is the tool's error, sent once; the token never shows script[:] = [(403, (), {"error": {"code": "not_yours", "message": f"bad {token}"}})] n = len(seen) out = tool(7, "list_prs", {}) assert out["isError"] and "not_yours" in out["content"][0]["text"] and len(seen) == n + 1 assert token not in json.dumps(out)
# oversize patch: refused locally, nothing sent with open(os.path.join(clone, "big.bin"), "wb") as f: f.write(os.urandom(MAX_PATCH)) n = len(seen) out = tool(8, "open_pr", {"title": "t"}) assert out["isError"] and "split the change" in out["content"][0]["text"], out assert len(seen) == n
assert rpc(9, "nope")["error"]["code"] == -32601 proc.stdin.close() proc.wait(10) assert token not in proc.stderr.read() server.shutdown() print("self-test passed")
if __name__ == "__main__": self_test() if sys.argv[1:] == ["--self-test"] else serve()1234567891011121 unmodified line14151617181920# One agent of a pybot swarm: one Harbor Trial per agent, each on its own copy of this task. The# shared state is outside the task: the pybot world (legion's resources.world, tools world.*; its# code is ../../world) and the board (resources.message_board, tools message_board.*). No# per-agent reward: tests/test.sh writes 0.schema_version = "1.4"[task]name = "legion/pybot-agent"description = "One agent of a swarm that builds a chatbot together: clone $PYBOT_REPO, submit and review through the shared world's tools, talk on the board."[metadata]world = "pybot"1 unmodified lineworld_api = "v1"[agent]timeout_sec = 10800.0 # legion's limits.agent_timeout_seconds overrides it[verifier]timeout_sec = 60.012345678910111 unmodified line13141516171819# One agent of a pybot swarm: one Harbor Trial per agent, each on its own copy of this task. The# shared state is outside the task: the pybot world (its code is ../../world), reached through# the pybot MCP server below, and the message board. No per-agent reward: tests/test.sh writes 0.schema_version = "1.4"[task]name = "huggingfaceswarms/pybot-agent"description = "One agent of a swarm that builds a chatbot together: clone $PYBOT_REPO, submit and review through the pybot tools, talk on the message board."[metadata]world = "pybot"1 unmodified lineworld_api = "v1"[agent]timeout_sec = 10800.0[verifier]timeout_sec = 60.0
18 unmodified lines1920212223242511 unmodified lines373839404142434433 unmodified lines78798081828318 unmodified linesunder `bot/modules/` and the shared parts next to it (README.md, "Interface" and"Architecture"), with tests under `tests/`.5. Run `python -m unittest discover -s tests` and talk to the whole bot:`legion-tool run_bot --json '{"ref_or_path":"pybot","lines":["Hello","Bye"]}'`.6. Compare with main, blind, before you open the PR:```sh11 unmodified lines## Open a PR7. Submit with `legion-tool open_pr --json '{"path":"pybot","branch":"your-topic","title":"Your change","description":"..."}'`. The description says what changed and why,and gives the comparison: the seed, the score line, the "turns answered" line, and oneexample it improves. At most two open PRs per agent.8. New PRs that add a module (a new file in `bot/modules/`) are limited swarm-wide to about33 unmodified linesit shows losses), revert it: `git revert` the merge locally and open a PR. Reverts arenever limited. Then fix the change properly; don't pile a guard on top of it.All world and board tools use `legion-tool <name> --json '<arguments>'`; `legion-tool --list`shows their parameters. There are no DMs: ask in your lane channel's thread and @mention theperson. Mention, reply and channel notifications arrive between rounds; run no pollers. Keep status and test logs in your notes. Never commit or post credentials.18 unmodified lines1920212223242511 unmodified lines373839404142434433 unmodified lines78798081828318 unmodified linesunder `bot/modules/` and the shared parts next to it (README.md, "Interface" and"Architecture"), with tests under `tests/`.5. Run `python -m unittest discover -s tests` and talk to the whole bot:`run_bot` with `ref_or_path` `"pybot"` and `lines` `["Hello", "Bye"]`.6. Compare with main, blind, before you open the PR:```sh11 unmodified lines## Open a PR7. Submit with `open_pr` (`path` `"pybot"`, `branch` `"your-topic"`, `title`, `description`).The description says what changed and why,and gives the comparison: the seed, the score line, the "turns answered" line, and oneexample it improves. At most two open PRs per agent.8. New PRs that add a module (a new file in `bot/modules/`) are limited swarm-wide to about33 unmodified linesit shows losses), revert it: `git revert` the merge locally and open a PR. Reverts arenever limited. Then fix the change properly; don't pile a guard on top of it.The pybot tools (`open_pr`, `review_pr`, `merge_pr`, ...) and the message board tools listtheir own parameters. There are no DMs: ask in your lane channel's thread and @mention theperson. Mention, reply and channel notifications arrive between rounds; run no pollers. Keep status and test logs in your notes. Never commit or post credentials.
README.md+7-2
tasks/pybot-agent/environment/Dockerfile+2-2
tasks/pybot-agent/instruction.md+4-6
tasks/pybot-agent/pybot_mcp.pyAdded+376
tasks/pybot-agent/task.toml+5-6
world/seed/CONTRIBUTING.md+5-5