glitchless-mcp 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,13 +11,29 @@ It's a stdio server. Run it with `npx`, no install needed:
11
11
  npx -y glitchless-mcp
12
12
  ```
13
13
 
14
+ ## Sign in to a workspace (Glitchless Cloud)
15
+
16
+ ```bash
17
+ npx -y glitchless-mcp login
18
+ ```
19
+
20
+ It prints a link and a code; you approve the code in the Glitchless dashboard, and it saves a workspace key in
21
+ `~/.config/glitchless/credentials.json` (readable only by you). From then on the server reaches every game in that
22
+ workspace: `glitchless_list_games` lists them, `glitchless_create_game` makes one and returns its client token, and
23
+ every tool takes `game` (a name or id). The key acts as you, with your role in the workspace, and never deletes data
24
+ or touches billing or people. `npx -y glitchless-mcp whoami` shows where you're signed in, `logout` deletes the saved
25
+ key, and Settings → Agent access in the dashboard lists and revokes keys. An agent can also sign in from inside a
26
+ chat with the `glitchless_sign_in` tool: it shows the link and code, and the running server switches over once you
27
+ approve.
28
+
14
29
  ## Settings
15
30
 
16
31
  | Variable | What |
17
32
  | --- | --- |
18
- | `GLITCHLESS_URL` | Your Glitchless server. Default `http://localhost:7777` |
19
- | `GLITCHLESS_API_KEY` | A secret read key (`gl_sk_…`), if the server needs one. Keep it out of git and out of the game |
20
- | `GLITCHLESS_SERVICE` | The game to use when a tool call doesn't name one. Optional |
33
+ | `GLITCHLESS_URL` | Your Glitchless server. Default: the signed-in workspace's, else `http://localhost:7777` |
34
+ | `GLITCHLESS_API_KEY` | A key, if the server needs one: a workspace key (`gl_ws_…`) for every game, or a secret key (`gl_sk_…`) for one. Overrides a sign-in. Keep it out of git and out of the game |
35
+ | `GLITCHLESS_GAME` | With a workspace key, the game to use when a call doesn't name one. Optional |
36
+ | `GLITCHLESS_SERVICE` | The service to use when a call doesn't name one. Optional |
21
37
 
22
38
  ## Add it to your agent
23
39
 
@@ -57,7 +73,10 @@ above go in its environment.
57
73
 
58
74
  | Tool | What it answers |
59
75
  | --- | --- |
60
- | `glitchless_list_games` | Which games report to the server, with their versions and environments |
76
+ | `glitchless_list_games` | Which games report to the server, with their versions and environments; signed in to a workspace, every game in it with its client token |
77
+ | `glitchless_sign_in` | Connect to a Glitchless Cloud workspace: a link and a code for the person to approve |
78
+ | `glitchless_create_game` | A new game in the workspace, with its client token and intake URL |
79
+ | `glitchless_share_board` | A read-only link to one board page, for a dev log, Discord or a game's "Live stats" link; `glitchless_list_share_links` and `glitchless_revoke_share_link` manage them |
61
80
  | `glitchless_triage` | Ranked findings: stutter per level and what it correlates with, leaks, top errors, difficulty spikes. Start here |
62
81
  | `glitchless_overview` | Headline numbers: sessions, players, crash-free sessions, frame time against the budget, rage quits |
63
82
  | `glitchless_performance` | Frame time per level, with draw calls, geometry counts and game gauges |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "glitchless-mcp",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "mcpName": "io.github.glitchless-gg/glitchless",
5
5
  "description": "Game observability MCP server: lets coding agents (Claude Code, Codex, Cursor and others) read your game's player telemetry and ranked findings, design its own dashboard, and run playtest bots.",
