Skip to main content
Glama

twine-play-mcp

English · 简体中文

An MCP server that lets AI agents play, test and QA Twine / interactive-fiction HTML games.

The agent reads the current passage, clicks numbered choices, fills inputs, watches story variables, answers game dialogs, snapshots state to explore branches, and can hand the user a live view of the real page — through a small, token-friendly tool surface instead of generic browser automation.

Agent  ──MCP(stdio)──>  twine-play-mcp  ──Playwright──>  headless Chrome
                              │                               │
                              │  static server (127.0.0.1)    │  injected page bridge
                              └────────> game HTML <──────────┘

Requirements

  • Node.js ≥ 20

  • Google Chrome installed (used via channel: 'chrome' — no 200 MB browser download)

  • Linux, macOS or Windows

Related MCP server: vnflight

Install

npm install -g twine-play-mcp   # or run it with: npx twine-play-mcp

The package ships the compiled server and the page bridge, so there is no build step.

Configure

Add the server to your MCP client. Any mcpServers-style client works:

{
  "mcpServers": {
    "twine-play": {
      "command": "npx",
      "args": ["-y", "twine-play-mcp"]
    }
  }
}

OpenCode uses its own shape (~/.config/opencode/opencode.json):

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "twine-play": { "type": "local", "command": ["npx", "-y", "twine-play-mcp"], "enabled": true }
  }
}

Ready-made files live in examples/. Environment variables — all optional:

  • TWMCP_CHROME_PATH — Chrome executable, if channel: 'chrome' cannot find it

  • TWMCP_DOWNLOAD_DIR — where browser downloads are captured (default ~/.cache/twine-play-mcp/downloads, with automatic fallback if unwritable)

  • TWMCP_VIEW_HOST / TWMCP_VIEW_PORT — live-view bind host (default 127.0.0.1) and first port (default 4571, auto-increments)

  • TWMCP_BLOCK_TRACKERS — set to 0 to stop blocking analytics hosts during playtesting

Quick start

Ask your agent to do this — the game path is an argument to the open_game tool, not a CLI argument. There is no twine-play-mcp game.html.

Open /path/to/game.html with twine-play-mcp and tell me what the first passage says.

What happens under the hood, and what the agent sees:

open_game({ source: "/path/to/game.html" })
  Opened game "game_c5ac1a" (/path/to/game.html)
  game_id: game_c5ac1a
  Story: TS Ero Trap Dungeon · Format: sugarcube 2.31.1 · ifid: ...
  Served from: http://127.0.0.1:41235/
  [sugarcube 2.31.1 · step 0 · engine=idle · passage: Title]
  ...
  Choices (1):
    1. Start -> Prologue

choose({ choice: 1 })          # or click_ui / interact / navigate
  Clicked: "Start" -> Prologue
  [sugarcube 2.31.1 · step 1 · engine=idle · passage: Prologue]
  ...

observe({ for_text: "You wake up" })    # wait for a timed passage, then read
interact({ ref: "i1", value: "Shiori" }) # fill a form field
snapshot({ action: "save", name: "before-boss" })
live_view({})                  # hand the user a URL to watch the real page

game_id is optional while exactly one game is open — omit it for less noise. With several games open you must pass it, and the error lists the candidates.

Tools

The surface is deliberately small: related verbs live together rather than each getting a tool (navigate covers back/restart/goto, snapshot covers save/load/list, get_logs covers console + journal). Types with one knob fold into action: / kind: parameters.

Open & read

Tool

What it does

open_game

Open a local file/folder or an http(s) URL and get the first observation.

observe

Current passage text, choices, inputs, dialog and status. Pass for_text or wait_ms to wait first.

session

list the open games, or close one.

Act

Tool

What it does

choose

Click a choice by its 1-based number or by label — dialog buttons included.

click_ui

Click sidebar buttons and menus by ref, CSS selector or visible text.

interact

Fill an input/select/checkbox by ref, or press a key.

navigate

back one passage, restart the story, or goto a named passage.

Inspect

Tool

What it does

find_ui

Find controls by text or input name; inspect a DOM subtree or discover overlay panels.

get_variables

Read SugarCube State.variables by dot path, or a shallow key summary.

