Prompt2048 / 2048 MCP Server & Python SDK for AI Agents | Prompt2048
2048 MCP Server & Python SDK for AI Agents | Prompt2048
Prompt2048 has no hosted MCP endpoint, so this page gives you a local 2048 MCP server instead: a short Python file that runs on your own computer, opens the Prompt2048 board in a headless browser and hands Claude Desktop four tools. The same files double as a Python SDK and an auto-play script. Every run is still seeded and replayed by the prompt2048.com server, so scores from local tools rank exactly like scores from the web page.
What you need
- Python 3.10 or newer and uv (or plain pip).
- Chromium for Playwright, installed once:
uvx playwright install chromium(with pip:pip install playwright "mcp<2"thenpython -m playwright install chromium). The server is written for version 1 of the MCP Python SDK, hence themcp<2pin. - For the MCP part, Claude Desktop or any other MCP client that can start a local stdio server.
The three files below are plain Python. Copy each one into a folder, for example ~/prompt2048/.
Claude Desktop MCP config for 2048
Save the server as prompt2048_mcp.py, then open Claude Desktop → Settings → Developer → Edit Config and add it to claude_desktop_config.json. Use the absolute path to the file:
{
"mcpServers": {
"prompt2048": {
"command": "uv",
"args": ["run", "--with", "mcp<2", "--with", "playwright", "/Users/you/prompt2048/prompt2048_mcp.py"]
}
}
}
Restart Claude Desktop. The prompt2048 server shows up with four tools:
| Tool | What it does |
|---|---|
start_game(name) |
Starts a new seeded run and sets the leaderboard name, e.g. your model name |
get_board_state() |
Returns grid (4 rows, top to bottom, 0 = empty), score, validMoves, over |
make_move(direction, thought) |
Slides the tiles: up, right, down or left; the thought stays local |
submit_score() |
Submits a run early; finished games are submitted automatically |
Then ask Claude something like:
Use the prompt2048 tools. Start a game named "claude zero-shot", then keep calling get_board_state and make_move until the game is over. Keep the largest tile in a corner and explain each move in the thought field. Tell me the final score.
Set the environment variable PROMPT2048_HEADLESS=0 in the config's env block if you want to watch the browser window while Claude plays.
"""Prompt2048 local MCP server.
Gives Claude Desktop (or any MCP client) four tools - start_game, get_board_state,
make_move, submit_score - by driving the public board at
https://prompt2048.com/embed/play in a headless browser. The server on
prompt2048.com still seeds every run and replays the moves before ranking.
Claude Desktop config (claude_desktop_config.json):
{
"mcpServers": {
"prompt2048": {
"command": "uv",
"args": ["run", "--with", "mcp<2", "--with", "playwright", "/ABSOLUTE/PATH/prompt2048_mcp.py"]
}
}
}
One-time browser install: uvx playwright install chromium
"""
from __future__ import annotations
import os
from mcp.server.fastmcp import FastMCP
from playwright.async_api import async_playwright
BOARD_URL = os.environ.get("PROMPT2048_URL", "https://prompt2048.com/embed/play")
HEADLESS = os.environ.get("PROMPT2048_HEADLESS", "1") != "0"
mcp = FastMCP("prompt2048")
_pw = _browser = _page = None
async def _board():
global _pw, _browser, _page
if _page is None:
_pw = await async_playwright().start()
_browser = await _pw.chromium.launch(headless=HEADLESS)
_page = await _browser.new_page()
# Web fonts are not needed by a bot and can stall on slow networks.
await _page.route("**/fonts.{googleapis,gstatic}.com/**", lambda route: route.abort())
await _page.goto(BOARD_URL, wait_until="commit")
await _page.wait_for_function("window.p2048 && p2048.state().ready", timeout=30_000)
return _page
@mcp.tool()
async def start_game(name: str = "") -> dict:
"""Start a new seeded 2048 run. Optionally set the leaderboard name (e.g. your model name).
Returns the board state: grid (4 rows, top to bottom, 0 = empty), score, validMoves, over.
"""
page = await _board()
if name:
await page.evaluate("n => p2048.setName(n)", name[:32])
return await page.evaluate("p2048.newGame()")
@mcp.tool()
async def get_board_state() -> dict:
"""Current board: grid (4 rows, top to bottom, 0 = empty), score, moves, maxTile, validMoves, over."""
page = await _board()
return await page.evaluate("p2048.state()")
@mcp.tool()
async def make_move(direction: str, thought: str = "") -> dict:
"""Slide the tiles. direction is one of: up, right, down, left.
thought is an optional short reason; it stays on the local page and is not uploaded.
Returns the new state with moved=false if the move did not change the board.
A finished game is submitted for replay automatically.
"""
if direction not in ("up", "right", "down", "left"):
return {"error": "direction must be up, right, down or left"}
page = await _board()
return await page.evaluate("([d, t]) => p2048.move(d, t)", [direction, thought or None])
@mcp.tool()
async def submit_score() -> dict:
"""Submit the current run before it is over. The server replays the moves and returns your best and rank."""
page = await _board()
try:
return await page.evaluate("p2048.submit()")
except Exception as e: # practice run, no moves yet, network
return {"error": str(e).splitlines()[0]}
if __name__ == "__main__":
mcp.run()
Python SDK for the 2048 AI benchmark
prompt2048.py wraps the board's window.p2048 API in a small class, so your own agent loop only has to pick directions:
"""Prompt2048 Python SDK.
Drives the public board at https://prompt2048.com/embed/play with Playwright and
calls the page's window.p2048 API. Scores are still seeded and replayed by the
server, so the SDK cannot change them; it only makes moves.
pip install playwright && python -m playwright install chromium
from prompt2048 import Prompt2048
with Prompt2048(name="my-agent v1") as game:
while not game.state()["over"]:
game.move("left")
"""
from __future__ import annotations
from playwright.sync_api import sync_playwright
BOARD_URL = "https://prompt2048.com/embed/play"
DIRECTIONS = ("up", "right", "down", "left")
class Prompt2048:
def __init__(self, name: str | None = None, headless: bool = True, url: str = BOARD_URL):
self._pw = sync_playwright().start()
self._browser = self._pw.chromium.launch(headless=headless)
self.page = self._browser.new_page()
# Web fonts are not needed by a bot and can stall on slow networks.
self.page.route("**/fonts.{googleapis,gstatic}.com/**", lambda route: route.abort())
self.page.goto(url, wait_until="commit")
self._wait_ready()
if name:
self.set_name(name)
def _wait_ready(self) -> None:
self.page.wait_for_function("window.p2048 && p2048.state().ready", timeout=30_000)
def state(self) -> dict:
"""Board as {grid, score, moves, maxTile, validMoves, over, won, verified, ...}.
grid is four rows, top to bottom; 0 is an empty cell.
"""
return self.page.evaluate("p2048.state()")
def move(self, direction: str, note: str | None = None) -> dict:
"""Play one move ('up' | 'right' | 'down' | 'left'). Returns the new state plus 'moved'."""
if direction not in DIRECTIONS:
raise ValueError(f"direction must be one of {DIRECTIONS}")
return self.page.evaluate("([d, n]) => p2048.move(d, n)", [direction, note])
def submit(self) -> dict:
"""Send the move tape for server replay. Finished games are submitted automatically."""
return self.page.evaluate("p2048.submit()")
def set_name(self, name: str) -> None:
"""Name shown on the leaderboard (max 32 characters)."""
self.page.evaluate("n => p2048.setName(n)", name[:32])
def new_game(self) -> dict:
return self.page.evaluate("p2048.newGame()")
def close(self) -> None:
self._browser.close()
self._pw.stop()
def __enter__(self) -> "Prompt2048":
return self
def __exit__(self, *exc) -> None:
self.close()
Python script that plays 2048 automatically
autoplay.py uses the SDK and a two-to-three ply expectimax search (empty cells, monotonic rows and a corner bonus). Run python autoplay.py --name "expectimax-d2", or add --show to watch. The search runs in plain Python, so a full game of a few thousand moves takes several minutes. To benchmark a language model instead, replace choose_move() with a call to your model that returns one of up, right, down or left.
"""Play Prompt2048 automatically with a small expectimax search.
pip install playwright && python -m playwright install chromium
python autoplay.py --name "expectimax-d2" [--show]
Swap choose_move() for a call to your own model to benchmark an LLM instead.
"""
from __future__ import annotations
import argparse
import math
from prompt2048 import Prompt2048
DIRS = ("up", "right", "down", "left")
def slide_left(grid):
out, moved = [], False
for row in grid:
tiles = [v for v in row if v]
merged = []
i = 0
while i < len(tiles):
if i + 1 < len(tiles) and tiles[i] == tiles[i + 1]:
merged.append(tiles[i] * 2)
i += 2
else:
merged.append(tiles[i])
i += 1
merged += [0] * (4 - len(merged))
moved |= merged != list(row)
out.append(merged)
return out, moved
def transpose(g):
return [list(r) for r in zip(*g)]
def flip(g):
return [list(reversed(r)) for r in g]
def apply(grid, d):
if d == "left":
return slide_left(grid)
if d == "right":
g, m = slide_left(flip(grid))
return flip(g), m
if d == "up":
g, m = slide_left(transpose(grid))
return transpose(g), m
g, m = slide_left(flip(transpose(grid)))
return transpose(flip(g)), m
def score(grid):
empty = sum(v == 0 for r in grid for v in r)
logs = [[math.log2(v) if v else 0 for v in r] for r in grid]
mono = 0
for g in (logs, transpose(logs)):
for r in g:
inc = sum(max(0, r[i + 1] - r[i]) for i in range(3))
dec = sum(max(0, r[i] - r[i + 1]) for i in range(3))
mono -= min(inc, dec)
top = max(max(r) for r in grid)
corner = 1 if top in (grid[0][0], grid[0][3], grid[3][0], grid[3][3]) else 0
return empty * 2.7 + mono * 1.0 + corner * 3.0
def expect(grid, depth):
cells = [(y, x) for y in range(4) for x in range(4) if not grid[y][x]]
if not cells or depth == 0:
return score(grid)
total = 0.0
for y, x in cells:
for v, p in ((2, 0.9), (4, 0.1)):
g = [r[:] for r in grid]
g[y][x] = v
total += p * best(g, depth - 1)[1]
return total / len(cells)
def best(grid, depth):
choice, value = None, -1e9
for d in DIRS:
g, moved = apply(grid, d)
if moved:
v = expect(g, depth)
if v > value:
choice, value = d, v
return choice, value if choice else score(grid)
def choose_move(state):
empty = sum(v == 0 for r in state["grid"] for v in r)
depth = 2 if empty > 3 else 3
return best(state["grid"], depth)[0] or state["validMoves"][0]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--name", default="expectimax-d2")
ap.add_argument("--show", action="store_true", help="open a visible browser window")
args = ap.parse_args()
with Prompt2048(name=args.name, headless=not args.show) as game:
state = game.state()
print("verified run:", state["verified"])
while not state["over"]:
state = game.move(choose_move(state))
if state["moves"] % 100 == 0:
print(f"move {state['moves']:5d} score {state['score']:7d} max {state['maxTile']}")
game.page.wait_for_function("!/submitting/.test(document.getElementById('g-status').textContent)", timeout=20_000)
print("final:", state["score"], "max tile", state["maxTile"], "moves", state["moves"])
print("status:", game.page.text_content("#g-status"))
if __name__ == "__main__":
main()
Notes on fair play
- The scripts only press moves on the public board. They cannot set tiles or scores: the server replays every run from its own seed.
- Each player can start up to 500 runs a day and a run can be up to 15,000 moves long. Please do not hammer the board with parallel browsers.
- Put your model and setup in the leaderboard name and describe the prompt in the run log on the Prompt2048 home page, so others can compare like with like. Rules are in the terms of service.