glitchless-mcp 0.8.0 → 0.10.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.
@@ -0,0 +1,153 @@
1
+ // Multiplayer: matches from every side, the network players play over, and the game's dedicated servers
2
+ // (docs/design/genre-coverage.md A7, A8, A9). A match is a group ID the game's server made, shared by everyone in it;
3
+ // network quality comes from each frame window's `net` and the disconnects the SDKs send; a server runs the SDK in
4
+ // server mode and its sessions are kept under the game's companion service, "<game>.server".
5
+ import { z } from 'zod';
6
+ import { query, resolveService, range, reply, common, tool, filters, slimIssue } from '../context.js';
7
+
8
+ // "<game>.server" → "<game>": these tools read a game's servers through the game itself.
9
+ const gameOf = (svc) => (svc.endsWith('.server') ? svc.slice(0, -'.server'.length) : svc);
10
+
11
+ // Seconds into a match as m:ss.
12
+ const clock = (s) => `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, '0')}`;
13
+
14
+ // Slot starts (seconds) → stretches "3:00–4:00", each slot `step` seconds long.
15
+ function stretches(ts, step) {
16
+ const out = [];
17
+ for (const t of [...ts].sort((a, b) => a - b)) {
18
+ const last = out.at(-1);
19
+ if (last && t - last[1] <= step) last[1] = t;
20
+ else out.push([t, t]);
21
+ }
22
+ return out.map(([a, b]) => `${clock(a)}–${clock(b + step)}`);
23
+ }
24
+
25
+ const median = (xs) => {
26
+ const s = xs.filter((v) => v != null).sort((a, b) => a - b);
27
+ return s.length ? s[Math.floor(s.length / 2)] : null;
28
+ };
29
+
30
+ // What a match page says first: whether the whole lobby lagged at once (the server or its network) or players lagged
31
+ // on their own (their connections), and what the server's ticks did then.
32
+ function verdict(m) {
33
+ const step = m.slot_s || 30;
34
+ const lobby = new Set(m.lobby_spikes || []);
35
+ const ticks = (m.server || []).flatMap((s) => s.slots);
36
+ const budget = (m.server || []).find((s) => s.budget_ms != null)?.budget_ms ?? null;
37
+ const during = median(ticks.filter((x) => lobby.has(x.t)).map((x) => x.tick_p95));
38
+ const otherwise = median(ticks.filter((x) => !lobby.has(x.t)).map((x) => x.tick_p95));
39
+ const alone = m.sessions.map((s) => ({ s, at: s.slots.filter((x) => x.spike && !lobby.has(x.t)).map((x) => x.t) })).filter((x) => x.at.length);
40
+ const parts = [];
41
+ if (lobby.size) {
42
+ parts.push(`The whole lobby lagged at once at ${stretches(lobby, step).join(', ')}: that's the server or its network, not players' connections.`);
43
+ if (during != null) parts.push(`The server's slowest ticks then: ${during} ms${budget ? ` against a ${budget} ms budget` : ''} (${otherwise ?? '?'} ms the rest of the match).`);
44
+ } else parts.push('No moment where the whole lobby lagged at once.');
45
+ if (alone.length) parts.push(`${alone.length} ${alone.length === 1 ? 'player' : 'players'} lagged on their own (their connection): ${alone.slice(0, 5).map((x) => `${x.s.session_id} at ${stretches(x.at, step).join(', ')}`).join('; ')}.`);
46
+ if (m.disconnects) parts.push(`${m.disconnects} disconnected (${Object.entries(m.disconnect_reasons || {}).map(([r, n]) => `${n} ${r.replace('_', ' ')}`).join(', ')}).`);
47
+ return parts.join(' ');
48
+ }
49
+
50
+ tool(
51
+ 'glitchless_match',
52
+ "Matches of a multiplayer game, from every side (the game marks a match with setGroup('match', id), the ID its server made; every SDK hashes it the same way, so its players and its server join up). Without id: the window's matches, the most recent first, or the worst by lag (ping) or disconnects (sort), each with its level, players, outcomes, disconnects, ping and lag (the share of connected play over 150 ms), and its server's tick. With id: one match slot by slot (30 seconds) from its start, with a verdict that tells a whole lobby lagging at once (the server or its network) from one player lagging (their connection): each player's ping, frame time, outcome and disconnects, the server's ticks against its budget and the players connected in the same slots, and the match's events. slots: true gives every slot of every player.",
53
+ {
54
+ ...common,
55
+ id: z.string().optional().describe('A match id (h_… or the game\'s own), from the list or a finding'),
56
+ sort: z.enum(['recent', 'lag', 'disconnects']).optional().describe('Without id: recent (default), lag (the worst ping p95 first) or disconnects'),
57
+ limit: z.number().int().min(1).max(200).optional().describe('Without id: how many matches (default 20)'),
58
+ slots: z.boolean().optional().describe('With id: every 30-second slot of every player and server (long for a big match); by default only the slots that lagged'),
59
+ },
60
+ async ({ service, hours, id, sort, limit, slots, ...f }) => {
61
+ const svc = gameOf(await resolveService(service));
62
+ if (!id) {
63
+ const d = await query('matches', { service: svc, ...filters(f), sort, limit: limit || 20, ...range(hours) });
64
+ const brief = d.matches
65
+ .map((m, i) => `${i + 1}. ${m.id}${m.level ? ` on ${m.level}` : ''}: ${m.sessions} players, ${clock(m.duration_s)}, ping p95 ${m.ping_p95 ?? '–'} ms${m.lag_pct != null ? ` (${m.lag_pct}% of play over 150 ms)` : ''}, ${m.disconnects} disconnects${m.server?.tick_p95 != null ? `, server tick p95 ${m.server.tick_p95} ms` : ''}`)
66
+ .join('\n');
67
+ return reply(`${d.total} match(es) in ${svc}${d.sort !== 'recent' ? `, the worst by ${d.sort} first` : ''}:\n${brief || 'None in this window: the game marks a match with setGroup("match", id).'}`, d.matches);
68
+ }
69
+ const d = await query('matches', { service: svc, ...filters(f), id, ...range(hours) });
70
+ if (d.error || !d.match) return reply(`No match ${id} in ${svc} in this window (${hours || 24}h): glitchless_match without id lists them`, {});
71
+ const m = d.match;
72
+ const lobby = new Set(m.lobby_spikes || []);
73
+ const players = m.sessions.map(({ slots: list, ...s }) => ({
74
+ ...s,
75
+ lagged_alone_at: list.filter((x) => x.spike && !lobby.has(x.t)).map((x) => x.t),
76
+ frame_p95_worst: Math.max(...list.map((x) => x.frame_p95 ?? 0)) || null,
77
+ hitches: list.reduce((n, x) => n + (x.hitches || 0), 0),
78
+ ...(slots ? { slots: list } : {}),
79
+ }));
80
+ const servers = (m.server || []).map((s) => {
81
+ const usual = median(s.slots.map((x) => x.tick_p95));
82
+ const over = s.slots.filter((x) => x.tick_p95 != null && (s.budget_ms != null ? x.tick_p95 > s.budget_ms : usual != null && x.tick_p95 > usual * 1.5));
83
+ return { session_id: s.session_id, budget_ms: s.budget_ms ?? null, tick_p95_usual: usual, players_max: Math.max(0, ...s.slots.map((x) => x.players ?? 0)), slow_slots: over.slice(0, 20), ...(slots ? { slots: s.slots } : {}) };
84
+ });
85
+ const { sessions: _, server: __, events, slots: starts, ...head } = m;
86
+ return reply(`Match ${m.id} in ${svc}: ${m.sessions.length} players on ${m.level ?? 'no level'}, ${clock(m.duration_s)}. ${verdict(m)}`, { ...head, ...(slots ? { slots: starts } : {}), players, servers, events: events.slice(0, 80) });
87
+ },
88
+ );
89
+
90
+ // One table's rows as an agent reads them.
91
+ const netRow = (r) => ({ key: r.key ?? r.value, sessions: r.sessions ?? null, ping_p50: r.ping_p50, ping_p95: r.ping_p95, lag_pct: r.lag_pct, loss_pct: r.loss_pct, disconnects: r.disconnects, disconnects_per_hour: r.disconnects_per_hour, disconnect_pct: r.disconnect_pct, disconnect_reasons: r.disconnect_reasons });
92
+
93
+ tool(
94
+ 'glitchless_network',
95
+ "Network quality of a multiplayer game: ping (median and the slowest 5%), lag (the share of connected play with a round trip over 150 ms), packet loss and jitter, and disconnects (per hour played, by reason, and the share of level attempts a disconnect ended: never counted as fails), overall and by level, version, platform and kind of connection (Wi-Fi, mobile data, wired), and by region when the game sets a region property (or by any property given as by). Also the worst matches by ping (glitchless_match opens one), and the network findings: a whole lobby lagging at once (the server), one kind of connection or region lagging (players' connections, or no server near them), disconnects rising in a release. The SDKs read it from the engine's netcode (Netcode for GameObjects, Mirror, Godot's ENet, Unreal's net driver, WebRTC) or the game's netSample calls.",
96
+ {
97
+ ...common,
98
+ by: z.string().optional().describe('A session property to split by besides the built-in ones, e.g. "region" (the default when the game sets one) or "$play": each of its values (up to 8) read on its own'),
99
+ },
100
+ async ({ service, hours, by, ...f }) => {
101
+ const svc = gameOf(await resolveService(service));
102
+ const ask = { service: svc, ...filters(f), ...range(hours) };
103
+ const ev = await query('events', ask);
104
+ // A property to split by: the one asked for, else the region where the game sets one (the performance query's
105
+ // by_prop gives its network rows in the same call).
106
+ const key = by ? by.replace(/^\$/, '') : (ev.properties || []).some((p) => p.key === 'region') ? 'region' : null;
107
+ const prop = key && (ev.properties || []).find((p) => p.key === key);
108
+ const [perf, worst, found] = await Promise.all([query('performance', { ...ask, ...(prop && !prop.identifier_like ? { by_prop: key } : {}) }), query('matches', { ...ask, sort: 'lag', limit: 5 }), query('findings', ask)]);
109
+ const net = perf.network;
110
+ if (!net) return reply(`No network data from ${svc} in this window: the SDKs read it from the game's netcode, or the game calls netSample about once a second while connected (the instrument skill says how for each engine)`, {});
111
+ const byProp = net.by_prop ? net.by_prop.rows.map(netRow) : null;
112
+ const k = net.kpis;
113
+ const title = `Network for ${svc} (${hours || 24}h): ping ${k.ping_p50} ms median, ${k.ping_p95} ms for the slowest 5%; ${k.lag_pct ?? 0}% of connected play over 150 ms; ${k.loss_pct ?? 0}% packet loss; ${k.disconnects} disconnects (${k.disconnects_per_hour ?? '–'} per hour played${k.disconnect_pct != null ? `, ${k.disconnect_pct}% of attempts` : ''})`;
114
+ return reply(title, {
115
+ kpis: k,
116
+ by_level: net.by_level.map(netRow),
117
+ by_version: net.by_version.map(netRow),
118
+ by_platform: net.by_platform.map(netRow),
119
+ by_link: net.by_link.map(netRow),
120
+ ...(byProp ? { [`by_${key}`]: byProp } : key && !prop ? { note: `No session property ${key} in this window (glitchless_events lists the ones the game sets)` } : {}),
121
+ worst_matches: worst.matches,
122
+ findings: found.findings.filter((x) => x.category === 'network'),
123
+ });
124
+ },
125
+ );
126
+
127
+ tool(
128
+ 'glitchless_servers',
129
+ "A multiplayer game's dedicated servers, when they run the Glitchless SDK in server mode (Node glitchless/server, or the Unity, Godot or Unreal server role): servers running now and the players connected to them; tick time against its budget (the slowest 5% of ticks, and the share of windows over budget) by players connected, by map and by version; CPU, memory and networked objects; crashes, each with the matches it ended and the players it dropped; long-running servers whose memory or objects keep climbing; the latest server runs; and the server findings (falling behind when full, a crash that ends matches, a leak). A server's sessions are kept apart from players' under the companion service \"<game>.server\": every other tool reads them with service \"<game>.server\" (glitchless_session for one server run, glitchless_get_error for a server crash's stack). Server sessions count as sessions like any other.",
130
+ { ...common },
131
+ async ({ service, hours, ...f }) => {
132
+ const svc = gameOf(await resolveService(service));
133
+ const ask = { service: svc, ...filters(f), ...range(hours) };
134
+ const [d, found] = await Promise.all([query('servers', ask), query('findings', ask)]);
135
+ const now = d.servers_now != null ? `${d.servers_now} running now with ${d.players_on_servers} players connected` : null;
136
+ if (!d.kpis) return reply(`${d.why || `No server of ${svc} sent anything in this window.`}${now ? ` (${now})` : ''}`, {});
137
+ const k = d.kpis;
138
+ const title = `Servers of ${svc} (${hours || 24}h): ${k.servers} server runs${now ? `, ${now}` : ''}; tick p95 ${k.tick_p95} ms${k.budget_ms ? ` against a ${k.budget_ms} ms budget (in ${k.over_budget_pct}% of 5-second windows, 5% or more of the ticks went over it)` : ''}; ${k.players ?? 0} players per server on average; ${k.crashed} crashed (${k.crash_free_pct}% crash-free). Their sessions: service "${svc}.server"`;
139
+ return reply(title, {
140
+ servers_now: d.servers_now ?? null,
141
+ players_on_servers: d.players_on_servers ?? null,
142
+ kpis: k,
143
+ by_players: d.by_players,
144
+ by_level: d.by_level,
145
+ by_version: d.by_version,
146
+ crashes: d.crashes.map((c) => ({ ...slimIssue(c), crashed_servers: c.crashed_servers, matches_ended: c.matches_ended, players_dropped: c.players_dropped, breadcrumbs: c.breadcrumbs?.slice(-6) })),
147
+ memory: d.memory,
148
+ climbing: d.climbing,
149
+ recent_runs: d.sessions.slice(0, 15),
150
+ findings: found.findings.filter((x) => x.id.startsWith('server-')),
151
+ });
152
+ },
153
+ );
@@ -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,17 +74,19 @@ 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(
85
82
  'glitchless_list_share_links',
86
- "A game's share links: which page each shows, when it expires, and whether it's revoked.",
83
+ "A game's share links: which page each shows, when it expires, when it was last opened (lastUsedAt, to about ten minutes), and whether it's revoked.",
87
84
  {},
88
85
  async ({ game }) => {
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
  );