get_logs

Console errors/HTTP failures and the play journal.

screenshot

PNG of the viewport — canvas games and visual QA.

live_view

Let the user watch the real page in their browser (~1 fps).

Files & state

Tool

What it does

snapshot

save / load / list in-session state snapshots for branch exploration.

upload_file

Upload a mod .zip, .save or image into an <input type=file>.

download_file

list the persistent download folder, or save/newest a captured file.

Detail for any tool is in its own description — call it and read the parameters. Output is formatted text for humans and models; pass format: "json" for JSON.parse-able output (observe, choose, click_ui, interact, navigate, snapshot, upload_file, download_file, open_game).

Watching the page

live_view starts a tiny local server (once per MCP process) and returns a URL like http://127.0.0.1:4571/v/game_c5ac1a. Open it and you watch the actual tab the agent is driving: a JPEG frame roughly once a second, plus passage, step, engine state and recent actions. It works with headless games, and frames are only captured while somebody is watching.

Agents: pick exactly one view per game. Use live_view by default (pass open: true once if the user wants you to launch it). Use open_game({ headless: false }) only when the user asks for a real browser window, and do not add a live view on top of it. screenshot is a one-shot visual check, never a stream. The server ships this policy in its MCP instructions field too.

Format support

Format

Detect

Text / choices

get_variables

Passage name

navigate(back)

snapshot

SugarCube 2.21+

✅

✅

✅ State.variables

✅

✅ Engine.backward

✅ Save.base64 / Save.deserialize

Harlowe 3

✅

✅

— (engine internals are private)

—

✅ sidebar undo

—

Snowman 2

✅

✅

— (use observe(include_variables:true))

✅

—

✅ state JSON

Chapbook 1

✅

✅

— (use observe(include_variables:true))

✅ trail

—

✅ restoreFromObject

Unknown HTML

generic

✅ DOM heuristics

—

—

—

—

observe reads variables for Snowman (story.state) and Chapbook (engine.state) as well; only get_variables' dot-path lookup is SugarCube-specific. Everything degrades gracefully: an unknown format still plays through the generic DOM path, and format-specific tools report unsupported instead of failing.

Troubleshooting

  • Could not launch Chrome — install Google Chrome, or point TWMCP_CHROME_PATH at the binary.

  • Multiple HTML files in <dir> — pass the specific .html file instead of the folder.

  • Nothing happens with the file path — the path goes to open_game; the CLI takes no arguments.

  • Live view port busy — it auto-increments from 4571; use the URL that was returned.

  • Downloads not appearing — read the folder path printed by download_file(action:"list"); it falls back to a writable location.

  • A tool reports unsupported — that story format lacks the API (see the matrix above).

Safety notes

  • Page scripts run in Chrome's sandbox; the bridge never exposes Node to the page. No arbitrary eval tool is exposed.

  • Analytics/tracker hosts are blocked by default (TWMCP_BLOCK_TRACKERS=0 to disable).

  • Links that leave the game are blocked unless allow_external: true. open_game serves a local game over 127.0.0.1 and reads files under the served root only.

Development

git clone https://github.com/adorablelovelymia/twine-play-mcp.git
cd twine-play-mcp
npm install
npm test            # build + 4-format fixture checks + tool-surface snapshot/budget

npm test needs no external game — the fixtures are in the repo. Heavier checks (npm run smoke, npm run spike, npm run clarity) drive a real game and need TWMCP_GAME=/path/to/game.html; without it they skip.

Architecture, the playbook for adding a story-format adapter, the script index and the roadmap are in CONTRIBUTING.md.

Available Tools

22 tools
backGo back one stepB

Undo the last passage navigation when the story format supports it (SugarCube: Engine.backward). Returns the new observation (text; format:"json" for JSON).

Inputs: game_id (required), format.

chooseClick a choiceA

Click a passage choice by its 1-based number from the last observation, or by (partial) label text. Numbered choices include dialog buttons (tagged [dialog] in observations) — so choose() answers dialogs too. Waits for the game to settle and returns the new observation. Pass expected to guard against clicking the wrong link.

Inputs: choice (required), game_id (required), format, expected, +1 more.

click_uiClick UI outside the passageA

