glitchless-mcp 0.4.0 → 0.6.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 |
@@ -76,6 +95,8 @@ above go in its environment.
76
95
  | `glitchless_deck_send` | Build the game, send it to the paired Steam Deck, add it to the Deck's library and optionally start it ([glitchless-deck](https://www.npmjs.com/package/glitchless-deck); pair once with `npx glitchless-deck pair`) |
77
96
  | `glitchless_deck_measure` | Measure a Unity, Godot or Unreal build on the Steam Deck and compare it with a saved run |
78
97
 
98
+ The reads take `hours`, `version`, `env` (e.g. `prod`) and `session_type` (`user` for players only, `synthetic` for bots, playtests and store test devices, `all`). Unless `env` or `session_type` is given, findings read the production sessions of players and say so; the other numbers count every session in the window.
99
+
79
100
  To let the agent drive the running game as well (measure frame times, inspect the scene, load a
80
101
  level), add the WebMCP server beside this one: `npx -y @jason.today/webmcp@latest --mcp`.
81
102
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "glitchless-mcp",
3
- "version": "0.4.0",
3
+ "version": "0.6.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": [
@@ -46,6 +46,7 @@
46
46
  "node": ">=20"
47
47
  },
48
48
  "scripts": {
49
+ "test": "node --test test/*.test.js",
49
50
  "bundle": "esbuild src/index.js --bundle --platform=node --format=esm --target=node20 --external:playwright --outfile=../../plugin/glitchless/mcp/glitchless-mcp.mjs --banner:js=\"import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);\""
50
51
  },
