glitchless-mcp 0.8.0 → 0.9.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,6 +11,10 @@ It's a stdio server. Run it with `npx`, no install needed:
11
11
  npx -y glitchless-mcp
12
12
  ```
13
13
 
14
+ Apps that connect to a URL instead of starting a process (claude.ai, ChatGPT, Claude Code's HTTP servers) use
15
+ Glitchless Cloud's hosted copy at `https://api.glitchless.gg/mcp` and sign in with OAuth: see
16
+ [Glitchless by URL](../../docs/remote-mcp.md). It has the same tools, less the ones that act on your own computer.
17
+
14
18
  ## Sign in to a workspace (Glitchless Cloud)
15
19
 
16
20
  ```bash
@@ -26,6 +30,18 @@ key, and Settings → Agent access in the dashboard lists and revokes keys. An a
26
30
  chat with the `glitchless_sign_in` tool: it shows the link and code, and the running server switches over once you
27
31
  approve.
28
32
 
33
+ ## Serve it over HTTP yourself
34
+
35
+ ```bash
36
+ npx -y glitchless-mcp serve [--port 3001] [--host 127.0.0.1]
37
+ ```
38
+
39
+ The tools that work from a server (all but sign-in, playtests and the Steam Deck) at `http://127.0.0.1:3001/mcp`, over
40
+ Streamable HTTP, for clients of the 2026-07-28 protocol and older ones alike. It reads with the same settings as the
41
+ stdio server (below), for a self-hosted server or a signed-in workspace. It answers this computer only, and checks
42
+ `Host` and `Origin` so web pages can't reach it; to listen on another address, set `GLITCHLESS_MCP_TOKEN` and have
43
+ clients send it as `Authorization: Bearer`.
44
+
29
45
  ## Settings
30
46
 
31
47
  | Variable | What |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "glitchless-mcp",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "mcpName": "io.github.glitchless-gg/glitchless",
5
5
  "description": "Game observability and analytics MCP server for Unity, Godot, Unreal, Three.js, Phaser and GameMaker games. Coding agents (Claude Code, Codex, Cursor and others) read your players' stutters, crashes, custom metrics and ranked findings, build the game's own dashboard, and run playtest bots.",
6
6
  "keywords": [
@@ -64,12 +64,13 @@
64
64
  "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);\""
65
65
  },
66
66
  "dependencies": {
67
- "@modelcontextprotocol/sdk": "^1.32.1",
67
+ "@modelcontextprotocol/server": "^2.4.0",
68
68
  "zod": "^4.6.7",
69
69
  "glitchless-playtest": "^0.2.0",
70
70
  "glitchless-deck": "^0.1.0"
71
71
  },
72
72
  "devDependencies": {
73
+ "@modelcontextprotocol/client": "^2.4.0",
73
74
  "esbuild": "^0.28.2"
74
75
  }
75
76
  }
package/src/context.js CHANGED
@@ -1,13 +1,16 @@
1
- // What every Glitchless MCP tool shares: the server, the Glitchless API it reads and writes, and the
2
- // helpers that shape a tool's reply. Each area's tools live in tools/<area>.js and register on import.
1
+ // What every Glitchless MCP tool shares: the connection to the Glitchless API it reads and writes, the helpers that
2
+ // shape a tool's reply, and the list of tools. Each area's tools live in tools/<area>.js and define themselves on
3
+ // import; createServer() builds a server from them, once for stdio (index.js) or once per HTTP request (http.js).
3
4
 
4
5
  import { AsyncLocalStorage } from 'node:async_hooks';
5
6
  import fs from 'node:fs';
6
7
  import os from 'node:os';
7
8
  import path from 'node:path';
8
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
9
+ import { McpServer } from '@modelcontextprotocol/server';
9
10
  import { z } from 'zod';
10
11
 
12
+ export const VERSION = '0.9.0';
13
+
11
14
  // Where `glitchless-mcp login` keeps its workspace key: { url, token, workspace: { id, name }, scopes }.
12
15
  export const CREDENTIALS_FILE = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'glitchless', 'credentials.json');
13
16
  export function readCredentials() {
@@ -18,42 +21,48 @@ export function readCredentials() {
18
21
  }
19
22
  }
