GameFuse Multiplayer for AI Coding Agents¶
Using Claude Code, Cursor or another MCP tool? Connect the GameFuse MCP server and your agent can upload, run and debug room code directly.
Built on Colyseus 0.16 (server:
colyseus; browser:colyseus.js, wrapped by the GameFuse client library). Do NOT write Colyseus code: noRoomsubclass, no@colyseus/schema, noonCreate/onJoin, nocolyseus.jsClient in the game. Write GameFuse room code (a default-export object withconfig,start,update,gameEnd, ...) and useGameFuseMultiplayerin the browser.room.stateis a plain server-only object; send clients what they need.
Everything needed to add real-time multiplayer to a browser game with GameFuse. This page is complete on its own. The same text is at https://docs.gamefuse.co/llms.txt.
Model¶
- Three pieces: the game in the browser (uses the client library), the GameFuse API at
https://gamefuse.co(players, tickets, saved data), the multiplayer server (runs room code, one copy per room). - You write two things: room code (one JavaScript file, runs on the multiplayer server, owns the rules and the state) and browser code (sends input, draws what room code sends).
- The multiplayer server does not sync state. Room code sends messages with
room.send/room.broadcast. Browsers send messages withroom.send. - Room code is the authority. Never trust
dataorplayer.options; both come from a browser.
Commands¶
npm i -g gamefuse
gamefuse multiplayer init --game-name pong --game-mode superpong --game 123
# makes pong-superpong-gamefuse-multiplayer/ with the files below
gamefuse multiplayer validate # bundle + check, no upload
gamefuse multiplayer deploy # validate, upload, make live
gamefuse multiplayer deploy --no-activate # upload, do not make live
gamefuse multiplayer deploy --notes "..." # attach a note
gamefuse multiplayer deploy --game-mode pong-dev # upload to another game mode than the folder's
gamefuse multiplayer list # versions
gamefuse multiplayer activate <version> # make a version live (rollback)
gamefuse multiplayer logs [--follow] # room.log output
- Upload key:
GAMEFUSE_UPLOAD_KEYin the project's.env(also read from the environment), or--key <key>.GAMEFUSE_GAME_IDin.envgives the game ID.initcreates.envand adds it to.gitignore. Looks likempk_+ 32 hex characters. Found in the dashboard: your game, Multiplayer, "Upload key". Never put it in browser code or commit it. - Run validate/deploy/list/activate/logs next to the multiplayer folder or inside it; with several folders, pass
--dir <folder>. Deploy uploads to the folder'sgameMode. --jsonon every command. Exit code 0 = worked. Everything talks to https://gamefuse.co; there is nothing to configure for the address.- Bundling:
entryis bundled with esbuild into one ESM file with no externals. Staticimports are bundled in.
Files¶
<game-name>-<game-mode>-gamefuse-multiplayer/ one folder per game mode, e.g. pong-superpong-gamefuse-multiplayer/
room.js room code (init writes a small working example)
gamefuse-room.d.ts types for room code
AGENTS.md notes for agents
multiplayer.json { "gameName": "pong", "gameMode": "superpong", "gameId": 0, "entry": "room.js" }
Set gameId in multiplayer.json to the game's ID (or pass --game to init). gameMode is the queue name players join; "default" runs for any queue with no code of its own.
Room code skeleton¶
Default export. start, update and gameEnd are required. The rest are optional.
export default {
config: {
minPlayers: 2, // start() is called when this many are in
maxPlayers: 2, // 1 to 32; the room locks when full
tickRate: 60, // update() calls per second, 1 to 60; 0 = no loop
reconnectSeconds: 15, // how long a dropped player's seat is held
},
start(room) {}, // the game begins
update(room, dt) {}, // every tick; dt in seconds
gameEnd(room, result) {}, // after room.end(result); last chance to save
playerJoined(room, player, { midGame }) {}, // optional; midGame = joined a game under way (config.joinAfterStart)
playerDropped(room, player) {}, // optional: connection lost, seat held
playerReturned(room, player) {}, // optional: they are back
playerLeft(room, player, how) {}, // optional: how = 'quit' | 'timeout'
message(room, player, type, data) {}, // optional: that player's browser sent room.send(type, data)
};
room (in room code)¶
room.id room id
room.code 6-character code (queue rooms have one too)
room.players [{ id, name, seat, connected, options }]
id = GameFuse user id; seat = 0, 1, 2... in join order;
options = what that browser passed when joining
room.state plain object, yours; never sent anywhere automatically
room.time seconds since start
room.random() 0 to 1
room.send(player, type, data) message to one player
room.broadcast(type, data) message to all players
room.broadcast(type, data, { except: player })
room.after(seconds, fn) run once later
room.log(...things) shows in the dashboard and `gamefuse multiplayer logs`
room.lock() nobody else may join
room.kick(player, reason) remove a player; their browser gets closed('kicked')
room.end(result) calls gameEnd(room, result), every browser gets closed('ended'), room closes
room.round { multiplayerGameRoundId, gameRoundIds: { [playerId]: id } }
made when the game starts; game type = queue name or 'private'
room.gamefuse the game's GameFuse data, see below
room.gamefuse¶
Full access to this one game's data. Not affected by the dashboard's "API route access" switches. Every call returns a promise. A user id from another game is an error. id = GameFuse user id = player.id.
users.get(id) -> { id, username, score, credits, guest, attributes: { key: value } }
users.addScore(id, n) -> { score }
users.setScore(id, n) -> { score }
users.addCredits(id, n) -> { credits }
users.setCredits(id, n) -> { credits }
attributes.set(id, key, value) -> { key, value }
attributes.remove(id, key) -> {}
leaderboard.add(id, name, score, metadata?) -> { id }
leaderboard.get(name, limit?) -> { entries: [{ user_id, username, score, metadata }] }
leaderboard.clear(id, name?) -> {}
rounds.update(gameRoundId, { score?, place?, metadata?, end_time? }) -> { id } end_time: true = now
rounds.finishMultiplayer(multiplayerGameRoundId, metadata?) -> { id } sets end_time
rounds.createMultiplayer({ game_type, metadata?, user_ids: [] }) -> { multiplayer_game_round_id, game_round_ids: { "<user_id>": id } }
variables.get() -> { variables: { key: value } }
store.items() -> { items: [...] }
store.give(id, storeItemId) -> {}
store.remove(id, storeItemId) -> {}
All are called as room.gamefuse.<name>, for example await room.gamefuse.users.addScore(player.id, 10).
Rules for room code¶
- No
setTimeout/setInterval. Useroom.after(seconds, fn)for once-later andupdate(room, dt)for every tick. - No
fetch. Useroom.gamefuse. - No
require, noimport()at run time. Use staticimportat the top; the command bundles it. - No
process, no files. Keep state inroom.state; save lasting data withroom.gamefuse. - Calling an unavailable thing throws an error that says what to use instead.
room.stateis not sent to anyone. Send what browsers need.- Browsers get no "game started" event. Broadcast your own message from
start. - Browsers do not receive
result. Broadcast final scores beforeroom.end(result). - Use
room.random()for randomness. - Validate every
message: checktype, check the shape ofdata, check it is that player's turn. - Save in
gameEnd, not every tick.room.gamefuseis limited to 120 calls a minute. - Keep
updatefast: under 8 ms on average. - After
playerReturned, send that player a full catch-up message. - Handle
playerLeftso a game does not wait forever for someone who is gone.
Room code example¶
const GOAL = 10;
export default {
config: { minPlayers: 2, maxPlayers: 2, tickRate: 0, reconnectSeconds: 15 },
start(room) {
room.lock();
room.state.taps = {};
for (const p of room.players) room.state.taps[p.id] = 0;
room.broadcast('start', { goal: GOAL });
},
update(room, dt) {},
message(room, player, type, data) {
if (type !== 'tap' || !room.state.taps || room.state.over) return;
room.state.taps[player.id] += 1;
room.broadcast('taps', room.state.taps);
if (room.state.taps[player.id] >= GOAL) finish(room, player);
},
playerReturned(room, player) {
room.send(player, 'taps', room.state.taps);
},
playerLeft(room, player, how) {
if (!room.state.taps || room.state.over) return;
const other = room.players.find((p) => p.id !== player.id);
if (other) finish(room, other);
},
async gameEnd(room, result) {
await room.gamefuse.users.addScore(result.winnerId, 1);
await room.gamefuse.rounds.update(room.round.gameRoundIds[result.winnerId], { place: 1, end_time: true });
await room.gamefuse.rounds.finishMultiplayer(room.round.multiplayerGameRoundId);
},
};
function finish(room, winner) {
room.state.over = true;
room.broadcast('winner', { id: winner.id, name: winner.name });
room.end({ winnerId: winner.id });
}
Browser client¶
import { GameFuseMultiplayer } from 'gamefuse-multiplayer';
const mp = new GameFuseMultiplayer({ gameId, gameToken });
await mp.signInAsGuest(); // makes a guest once; token kept in localStorage under gamefuse.guest.<gameId>
mp.useToken(authenticationToken); // instead, for a player signed in to GameFuse
const room = await mp.joinQueue('1v1', { clientVersion: '1', ...anyOptions }); // waits in a room until matched
const room = await mp.createRoom({ ...options }); // private room; share room.code (runs the "default" mode)
const room = await mp.createRoom('superpong', { ...options }); // private room running the superpong mode's room code
const room = await mp.joinRoom('K7M2QX', { ...options }); // join a private room by code
const room = await mp.resume(); // after a page reload: the room, or null
room.code // 6-character code
room.me // { id, name, seat }
room.send(type, data) // to room code's message()
room.leave() // quit on purpose; room code sees playerLeft(..., 'quit')
room.on('message', (type, data) => {}) // from room.send / room.broadcast in room code
room.on('players', (players) => {}) // [{ id, name, seat, connected }] whenever it changes
room.on('reconnecting', () => {}) // my connection dropped; the library is retrying
room.on('reconnected', () => {}) // back in
room.on('closed', (reason) => {}) // 'ended' | 'kicked' | 'lost' | 'left'
gameIdandgameTokenare the game's ID and API token.- Every join gets a fresh ticket from the GameFuse API. You do not handle tickets.
- Join options are passed to room code as
player.options. - The guest is stored in
localStorage, so two tabs of one browser are the same player. Test with two browsers, or one normal and one private window.
Browser example:
const mp = new GameFuseMultiplayer({ gameId: 123, gameToken: 'your-game-api-token' });
await mp.signInAsGuest();
const room = (await mp.resume()) || (await mp.joinQueue('1v1', { clientVersion: '1' }));
room.on('message', (type, data) => {
if (type === 'start') showGame(data.goal);
if (type === 'taps') drawTaps(data[room.me.id]);
if (type === 'winner') showResult(data.id === room.me.id);
});
room.on('players', (players) => drawPlayers(players));
room.on('reconnecting', () => showBanner('Reconnecting...'));
room.on('reconnected', () => hideBanner());
room.on('closed', (reason) => showMenu(reason));
tapButton.addEventListener('click', () => room.send('tap', {}));
Other clients¶
All clients join the same rooms and run the same room code. Pick the one for the game's engine.
- JavaScript SDK (
game-fuse-js):GameFuseMultiplayeris built intogameFuseFull.min.jsandV3/gameFuseMultiplayer.js(no dependencies). Same API as above.new GameFuseMultiplayer()with no options usesGameFuse.setUpGame's game;mp.useToken()with no token uses the player signed in with the SDK. - Unity C# (
game-fuse-cs, namespaceGameFuseCSharp): afterGameFuse.SetUpGame,var mp = GameFuseMultiplayerUnity.Create();thenawait mp.SignInAsGuest()(ormp.UseGameFuseUser()/mp.UseToken(t)),await mp.JoinQueue("1v1", new Dictionary<string, object> { { "clientVersion", "1" } }),CreateRoom(gameMode, options),JoinRoom(code, options),LeaveQueue(),Resume(). Room:Code,Me(Id,Name,Seat),Players,Send(type, data),Leave(), eventsOnMessage((type, data) => ...),OnPlayers,OnReconnecting,OnReconnected,OnClosed((reason, detail) => ...). Failed joins throwGameFuseMultiplayerExceptionwithCode. Events run on Unity's main thread. Message data isnull/bool/long/double/string/List<object>/Dictionary<string, object>. Not supported in Unity WebGL builds. - Unreal C++ and Blueprints (
game-fuse-cpp):UGameFuseMultiplayergame instance subsystem (usesUGameFuseManager::SetUpGame's game).SignInAsGuest(FGFMultiplayerCallback),UseGameFuseUserToken(),UseToken(t),JoinQueue(Queue, TSharedPtr<FJsonObject> Options, FGFMultiplayerJoinCallback),CreateRoom(GameMode, Options, cb)(empty = default),JoinRoom(Code, Options, cb),LeaveQueue(),Resume(cb). Callbacks get(bool bSuccess, UGameFuseRoom* Room, const FGFMultiplayerError& Error);Error.Codeas above.UGameFuseRoom:GetCode(),GetMe(),GetPlayers(),Send(Type, FJsonValue)/SendObject/SendJson(false over 4 KB),Leave(), delegatesOnMessage(Blueprint, data as JSON text) /OnMessageNative(TSharedPtr<FJsonValue>),OnPlayers,OnReconnecting,OnReconnected,OnClosed(Reason, Detail). Everything fires on the game thread. Module needs"GameFuse"and"Json"in Build.cs.
Matchmaking¶
- Queue: players with the same game + queue name +
clientVersion+ live version of the room code go into the same open room, first come first served. startis called whenminPlayersare in. The room locks atmaxPlayers. Callroom.lock()to lock sooner.- Private room:
createRoomgives a 6-characterroom.code; others calljoinRoom(code). - Game modes: the queue name IS the game mode. Each mode has its own uploaded room code and live version (one
<game>-<mode>-gamefuse-multiplayerfolder per mode, made withinit --game-mode <queue name>); a queue with no code of its own runs the "default" mode. One upload key covers every mode. Mode names: lowercase letters, digits,-,_, max 40 chars. For work in progress use a separate mode such aspong-devandjoinQueue('pong-dev')in development builds. - Change
clientVersionwhen a new build of the game cannot play with the old one.
Drops and rejoining¶
- Drop: room code gets
playerDropped;player.connectedis false; the seat is held forreconnectSeconds. That browser getsreconnecting. - The library retries on its own after 0.5, 1, 2, 3, 4, 5 seconds and on, for as long as the seat is held.
- Back in time: room code gets
playerReturned; that browser getsreconnected. - Not back in time: room code gets
playerLeft(room, player, 'timeout'); that browser getsclosed('lost'). - Page reload: the library keeps what it needs in
sessionStorage. Callmp.resume()on page start before joining; it gives the room or null. closedreasons:'ended'(room code calledroom.end),'kicked'(room.kick),'lost'(could not get back in time),'left'(this browser calledroom.leave()).
Limits¶
message from a player 4 KB each, 60 a second per player extra are dropped and logged; room code never sees them
tick (update) under 8 ms average over a second first breach logged, three breaches close the room
memory 128 MB per room first breach logged, three breaches close the room
room lifetime 60 minutes first breach logged, three breaches close the room
room.gamefuse calls 120 a minute first breach logged, three breaches close the room
room code bundle 5 MB upload refused, 413
usage budget (whole game) Starter (shared server): CPU 20% of a core, memory 256 MB, network 600 KB/s, averaged over a minute.
Paid plans run the game on its own server with a bigger budget: Small 40%/350 MB, Medium 85%/1.6 GB, Large 170%/3.3 GB.
Over budget: no NEW rooms (joinQueue/createRoom reject with a "busy" message); running games carry on.
There is no cap on the number of rooms or players.
players per room 32 (maxPlayers 1 to 32) room locks at maxPlayers
tickRate 1 to 60, or 0 for no loop
guest sign-in 10 a minute per IP 429
ticket lasts 60 seconds
guests removed after 30 days without playing
Stopping players writing their own scores¶
Once room code saves scores, tell the developer to switch the same routes off for players: GameFuse dashboard, open the game, "API access" tab, "API route access" section, untick the "Players" box on rows such as "Add to a user's score", "Set a user's score", "Add store credits for a user", "Set store credits for a user", "Create a leaderboard entry", "Create a game round for a user", "Update a game round", then press "Save route access". room.gamefuse keeps working; it always has full access to that one game.
Upload API¶
For scripting without the gamefuse command. Base https://gamefuse.co. Header on every call: multiplayer-upload-key: mpk_.... Errors are { "error": "..." }. 401 = key missing or wrong. 403 = key belongs to a different game than game_id.
POST /api/v3/multiplayer/deployments
body { "game_id": 123, "code": "<whole bundle>", "notes": "optional", "activate": true }
201 { id, version, sha256, size_bytes, status }
status "active" = passed the check, now live
status "checked" = passed, not live (activate not set)
status "uploaded" = plus a "warning" string: the multiplayer server could not be reached to check it;
stored but NOT live; it is checked when you activate it
422 { "error", "problems": ["..."] } failed the check; the version is kept with status "rejected"
422 code missing
413 code over 5 MB
GET /api/v3/multiplayer/deployments?game_id=123
ok { deployments: [{ id, version, mode, sha256, size_bytes, status, notes, created_at }], active_versions: { mode: version }, active_version }
newest first; active_version = the "default" mode's live version (or the ?mode= one); null when nothing is live
POST /api/v3/multiplayer/deployments/:id/activate (:id is the deployment id, not the version number)
body { "game_id": 123 }
200 { id, version, sha256, size_bytes, status: "active" }
422 that version is "rejected"
503 a not-yet-checked version needs checking and the multiplayer server cannot be reached; nothing changes
GET /api/v3/multiplayer/logs?game_id=123&limit=200
ok { lines: [{ at, room, level, text }] }
503 { error } the multiplayer server cannot be reached
Statuses: uploaded, checked, active, retired (was live, replaced), rejected.
npx esbuild pong-superpong-gamefuse-multiplayer/room.js --bundle --format=esm --outfile=dist/room.js
jq -Rs '{game_id: 123, code: ., activate: true}' dist/room.js \
| curl -sS -X POST https://gamefuse.co/api/v3/multiplayer/deployments \
-H "multiplayer-upload-key: $GAMEFUSE_UPLOAD_KEY" \
-H "Content-Type: application/json" \
-d @-
Calls the client library makes¶
Only needed without the client library.
POST /api/v3/users/guest
body { "game_id": 123, "game_token": "..." }
ok { id, username, authentication_token, guest: true }
429 more than 10 a minute from one IP
POST /api/v3/multiplayer/tickets
header authentication-token: <the player's authentication_token>
ok { ticket, host_url, expires_in: 60 }
403 { error } multiplayer is switched off for the game
Checklist¶
npm i -g gamefuse, thengamefuse multiplayer init --game-name <name> --game-mode <queue name> --game <id>.- Check
gameIdandgameModein<name>-<mode>-gamefuse-multiplayer/multiplayer.json. - Write
room.jsin that folder:config,start,update,gameEnd, andmessage. gamefuse multiplayer validate.- Ask the developer to put the upload key in
.envasGAMEFUSE_UPLOAD_KEY(do not paste it into code or commit it). Multiplayer must be switched on for the game. gamefuse multiplayer deploy.- In the game (browser shown; Unity and Unreal in Other clients):
new GameFuseMultiplayer(...),signInAsGuest()oruseToken(),resume()thenjoinQueue/createRoom/joinRoom, wireroom.on(...)androom.send(...). - Test with two browsers. Read
gamefuse multiplayer logs --follow.
Matchmaking (optional)¶
- Default (no findRoom): joinQueue puts the player in the oldest open room of that queue that has players and a free seat, else a new room. A queue room that has not started
matchmaking.waitSeconds(default 180) after opening closes; clients getclosed('no_match', 'No one is online right now. Try again later.'). - Custom: export
matchmaking: { waitSeconds?, everySeconds?, attributes?: ['skill'] }andfindRoom(player, lobby). Players wait in a lobby (no room) until placed; joinQueue resolves on placement, rejects with error.code 'no_match' | 'rejected' | 'cancelled' (mp.leaveQueue()). player:{ id, name, options, attributes, waitedSeconds, secondsLeft }(attributes are GameFuse user attribute strings).lobby:{ rooms: [{ id, code, players, seatsLeft, maxPlayers, started, ageSeconds }], waiting: [player], config, random() }and the answersjoin(room),create(players?),wait(),reject(message). Return one (or nothing = wait).- findRoom is synchronous, has no
roomand noroom.gamefuse, and one round for everyone waiting must take under 1 second. Answers are applied oldest player first and later calls see their effect. - Full guide with recipes (skill widening over time, gather-then-pair, regions, parties, bans): docs page "Custom Matchmaking".
Joining a game under way¶
config.joinAfterStart(defaultfalse): when false the room locks asstartruns, so nobody joins a running game; when true players can join untilmaxPlayers.- A late player gets
playerJoined(room, player, { midGame: true })andplayer.joinedMidGame === true.startdoes not run again: do for them whatstartdid for others androom.sendthem the current state. - GameFuse adds a game round for a late player to the match's round, so
room.round.gameRoundIds[player.id]exists for them (shortly after they join).