6
6
  "keywords": [
package/src/context.js CHANGED
@@ -2,28 +2,92 @@
2
2
  // helpers that shape a tool's reply. Each area's tools live in tools/<area>.js and register on import.
3
3
 
4
4
  import { AsyncLocalStorage } from 'node:async_hooks';
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
5
8
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
6
9
  import { z } from 'zod';
7
10
 
8
- export const BASE = (process.env.GLITCHLESS_URL || 'http://localhost:7777').replace(/\/$/, '');
9
- export const API_KEY = process.env.GLITCHLESS_API_KEY || '';
11
+ // Where `glitchless-mcp login` keeps its workspace key: { url, token, workspace: { id, name }, scopes }.
12
+ export const CREDENTIALS_FILE = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'glitchless', 'credentials.json');
13
+ export function readCredentials() {
14
+ try {
15
+ return JSON.parse(fs.readFileSync(CREDENTIALS_FILE, 'utf8'));
16
+ } catch {
17
+ return null;
18
+ }
19
+ }
20
+
21
+ // GLITCHLESS_API_KEY wins; without it, a saved sign-in. A game key (gl_sk_…) reaches one game; a workspace key
22
+ // (gl_ws_…) every game in its workspace, and then every tool takes `game`.
23
+ const saved = process.env.GLITCHLESS_API_KEY ? null : readCredentials();
24
+ export let BASE = (process.env.GLITCHLESS_URL || saved?.url || 'http://localhost:7777').replace(/\/$/, '');
25
+ export let API_KEY = process.env.GLITCHLESS_API_KEY || saved?.token || '';
10
26
  export const DEFAULT_SERVICE = process.env.GLITCHLESS_SERVICE || '';
27
+ export const isWorkspace = () => API_KEY.startsWith('gl_ws_');
28
+
29
+ // After a sign-in from inside the agent (glitchless_sign_in): the running server switches to the new key.
30
+ export function useCredentials({ url, token }) {
31
+ BASE = String(url).replace(/\/$/, '');
32
+ API_KEY = token;
33
+ games = null;
34
+ }
11
35
 
12
36
  export const server = new McpServer(
13
- { name: 'glitchless', version: '0.4.0' },
37
+ { name: 'glitchless', version: '0.5.0' },
14
38
  {
15
39
  instructions:
16
- 'Glitchless is observability for games made with Three.js, Phaser, Babylon.js, PlayCanvas, Unity, Godot, Unreal or GameMaker. Start with glitchless_triage to get ranked, evidence-backed findings for a game, then drill in with glitchless_performance, glitchless_get_error, glitchless_death_hotspots or glitchless_session. When players or playtesters send bug reports from inside the game (an F8 form or a button), glitchless_bug_reports lists them with what they wrote, the level and where they stood, and opens one with its screenshot. For metrics the game defines itself (what it sends with track(): plays, purchases, paywall views and so on) and funnels between them, use glitchless_events. For a game connected to a store (Steam, Google Play, the App Store), glitchless_store_reviews reads what players wrote there by build, with the hardware and Steam Deck playtime reviewers show, next to what Glitchless measured on that build, and glitchless_store_vitals what the store itself measured (slow rendering, crashes, ANRs, hangs) next to Glitchless, version by version. Each game has its own dashboard, a list of pages (boards of panels, and built-in views such as Errors, Sessions and Live Tail): read it with glitchless_dashboard, and after instrumenting a game, design one that fits it with glitchless_set_dashboard. Before changing game code, run glitchless_playtest with save_as "baseline"; after the change, run glitchless_playtest again to compare, and treat a FAIL as unfinished work. After shipping a fix (bump the version passed to Glitchless.init), use glitchless_compare_versions to confirm it with real players. If the game is running in a browser with WebMCP connected, its live tools (glitchless_live_performance, glitchless_measure, glitchless_inspect_scene, and game tools such as zoomies_load_level) let you reproduce and measure issues directly. Unity, Godot, Unreal and GameMaker builds measure themselves when run with --glitchless-measure=SECONDS (-glitchless-measure in Unreal and GameMaker); in the Unreal editor, Unreal MCP with the Glitchless Toolset has a Measure tool.',
40
+ 'Glitchless is observability for games made with Three.js, Phaser, Babylon.js, PlayCanvas, Unity, Godot, Unreal or GameMaker. On Glitchless Cloud, glitchless_sign_in connects you to the person\'s whole workspace (they approve a code in the browser): then glitchless_list_games lists every game, glitchless_create_game makes one and hands back its client token, every tool takes game (by name), and glitchless_share_board makes a read-only link to a board. Start with glitchless_triage to get ranked, evidence-backed findings for a game, then drill in with glitchless_performance, glitchless_get_error, glitchless_death_hotspots or glitchless_session. When players or playtesters send bug reports from inside the game (an F8 form or a button), glitchless_bug_reports lists them with what they wrote, the level and where they stood, and opens one with its screenshot. For metrics the game defines itself (what it sends with track(): plays, purchases, paywall views and so on) and funnels between them, use glitchless_events. For a game connected to a store (Steam, Google Play, the App Store), glitchless_store_reviews reads what players wrote there by build, with the hardware and Steam Deck playtime reviewers show, next to what Glitchless measured on that build, and glitchless_store_vitals what the store itself measured (slow rendering, crashes, ANRs, hangs) next to Glitchless, version by version. Each game has its own dashboard, a list of pages (boards of panels, and built-in views such as Errors, Sessions and Live Tail): read it with glitchless_dashboard, and after instrumenting a game, design one that fits it with glitchless_set_dashboard. Before changing game code, run glitchless_playtest with save_as "baseline"; after the change, run glitchless_playtest again to compare, and treat a FAIL as unfinished work. After shipping a fix (bump the version passed to Glitchless.init), use glitchless_compare_versions to confirm it with real players. If the game is running in a browser with WebMCP connected, its live tools (glitchless_live_performance, glitchless_measure, glitchless_inspect_scene, and game tools such as zoomies_load_level) let you reproduce and measure issues directly. Unity, Godot, Unreal and GameMaker builds measure themselves when run with --glitchless-measure=SECONDS (-glitchless-measure in Unreal and GameMaker); in the Unreal editor, Unreal MCP with the Glitchless Toolset has a Measure tool.',
17
41
  },
18
42
  );