20
23
 
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`.
24
+ // A connection: the Glitchless API an agent reaches and the key it reaches it with. A game key (gl_sk_…) reaches one
25
+ // game; a workspace key (gl_ws_…) every game in its workspace, and then every tool takes `game`. `game` is the one
26
+ // the agent last named; `fetch` is how requests go out (Glitchless Cloud answers its own MCP requests in-process).
27
+ export function connection({ base, apiKey = '', service = '', game = '', fetch = globalThis.fetch, client = '' }) {
28
+ return { base: String(base).replace(/\/$/, ''), apiKey, service, game, fetch, client, games: null };
29
+ }
30
+
31
+ // On stdio, the one connection: GLITCHLESS_API_KEY wins; without it, a saved sign-in. Over HTTP each request runs
32
+ // with the connection its bearer token gives (createServer's `connection`).
23
33
  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 || '';
26
- export const DEFAULT_SERVICE = process.env.GLITCHLESS_SERVICE || '';
27
- export const isWorkspace = () => API_KEY.startsWith('gl_ws_');
34
+ const local = connection({
35
+ base: process.env.GLITCHLESS_URL || saved?.url || 'http://localhost:7777',
36
+ apiKey: process.env.GLITCHLESS_API_KEY || saved?.token || '',
37
+ service: process.env.GLITCHLESS_SERVICE || '',
38
+ game: process.env.GLITCHLESS_GAME || '',
39
+ });
40
+ const connections = new AsyncLocalStorage();
41
+ const conn = () => connections.getStore() ?? local;
42
+
43
+ export const base = () => conn().base;
44
+ export const apiKey = () => conn().apiKey;
45
+ export const defaultService = () => conn().service;
46
+ export const isWorkspace = () => conn().apiKey.startsWith('gl_ws_');
28
47
 
29
48
  // After a sign-in from inside the agent (glitchless_sign_in): the running server switches to the new key.
30
49
  export function useCredentials({ url, token }) {
31
- BASE = String(url).replace(/\/$/, '');
32
- API_KEY = token;
33
- games = null;
50
+ Object.assign(local, { base: String(url).replace(/\/$/, ''), apiKey: token, games: null });
34
51
  }
35
52
 
36
- export const server = new McpServer(
37
- { name: 'glitchless', version: '0.8.0' },
38
- {
39
- instructions:
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. For a game connected to RevenueCat or to its own Stripe account, glitchless_revenue reads its real revenue by day, version and country (RevenueCat: production purchases only, by store too, installs and active users; Stripe: refunds, fees, net, new paying customers and revenue by product), next to the sessions, players and new players Glitchless measured and what the game\'s own purchase events add up to. 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.',
41
- },
42
- );
43
-
44
53
  // 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 || '';
54
+ // connection last used (or GLITCHLESS_GAME), else the only game.
48
55
  export async function workspaceGames(fresh = false) {
49
- if (!fresh && games && Date.now() - games.at < 30_000) return games.list;
56
+ const c = conn();
57
+ if (!fresh && c.games && Date.now() - c.games.at < 30_000) return c.games.list;
50
58
  const { games: list } = await agent('GET', '/games');
51
- games = { at: Date.now(), list };
59
+ c.games = { at: Date.now(), list };
52
60
  return list;
53
61
  }
54
62
 
55
63
  export async function projectFor(game) {
56
- const want = game || currentGame;
64
+ const c = conn();
65
+ const want = game || c.game;
57
66
  let list = await workspaceGames();
58
67
  const find = () => list.find((g) => g.id === want) ?? list.find((g) => g.name.toLowerCase() === String(want).toLowerCase());
59
68
  let hit = want ? find() : list.length === 1 ? list[0] : null;
@@ -62,21 +71,21 @@ export async function projectFor(game) {
62
71
  hit = find();
63
72
  }
64
73
  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;
74
+ c.game = hit.id;
66
75
  return hit.id;
67
76
  }
68
77
 
69
78
  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 };
79
+ const client = conn().client || calls.getStore()?.server?.server.getClientVersion?.()?.name || 'mcp';
80
+ return { 'x-glitchless-client': client, ...(apiKey() ? { 'x-glitchless-api-key': apiKey() } : {}), ...(isWorkspace() ? { 'x-glitchless-project': await projectFor(calls.getStore()?.game) } : {}), ...extra };
72
81
  }
73
82
 
74
83
  // A workspace key's own routes (/v1/agent/…, Glitchless Cloud).
75
84
  export async function agent(method, p, body) {
76
85
  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}`, {
86
+ const res = await conn().fetch(`${base()}/v1/agent${p}`, {
78
87
  method,
79
- headers: { 'x-glitchless-api-key': API_KEY, ...(body ? { 'content-type': 'application/json' } : {}) },
88
+ headers: { 'x-glitchless-api-key': apiKey(), ...(body ? { 'content-type': 'application/json' } : {}) },
80
89
  ...(body ? { body: JSON.stringify(body) } : {}),
81
90
  });
82
91
  const data = await res.json().catch(() => ({}));
@@ -87,7 +96,7 @@ export async function agent(method, p, body) {
87
96
  export async function query(name, params = {}) {
88
97
  const qs = new URLSearchParams();
89
98
  for (const [k, v] of Object.entries(params)) if (v != null && v !== '') qs.set(k, String(v));
90
- const res = await fetch(`${BASE}/v1/query/${name}?${qs}`, { headers: await headers() });
99
+ const res = await conn().fetch(`${base()}/v1/query/${name}?${qs}`, { headers: await headers() });
91
100
  if (!res.ok) throw new Error(`Glitchless API ${name} → HTTP ${res.status}: ${(await res.text()).slice(0, 200)}`);
92
101
  const data = await res.json();
93
102
  const call = calls.getStore();
@@ -95,7 +104,8 @@ export async function query(name, params = {}) {
95
104
  return data;
96
105
  }
97
106
 
98
- // The tool call being answered: the meta of its last query, for windowNote().
107
+ // The tool call being answered: the game it names, the server answering it, and the meta of its last query, for
108
+ // windowNote().
99
109
  const calls = new AsyncLocalStorage();
100
110
 
101
111
  // How the window was answered, when an agent should know: by day past 31 days, what is estimated, what a
@@ -112,7 +122,7 @@ function windowNote() {
112
122
  }
113
123
 
114
124
  export async function write(method, p, body) {
115
- const res = await fetch(`${BASE}${p}`, {
125
+ const res = await conn().fetch(`${base()}${p}`, {
116
126
  method,
117
127
  headers: await headers({ 'content-type': 'application/json' }),
118
128
  ...(body ? { body: JSON.stringify(body) } : {}),
@@ -125,7 +135,7 @@ export async function write(method, p, body) {
125
135
 
126
136
  export async function resolveService(service) {
127
137
  if (service) return service;
128
- if (DEFAULT_SERVICE) return DEFAULT_SERVICE;
138
+ if (defaultService()) return defaultService();
129
139
  const { services } = await query('services');
130
140
  if (!services?.length) throw new Error('No games are reporting to Glitchless yet. Add the SDK and play a level first.');
131
141
  return services.sort((a, b) => b.last_seen - a.last_seen)[0].service;
@@ -151,7 +161,7 @@ export const common = {
151
161
  .min(0.25)
152
162
  .max(9600)
153
163
  .optional()
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."),
164
+ .describe("Look-back window in hours (default 24), as far back as the workspace keeps data on Glitchless Cloud (the answer says when it starts later than asked). Past 744 (31 days) answers are by day."),
155
165
  version: z.string().optional().describe('Only include sessions from this game version'),
156
166
  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
167
  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")'),
@@ -166,23 +176,79 @@ export function filters({ version, steam_branch, env, session_type } = {}) {
166
176
  return { version, steam_branch, env, type: session_type };
167
177
  }
168
178
 
179
+ // ── the tools ─────────────────────────────────────────────────────
180
+ // Every tool as its file defined it: { name, config, handler, scope, local }. Over HTTP a tool shows only to a
181
+ // connection whose scopes include its `scope` (read, dashboard or manage, as a workspace key's), and `local` tools
182
+ // (signing in, playtests, the Steam Deck) are left out: they act on the computer the server runs on.
183
+ const tools = [];
184
+
185
+ // The annotations a read gets: it changes nothing and reads only the person's own Glitchless data.
186
+ const READS = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
187
+
188
+ export function define(name, config, handler, { scope = 'read', local = false } = {}) {
189
+ tools.push({ name, config: { ...config, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false, ...config.annotations } }, handler, scope, local });
190
+ }
191
+
192
+ // A read-only tool.
193
+ export function tool(name, description, schema, handler) {
194
+ define(name, { description, inputSchema: schema, annotations: READS }, handler);
195
+ }
196
+
197
+ // The tools a server built with these options shows: { name, title, description, annotations, scope, local }.
198
+ export function toolList({ remote = false, scopes = null } = {}) {
199
+ return tools.filter((t) => !(remote && t.local) && (!scopes || scopes.includes(t.scope))).map((t) => ({ name: t.name, title: titleOf(t), description: t.config.description, annotations: t.config.annotations, scope: t.scope, local: t.local }));
200
+ }
201
+
202
+ // "glitchless_store_reviews" → "Store reviews", unless the tool names its own title.
203
+ const titleOf = (t) => t.config.title ?? `${t.name.replace(/^glitchless_/, '').replace(/_/g, ' ').replace(/^./, (c) => c.toUpperCase())}`;
204
+
169
205
  // Every tool takes `game` (by name or id): with a workspace key it picks the game, with a game key it's ignored.
170
206
  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
207
 
175
- // A read-only tool: errors come back as a tool error, not a thrown exception.
176
- export function tool(name, description, schema, handler) {
177
- server.registerTool(name, { description, inputSchema: schema, annotations: { readOnlyHint: true } }, async (args) =>
178
- calls.run({ game: args.game }, async () => {
179
- try {
180
- return await handler(args || {});
181
- } catch (err) {
182
- return fail(err);
183
- }
184
- }),
208
+ // A server with the tools. remote: the HTTP server's set (no local tools, and instructions to match); scopes: show
209
+ // only the tools these scopes allow; connection: what every call runs with (default: this process's own).
210
+ export function createServer({ remote = false, scopes = null, connection: c = null } = {}) {
211
+ const server = new McpServer(
212
+ { name: 'glitchless', title: 'Glitchless', version: VERSION, websiteUrl: 'https://www.glitchless.gg', icons: [{ src: 'https://app.glitchless.gg/brand/glitchless-icon-512.png', mimeType: 'image/png', sizes: ['512x512'] }] },
213
+ { instructions: instructions(remote) },
185
214
  );
215
+ for (const t of tools) {
216
+ if ((remote && t.local) || (scopes && !scopes.includes(t.scope))) continue;
217
+ const { inputSchema = {}, ...config } = t.config;
218
+ server.registerTool(t.name, { ...config, title: titleOf(t), inputSchema: z.object({ game: gameField, ...inputSchema }) }, (args = {}, ctx) => {
219
+ const run = () =>
220
+ calls.run({ game: args.game, server }, async () => {
221
+ try {
222
+ return await t.handler(args, ctx);
223
+ } catch (err) {
224
+ return fail(err);
225
+ }
226
+ });
227
+ return c ? connections.run(c, run) : run();
228
+ });
229
+ }
230
+ return server;
231
+ }
232
+
233
+ function instructions(remote) {
234
+ return [
235
+ 'Glitchless is observability for games made with Three.js, Phaser, Babylon.js, PlayCanvas, Unity, Godot, Unreal or GameMaker.',
236
+ remote
237
+ ? "You're connected to the person's Glitchless workspace: 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."
238
+ : "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.",
239
+ '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.',
240
+ '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.',
241
+ '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.',
242
+ '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.',
243
+ "For a game connected to RevenueCat or to its own Stripe account, glitchless_revenue reads its real revenue by day, version and country (RevenueCat: production purchases only, by store too, installs and active users; Stripe: refunds, fees, net, new paying customers and revenue by product), next to the sessions, players and new players Glitchless measured and what the game's own purchase events add up to.",
244
+ "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.",
245
+ ...(remote
246
+ ? ['After shipping a fix (bump the version passed to Glitchless.init), use glitchless_compare_versions to confirm it with real players.']
247
+ : [
248
+ '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.',
249
+ '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.',
250
+ ]),
251
+ ].join(' ');
186
252
  }
187
253
 
188
254
  export function slimIssue(i) {
@@ -0,0 +1,9 @@
1
+ // The tools that work from a server anywhere: they read and write through the Glitchless API. http.js serves these;
2
+ // index.js (stdio) adds the ones that act on the computer the agent runs on (playtests, the Steam Deck).
3
+ import './tools/core.js';
4
+ import './tools/analytics.js';
5
+ import './tools/dashboard.js';
6
+ import './tools/reports.js';
7
+ import './tools/store-reviews.js';
8
+ import './tools/revenue.js';
9
+ import './tools/workspace.js';
package/src/http.js ADDED
@@ -0,0 +1,110 @@
1
+ // Glitchless's MCP server over Streamable HTTP, for clients that connect to a URL instead of starting a process
2
+ // (claude.ai and ChatGPT connectors, agents on another machine). Every request gets a server of its own
3
+ // (createServer), so nothing lives between requests: it runs behind a load balancer or in a serverless function, and
4
+ // answers clients of the 2026-07-28 protocol and older ones that open with initialize alike. The tools that act on
5
+ // the computer the server runs on (playtests, the Steam Deck, the device sign-in) are left out.
6
+ //
7
+ // The host checks each request's credentials, then hands over the connection it runs with and its scopes:
8
+ //
9
+ // const mcp = createHttpHandler();
10
+ // http.createServer((req, res) => mcp.handle(req, res, { connection, scopes }));
11
+ //
12
+ // Glitchless Cloud signs people in with OAuth and runs each request with their workspace key; `glitchless-mcp serve`
13
+ // (serve() below) serves this machine's own key or self-hosted server.
14
+ import crypto from 'node:crypto';
15
+ import http from 'node:http';
16
+ import { createMcpHandler } from '@modelcontextprotocol/server';
17
+ import { createServer, base } from './context.js';
18
+ import './hosted-tools.js';
19
+
20
+ export const MAX_BODY = 4 * 1024 * 1024;
21
+
22
+ // → { fetch(Request, { authInfo }) → Response, handle(req, res, opts), close() }. opts: { connection (default: this
23
+ // process's own), scopes (default: every tool), token, clientId }.
24
+ export function createHttpHandler({ responseMode = 'auto', onerror } = {}) {
25
+ const mcp = createMcpHandler(({ authInfo }) => createServer({ remote: true, connection: authInfo?.extra?.connection ?? null, scopes: authInfo?.extra?.scopes ?? null }), { responseMode, onerror, maxRequestBodySize: MAX_BODY });
26
+ return {
27
+ fetch: mcp.fetch,
28
+ async handle(req, res, { connection = null, scopes = null, token = '', clientId = '' } = {}) {
29
+ const request = await toRequest(req, res);
30
+ if (!request) return;
31
+ await send(res, await mcp.fetch(request, { authInfo: { token, clientId, scopes: scopes ?? [], extra: { connection, scopes } } }));
32
+ },
33
+ close: mcp.close,
34
+ };
35
+ }
36
+
37
+ // A Node request as a web Request (null once it has answered 413 itself), aborted if the client goes away.
38
+ async function toRequest(req, res) {
39
+ const chunks = [];
40
+ let size = 0;
41
+ for await (const chunk of req) {
42
+ size += chunk.length;
43
+ if (size > MAX_BODY) {
44
+ res.writeHead(413, { 'content-type': 'application/json' }).end(JSON.stringify({ error: 'Request body too large.' }));
45
+ return null;
46
+ }
47
+ chunks.push(chunk);
48
+ }
49
+ const headers = new Headers();
50
+ for (const [k, v] of Object.entries(req.headers)) if (v != null) headers.set(k, Array.isArray(v) ? v.join(', ') : v);
51
+ const abort = new AbortController();
52
+ res.on('close', () => res.writableFinished || abort.abort());
53
+ const body = req.method === 'GET' || req.method === 'HEAD' || !size ? undefined : Buffer.concat(chunks);
54
+ return new Request(new URL(req.url, `http://${req.headers.host || 'localhost'}`), { method: req.method, headers, body, signal: abort.signal });
55
+ }
56
+
57
+ async function send(res, response) {
58
+ const headers = {};
59
+ response.headers.forEach((v, k) => (headers[k] = v));
60
+ res.writeHead(response.status, headers);
61
+ if (response.body) for await (const chunk of response.body) res.write(chunk);
62
+ res.end();
63
+ }
64
+
65
+ // ── glitchless-mcp serve ─────────────────────────────────────────
66
+ // The hosted tools at http://<host>:<port>/mcp, reading with this machine's key or self-hosted server (as the stdio
67
+ // server does: GLITCHLESS_URL, GLITCHLESS_API_KEY or a saved sign-in). On this computer only by default, where it
68
+ // checks Host and Origin against DNS rebinding; to listen beyond it, set GLITCHLESS_MCP_TOKEN and clients send it as
69
+ // Authorization: Bearer.
70
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
71
+ const hostname = (value) => {
72
+ try {
73
+ return new URL(value.includes('://') ? value : `http://${value}`).hostname;
74
+ } catch {
75
+ return '';
76
+ }
77
+ };
78
+
79
+ // → the listening http.Server; throws when told to listen beyond this computer without a token.
80
+ export async function serve(argv = []) {
81
+ const flag = (name) => {
82
+ const i = argv.indexOf(`--${name}`);
83
+ return i >= 0 ? argv[i + 1] : null;
84
+ };
85
+ const port = Number(flag('port') || process.env.PORT || 3001);
86
+ const host = flag('host') || '127.0.0.1';
87
+ const token = process.env.GLITCHLESS_MCP_TOKEN || '';
88
+ const local = LOOPBACK.has(host);
89
+ if (!local && !token) throw new Error(`Listening on ${host} lets other computers in: set GLITCHLESS_MCP_TOKEN, and clients send it as Authorization: Bearer.`);
90
+ const mcp = createHttpHandler();
91
+ const server = http.createServer(async (req, res) => {
92
+ const deny = (status, error, extra = {}) => res.writeHead(status, { 'content-type': 'application/json', ...extra }).end(JSON.stringify({ error }));
93
+ if (new URL(req.url, 'http://local').pathname !== '/mcp') return deny(404, 'Not found: the MCP endpoint is /mcp.');
94
+ if (local && (!LOOPBACK.has(hostname(req.headers.host || '')) || (req.headers.origin && !LOOPBACK.has(hostname(req.headers.origin))))) return deny(403, 'Only this computer may call this server.');
95
+ if (token) {
96
+ const given = crypto.createHash('sha256').update(String(req.headers.authorization || '').replace(/^Bearer\s+/i, '')).digest();
97
+ if (!crypto.timingSafeEqual(given, crypto.createHash('sha256').update(token).digest())) return deny(401, 'Send GLITCHLESS_MCP_TOKEN as Authorization: Bearer.', { 'www-authenticate': 'Bearer' });
98
+ }
99
+ try {
100
+ await mcp.handle(req, res);
101
+ } catch (err) {
102
+ console.error(err);
103
+ if (!res.headersSent) deny(500, 'Something went wrong.');
104
+ else res.end();
105
+ }
106
+ });
107
+ await new Promise((resolve, reject) => server.once('error', reject).listen(port, host, resolve));
108
+ console.error(`Glitchless MCP on http://${host.includes(':') ? `[${host}]` : host}:${server.address().port}/mcp, reading ${base()}`);
109
+ return server;
110
+ }
package/src/index.js CHANGED
@@ -10,25 +10,29 @@
10
10
  //
11
11
  // npx -y glitchless-mcp login (also: whoami, logout)
12
12
  //
13
- // The shared server and helpers are in context.js; each area's tools are in tools/<area>.js, and a new
14
- // area is one more file imported here.
15
-
16
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
13
+ // Or serve it over Streamable HTTP, for clients that connect to a URL (http.js):
14
+ //
15
+ // npx -y glitchless-mcp serve [--port 3001] [--host 127.0.0.1]
16
+ //
17
+ // The connection and the list of tools are in context.js; each area's tools are in tools/<area>.js, and a new area
18
+ // is one more file imported in hosted-tools.js (or here, for a tool that acts on this computer).
17
19
 
18
20
  if (['login', 'logout', 'whoami'].includes(process.argv[2])) {
19
21
  const { cli } = await import('./login.js');
20
22
  process.exit(await cli(process.argv.slice(2)));
21
23
  }
22
24
 
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/revenue.js');
32
- await import('./tools/workspace.js');
33
-
34
- await server.connect(new StdioServerTransport());
25
+ if (process.argv[2] === 'serve') {
26
+ const { serve } = await import('./http.js');
27
+ await serve(process.argv.slice(3)).catch((err) => {
28
+ console.error(err.message);
29
+ process.exit(1);
30
+ });
31
+ } else {
32
+ const { serveStdio } = await import('@modelcontextprotocol/server/stdio');
33
+ const { createServer } = await import('./context.js');
34
+ await import('./hosted-tools.js');
35
+ await import('./tools/playtest.js');
36
+ await import('./tools/deck.js');
37
+ serveStdio(() => createServer());
38
+ }
@@ -26,13 +26,13 @@ tool(
26
26
 
27
27
  tool(
28
28
  'glitchless_compare_versions',
29
- 'Compare game versions side by side, in the game\'s own terms first: the stats on its boards (glitchless_dashboard) and its own events per session, then the built-in measures it reports (frame time overall and per level, hitches/min, crash-free and error-free sessions, errors per session, level completion, rage-quit rate, deaths per session, geometry growth). Use it to confirm a fix or a design change after shipping a new version. For a game on Steam, by "steam_branch" compares Steam branches instead (a beta against "public"), and by "steam_build" Steam builds: a and b are then branch names or build ids.',
29
+ 'Compare game versions side by side, in the game\'s own terms first: the stats on its boards (glitchless_dashboard) and its own events per session, then the built-in measures it reports (frame time overall and per level, hitches/min, crash-free and error-free sessions, errors per session, level completion, rage-quit rate, deaths per session, geometry growth). Use it to confirm a fix or a design change after shipping a new version. Versions come in release order (when each first showed up at all, not in this window), so by default it compares the newest with the one before it, also while players of older versions still play. For a game on Steam, by "steam_branch" compares Steam branches instead (a beta against "public"), and by "steam_build" Steam builds: a and b are then branch names or build ids.',
30
30
  {
31
31
  service: common.service,
32
32
  hours: common.hours,
33
33
  env: common.env,
34
34
  session_type: common.session_type,
35
- a: z.string().optional().describe('Baseline version, branch or build (default: second newest)'),
35
+ a: z.string().optional().describe('Baseline version, branch or build (default: the one before the newest)'),
36
36
  b: z.string().optional().describe('New version, branch or build (default: newest)'),
37
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'),
38
38
  },
@@ -54,6 +54,6 @@ tool(
54
54
  const levels = [...new Set([...Object.keys(va.level_p95 || {}), ...Object.keys(vb.level_p95 || {})])];
55
55
  const level_p95 = Object.fromEntries(levels.map((l) => [l, { [va.version]: va.level_p95?.[l] ?? null, [vb.version]: vb.level_p95?.[l] ?? null }]));
56
56
  // Branches and builds are compared from the sessions' own frame windows, which carry no level: no level_p95.
57
- return reply(`${svc}: ${steam ? `${what} ` : ''}${va.version} (${va.sessions} sessions) vs ${vb.version} (${vb.sessions} sessions)`, { board: own, events_per_session: events, delta, ...(steam ? {} : { level_p95 }), [steam ? `all_${steam === 'steam_branch' ? 'branches' : 'builds'}` : 'all_versions']: versions.map((v) => ({ [steam || 'version']: v.version, sessions: v.sessions, first_seen: new Date(v.first_seen).toISOString() })) });
57
+ return reply(`${svc}: ${steam ? `${what} ` : ''}${va.version} (${va.sessions} sessions) vs ${vb.version} (${vb.sessions} sessions)`, { board: own, events_per_session: events, delta, ...(steam ? {} : { level_p95 }), [steam ? `all_${steam === 'steam_branch' ? 'branches' : 'builds'}` : 'all_versions']: versions.map((v) => ({ [steam || 'version']: v.version, sessions: v.sessions, first_seen: new Date(v.first_seen).toISOString(), ...(steam ? {} : { first_seen_ever: v.first_seen_ever == null ? null : new Date(v.first_seen_ever).toISOString() }) })) });
58
58
  },
59
59
  );
package/src/tools/core.js CHANGED
@@ -1,7 +1,7 @@
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, filters, isWorkspace, workspaceGames } from '../context.js';
4
+ import { base, query, resolveService, range, reply, common, tool, slimIssue, slimGroup, filters, isWorkspace, workspaceGames } from '../context.js';
5
5
 
6
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
7
  if (isWorkspace()) {
@@ -9,7 +9,7 @@ tool('glitchless_list_games', 'List the games: with a workspace key, every game
9
9
  return reply(`${list.length} game(s) in this workspace. Name one with game in any tool:`, list);
10
10
  }
11
11
  const { services } = await query('services');
12
- return reply(`${services.length} game(s) reporting to ${BASE}`, services.map((s) => ({ ...s, last_seen: new Date(s.last_seen).toISOString() })));
12
+ return reply(`${services.length} game(s) reporting to ${base()}`, services.map((s) => ({ ...s, last_seen: new Date(s.last_seen).toISOString() })));
13
13
  });
14
14
 
15
15
  tool(
@@ -1,21 +1,23 @@
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, filters } from '../context.js';
3
+ import { define, query, write, resolveService, range, reply, common, tool, filters } from '../context.js';
4
4
 
5
5
  tool(
6
6
  'glitchless_dashboard',
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.",
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. `brand` is the game's branding on its boards and share links: its accent colour (set with glitchless_set_dashboard's accent) and whether it has a logo and a banner (people upload those in the dashboard: Edit pages → Look).",
8
8
  { ...common, page: z.string().optional().describe('Id of the board page to evaluate (default: the first board)') },
9
9
  async ({ service, hours, page, ...f }) => {
10
10
  const svc = await resolveService(service);
11
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
13
  const b = await query('board', { service: svc, ...filters(f), page, ...range(hours) });
14
+ // A server without branding (501), or none set: no brand.
15
+ const brand = (await write('GET', `/v1/brand?service=${encodeURIComponent(svc)}`).catch(() => null))?.brand;
14
16
  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
17
  // A positions panel can hold thousands of bins: its busiest ten say where players die.
16
18
  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);
17
19
  const board = b.board ? { page: b.board.page, title: b.board.title, panels: b.board.panels.map(({ ts, series, p50, p95, ...p }) => brief(p)) } : { error: b.error };
18
- return reply(`Dashboard for ${svc} (${dashboard.source}${dashboard.updated_by ? `, saved by ${dashboard.updated_by}` : ''}):`, { pages, board, spec: dashboard.spec });
20
+ return reply(`Dashboard for ${svc} (${dashboard.source}${dashboard.updated_by ? `, saved by ${dashboard.updated_by}` : ''}):`, { pages, board, spec: dashboard.spec, brand: brand ? { accent: brand.accent, logo: !!brand.logo, banner: !!brand.banner } : null });
19
21
  },
20
22
  );
21
23
 
@@ -23,7 +25,7 @@ const panelSchema = z
23
25
  .object({
24
26
  type: z.enum(['stat', 'series', 'breakdown', 'funnel', 'levels', 'frame_time', 'errors', 'deaths', 'events', 'findings', 'sessions', 'versions', 'live', 'reports', 'retention', 'positions']).describe('retention: D1, D7 and D30 by the day players were first seen; needs player IDs (privacy install or full). positions: where players died on one level (and where they went), as counts per bin: safe on a shared board, and a game can poll it through a share link to draw its own dead'),
25
27
  title: z.string().optional().describe("In the game's own words, e.g. \"Stops won vs lost\""),
26
- note: z.string().optional().describe('One line on why this panel matters'),
28
+ note: z.string().optional().describe("One line on why this panel matters: people read it behind the info icon next to the panel's title"),
27
29
  size: z.enum(['s', 'm', 'l']).optional().describe('s = a quarter row (stats), m = half, l = full width'),
28
30
  metric: z.string().optional().describe('stat: sessions, players, avg_session_s, crash_free_pct, error_free_pct, frame_p95, avg_fps, hitches_per_min, errors, deaths, rage_quit_pct or players_now (sessions playing in the last two minutes, whatever the range)'),
29
31
  event: z.string().optional().describe('stat, series, breakdown: one event, "name", "name=value" or "name:key=value". A series or breakdown by $platform, $browser or $device_tier can leave it out: then it counts sessions (and players, with player IDs) in each'),
@@ -70,38 +72,45 @@ const pageSchema = z
70
72
  })
71
73
  .describe('One page: either panels (a board) or view (a built-in view)');
72
74
 
73
- server.registerTool(
75
+ define(
74
76
  'glitchless_set_dashboard',
75
77
  {
78
+ title: 'Save dashboard',
76
79
  description:
77
- "Save the game's dashboard: its pages, in the order the sidebar shows them. Each page is a board of panels in the game's own words, or a built-in view (events, performance, errors, players, heatmaps, sessions, versions, live, reports) the game keeps, renames or drops. Design it for this game, not for a genre it isn't: a puzzle game cares about solve time and hints, a mobile game about opens, modes, the paywall and purchases (revenue: a stat with sum \"amount\" of \"purchase\"; revenue per player: per \"$players\"; conversion: event \"purchase\" per \"$players\"; revenue by item: a breakdown with sum), a platformer about deaths per level (and a positions panel for where on a level they die). For a game on several platforms, a breakdown by $platform splits players or an event between them (iOS vs Android, PC vs Mac vs Steam Deck); a web game splits by $browser, and any game by $device_tier. The first page opens first. Use the events the game sends (glitchless_events lists them, with their attributes); on a board, stats first, then the game's own events and funnels, then levels, frame_time and errors. Leave out what the game has no data for (no Heatmaps page for a game without positions, no reports page for a game that doesn't turn bug reports on). Send every page: read the current ones with glitchless_dashboard (its spec), change them, send them all back. Pass reset: true to go back to the automatic dashboard. Needs a secret key with the dashboard scope.",
80
+ "Save the game's dashboard: its pages, in the order the sidebar shows them. Each page is a board of panels in the game's own words, or a built-in view (events, performance, errors, players, heatmaps, sessions, versions, live, reports) the game keeps, renames or drops. Design it for this game, not for a genre it isn't: a puzzle game cares about solve time and hints, a mobile game about opens, modes, the paywall and purchases (revenue: a stat with sum \"amount\" of \"purchase\"; revenue per player: per \"$players\"; conversion: event \"purchase\" per \"$players\"; revenue by item: a breakdown with sum), a platformer about deaths per level (and a positions panel for where on a level they die). For a game on several platforms, a breakdown by $platform splits players or an event between them (iOS vs Android, PC vs Mac vs Steam Deck); a web game splits by $browser, and any game by $device_tier. The first page opens first. Use the events the game sends (glitchless_events lists them, with their attributes); on a board, stats first, then the game's own events and funnels, then levels, frame_time and errors. Leave out what the game has no data for (no Heatmaps page for a game without positions, no reports page for a game that doesn't turn bug reports on). Send every page: read the current ones with glitchless_dashboard (its spec), change them, send them all back. Pass reset: true to go back to the automatic dashboard. accent sets the colour of the game's boards and share links (links, the selected page, stats, the main chart series, the map); it can be sent alone. Needs a secret key with the dashboard scope.",
78
81
  inputSchema: {
79
82
  service: z.string().optional().describe('Game service name (defaults to the most recently active game)'),
80
83
  pages: z.array(pageSchema).optional(),
81
84
  currency: z.string().optional().describe('The game\'s one currency for money panels, an ISO 4217 code such as "USD" (default: the one most of its purchases are sent in). Send it again with every save: glitchless_dashboard\'s spec has it'),
82
85
  reset: z.boolean().optional().describe('Delete the saved dashboard and go back to the automatic one'),
86
+ accent: z
87
+ .string()
88
+ .nullable()
89
+ .optional()
90
+ .describe('The accent colour of the game\'s boards and share links, "#rrggbb" (the game\'s own colour, such as its logo\'s), or null for none. Kept apart from the pages: send it alone to change only the colour. The dashboard darkens or lightens it where it would be hard to read. The logo and a banner (key art) are uploaded in the dashboard: Edit pages → Look'),
83
91
  },
84
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
92
+ // It replaces the saved pages (and reset: true deletes them), so it counts as destructive.
93
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
85
94
  },
86
- async ({ service, pages, currency, reset }) => {
87
- try {
88
- const svc = await resolveService(service);
89
- if (!reset && !pages?.length) throw new Error('give pages, or reset: true');
90
- const res = await write(reset ? 'DELETE' : 'PUT', `/v1/dashboard?service=${encodeURIComponent(svc)}`, reset ? null : { ...(currency ? { currency } : {}), pages });
91
- if (reset) return reply(`Dashboard for ${svc} reset to automatic.`, {});
92
- // How each board looks with the last 7 days, so empty panels show up now rather than in the dashboard.
93
- const lines = [];
94
- for (const p of res.dashboard.pages) {
95
- if (p.view) {
96
- lines.push(`${p.title} (built-in ${p.view} view)`);
97
- continue;
98
- }
99
- const { board } = await query('board', { service: svc, page: p.id, ...range(168) });
100
- lines.push(`${p.title}:`, ...board.panels.map((x) => ` - ${x.title}${x.empty ? ` (no data yet: ${x.why})` : ''}${x.mismatch?.length ? ` (left out, another currency: ${x.mismatch.map((m) => `${m.events} in ${m.currency}`).join(', ')})` : ''}`));
95
+ async ({ service, pages, currency, reset, accent }) => {
96
+ const svc = await resolveService(service);
97
+ if (!reset && !pages?.length && accent === undefined) throw new Error('give pages, accent, or reset: true');
98
+ const branded = accent === undefined ? null : (await write('PUT', `/v1/brand?service=${encodeURIComponent(svc)}`, { accent })).brand;
99
+ const colour = accent === undefined ? '' : ` Accent: ${branded?.accent ?? 'none'}.`;
100
+ if (!reset && !pages?.length) return reply(`Saved the look of ${svc}'s boards.${colour}`, {});
101
+ const res = await write(reset ? 'DELETE' : 'PUT', `/v1/dashboard?service=${encodeURIComponent(svc)}`, reset ? null : { ...(currency ? { currency } : {}), pages });
102
+ if (reset) return reply(`Dashboard for ${svc} reset to automatic.${colour}`, {});
103
+ // How each board looks with the last 7 days, so empty panels show up now rather than in the dashboard.
104
+ const lines = [];
105
+ for (const p of res.dashboard.pages) {
106
+ if (p.view) {
107
+ lines.push(`${p.title} (built-in ${p.view} view)`);
108
+ continue;
101
109
  }
102
- return reply(`Saved the dashboard for ${svc} (${res.dashboard.pages.length} pages${res.dashboard.currency ? `, money in ${res.dashboard.currency}` : ''}). How it looks with the last 7 days:\n${lines.join('\n')}`, {});
103
- } catch (err) {
104
- return fail(err);
110
+ const { board } = await query('board', { service: svc, page: p.id, ...range(168) });
111
+ lines.push(`${p.title}:`, ...board.panels.map((x) => ` - ${x.title}${x.empty ? ` (no data yet: ${x.why})` : ''}${x.mismatch?.length ? ` (left out, another currency: ${x.mismatch.map((m) => `${m.events} in ${m.currency}`).join(', ')})` : ''}`));
105
112
  }
113
+ return reply(`Saved the dashboard for ${svc} (${res.dashboard.pages.length} pages${res.dashboard.currency ? `, money in ${res.dashboard.currency}` : ''}).${colour} How it looks with the last 7 days:\n${lines.join('\n')}`, {});
106
114
  },
115
+ { scope: 'dashboard' },
107
116
  );
package/src/tools/deck.js CHANGED
@@ -1,25 +1,26 @@
1
1
  // Steam Deck tools: send a build to the paired Deck (and start it), and measure it there with the
2
2
  // Glitchless SDK's --glitchless-measure, compared with a saved run. Both act on the Deck and write files
3
- // (the build on the Deck, .glitchless/deck/<id>/<name>.json in the project), so neither is read-only.
3
+ // (the build on the Deck, .glitchless/deck/<id>/<name>.json in the project), so neither is read-only, and both act on
4
+ // this computer's network, so neither is served over HTTP.
4
5
  // Pairing is not a tool: it needs the person to approve it on the Deck (glitchless-deck pair).
5
6
 
6
7
  import path from 'node:path';
7
8
  import { z } from 'zod';
8
9
  import { gameNamed, send, launch, measure, Problem } from 'glitchless-deck';
9
- import { server, fail } from '../context.js';
10
+ import { define, fail } from '../context.js';
10
11
 
11
12
  const common = {
12
13
  game: z.string().optional().describe('Game id from glitchless.deck.json (optional when the project has one game)'),
13
14
  project: z.string().optional().describe('Folder with the glitchless.deck.json (default: the folder the agent works in)'),
14
15
  };
15
16
 
16
- function progress(extra) {
17
- const token = extra?._meta?.progressToken;
17
+ function progress(ctx) {
18
+ const token = ctx?.mcpReq._meta?.progressToken;
18
19
  let step = 0;
19
20
  const lines = [];
20
21
  const log = (message) => {
21
22
  lines.push(message);
22
- if (token != null) extra.sendNotification({ method: 'notifications/progress', params: { progressToken: token, progress: ++step, message } }).catch(() => {});
23
+ if (token != null) ctx.mcpReq.notify({ method: 'notifications/progress', params: { progressToken: token, progress: ++step, message } }).catch(() => {});
23
24
  };
24
25
  return { log, lines };
25
26
  }
@@ -31,9 +32,10 @@ function find(game, project) {
31
32
  // What the person has to do is the answer, not a stack trace.
32
33
  const problem = (err, lines) => (err instanceof Problem ? { content: [{ type: 'text', text: `${lines.length ? `${lines.join('\n')}\n\n` : ''}${err.message}` }], isError: true } : fail(err));
33
34
 
34
- server.registerTool(
35
+ define(
35
36
  'glitchless_deck_send',
36
37
  {
38
+ title: 'Send to Steam Deck',
37
39
  description:
38
40
  'Send the game to the Steam Deck paired with this computer and put it in the Deck\'s library as "Devkit Game: <id>": runs the build (Godot Linux export, Unity Linux64, Unreal, a web build, or the project\'s own command), checks it is something the Deck runs (Linux x86-64, or Windows x64 through Proton), copies only what changed, and optionally starts it. Reads glitchless.deck.json in the project (glitchless-deck init writes one). Needs the Deck awake on this network and paired once with `glitchless-deck pair`, which the user approves on the Deck.',
39
41
  inputSchema: {
@@ -45,8 +47,8 @@ server.registerTool(
45
47
  },
46
48
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
47
49
  },
48
- async ({ game, project, build, launch: start, glitchless, intake } = {}, extra) => {
49
- const { log, lines } = progress(extra);
50
+ async ({ game, project, build, launch: start, glitchless, intake } = {}, ctx) => {
51
+ const { log, lines } = progress(ctx);
50
52
  try {
51
53
  const g = find(game, project);
52
54
  const r = await send(g, { build: build !== false, glitchless: !!glitchless, intake, log });
@@ -56,11 +58,13 @@ server.registerTool(
56
58
  return problem(err, lines);
57
59
  }
58
60
  },
61
+ { local: true },
59
62
  );
60
63
 
61
- server.registerTool(
64
+ define(
62
65
  'glitchless_deck_measure',
63
66
  {
67
+ title: 'Measure on Steam Deck',
64
68
  description:
65
69
  'Measure the game on the Steam Deck: Steam starts it (as "Devkit Game: <id>_measure") with --glitchless-measure, the Glitchless SDK records frame time, slow frames, hitches, render and update CPU, draw calls and new errors, then the game quits and the numbers come back here. Saved in .glitchless/deck/<id>/ and compared with a saved run (by default "baseline") using the same thresholds as glitchless_playtest; a FAIL lists the regressions. Call with save_as "baseline" BEFORE changing code, send the new build with glitchless_deck_send, then call again without arguments. For Unity, Godot and Unreal builds with the Glitchless SDK (web games: use glitchless_playtest). Takes the warm-up plus the seconds plus about 10 seconds.',
66
70
  inputSchema: {
@@ -74,8 +78,8 @@ server.registerTool(
74
78
  },
75
79
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
76
80
  },
77
- async ({ game, project, seconds, warmup, save_as, compare_to, args, glitchless } = {}, extra) => {
78
- const { log, lines } = progress(extra);
81
+ async ({ game, project, seconds, warmup, save_as, compare_to, args, glitchless } = {}, ctx) => {
82
+ const { log, lines } = progress(ctx);
79
83
  try {
80
84
  const r = await measure(find(game, project), { seconds: seconds ?? 10, warmup: warmup ?? 3, saveAs: save_as, compareTo: compare_to, args: args || [], glitchless: !!glitchless, log });
81
85
  const files = Object.entries(r.files || {}).map(([k, f]) => `${k}: ${f}`).join('\n');
@@ -84,4 +88,5 @@ server.registerTool(
84
88
  return problem(err, lines);
85
89
  }
86
90
  },
91
+ { local: true },
87
92
  );
@@ -2,9 +2,9 @@
2
2
  // in the project, so it is registered without the read-only hint.
3
3
  import { z } from 'zod';
4
4
  import { playtest } from 'glitchless-playtest';
5
- import { server, BASE, API_KEY, DEFAULT_SERVICE, fail } from '../context.js';
5
+ import { define, base, apiKey, defaultService, fail } from '../context.js';
6
6
 
7
- server.registerTool(
7
+ define(
8
8
  'glitchless_playtest',
9
9
  {
10
10
  description:
@@ -18,11 +18,11 @@ server.registerTool(
18
18
  },
19
19
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
20
20
  },
21
- async ({ save_as, compare_to, quick, game_url, max_seconds } = {}, extra) => {
22
- const token = extra?._meta?.progressToken;
21
+ async ({ save_as, compare_to, quick, game_url, max_seconds } = {}, ctx) => {
22
+ const token = ctx?.mcpReq._meta?.progressToken;
23
23
  let step = 0;
24
24
  const log = (message) => {
25
- if (token != null) extra.sendNotification({ method: 'notifications/progress', params: { progressToken: token, progress: ++step, message } }).catch(() => {});
25
+ if (token != null) ctx.mcpReq.notify({ method: 'notifications/progress', params: { progressToken: token, progress: ++step, message } }).catch(() => {});
26
26
  };
27
27
  try {
28
28
  const r = await playtest({
@@ -30,7 +30,7 @@ server.registerTool(
30
30
  compareTo: compare_to,
31
31
  quick,
32
32
  maxSeconds: max_seconds,
33
- config: { server: BASE, api_key: API_KEY || undefined, service: DEFAULT_SERVICE || undefined, game: game_url },
33
+ config: { server: base(), api_key: apiKey() || undefined, service: defaultService() || undefined, game: game_url },
34
34
  log,
35
35
  });
36
36
  const files = Object.entries(r.files || {}).map(([k, f]) => `${k}: ${f}`).join('\n');
@@ -39,4 +39,6 @@ server.registerTool(
39
39
  return fail(err);
40
40
  }
41
41
  },
42
+ // It plays the game in Chrome on this computer, so it is not served over HTTP.
43
+ { local: true },
42
44
  );
@@ -1,18 +1,12 @@
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`.
1
+ // A workspace's games, for an agent signed in with a workspace key (glitchless_sign_in, `glitchless-mcp login`, or
2
+ // OAuth over HTTP): sign in, create a game, and make or revoke share links. Listing games, reading any of them and
3
+ // saving their dashboards are the other tools, with `game`.
4
4
  import { z } from 'zod';
5
- import { server, BASE, isWorkspace, agent, workspaceGames, projectFor, resolveService, reply, fail, useCredentials, readCredentials } from '../context.js';
5
+ import { define, base, isWorkspace, agent, workspaceGames, projectFor, resolveService, reply, useCredentials, readCredentials } from '../context.js';
6
6
  import { startSignIn, CLOUD_URL } from '../login.js';
7
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
- });
8
+ // A tool that needs the manage scope. opts: { title, annotations, scope, local }.
9
+ const act = (name, description, inputSchema, handler, { title, annotations, ...opts } = {}) => define(name, { title, description, inputSchema, annotations }, handler, { scope: 'manage', ...opts });
16
10
 
17
11
  let signingIn = null;
18
12
 
@@ -23,7 +17,7 @@ act(
23
17
  async ({ url }) => {
24
18
  if (isWorkspace()) {
25
19
  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) });
20
+ return reply(`Already signed in to ${c?.workspace?.name ?? 'a workspace'} on ${base()}.`, { games: (await workspaceGames(true)).map((g) => g.name) });
27
21
  }
28
22
  if (signingIn?.done) {
29
23
  const c = signingIn.done;
@@ -37,7 +31,7 @@ act(
37
31
  throw err;
38
32
  }
39
33
  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) });
34
+ const started = await startSignIn({ url: url || (base().includes('localhost') ? CLOUD_URL : base()) });
41
35
  signingIn = { verification_url: started.verification_url, user_code: started.user_code };
42
36
  started.wait().then(
43
37
  (c) => {
@@ -48,7 +42,8 @@ act(
48
42
  );
49
43
  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
44
  },
51
- { openWorldHint: true },
45
+ // Over HTTP the person signs in with OAuth before any tool runs, so this one is for stdio only.
46
+ { title: 'Sign in', annotations: { openWorldHint: true }, scope: 'read', local: true },
52
47
  );
53
48
 
54
49
  act(
@@ -79,6 +74,8 @@ act(
79
74
  const out = await agent('POST', `/games/${pid}/shares`, { service: svc, page, name, days, sums: sums === true });
80
75
  return reply(`Share link to ${svc}'s "${page}" page (shown once):\n${out.url}`, out.share);
81
76
  },
77
+ // Anyone with the link sees the board, signed out: it publishes beyond the workspace.
78
+ { annotations: { openWorldHint: true } },
82
79
  );
83
80
 
84
81
  act(
@@ -89,7 +86,7 @@ act(
89
86
  const pid = await projectFor(game);
90
87
  return reply('Share links:', (await agent('GET', `/games/${pid}/shares`)).shares);
91
88
  },
92
- { readOnlyHint: true },
89
+ { annotations: { readOnlyHint: true, idempotentHint: true } },
93
90
  );
94
91
 
95
92
  act(
@@ -101,5 +98,5 @@ act(
101
98
  await agent('DELETE', `/games/${pid}/shares/${encodeURIComponent(id)}`);
102
99
  return reply(`Revoked ${id}.`, {});
103
100
  },
104
- { destructiveHint: true },
101
+ { annotations: { destructiveHint: true, idempotentHint: true } },
105
102
  );