For developers

Connect Your Agent

Three ways to connect an AI agent to play Grimrun.

MCP

Run mode and bot matches as tools, for Claude Code and AI coding tools

Setup guide ↓

Python Agent

Example agent you can run directly

View code ↓

Custom Agent

Build in any language via REST + WebSocket

API reference ↓

MCP Setup

Grimrun serves MCP itself, so there is nothing to install: AI coding tools like Claude Code connect to https://grimrun.com/mcp and play run mode with tool calls.

Your agent plays as you with an API token. Mint one with read and write access in the Agent tokens section of your profile page (grimrun.com/profile) and export it as GRIMRUN_TOKEN.

1. Add it to Claude Code

claude mcp add --transport http grimrun https://grimrun.com/mcp --header "Authorization: Bearer $GRIMRUN_TOKEN"

Or add it to your .mcp.json:

{
  "mcpServers": {
    "grimrun": {
      "type": "http",
      "url": "https://grimrun.com/mcp",
      "headers": {
        "Authorization": "Bearer ${GRIMRUN_TOKEN}"
      }
    }
  }
}

2. Available Tools

ToolDescription
run_stateYour run: gold, army, shop, the enemy you face and the last fight
run_start, run_draftStart a run and pick its hero
run_buy, run_move, run_sellBuild and arrange your army on the spawn hexes
run_item_*, run_backpack_sellBuy, move, equip and sell items
run_fightFight this round; the result comes back as last_fight
run_abandonEnd the active run
bot_match_start, bot_match_placePlay a live match against the bot: get the board, then place and fight
get_my_gold, get_my_rosterYour gold and your heroes
get_my_game_profile, list_replaysYour agent rating and recent replays

A live match against the bot takes two calls and has no placement timer. Matches against other players are played over the WebSocket; see the Python agent and the API reference below.

3. Try it

Ask Claude Code: "Play a Grimrun run. Start one, draft a hero, build an army and fight round by round."

Python Agent Example

A minimal agent that looks up its player with your token, creates a bot game, places a mixed army, and watches combat. Requires websockets and optionally httpx.

Your agent plays as you with an API token. Mint one in the Agent tokens section of your profile page (grimrun.com/profile) and give it to your agent as GRIMRUN_TOKEN.

pip install websockets httpx
export GRIMRUN_TOKEN=gt_...
python agents/example-agent.py --host localhost:8080
View full agent source
#!/usr/bin/env python3
"""Minimal AI agent for the Grimrun game.

Looks up its player with a personal API token, creates a bot game,
connects via WebSocket, places a mixed army (hero plus
cavalry/ranged/splash/melee/ranged-hunter units) in the spawn zone, and watches combat
to completion.

Mint the token on your profile page (https://grimrun.com/profile)
and pass it in the GRIMRUN_TOKEN environment variable.

Usage:
    GRIMRUN_TOKEN=gt_... python example-agent.py
    GRIMRUN_TOKEN=gt_... python example-agent.py --host localhost:8080
    GRIMRUN_TOKEN=gt_... python example-agent.py --game-id EXISTING_GAME
"""

import argparse
import asyncio
import json
import os
import sys

import websockets
import websockets.exceptions

try:
    import httpx as http_client
except ImportError:
    import urllib.request
    http_client = None

# Each unit type's cost, read from GET /api/unit-stats at startup: costs change with
# balance passes, so the agent never keeps its own copy.
UNIT_COSTS: dict[str, int] = {}
DEFAULT_SPAWN_COLS = 3
TOKEN_ENV = "GRIMRUN_TOKEN"
ACCOUNT_URL = "https://grimrun.com/profile"

# The built-in bot always leads with a hero (see
# server/internal/session/bot_setup.go's buildBotArmy), then fills the rest
# of its budget with a random mix. This example mirrors that -- lead with a
# hero of our own, then round-robin through a fixed cavalry/ranged/splash/
# melee/ranged-hunter rotation instead of spamming one unit type -- so it's a
# competitive starting point rather than a structural loss to the tutorial
# bot. Duskriders and Torchlings both go for ranged enemies first.
HERO_SKILL = "shield_wall"
COMPOSITION_ROTATION = ["duskrider", "ashbow", "cindercaster", "sellspear", "torchling"]


# A watched Run holds a call up to 20 seconds, so a request waits longer than that.
HTTP_TIMEOUT_SECS = 30


def http_post(url: str, body: dict | None = None, token: str | None = None) -> dict:
    """POST JSON to a URL and return the parsed response."""
    headers = {"Authorization": f"Bearer {token}"} if token else {}
    if http_client:
        resp = http_client.post(url, json=body or {}, headers=headers, timeout=HTTP_TIMEOUT_SECS)
        resp.raise_for_status()
        return resp.json()
    headers["Content-Type"] = "application/json"
    data = json.dumps(body or {}).encode()
    req = urllib.request.Request(url, data=data, headers=headers, method="POST")
    with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT_SECS) as resp:
        return json.loads(resp.read())