Click dialogs, sidebar buttons and menus (SAVES, OPTIONS, ModLoader banner, modal buttons) by ref, CSS selector or visible text. Text matching covers -based controls too (SugarCube radio/checkbox options like "Jet black" or "Punch"); shortest match wins, exact=true for exact text. Returns the new observation (text; format:"json" for JSON). Use choose() for numbered passage choices and dialog buttons.

Inputs: game_id (required), ref, text, exact, +2 more.

close_gameClose a gameB

Close the browser tab and static server for a game session.

Inputs: game_id (required).

download_fileSave a captured browser download to a fileA

Browser file control for any game: every download is captured into the tool's download folder (see list_downloads). Three modes: (a) pass trigger_text/trigger_ref/trigger_selector to click the game's download button and take that file; (b) pass name or index to take an already-captured file from the folder; (c) pass none of those to take the newest file in the folder. Without path the file stays in the download folder (path = its location); with path (a file or a directory) a copy is placed there too. Returns the path, size and the new observation.

Inputs: game_id (required), name, path, index, +5 more.

find_uiFind a control by textA

Search visible controls (buttons, links, labels, inputs) by label text and/or input name; returns refs usable with click_ui(ref), interact(ref, value) and upload_file(ref). This is the fastest way to reach radio/checkbox options (e.g. "Jet black", "Punch") and any input beyond the 40-item observation window. Results are capped by limit; no game state changes.

Inputs: game_id (required), kind, name, text, +2 more.

get_console_errorsGet console errorsB

Return JavaScript errors/warnings captured from the page (useful for playtesting / QA).

Inputs: game_id (required), clear.

get_journalGet the play journalA

Return this session's action history: every passage visited and every choice taken (including back/load events). Useful to summarise a playthrough, resume a run, or report coverage for QA.

Inputs: game_id (required), clear, limit.

get_variablesRead story variablesA

Read specific story variables (SugarCube State.variables) by dot path, e.g. ["haircolour", "background", "player.background"]. Accepts "V.x", "variables.x" or plain "x". With no paths, returns a shallow summary of the top-level keys. Output is JSON.

Inputs: game_id (required), paths.

inspect_uiInspect a UI panelA

Inspect DOM outside the passage. Pass a CSS selector to get its text, buttons (with refs usable in click_ui) and inputs (file inputs usable in upload_file). Without a selector, lists overlay panels (mod GUIs, dev panels) that contain buttons or file inputs.

Inputs: game_id (required), selector.

interactFill an input or press a keyA

Interact with input fields or the keyboard: set a value on an input/textarea/select by ref, or press a key (e.g. "Enter", "ArrowUp"). For radios/checkboxes pass value "true" or "false". Inputs are refs from the last observation (or find_ui). Returns the new observation; pass format:"json" for a JSON string.

Inputs: game_id (required), key, ref, value, +1 more.

list_downloadsList captured browser downloadsA

List files captured from the browser into the tool's download folder (any game; the folder persists across sessions and MCP restarts). Use download_file(name|index, path) to copy one anywhere. Shows name, size, capture time and the absolute folder path.

Inputs: limit.

list_gamesList open gamesA

List the currently open game sessions with their id, source, story title and step count.

Inputs: no named parameters.

live_viewOpen a live view of the game pageA

Give the user eyes on the actual page the agent is controlling: starts a tiny local web server (once per MCP process) that streams JPEG screenshots of the real Playwright tab (~1/s) together with passage, step, engine state, recent actions and the passage text. Returns a URL like http://127.0.0.1:4571/v/game_abc — open it in any browser (works with headless games too). Frames are captured only while someone is watching. Set open:true to also launch the URL in the default browser. DISPLAY POLICY: this is the default — and usually the only — way to show a game. One view per game: do not also switch to a headed window or loop screenshot; repeated calls return the same URL and never launch a second browser tab.

Inputs: game_id (required), open.

load_stateLoad an in-session snapshotB

Restore a snapshot created by save_state and return the resulting observation (text; format:"json" for JSON).

Inputs: game_id (required), name, format.

observeObserve current game stateA