19
43
 
44
+ // The games a workspace key reaches, cached briefly; the game each call names (by name or id), else the one the
45
+ // session last used (or GLITCHLESS_GAME), else the only game.
46
+ let games = null;
47
+ let currentGame = process.env.GLITCHLESS_GAME || '';
48
+ export async function workspaceGames(fresh = false) {
49
+ if (!fresh && games && Date.now() - games.at < 30_000) return games.list;
50
+ const { games: list } = await agent('GET', '/games');
51
+ games = { at: Date.now(), list };
52
+ return list;
53
+ }
54
+
55
+ export async function projectFor(game) {
56
+ const want = game || currentGame;
57
+ let list = await workspaceGames();
58
+ const find = () => list.find((g) => g.id === want) ?? list.find((g) => g.name.toLowerCase() === String(want).toLowerCase());
59
+ let hit = want ? find() : list.length === 1 ? list[0] : null;
60
+ if (want && !hit) {
61
+ list = await workspaceGames(true);
62
+ hit = find();
63
+ }
64
+ if (!hit) throw new Error(want ? `No game called "${want}" in this workspace. Games: ${list.map((g) => g.name).join(', ') || 'none yet'}.` : `Name the game this is about (game: "<name>"): ${list.map((g) => g.name).join(', ') || 'none yet; glitchless_create_game makes one'}.`);
65
+ currentGame = hit.id;
66
+ return hit.id;
67
+ }
68
+
69
+ async function headers(extra = {}) {
70
+ const client = server.server.getClientVersion?.()?.name || 'mcp';
71
+ return { 'x-glitchless-client': client, ...(API_KEY ? { 'x-glitchless-api-key': API_KEY } : {}), ...(isWorkspace() ? { 'x-glitchless-project': await projectFor(calls.getStore()?.game) } : {}), ...extra };
72
+ }
73
+
74
+ // A workspace key's own routes (/v1/agent/…, Glitchless Cloud).
75
+ export async function agent(method, p, body) {
76
+ if (!isWorkspace()) throw new Error('This needs a workspace: sign in with glitchless_sign_in (or run `npx -y glitchless-mcp login`) on Glitchless Cloud.');
77
+ const res = await fetch(`${BASE}/v1/agent${p}`, {
78
+ method,
79
+ headers: { 'x-glitchless-api-key': API_KEY, ...(body ? { 'content-type': 'application/json' } : {}) },
80
+ ...(body ? { body: JSON.stringify(body) } : {}),
81
+ });
82
+ const data = await res.json().catch(() => ({}));
83
+ if (!res.ok) throw new Error(`${data.error || `HTTP ${res.status}`}`);
84
+ return data;
85
+ }
86
+
20
87
  export async function query(name, params = {}) {
21
88
  const qs = new URLSearchParams();
22
89
  for (const [k, v] of Object.entries(params)) if (v != null && v !== '') qs.set(k, String(v));
23
- const client = server.server.getClientVersion?.()?.name || 'mcp';
24
- const res = await fetch(`${BASE}/v1/query/${name}?${qs}`, {
25
- headers: { 'x-glitchless-client': client, ...(API_KEY ? { 'x-glitchless-api-key': API_KEY } : {}) },
26
- });
90
+ const res = await fetch(`${BASE}/v1/query/${name}?${qs}`, { headers: await headers() });
27
91
  if (!res.ok) throw new Error(`Glitchless API ${name} → HTTP ${res.status}: ${(await res.text()).slice(0, 200)}`);
28
92
  const data = await res.json();
29
93
  const call = calls.getStore();
@@ -47,16 +111,15 @@ function windowNote() {
47
111
  return parts.length ? `\n(Note: ${parts.join('; ')}.)` : '';
48
112
  }
49
113
 
50
- export async function write(method, path, body) {
51
- const client = server.server.getClientVersion?.()?.name || 'mcp';
52
- const res = await fetch(`${BASE}${path}`, {
114
+ export async function write(method, p, body) {
115
+ const res = await fetch(`${BASE}${p}`, {
53
116
  method,
54
- headers: { 'content-type': 'application/json', 'x-glitchless-client': client, ...(API_KEY ? { 'x-glitchless-api-key': API_KEY } : {}) },
117
+ headers: await headers({ 'content-type': 'application/json' }),
55
118
  ...(body ? { body: JSON.stringify(body) } : {}),
56
119
  });
57
120
  const data = await res.json().catch(() => ({}));
58
- if (res.status === 403) throw new Error(`${data.error || 'forbidden'}. Saving a dashboard needs a secret key with the dashboard scope (create one in the dashboard's settings).`);
59
- if (!res.ok) throw new Error(`Glitchless API ${method} ${path} → HTTP ${res.status}: ${data.error || ''}`);
121
+ if (res.status === 403) throw new Error(`${data.error || 'forbidden'}. Saving a dashboard needs a key with the dashboard scope (a workspace key from glitchless_sign_in has it).`);
122
+ if (!res.ok) throw new Error(`Glitchless API ${method} ${p} → HTTP ${res.status}: ${data.error || ''}`);
60
123
  return data;
61
124
  }
62
125
 
@@ -93,10 +156,16 @@ export const common = {
93
156
  steam_branch: z.string().optional().describe('Only include sessions that ran this Steam branch ("public", or a beta\'s name); games that use Steamworks send it'),
94
157
  };
95
158
 
159
+ // Every tool takes `game` (by name or id): with a workspace key it picks the game, with a game key it's ignored.
160
+ const gameField = z.string().optional().describe('The game, by name or id, when signed in to a workspace (glitchless_list_games lists them); later calls keep it. Ignored with a key for one game.');
161
+ const register = server.registerTool.bind(server);
162
+ server.registerTool = (name, config, handler) =>
163
+ register(name, { ...config, inputSchema: { ...(config.inputSchema || {}), game: gameField } }, (args, extra) => calls.run({ game: args?.game }, () => handler(args || {}, extra)));
164
+
96
165
  // A read-only tool: errors come back as a tool error, not a thrown exception.
97
166
  export function tool(name, description, schema, handler) {
98
167
  server.registerTool(name, { description, inputSchema: schema, annotations: { readOnlyHint: true } }, async (args) =>
99
- calls.run({}, async () => {
168
+ calls.run({ game: args.game }, async () => {
100
169
  try {
101
170
  return await handler(args || {});
102
171
  } catch (err) {
package/src/index.js CHANGED
@@ -6,17 +6,28 @@
6
6
  //
7
7
  // claude mcp add glitchless -e GLITCHLESS_URL=http://localhost:7777 -- npx -y glitchless-mcp
8
8
  //
9
+ // On Glitchless Cloud, sign in once to reach every game in a workspace (it shows a code to approve in the browser):
10
+ //
11
+ // npx -y glitchless-mcp login (also: whoami, logout)
12
+ //
9
13
  // The shared server and helpers are in context.js; each area's tools are in tools/<area>.js, and a new
10
14
  // area is one more file imported here.
11
15
 
12
16
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
13
- import { server } from './context.js';
14
- import './tools/core.js';
15
- import './tools/analytics.js';
16
- import './tools/dashboard.js';
17
- import './tools/playtest.js';
18
- import './tools/reports.js';
19
- import './tools/deck.js';
20
- import './tools/store-reviews.js';
17
+
18
+ if (['login', 'logout', 'whoami'].includes(process.argv[2])) {
19
+ const { cli } = await import('./login.js');
20
+ process.exit(await cli(process.argv.slice(2)));
21
+ }
22
+
23
+ const { server } = await import('./context.js');
24
+ await import('./tools/core.js');
25
+ await import('./tools/analytics.js');
26
+ await import('./tools/dashboard.js');
27
+ await import('./tools/playtest.js');
28
+ await import('./tools/reports.js');
29
+ await import('./tools/deck.js');
30
+ await import('./tools/store-reviews.js');
31
+ await import('./tools/workspace.js');
21
32
 
22
33
  await server.connect(new StdioServerTransport());
package/src/login.js ADDED
@@ -0,0 +1,93 @@
1
+ // Signing in to a Glitchless Cloud workspace, for an agent: `npx -y glitchless-mcp login` in a terminal, or the
2
+ // glitchless_sign_in tool from inside the agent. Glitchless shows a code and a link; the person approves it in
3
+ // the dashboard; the workspace key it hands back is saved to CREDENTIALS_FILE (only readable by you), where the MCP
4
+ // server finds it.
5
+ //
6
+ // npx -y glitchless-mcp login [--url https://api.glitchless.gg] [--no-browser]
7
+ // npx -y glitchless-mcp whoami
8
+ // npx -y glitchless-mcp logout
9
+ import fs from 'node:fs';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+ import { spawn } from 'node:child_process';
13
+ import { CREDENTIALS_FILE, readCredentials } from './context.js';
14
+
15
+ export const CLOUD_URL = 'https://api.glitchless.gg';
16
+
17
+ async function call(url, p, body) {
18
+ const res = await fetch(`${url}/v1/agent${p}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
19
+ const data = await res.json().catch(() => ({}));
20
+ if (res.status === 404 && p === '/connect') throw new Error(`${url} has no agent sign-in. A self-hosted Glitchless server needs no key; set GLITCHLESS_URL to it instead.`);
21
+ if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
22
+ return data;
23
+ }
24
+
25
+ // → { verification_url, user_code, wait() }: wait() resolves with the saved credentials, or rejects when the
26
+ // person turns it down or the code expires.
27
+ export async function startSignIn({ url = CLOUD_URL, client = `glitchless-mcp on ${os.hostname()}` } = {}) {
28
+ url = url.replace(/\/$/, '');
29
+ const start = await call(url, '/connect', { client });
30
+ const deadline = Date.now() + start.expires_in * 1000;
31
+ let interval = (start.interval || 2) * 1000;
32
+ async function wait() {
33
+ while (Date.now() < deadline) {
34
+ await new Promise((r) => setTimeout(r, interval));
35
+ const poll = await call(url, '/connect/poll', { device_code: start.device_code });
36
+ if (poll.status === 'slow_down') interval += 1000;
37
+ else if (poll.status === 'denied') throw new Error('The sign-in was turned down in the dashboard.');
38
+ else if (poll.status === 'expired') throw new Error('The sign-in code expired. Start again.');
39
+ else if (poll.status === 'approved') return saveCredentials({ url, token: poll.token, workspace: poll.workspace, scopes: poll.scopes });
40
+ }
41
+ throw new Error('The sign-in code expired before it was approved. Start again.');
42
+ }
43
+ return { verification_url: start.verification_url, user_code: start.user_code, wait };
44
+ }
45
+
46
+ export function saveCredentials(c) {
47
+ const credentials = { ...c, savedAt: new Date().toISOString() };
48
+ fs.mkdirSync(path.dirname(CREDENTIALS_FILE), { recursive: true, mode: 0o700 });
49
+ fs.writeFileSync(CREDENTIALS_FILE, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 0o600 });
50
+ return credentials;
51
+ }
52
+
53
+ function openBrowser(link) {
54
+ const [cmd, args] = process.platform === 'darwin' ? ['open', [link]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', link]] : ['xdg-open', [link]];
55
+ try {
56
+ spawn(cmd, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref();
57
+ } catch {}
58
+ }
59
+
60
+ // The command line: login, whoami, logout. → the exit code.
61
+ export async function cli(argv) {
62
+ const [command, ...rest] = argv;
63
+ const flag = (name) => {
64
+ const i = rest.indexOf(`--${name}`);
65
+ return i >= 0 ? rest[i + 1] : null;
66
+ };
67
+ if (command === 'logout') {
68
+ fs.rmSync(CREDENTIALS_FILE, { force: true });
69
+ console.log('Signed out: the saved workspace key is deleted. Revoke it in Settings → Agent access if it may have leaked.');
70
+ return 0;
71
+ }
72
+ if (command === 'whoami') {
73
+ const c = readCredentials();
74
+ if (!c) {
75
+ console.log('Not signed in. Run: npx -y glitchless-mcp login');
76
+ return 1;
77
+ }
78
+ console.log(`Signed in to ${c.workspace?.name ?? c.workspace?.id} on ${c.url} (${(c.scopes || []).join(', ')}), since ${c.savedAt}.`);
79
+ return 0;
80
+ }
81
+ const url = flag('url') || process.env.GLITCHLESS_URL || CLOUD_URL;
82
+ const { verification_url, user_code, wait } = await startSignIn({ url });
83
+ console.log(`To connect this agent to Glitchless, open:\n\n ${verification_url}\n\nand check the page shows the code ${user_code}. Waiting for approval…`);
84
+ if (!rest.includes('--no-browser')) openBrowser(verification_url);
85
+ try {
86
+ const c = await wait();
87
+ console.log(`\nConnected to ${c.workspace?.name ?? 'your workspace'} (${c.scopes.join(', ')}). The key is saved in ${CREDENTIALS_FILE}.\nRestart your agent's Glitchless MCP server (or start a new session) to use it.`);
88
+ return 0;
89
+ } catch (err) {
90
+ console.error(`\n${err.message}`);
91
+ return 1;
92
+ }
93
+ }
package/src/tools/core.js CHANGED
@@ -1,9 +1,13 @@
1
1
  // The built-in reads: which games report, findings, headline numbers, frame time, errors, levels,
2
2
  // death hotspots and one session in detail.
3
3
  import { z } from 'zod';
4
- import { BASE, query, resolveService, range, reply, common, tool, slimIssue, slimGroup } from '../context.js';
4
+ import { BASE, query, resolveService, range, reply, common, tool, slimIssue, slimGroup, isWorkspace, workspaceGames } from '../context.js';
5
5
 
6
- tool('glitchless_list_games', 'List the games reporting to Glitchless, with their versions, environments and when they were last seen.', {}, async () => {
6
+ tool('glitchless_list_games', 'List the games: with a workspace key, every game in the workspace (its id, name, client token and the services reporting to it); with a key for one game, its services, versions, environments and when they were last seen.', {}, async () => {
7
+ if (isWorkspace()) {
8
+ const list = await workspaceGames(true);
9
+ return reply(`${list.length} game(s) in this workspace. Name one with game in any tool:`, list);
10
+ }
7
11
  const { services } = await query('services');
8
12
  return reply(`${services.length} game(s) reporting to ${BASE}`, services.map((s) => ({ ...s, last_seen: new Date(s.last_seen).toISOString() })));
9
13
  });
@@ -0,0 +1,105 @@
1
+ // A workspace's games, for an agent signed in with a workspace key (glitchless_sign_in, or `glitchless-mcp login`):
2
+ // sign in, create a game, and make or revoke share links. Listing games, reading any of them and saving their
3
+ // dashboards are the other tools, with `game`.
4
+ import { z } from 'zod';
5
+ import { server, BASE, isWorkspace, agent, workspaceGames, projectFor, resolveService, reply, fail, useCredentials, readCredentials } from '../context.js';
6
+ import { startSignIn, CLOUD_URL } from '../login.js';
7
+
8
+ const act = (name, description, inputSchema, handler, annotations = {}) =>
9
+ server.registerTool(name, { description, inputSchema, annotations: { readOnlyHint: false, ...annotations } }, async (args) => {
10
+ try {
11
+ return await handler(args);
12
+ } catch (err) {
13
+ return fail(err);
14
+ }
15
+ });
16
+
17
+ let signingIn = null;
18
+
19
+ act(
20
+ 'glitchless_sign_in',
21
+ "Connect this agent to a Glitchless Cloud workspace, so it can create games, read any of them, design their dashboards and make share links. Returns a link and a code: show both to the person and ask them to approve it in the browser. Then call this tool again (or any other) — once it's approved, this server uses the workspace key right away, and keeps it for later sessions.",
22
+ { url: z.string().optional().describe(`The Glitchless API (default ${CLOUD_URL})`) },
23
+ async ({ url }) => {
24
+ if (isWorkspace()) {
25
+ const c = readCredentials();
26
+ return reply(`Already signed in to ${c?.workspace?.name ?? 'a workspace'} on ${BASE}.`, { games: (await workspaceGames(true)).map((g) => g.name) });
27
+ }
28
+ if (signingIn?.done) {
29
+ const c = signingIn.done;
30
+ signingIn = null;
31
+ useCredentials(c);
32
+ return reply(`Signed in to ${c.workspace?.name ?? 'the workspace'} (${c.scopes.join(', ')}).`, { games: (await workspaceGames(true)).map((g) => g.name) });
33
+ }
34
+ if (signingIn?.error) {
35
+ const err = signingIn.error;
36
+ signingIn = null;
37
+ throw err;
38
+ }
39
+ if (signingIn) return reply(`Still waiting for approval. Ask the person to open ${signingIn.verification_url} and approve the code ${signingIn.user_code}.`, {});
40
+ const started = await startSignIn({ url: url || (BASE.includes('localhost') ? CLOUD_URL : BASE) });
41
+ signingIn = { verification_url: started.verification_url, user_code: started.user_code };
42
+ started.wait().then(
43
+ (c) => {
44
+ signingIn = { ...signingIn, done: c };
45
+ useCredentials(c);
46
+ },
47
+ (err) => (signingIn = { ...signingIn, error: err }),
48
+ );
49
+ return reply(`Ask the person to open this link and approve the code ${started.user_code}:\n${started.verification_url}\nThe code works for 10 minutes. This server switches to the workspace as soon as it's approved.`, {});
50
+ },
51
+ { openWorldHint: true },
52
+ );
53
+
54
+ act(
55
+ 'glitchless_create_game',
56
+ "Create a game in the signed-in workspace. Returns its client token (gl_pub_…, the public key game builds send with) and the intake URL to put in the game's Glitchless.init; the instrument skill says where for each engine. Later calls can name it with game.",
57
+ { name: z.string().describe("The game's name, as players know it") },
58
+ async ({ name }) => {
59
+ const made = await agent('POST', '/games', { name });
60
+ await workspaceGames(true);
61
+ await projectFor(made.game.id);
62
+ return reply(`Created ${made.game.name}. Initialise Glitchless with this client token and intake:`, made);
63
+ },
64
+ );
65
+
66
+ act(
67
+ 'glitchless_share_board',
68
+ "Make a read-only share link to one board page of a game: for a dev log, Discord, a publisher, or a game's own \"Live stats\" link. Anyone with it sees that board and nothing else, signed out. No expiry unless days is set; sums (revenue, totals) show only with sums: true. The link is shown once.",
69
+ {
70
+ service: z.string().optional().describe("The game's service (default: its most recently active one)"),
71
+ page: z.string().describe("The board page's id (glitchless_dashboard lists them)"),
72
+ name: z.string().optional().describe('What the link is for, e.g. "Dev log"'),
73
+ days: z.number().optional().describe('Expire after 1, 7, 30, 90 or 365 days'),
74
+ sums: z.boolean().optional().describe('Show sums such as revenue'),
75
+ },
76
+ async ({ service, page, name, days, sums, game }) => {
77
+ const pid = await projectFor(game);
78
+ const svc = await resolveService(service);
79
+ const out = await agent('POST', `/games/${pid}/shares`, { service: svc, page, name, days, sums: sums === true });
80
+ return reply(`Share link to ${svc}'s "${page}" page (shown once):\n${out.url}`, out.share);
81
+ },
82
+ );
83
+
84
+ act(
85
+ 'glitchless_list_share_links',
86
+ "A game's share links: which page each shows, when it expires, and whether it's revoked.",
87
+ {},
88
+ async ({ game }) => {
89
+ const pid = await projectFor(game);
90
+ return reply('Share links:', (await agent('GET', `/games/${pid}/shares`)).shares);
91
+ },
92
+ { readOnlyHint: true },
93
+ );
94
+
95
+ act(
96
+ 'glitchless_revoke_share_link',
97
+ 'Revoke a share link: it stops working at once, for everyone who has it.',
98
+ { id: z.string().describe("The link's id from glitchless_list_share_links") },
99
+ async ({ id, game }) => {
100
+ const pid = await projectFor(game);
101
+ await agent('DELETE', `/games/${pid}/shares/${encodeURIComponent(id)}`);
102
+ return reply(`Revoked ${id}.`, {});
103
+ },
104
+ { destructiveHint: true },
105
+ );