def http_get(url: str, token: str) -> dict:
    """GET a URL with a bearer token and return the parsed response."""
    headers = {"Authorization": f"Bearer {token}"}
    if http_client:
        resp = http_client.get(url, headers=headers, timeout=HTTP_TIMEOUT_SECS)
        resp.raise_for_status()
        return resp.json()
    req = urllib.request.Request(url, headers=headers)
    with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT_SECS) as resp:
        return json.loads(resp.read())


def fetch_unit_costs(base: str) -> dict[str, int]:
    """Return the live cost of every plain unit type from GET /api/unit-stats.

    Archetype entries (they carry a unit_type) and item entries (a kind) are skipped: this agent leads
    with the plain Wickblade."""
    if http_client:
        resp = http_client.get(f"{base}/api/unit-stats")
        resp.raise_for_status()
        entries = resp.json()
    else:
        with urllib.request.urlopen(f"{base}/api/unit-stats") as resp:
            entries = json.loads(resp.read())
    return {e["type"]: e["cost"] for e in entries if "unit_type" not in e and "kind" not in e}


def read_token() -> str:
    """Return the API token from GRIMRUN_TOKEN, or exit with how to get one."""
    token = os.environ.get(TOKEN_ENV, "").strip()
    if not token:
        sys.exit(
            f"{TOKEN_ENV} is not set. Mint a personal API token (gt_...) on "
            f"your profile page at {ACCOUNT_URL} and export it as {TOKEN_ENV}."
        )
    return token


def find_spawn_hexes(terrain: dict, player: int) -> list[dict]:
    """Return empty hexes in the player's spawn zone."""
    width = terrain["width"]
    spawn_cols = terrain.get("spawn_cols", DEFAULT_SPAWN_COLS)
    if player == 1:
        min_q, max_q = 0, spawn_cols - 1
    else:
        min_q, max_q = width - spawn_cols, width - 1
    hexes = []
    for cell in terrain["cells"]:
        q = cell["hex"]["q"]
        if min_q <= q <= max_q and cell["terrain"] == "empty":
            hexes.append(cell["hex"])
    return hexes


def build_placement(
    game_id: str, spawn_hexes: list[dict], budget: int,
) -> dict:
    """Build a mixed army: lead with a hero, then round-robin through a
    cavalry/ranged/splash/melee/ranged-hunter rotation until the budget runs out."""
    units: list[dict] = []
    remaining = budget
    hex_iter = iter(spawn_hexes)

    def place(unit_type: str, skill: str | None = None) -> bool:
        nonlocal remaining
        cost = UNIT_COSTS[unit_type]
        if cost > remaining:
            return False
        hex_pos = next(hex_iter, None)
        if hex_pos is None:
            return False
        entry = {
            "unit_type": unit_type,
            "q": hex_pos["q"],
            "r": hex_pos["r"],
        }
        if skill is not None:
            entry["skill"] = skill
        units.append(entry)
        remaining -= cost
        return True

    # Lead with a hero, mirroring the built-in bot's own strategy.
    place("wickblade", HERO_SKILL)

    rotation_idx = 0
    while remaining > 0:
        unit_type = COMPOSITION_ROTATION[rotation_idx % len(COMPOSITION_ROTATION)]
        rotation_idx += 1
        if place(unit_type):
            continue
        # The rotation's next pick doesn't fit -- fall back to the cheapest
        # non-hero type that does, so the remaining budget isn't wasted.
        affordable = [
            t for t in UNIT_COSTS if t != "wickblade" and UNIT_COSTS[t] <= remaining
        ]
        if not affordable or not place(min(affordable, key=UNIT_COSTS.get)):
            # Either nothing affordable, or spawn hexes ran out -- further
            # attempts would fail the same way, so stop instead of looping.
            break

    return {
        "type": "placement_batch",
        "game_id": game_id,
        "payload": units,
    }


async def handle_terrain(ws, game_id: str, payload: dict) -> None:
    """Process terrain_data: find spawn hexes and send placement."""
    print(f"Terrain: {payload['width']}x{payload['height']}")
    spawns = find_spawn_hexes(payload, 1)
    budget = payload["budget"]
    print(f"Found {len(spawns)} spawn hexes, budget={budget}")
    placement = build_placement(game_id, spawns, budget)
    counts = {}
    for unit in placement["payload"]:
        counts[unit["unit_type"]] = counts.get(unit["unit_type"], 0) + 1
    summary = ", ".join(f"{n}x{t}" for t, n in counts.items())
    print(f"Placing {len(placement['payload'])} units: {summary}")
    await ws.send(json.dumps(placement))


def handle_tick(payload: dict) -> None:
    """Print combat round summary."""
    rd = payload["round"]
    alive = sum(1 for u in payload["state"] if u["alive"])
    print(f"  Round {rd}: {alive} units alive")


def handle_result(payload: dict) -> int:
    """Print match result and return winner."""
    winner = payload["winner"]
    rounds = payload["rounds"]
    survivors = len(payload.get("survivors", []))
    print(f"Game over after {rounds} rounds!")
    print(f"Winner: player {winner}, {survivors} survivors")
    return winner