Read the current passage: text, numbered choices, input fields, dialog state and status text. Returns a formatted text observation (string); pass format:"json" for a JSON string. Inputs are paginated in windows of 40: when truncated, the header says e.g. "Inputs (41-80 of 132)" — call again with inputs_offset=80. Use find_ui(text) to jump to a specific control, get_variables for specific story variables, and since_last=true when polling to save tokens.

Inputs: game_id (required), format, since_last, inputs_limit, +4 more.

open_gameOpen a Twine gameA

Open a Twine / interactive-fiction HTML game and return the first observation (passage text, numbered choices, inputs, dialog). Accepts a local .html file, a game folder (index.html or a single html is picked), or an http(s) URL. Local games are served over 127.0.0.1 so saves work. Returns a formatted text observation (string); pass format:"json" for a JSON string. Inputs are listed in windows of 40 (see inputs_offset/inputs_limit on observe) and find_ui(text) locates any control by label.

Inputs: source (required), seed, format, headless, +3 more.

restartRestart the gameB

Restart the story from the beginning (optionally with a new PRNG seed). Returns the first observation (text; format:"json" for JSON).

Inputs: game_id (required), seed, format.

save_stateSave an in-session snapshotA

Save the full game state under a name so you can branch: save -> try a path -> load_state -> try another path. Supported natively by SugarCube; other formats report unsupported.

Inputs: game_id (required), name.

screenshotScreenshot the gameA

Take a PNG screenshot of the game viewport. Useful for canvas/image-driven games and visual QA. Pass path to save it to a file (returns the path instead of the image). One-shot: this is not a live view — to let the user watch the game, call live_view once instead of taking screenshots repeatedly.

Inputs: game_id (required), path.

upload_fileUpload a file into the gameA

Upload a local file (mod .zip, exported .save, image) into an in the game. Provide trigger_text/trigger_ref for buttons that open a picker ("Load from File…", "Import"), or let it target the file input directly. If a hardcoded selector like #saves-import does not exist in the build, use find_ui("Load from File") and pass its ref as trigger_ref. Returns the new observation (text; format:"json" for JSON).

Inputs: path (required), game_id (required), ref, format, +4 more.

waitWait for the gameB

Wait for time (ms), for a text to appear, and/or for the page to settle, then return the new observation. Useful for timed passages and animations. Returns text; pass format:"json" for a JSON string.

Inputs: game_id (required), ms, format, for_text, +1 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.7/5.0

    Scored across 22 tools

    Disambiguation4/5

    Most tools target distinct actions (observe, choose, save/load, screenshots, files), but there are ambiguous pairs: choose() explicitly answers dialog buttons while click_ui() claims to 'click dialogs', and find_ui vs inspect_ui both locate controls. These overlaps require careful description reading to pick correctly.

    Naming Consistency4/5

    All names are snake_case and follow a verb_noun pattern for resource-targeting tools (save_state, open_game, get_variables, list_downloads). The spread of bare verbs (observe, choose, wait, back, restart, find_ui, inspect_ui, click_ui) deviates slightly, though it reads as an intentional convention for acting on the current game state.

    Tool Count3/5

    22 tools is on the heavy side for a game-automation server. Several functions arguably overlap (choose/click_ui, find_ui/inspect_ui, screenshot/live_view), suggesting some consolidation is possible, though most tools do earn their place.

    Completeness4/5

    The surface spans the full play lifecycle: open/close, observe, choose/interact, wait, back/restart, save/load state, screenshots/live view, file upload/download, variables, console errors, journal, and UI inspection. Minor gaps exist (no direct story-variable setter, no passage search/jump), but these are workaroundable via interact and find_ui.

    Maintenance

    ActivitySlowing
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables AI agents to run and manage a worldview-agnostic interactive fiction engine, including world initialization, deterministic action resolution, SillyTavern card and lorebook imports, narration context, state tracking, and recaps.
      1
      MIT
    • F
      license
      Not graded
      quality
      A
      maintenance
      Enables AI agents to browse and interact with web pages through a token-efficient, structured page representation — orientation summaries, targeted element queries, and full detail only on request — instead of raw accessibility-tree dumps. Supports navigation, interaction, forms, screenshots, console and network monitoring, session/tab management, and browser-based development auditing.
      4 npm
      -