51
52
  "dependencies": {
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.6.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
 
@@ -91,12 +154,28 @@ export const common = {
91
154
  .describe("Look-back window in hours (default 24). Up to the plan's retention on Glitchless Cloud: 336 (14 days) on Free, 2160 (90 days) on Indie, 9600 (400 days) on Studio. Past 744 (31 days) answers are by day."),
92
155
  version: z.string().optional().describe('Only include sessions from this game version'),
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'),
157
+ env: z.string().optional().describe('Only include sessions from this environment, e.g. "prod" (what the game passes to init; builds a developer runs usually send "dev")'),
158
+ session_type: z
159
+ .enum(['user', 'synthetic', 'all'])
160
+ .optional()
161
+ .describe('"user": players only; "synthetic": bots, playtests and store test devices only; "all" or unset: both. Findings (glitchless_triage, and the overview\'s) read the production sessions of players unless env or session_type is given'),
94
162
  };
95
163
 
164
+ // The filters every read passes on to the Glitchless API.
165
+ export function filters({ version, steam_branch, env, session_type } = {}) {
166
+ return { version, steam_branch, env, type: session_type };
167
+ }
168
+
169
+ // Every tool takes `game` (by name or id): with a workspace key it picks the game, with a game key it's ignored.
170
+ 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.');
171
+ const register = server.registerTool.bind(server);
172
+ server.registerTool = (name, config, handler) =>
173
+ register(name, { ...config, inputSchema: { ...(config.inputSchema || {}), game: gameField } }, (args, extra) => calls.run({ game: args?.game }, () => handler(args || {}, extra)));
174
+
96
175
  // A read-only tool: errors come back as a tool error, not a thrown exception.
97
176
  export function tool(name, description, schema, handler) {
98
177
  server.registerTool(name, { description, inputSchema: schema, annotations: { readOnlyHint: true } }, async (args) =>
99
- calls.run({}, async () => {
178
+ calls.run({ game: args.game }, async () => {
100
179
  try {
101
180
  return await handler(args || {});
102
181
  } 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
+ }
@@ -1,6 +1,6 @@
1
1
  // The game's own metrics: its custom events and funnels, and versions compared in its own terms.
2
2
  import { z } from 'zod';
3
- import { query, resolveService, range, reply, common, tool } from '../context.js';
3
+ import { query, resolveService, range, reply, common, tool, filters } from '../context.js';
4
4
 
5
5
  tool(
6
6
  'glitchless_events',
@@ -10,9 +10,9 @@ tool(
10
10
  name: z.string().optional().describe('Only this event, e.g. "paywall"'),
11
11
  funnel: z.string().optional().describe('Steps in order, comma-separated: "open,paywall,buy". A step can require a value: "buy=done" (any attribute) or "buy:step=done"'),
12
12
  },
13
- async ({ service, hours, version, steam_branch, name, funnel }) => {
13
+ async ({ service, hours, name, funnel, ...f }) => {
14
14
  const svc = await resolveService(service);
15
- const d = await query('events', { service: svc, version, steam_branch, name, funnel, ...range(hours) });
15
+ const d = await query('events', { service: svc, ...filters(f), name, funnel, ...range(hours) });
16
16
  const brief = d.events
17
17
  .slice(0, 15)
18
18
  .map((e) => `${e.name}: ${e.count} in ${e.sessions} session(s)${(e.sums || []).length ? `; ${e.sums.map((x) => `${x.attr} sum ${x.sum}${x.currency ? ` ${x.currency}` : ''}`).join(', ')}` : ''}`)
@@ -30,14 +30,16 @@ tool(
30
30
  {
31
31
  service: common.service,
32
32
  hours: common.hours,
33
+ env: common.env,
34
+ session_type: common.session_type,
33
35
  a: z.string().optional().describe('Baseline version, branch or build (default: second newest)'),
34
36
  b: z.string().optional().describe('New version, branch or build (default: newest)'),
35
37
  by: z.enum(['version', 'steam_branch', 'steam_build']).optional().describe('What to compare (default version). steam_branch and steam_build need a game that uses Steamworks'),
36
38
  },
37
- async ({ service, hours, a, b, by }) => {
39
+ async ({ service, hours, a, b, by, env, session_type }) => {
38
40
  const svc = await resolveService(service);
39
41
  const steam = by && by !== 'version' ? by : null;
40
- const { versions, has = {}, board = [] } = await query('versions', { service: svc, ...(steam ? { by: steam } : {}), ...range(hours || 72) });
42
+ const { versions, has = {}, board = [] } = await query('versions', { service: svc, ...filters({ env, session_type }), ...(steam ? { by: steam } : {}), ...range(hours || 72) });
41
43
  const what = steam === 'steam_branch' ? 'Steam branch' : steam === 'steam_build' ? 'Steam build' : 'version';
42
44
  if (steam && !versions.length) return reply(`No session of ${svc} sent its ${what} in this window: the SDKs read it from Steamworks when the game uses it and runs from Steam`, versions);
43
45
  if (versions.length < 2 && !(a && b)) return reply(`Only one ${what} of ${svc} has reported in this window`, versions);
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, filters, 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
  });
@@ -12,17 +16,18 @@ tool(
12
16
  'glitchless_triage',
13
17
  "Ranked findings for a game: performance spikes per level (with the gauges and events they correlate with), memory leaks, top errors, difficulty spikes / rage-quit hotspots and version regressions — ranked by severity and player impact, each with evidence and a suggested fix. Start here when asked 'what's wrong with my game?'.",
14
18
  { ...common },
15
- async ({ service, hours, version, steam_branch }) => {
19
+ async ({ service, hours, ...f }) => {
16
20
  const svc = await resolveService(service);
17
- const { findings, meta } = await query('findings', { service: svc, version, steam_branch, ...range(hours) });
21
+ const { version } = f;
22
+ const { findings, meta } = await query('findings', { service: svc, ...filters(f), ...range(hours) });
18
23
  const brief = findings.map((f, i) => `${i + 1}. [${f.severity.toUpperCase()}] ${f.title}`).join('\n');
19
24
  return reply(`Findings for ${svc} (${hours || 24}h${version ? `, ${version}` : ''}):\n${brief || 'Nothing unusual.'}\n\nFull findings with evidence (window ${new Date(meta?.from).toISOString()} → now):`, findings);
20
25
  },
21
26
  );
22
27
 
23
- tool('glitchless_overview', 'Headline KPIs for a game: sessions, players, crash-free and error-free sessions, frame-time p50/p95/p99 vs budget, hitches per minute, rage quits, top errors and the level funnel.', { ...common }, async ({ service, hours, version, steam_branch }) => {
28
+ tool('glitchless_overview', 'Headline KPIs for a game: sessions, players, crash-free and error-free sessions, frame-time p50/p95/p99 vs budget, hitches per minute, rage quits, top errors and the level funnel.', { ...common }, async ({ service, hours, ...f }) => {
24
29
  const svc = await resolveService(service);
25
- const d = await query('overview', { service: svc, version, steam_branch, ...range(hours) });
30
+ const d = await query('overview', { service: svc, ...filters(f), ...range(hours) });
26
31
  return reply(`Overview for ${svc}`, { kpis: d.kpis, deployments: d.deployments, top_errors: d.top_errors.map(slimIssue), funnel: d.funnel });
27
32
  });
28
33
 
@@ -30,9 +35,9 @@ tool(
30
35
  'glitchless_performance',
31
36
  'Frame-time breakdown for a game: global percentiles vs the frame budget, per-level p50/p95/p99 with draw calls / triangles / geometry counts / game-context gauges, hitch causes (script, shader compile, PSO compile in Unreal, GC, asset or map load), what is on screen during hitches, which events precede hitches, per GPU tier / browser / version, memory growth per level load and the slowest recent hitches with script attribution.',
32
37
  { ...common, level: z.string().optional().describe('Focus on one level id, e.g. "level-2"') },
33
- async ({ service, hours, version, steam_branch, level }) => {
38
+ async ({ service, hours, level, ...f }) => {
34
39
  const svc = await resolveService(service);
35
- const d = await query('performance', { service: svc, version, steam_branch, ...range(hours) });
40
+ const d = await query('performance', { service: svc, ...filters(f), ...range(hours) });
36
41
  const hitches = (level ? d.hitches.filter((h) => h.level === level) : d.hitches).slice(0, 12);
37
42
  return reply(`Frame performance for ${svc}${level ? ` (${level})` : ''}`, {
38
43
  kpis: d.kpis,
@@ -53,9 +58,9 @@ tool(
53
58
  'glitchless_get_error',
54
59
  'Error Tracking for a game. Without a fingerprint: the list of error issues ranked by sessions affected. With a fingerprint: the full issue — message, location, stack trace, affected levels/versions, occurrence counts and breadcrumbs (the game events right before it fired). For a minified web build whose source maps were uploaded (glitchless-sourcemaps), location and stack are the original ones, `frames` gives each frame with its line of code, and `minified` what the browser reported.',
55
60
  { ...common, fingerprint: z.string().optional().describe('Issue fingerprint from the list or from glitchless_triage') },
56
- async ({ service, hours, version, steam_branch, fingerprint }) => {
61
+ async ({ service, hours, fingerprint, ...f }) => {
57
62
  const svc = await resolveService(service);
58
- const { issues } = await query('errors', { service: svc, version, steam_branch, ...range(hours) });
63
+ const { issues } = await query('errors', { service: svc, ...filters(f), ...range(hours) });
59
64
  if (!fingerprint) return reply(`${issues.length} error issue(s) in ${svc}`, issues.map(slimIssue));
60
65
  const issue = issues.find((i) => i.fingerprint === fingerprint || i.fingerprint?.startsWith(fingerprint));
61
66
  if (!issue) return reply(`No issue ${fingerprint} in ${svc} in this window. Known issues:`, issues.map(slimIssue));
@@ -64,9 +69,9 @@ tool(
64
69
  },
65
70
  );
66
71
 
67
- tool('glitchless_player_funnel', 'Player experience per level: sessions that started vs completed each level, attempts, deaths per session and their causes, average clear time, rage quits (quit ≤20s after dying), session length distribution and recent rage quits with positions. Also retention: of the players first seen each day, the share back 1, 7 and 30 days later (D1, D7, D30; hours of 48 or more for D1). Retention needs player IDs: status "anonymous" means the game sends none, and privacy "install" in the SDK turns them on.', { ...common }, async ({ service, hours, version, steam_branch }) => {
72
+ tool('glitchless_player_funnel', 'Player experience per level: sessions that started vs completed each level, attempts, deaths per session and their causes, average clear time, rage quits (quit ≤20s after dying), session length distribution and recent rage quits with positions. Also retention: of the players first seen each day, the share back 1, 7 and 30 days later (D1, D7, D30; hours of 48 or more for D1). Retention needs player IDs: status "anonymous" means the game sends none, and privacy "install" in the SDK turns them on.', { ...common }, async ({ service, hours, ...f }) => {
68
73
  const svc = await resolveService(service);
69
- const d = await query('players', { service: svc, version, steam_branch, ...range(hours) });
74
+ const d = await query('players', { service: svc, ...filters(f), ...range(hours) });
70
75
  return reply(`Player funnel for ${svc}`, { kpis: d.kpis, funnel: d.funnel, session_length: d.session_length, recent_rage_quits: d.rage_quits.slice(0, 15), retention: d.retention });
71
76
  });
72
77
 
@@ -74,9 +79,9 @@ tool(
74
79
  'glitchless_death_hotspots',
75
80
  'Where players die on a level: clustered death positions in world coordinates (x range, share of the level’s deaths, top cause, rage quits at that spot), plus the level bounds and completion stats. Use it to find difficulty spikes, then look up the level data around those coordinates.',
76
81
  { ...common, level: z.string().describe('Level id, e.g. "level-3"') },
77
- async ({ service, hours, version, steam_branch, level }) => {
82
+ async ({ service, hours, level, ...f }) => {
78
83
  const svc = await resolveService(service);
79
- const d = await query('heatmap', { service: svc, version, steam_branch, level, ...range(hours) });
84
+ const d = await query('heatmap', { service: svc, ...filters(f), level, ...range(hours) });
80
85
  return reply(`Death hotspots on ${level} in ${svc}`, { level: d.level, axis: d.axis, bounds: d.bounds, hotspots: d.hotspots, level_stats: d.stats, total_deaths: d.deaths?.length ?? 0, position_samples: d.density?.samples ?? 0 });
81
86
  },
82
87
  );
@@ -1,16 +1,16 @@
1
1
  // The game's own dashboard: read its pages and one board's numbers, and save a new design.
2
2
  import { z } from 'zod';
3
- import { server, query, write, resolveService, range, reply, fail, common, tool } from '../context.js';
3
+ import { server, query, write, resolveService, range, reply, fail, common, tool, filters } from '../context.js';
4
4
 
5
5
  tool(
6
6
  'glitchless_dashboard',
7
7
  "The game's dashboard: its pages in order, each a board (panels in the game's own terms) or a built-in view (events, performance, errors, players, heatmaps, sessions, versions, live, reports), and one board's panels with their numbers for the window. `page` picks the board (default: the first). `source` says whether the dashboard was saved (by an agent or a person) or made automatically from what the game sends; `spec` (its pages, and its currency if it has one) is what to edit and send back to glitchless_set_dashboard. Money panels answer their `currency`, and `mismatch` lists amounts sent in another currency, which are left out.",
8
8
  { ...common, page: z.string().optional().describe('Id of the board page to evaluate (default: the first board)') },
9
- async ({ service, hours, version, steam_branch, page }) => {
9
+ async ({ service, hours, page, ...f }) => {
10
10
  const svc = await resolveService(service);
11
- const { dashboard } = await query('dashboard', { service: svc, version, steam_branch, ...range(hours) });
11
+ const { dashboard } = await query('dashboard', { service: svc, ...filters(f), ...range(hours) });
12
12
  if (!dashboard) return reply(`${svc} has sent no data yet`, {});
13
- const b = await query('board', { service: svc, version, steam_branch, page, ...range(hours) });
13
+ const b = await query('board', { service: svc, ...filters(f), page, ...range(hours) });
14
14
  const pages = dashboard.pages.map((p) => ({ id: p.id, title: p.title, ...(p.view ? { view: p.view, ...(p.options ? { options: p.options } : {}) } : { panels: p.panels }) }));
15
15
  // A positions panel can hold thousands of bins: its busiest ten say where players die.
16
16
  const brief = (p) => (p.type === 'positions' && !p.empty ? { ...p, deaths: p.deaths?.slice(0, 10), path: p.path && { ...p.path, cells: p.path.cells.slice(0, 10) } } : p);
@@ -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
+ );