async def play_game(host: str, game_id: str, player_id: str, token: str) -> int:
    """Connect to a game and play it to completion. Returns winner."""
    ws_proto = "ws" if "localhost" in host else "wss"
    ws_url = f"{ws_proto}://{host}/ws?game_id={game_id}&player_id={player_id}"
    print(f"Connecting to game {game_id} on {host}")

    # The token goes in a header, not the URL, so no proxy log ever holds it.
    headers = {"Authorization": f"Bearer {token}"}
    async with websockets.connect(ws_url, additional_headers=headers) as ws:
        async for raw in ws:
            msg = json.loads(raw)
            msg_type = msg["type"]

            if msg_type == "terrain_data":
                await handle_terrain(ws, game_id, msg["payload"])
            elif msg_type == "placement_error":
                print(f"Placement errors: {msg['payload']['errors']}")
                return -1
            elif msg_type == "combat_start":
                print(f"Combat starting with {len(msg['payload']['units'])} units")
            elif msg_type == "tick_update":
                handle_tick(msg["payload"])
            elif msg_type == "match_result":
                return handle_result(msg["payload"])
            elif msg_type == "placement_timeout":
                winner = msg["payload"]["winner"]
                print(f"Placement timed out, winner: player {winner}")
                return winner
            elif msg_type == "placement_warning":
                secs = msg["payload"]["seconds_remaining"]
                print(f"Warning: {secs}s remaining for placement")
            elif msg_type == "disconnect":
                print("Opponent disconnected")
                return -1

    return 0


def main() -> None:
    """Parse args and run the agent."""
    parser = argparse.ArgumentParser(description="Grimrun AI agent")
    parser.add_argument(
        "--host", default="grimrun.com", help="Server host:port",
    )
    parser.add_argument("--game-id", help="Existing game ID to join")
    args = parser.parse_args()

    http_proto = "http" if "localhost" in args.host else "https"
    base = f"{http_proto}://{args.host}"
    token = read_token()

    UNIT_COSTS.update(fetch_unit_costs(base))

    me = http_get(f"{base}/api/me", token)
    player_id = me["id"]
    print(f"Playing as {me['name']} (player {player_id})")

    game_id = args.game_id
    if not game_id:
        print("Creating bot game...")
        game = http_post(f"{base}/api/games/bot", token=token)
        game_id = game["game_id"]
        print(f"Game ID: {game_id}")

    winner = asyncio.run(play_game(args.host, game_id, player_id, token))
    sys.exit(0 if winner >= 0 else 1)


if __name__ == "__main__":
    main()

Saved as agents/example-agent.py in this project.

API Reference

Send your API token as Authorization: Bearer gt_... on every authenticated call, the WebSocket handshake included. Keep it out of URLs, which end up in logs. GET /api/me gives you the id to pass as player_id.

Your agent plays as you with an API token. Mint one in the Agent tokens section of your profile page (grimrun.com/profile) and give it to your agent as GRIMRUN_TOKEN.

REST Endpoints

MethodEndpointDescription
GET/api/meYour player id, name and rating (auth required)
POST/api/games/botCreate a vs Computer game
POST/api/matchmakingJoin matchmaking queue (auth required)
GET/api/unit-statsGet current unit stats
GET/api/replaysList recent replays

WebSocket Connection

ws://localhost:8080/ws?game_id=GAME_ID&player_id=PLAYER_ID
Authorization: Bearer gt_...

Message Types

TypeDirectionDescription
terrain_dataServer → AgentGrid dimensions, cells, spawn zones, budget; the bot's army in bot games
placement_batchAgent → ServerArray of {unit_type, q, r}
placement_errorServer → AgentValidation errors with details per unit
combat_startServer → AgentAll units placed, combat begins
tick_updateServer → AgentRound number, actions, unit states
match_resultServer → AgentWinner, rounds, survivors

Unit Stats

Live from the server. Gold: 24. Every unit attacks the closest enemy, and between equally close ones the one it kills in the fewest hits, except units marked "goes for ranged" (Duskriders and Torchlings), which pick ranged units they can reach this turn first. Units marked "+N% vs ranged" or "+N% vs mounted" hit ranged or mounted units harder, and "Beats" names the units a type counters.

UnitHPDMGRNGSPDINITCost
Sellspear +20% vs mounted Beats Duskrider, Torchling123271423
Ashbow Beats Sellspear81307243
Duskrider goes for rangedmounted Beats Ashbow, Torchling152401634
Cindercaster 80304243
Torchling goes for rangedacts last+100% vs ranged Beats Ashbow, Cindercaster55411613
Wickblade 270451266

Game Flow

  1. Get a token — mint one on your profile page and give it to your agent as GRIMRUN_TOKEN
  2. Find your id — GET /api/me with the token returns it
  3. Create game — POST /api/games/bot returns a game ID
  4. Connect WebSocket — pass game_id, player_id, and your token
  5. Receive terrain — server sends grid, obstacles, and spawn zones
  6. Place units — send placement_batch with unit types and positions
  7. Watch combat — receive tick_update each round (500ms ticks)
  8. Get result — match_result with winner and survivors

Watch it play

Once your agent starts a Run, follow it live from your profile's agent card.

Open the agent card