@chrischall/warapp-mcp 0.22.1 → 0.23.1

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.
Files changed (72) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +49 -3
  4. package/dist/analysis/coalition.js +3 -2
  5. package/dist/analysis/outlook.js +42 -2
  6. package/dist/analysis/plan/captures.js +3 -1
  7. package/dist/analysis/plan/relations.js +1 -1
  8. package/dist/analysis/plan/report.js +2 -2
  9. package/dist/analysis/plan/targets.js +48 -12
  10. package/dist/analysis/plan/threats.js +55 -2
  11. package/dist/analysis/planner.js +2 -1
  12. package/dist/analysis/relations.js +40 -7
  13. package/dist/bundle.js +10250 -3744
  14. package/dist/chat.js +93 -3
  15. package/dist/clans.js +308 -0
  16. package/dist/forums.js +70 -0
  17. package/dist/friends.js +83 -0
  18. package/dist/index.js +1 -1
  19. package/dist/invite-code.js +46 -0
  20. package/dist/join-color.js +23 -13
  21. package/dist/ladders.js +360 -0
  22. package/dist/mail.js +295 -0
  23. package/dist/my-games.js +18 -1
  24. package/dist/notifications.js +22 -4
  25. package/dist/open-games.js +29 -2
  26. package/dist/outlook-log.js +1 -0
  27. package/dist/protocol/bundle.js +4 -4
  28. package/dist/protocol/codec.js +1 -1
  29. package/dist/protocol/methods.js +690 -8
  30. package/dist/protocol/rpc.js +28 -3
  31. package/dist/push/socketio.js +2 -2
  32. package/dist/quickmatch.js +264 -0
  33. package/dist/surrender-pending.js +62 -2
  34. package/dist/templates.js +451 -0
  35. package/dist/tools/boot-player.js +165 -0
  36. package/dist/tools/calibration-harness.js +8 -1
  37. package/dist/tools/calibration.js +14 -2
  38. package/dist/tools/chat.js +19 -0
  39. package/dist/tools/clan-writes.js +208 -0
  40. package/dist/tools/clans.js +181 -0
  41. package/dist/tools/end-game-common.js +49 -0
  42. package/dist/tools/forums.js +535 -0
  43. package/dist/tools/friends.js +50 -0
  44. package/dist/tools/game.js +21 -3
  45. package/dist/tools/index.js +39 -0
  46. package/dist/tools/invites.js +347 -0
  47. package/dist/tools/join-game.js +4 -4
  48. package/dist/tools/ladders.js +418 -0
  49. package/dist/tools/leave-game.js +85 -27
  50. package/dist/tools/live-context.js +2 -2
  51. package/dist/tools/mail.js +600 -0
  52. package/dist/tools/my-games.js +50 -6
  53. package/dist/tools/notifications.js +12 -3
  54. package/dist/tools/nudge.js +178 -0
  55. package/dist/tools/quickmatch.js +481 -0
  56. package/dist/tools/react.js +177 -0
  57. package/dist/tools/relations.js +3 -2
  58. package/dist/tools/session.js +6 -2
  59. package/dist/tools/team-surrender.js +206 -0
  60. package/dist/tools/templates.js +342 -0
  61. package/dist/tools/tournaments.js +495 -0
  62. package/dist/tools/turn.js +4 -1
  63. package/dist/tools/vote-to-end.js +142 -0
  64. package/dist/tools/write-kit.js +22 -1
  65. package/dist/tournaments.js +321 -0
  66. package/dist/trend.js +1 -0
  67. package/dist/version.js +1 -1
  68. package/manifest.json +190 -2
  69. package/mint.yaml +3 -4
  70. package/package.json +1 -1
  71. package/server.json +2 -2
  72. package/skills/warapp-mcp/SKILL.md +39 -6
@@ -0,0 +1,418 @@
1
+ // Ladders (#637): warapp_get_ladders, warapp_get_ladder and warapp_get_ladder_player (read-only), and
2
+ // warapp_join_ladder and warapp_leave_ladder (confirm-gated). Methods and layouts read from the 6.09 client bundle,
3
+ // UNVERIFIED live (docs/WEB-PROTOCOL.md, Ladders).
4
+ //
5
+ // Player data goes through src/ladders.ts' allowlist (ids, names, rank, rating, league, games at once, record), and
6
+ // every name through untrustedText. Joining commits the account to ladder games war.app creates on its own; the
7
+ // preview says what (the games at once, the seasonal ladder's pace and game count, the template id the games use).
8
+ // Leaving is not a loss: war.app's own help (in the client) says it keeps every ladder game already running, which
9
+ // still counts toward the rating, and only stops new ones — so the leave is not marked destructive.
10
+ import { CONFIRM_INJECTION_RULE, toolAnnotations } from '@chrischall/mcp-utils';
11
+ import { z } from 'zod';
12
+ import { LADDER_KEYS, LADDERS, readJoinLadderResult, readLadderGames, readLadderPlayer, readLadderPlayers, readLadderSeason, readLadderSeasons, readLadderStats, } from '../ladders.js';
13
+ import { inGameId } from '../live.js';
14
+ import { LADDER_PAGE, Method, writeGetLadderGamesParams, writeGetLadderPlayerParams, writeGetLadderPlayersParams, writeGetLadderSeasonParams, writeJoinLadderParams, writeLeaveLadderParams, } from '../protocol/methods.js';
15
+ import { WarappServerError } from '../protocol/rpc.js';
16
+ import { readAnnotations, respond, shownAccount, UNTRUSTED_PREVIEW_NOTE, untrustedDescription, untrustedText } from './common.js';
17
+ import { mintMeta } from './hints.js';
18
+ import { failureText, requireApprovedAccount, writeAccount } from './live-context.js';
19
+ import { BRIDGE_NOTE } from './live.js';
20
+ import { defineGatedWrite, refuse, requireMe, sendAndVerify, worded } from './write-kit.js';
21
+ /** Every answer says so: nothing here has been checked against a real reply. */
22
+ export const LADDERS_UNVERIFIED = "Read from war.app's client code, UNVERIFIED live: the ladder methods and their replies have not been checked against war.app yet.";
23
+ /** The ladder refusals, worded from the codes' names in the client (UNVERIFIED live). */
24
+ const LADDER_ERRORS = {
25
+ 280: 'war.app does not know that ladder (LadderKeyNotFound).',
26
+ 281: 'That player is not on this ladder season (LadderPlayerKeyNotFound).',
27
+ 286: 'The account is not on that ladder (CannotSetSimultaneousGamesIfNotInLadder).',
28
+ 289: 'war.app will not let this account join ladders yet (CannotJoinLadderIfNotSignedUp): it must be a fully signed-up account.',
29
+ 295: 'This ladder is locked for the account (JoiningThisLadderLocked): it has not unlocked it yet (war.app\'s help gives the level each ladder needs).',
30
+ 306: 'That needs a team ladder (RequiresTeamLadder).',
31
+ 340: 'That ladder season does not exist (LadderSeasonKeyNotFound).',
32
+ 570: 'A teammate is on vacation, so the team cannot join the ladder yet (CannotJoinLadderWhileTeammateOnVacation).',
33
+ };
34
+ /** CannotLeaveLadderNotIn: the client treats it as already left. */
35
+ const NOT_IN_LADDER = 287;
36
+ const ladderArg = z.enum(LADDER_KEYS).describe('The ladder: `1v1`, `2v2`, `3v3` or `seasonal`.');
37
+ const seasonArg = z
38
+ .number()
39
+ .int()
40
+ .min(0)
41
+ .describe('A ladder season id (the seasonal ladder has one per season, from warapp_get_ladders; the others one each: 1v1 0, 2v2 1, 3v3 4).');
42
+ const shownName = (name) => (name === null ? null : untrustedText(name));
43
+ const standingView = (p) => ({ ...p, name: shownName(p.name) });
44
+ const gameView = (g) => ({ ...g, players: g.players.map((p) => ({ ...p, name: shownName(p.name) })) });
45
+ const seasonView = (s) => ({
46
+ ...s,
47
+ template: shownName(s.template),
48
+ ...(s.winners ? { winners: s.winners.map((w) => ({ ...w, name: shownName(w.name) })) } : {}),
49
+ });
50
+ const ladderInfo = (key) => {
51
+ const { id, name, seasonId, teamSize, gamesAtOnce, minLevel } = LADDERS[key];
52
+ return { ladder: key, id, name, seasonId, teamSize, gamesAtOnce, minLevel };
53
+ };
54
+ /** One ladder read, a refusal worded where the client names its code. */
55
+ async function ladderCall(ctx, name, write, read) {
56
+ try {
57
+ const env = await ctx.rpc.call(name, Method[name], write);
58
+ return await read(env.body);
59
+ }
60
+ catch (e) {
61
+ if (e instanceof WarappServerError && LADDER_ERRORS[e.code])
62
+ throw new WarappServerError(e.code, `${LADDER_ERRORS[e.code]} (war.app error ${e.code})`);
63
+ throw e;
64
+ }
65
+ }
66
+ const readSeasons = async (ctx) => {
67
+ const bundle = await ctx.bundle();
68
+ return ladderCall(ctx, 'GetLadderSeasons', undefined, (body) => readLadderSeasons(bundle, body));
69
+ };
70
+ const readSeasonPage = async (ctx, seasonId) => {
71
+ const bundle = await ctx.bundle();
72
+ return ladderCall(ctx, 'GetLadderSeason', (w) => writeGetLadderSeasonParams(w, { seasonId }), (body) => readLadderSeason(bundle, body));
73
+ };
74
+ /** The seasonal ladder's season now: the one in progress, else the first war.app lists. */
75
+ function currentSeasonal(seasons) {
76
+ return seasons.find((s) => s.state === 'in-progress') ?? seasons[0];
77
+ }
78
+ /** The season a call names: `season_id`, else the ladder's own (the seasonal ladder's current). */
79
+ async function resolveSeason(ctx, ladder, seasonId) {
80
+ if (seasonId !== undefined)
81
+ return seasonId;
82
+ if (ladder === undefined)
83
+ refuse('Name a ladder (`ladder`) or a season (`season_id`), so nothing was read.', 'warapp_get_ladders lists them.');
84
+ const own = LADDERS[ladder].seasonId;
85
+ if (own !== null)
86
+ return own;
87
+ const current = currentSeasonal(await readSeasons(ctx));
88
+ if (!current)
89
+ refuse('war.app listed no season of the seasonal ladder, so there is none to read.', 'Check warapp_get_ladders.');
90
+ return current.seasonId;
91
+ }
92
+ /** The signed-in account's in-game id (its GameFeed id without the check digits). */
93
+ const myInGameId = async (ctx) => inGameId({ id: await requireMe(ctx, { consequence: 'nothing was read' }) });
94
+ export function registerLadderTools(server, ctx) {
95
+ server.registerTool('warapp_get_ladders', {
96
+ title: 'List the war.app ladders and my standings',
97
+ description: untrustedDescription('The war.app (Warzone) ladders — 1v1, 2v2, 3v3 and seasonal — and your standing on each you have played ' +
98
+ "(war.app's GetLadderStats: rank, rating, best rank and rating, league, games held at once, `participating`), plus the " +
99
+ "seasonal ladder's seasons (war.app's GetLadderSeasons: id, number, state, template, start and end, games per season, " +
100
+ 'winners by id and name). Each ladder lists its season id, team size, games-at-once range and the level war.app\'s help ' +
101
+ `gives for joining it. Ids and names only; nothing else about a player is read out. ${BRIDGE_NOTE} Read-only. ${LADDERS_UNVERIFIED}`),
102
+ _meta: mintMeta('lookup', ['war.app ladders', 'my ladder rank', 'ladder rating', 'seasonal ladder']),
103
+ annotations: readAnnotations('List war.app ladders and my standings'),
104
+ inputSchema: z.object({}),
105
+ }, async () => {
106
+ const bundle = await ctx.bundle();
107
+ const mine = await ladderCall(ctx, 'GetLadderStats', undefined, (body) => readLadderStats(bundle, body));
108
+ let seasons = null;
109
+ let seasonsNote;
110
+ try {
111
+ seasons = await readSeasons(ctx);
112
+ }
113
+ catch (e) {
114
+ seasonsNote = `The seasonal ladder's seasons could not be read (${failureText(e)}).`;
115
+ }
116
+ const current = seasons ? currentSeasonal(seasons) : undefined;
117
+ return respond(undefined, ['compact'], () => ({
118
+ ladders: LADDER_KEYS.map((k) => ({ ...ladderInfo(k), ...(k === 'seasonal' ? { seasonId: current?.seasonId ?? null } : {}) })),
119
+ myStandings: mine.map((s) => ({ ...s, standing: s.standing ? standingView(s.standing) : null })),
120
+ seasonal: seasons ? { current: current?.seasonId ?? null, seasons: seasons.map(seasonView) } : null,
121
+ ...(seasonsNote ? { seasonsNote } : {}),
122
+ unverified: LADDERS_UNVERIFIED,
123
+ }));
124
+ });
125
+ server.registerTool('warapp_get_ladder', {
126
+ title: 'Read a war.app ladder season',
127
+ description: untrustedDescription('One war.app (Warzone) ladder season. `view: "overview"` (default; war.app\'s GetLadderSeason): the season (state, ' +
128
+ 'template, dates), how many players take part, the top players, the players ranked around you, your own standing ' +
129
+ '(`me`, null when you are not on it) and its recent games. `view: "players"` (GetLadderPlayers): the standings, ' +
130
+ `${LADDER_PAGE} a page from \`start\`. \`view: "games"\` (GetLadderGames): the games, ${LADDER_PAGE} a page from \`start\`, ` +
131
+ "only `player_id`'s when given. Name the season by `ladder` (the seasonal ladder: its current season) or `season_id`. " +
132
+ 'Players are in-game ids (a GameFeed id without its check digits) and delimited names, with rank, rating, league and ' +
133
+ `games at once; each game lists its players by team and the winners once finished. ${BRIDGE_NOTE} Read-only. ${LADDERS_UNVERIFIED}`),
134
+ _meta: mintMeta('lookup', ['ladder standings', 'ladder leaderboard', 'ladder games']),
135
+ annotations: readAnnotations('Read a war.app ladder season'),
136
+ inputSchema: z.object({
137
+ ladder: ladderArg.optional(),
138
+ season_id: seasonArg.optional(),
139
+ view: z.enum(['overview', 'players', 'games']).optional().describe('What to read (default `overview`).'),
140
+ start: z.number().int().min(0).optional().describe(`Where a players or games page starts (default 0; pages of ${LADDER_PAGE}).`),
141
+ player_id: z.number().int().positive().optional().describe('The games view only: just this player\'s games (in-game id).'),
142
+ }),
143
+ }, async ({ ladder, season_id, view, start, player_id }) => {
144
+ const seasonId = await resolveSeason(ctx, ladder, season_id);
145
+ const bundle = await ctx.bundle();
146
+ const at = start ?? 0;
147
+ if ((view ?? 'overview') === 'overview') {
148
+ const page = await readSeasonPage(ctx, seasonId);
149
+ return respond(undefined, ['compact'], () => ({
150
+ seasonId,
151
+ season: seasonView(page.season),
152
+ playerCount: page.playerCount,
153
+ me: page.me ? standingView(page.me) : null,
154
+ top: page.top.map(standingView),
155
+ aroundMe: page.aroundMe.map(standingView),
156
+ recentGames: page.games.map(gameView),
157
+ unverified: LADDERS_UNVERIFIED,
158
+ }));
159
+ }
160
+ if (view === 'players') {
161
+ const p = await ladderCall(ctx, 'GetLadderPlayers', (w) => writeGetLadderPlayersParams(w, { seasonId, start: at }), (body) => readLadderPlayers(bundle, body));
162
+ return respond(undefined, ['compact'], () => ({
163
+ seasonId,
164
+ start: at,
165
+ total: p.total,
166
+ players: p.players.map(standingView),
167
+ ...(p.total !== null && at + LADDER_PAGE < p.total ? { next: at + LADDER_PAGE } : {}),
168
+ unverified: LADDERS_UNVERIFIED,
169
+ }));
170
+ }
171
+ const g = await ladderCall(ctx, 'GetLadderGames', (w) => writeGetLadderGamesParams(w, { seasonId, start: at, ...(player_id !== undefined ? { playerId: player_id } : {}) }), (body) => readLadderGames(bundle, body));
172
+ return respond(undefined, ['compact'], () => ({
173
+ seasonId,
174
+ start: at,
175
+ ...(player_id !== undefined ? { playerId: player_id } : {}),
176
+ total: g.total,
177
+ games: g.games.map(gameView),
178
+ ...(g.total !== null && at + LADDER_PAGE < g.total ? { next: at + LADDER_PAGE } : {}),
179
+ unverified: LADDERS_UNVERIFIED,
180
+ }));
181
+ });
182
+ server.registerTool('warapp_get_ladder_player', {
183
+ title: "Read a player's war.app ladder record",
184
+ description: untrustedDescription("One player's page on a war.app (Warzone) ladder season (war.app's GetLadderPlayer): their standing (rank, rating, best " +
185
+ 'rank and rating, league, games at once, TrueSkill), teammates on a team ladder, notable wins, the newest rating ' +
186
+ 'points, their recent ladder games and the `record` (wins, losses, in progress) over the games listed. `player_id` is ' +
187
+ 'the in-game id (a GameFeed id without its check digits; default you). Name the season by `ladder` or `season_id`. ' +
188
+ `Ids, names and ladder figures only. ${BRIDGE_NOTE} Read-only. ${LADDERS_UNVERIFIED}`),
189
+ _meta: mintMeta('lookup', ['ladder player', 'ladder record', 'ladder rating history']),
190
+ annotations: readAnnotations("Read a player's war.app ladder record"),
191
+ inputSchema: z.object({
192
+ ladder: ladderArg.optional(),
193
+ season_id: seasonArg.optional(),
194
+ player_id: z.number().int().positive().optional().describe('The player (in-game id); default the signed-in account.'),
195
+ }),
196
+ }, async ({ ladder, season_id, player_id }) => {
197
+ const seasonId = await resolveSeason(ctx, ladder, season_id);
198
+ const playerId = player_id ?? (await myInGameId(ctx));
199
+ const bundle = await ctx.bundle();
200
+ const p = await ladderCall(ctx, 'GetLadderPlayer', (w) => writeGetLadderPlayerParams(w, { seasonId, playerId }), (body) => readLadderPlayer(bundle, body, playerId));
201
+ return respond(undefined, ['compact'], () => ({
202
+ seasonId,
203
+ season: seasonView(p.season),
204
+ player: standingView(p.player),
205
+ teammates: p.teammates.map(standingView),
206
+ record: p.record,
207
+ notableWins: p.notableWins.map((n) => ({ ...n, opponent: n.opponent ? standingView(n.opponent) : null })),
208
+ ratingHistory: p.ratingHistory,
209
+ recentGames: p.games.map(gameView),
210
+ unverified: LADDERS_UNVERIFIED,
211
+ }));
212
+ });
213
+ registerJoinLadder(server, ctx);
214
+ registerLeaveLadder(server, ctx);
215
+ }
216
+ /** What joining commits the account to, from the ladder and its season (in our words). */
217
+ function joinCommitments(ladder, gamesAtOnce, page) {
218
+ const out = [];
219
+ if (ladder === 'seasonal') {
220
+ const n = page.season.gamesInSeason;
221
+ out.push(`war.app creates your seasonal ladder games itself: one game every 3 days until you have played ${n ?? 'the season\'s'} game${n === 1 ? '' : 's'}, the most the season gives.`);
222
+ }
223
+ else {
224
+ out.push(`war.app creates your ladder games itself and keeps ${gamesAtOnce} running at once, starting a new one as each finishes; the first usually comes within a few hours.`);
225
+ }
226
+ out.push('Ladder games are created for you: war.app does not let you decline one, and every one counts toward your ladder rating.');
227
+ const template = page.season.templateId;
228
+ out.push(`The games use the season's template${template !== null ? ` (template ${template})` : ''}: its boot time applies, and this server does not read the template's settings, so check them before joining.`);
229
+ if (LADDERS[ladder].teamSize > 1)
230
+ out.push('You join by yourself (team proposals are not supported here).');
231
+ out.push('Joining ends a vacation if you are on one: you become bootable an hour later.');
232
+ return out;
233
+ }
234
+ function registerJoinLadder(server, ctx) {
235
+ defineGatedWrite(server, {
236
+ title: 'Join a war.app ladder',
237
+ _meta: mintMeta('change', ['join ladder', 'enter ladder']),
238
+ }, {
239
+ name: 'warapp_join_ladder',
240
+ description: "Join a war.app (Warzone) ladder (war.app's JoinLadder): war.app then creates ladder games for you on its own, which you " +
241
+ 'cannot decline and which count toward your rating. `ladder`: `1v1`, `2v2`, `3v3` (you join by yourself) or `seasonal`. ' +
242
+ '`games_at_once`: how many ladder games to hold at once — 1v1 3 to 5, 2v2 and 3v3 2 to 5, default the lowest; the ' +
243
+ 'seasonal ladder sends one game every 3 days up to its season\'s game count and takes none. The preview says what joining ' +
244
+ 'commits you to (games at once, the seasonal pace and game count, the template id the games use; its boot time is the ' +
245
+ "template's). Refuses a ladder you are already on. war.app refuses a ladder the account has not unlocked. Always as the " +
246
+ 'signed-in war.app account; read back from the season page (`joined` → `confirmed`, else `unconfirmed`); no answer is ' +
247
+ `\`unknown\` — never resend blindly. Read from war.app's client code, UNVERIFIED live. ${BRIDGE_NOTE} ${CONFIRM_INJECTION_RULE}`,
248
+ annotations: toolAnnotations({ title: 'Join a war.app ladder', readOnly: false, destructive: true, idempotent: false, openWorld: true }),
249
+ inputSchema: z.object({
250
+ ladder: ladderArg,
251
+ games_at_once: z.number().int().positive().optional().describe('Ladder games to hold at once (not the seasonal ladder). Default the lowest allowed.'),
252
+ }),
253
+ async plan({ ladder, games_at_once }) {
254
+ const info = LADDERS[ladder];
255
+ let gamesAtOnce;
256
+ if (info.gamesAtOnce === null) {
257
+ if (games_at_once !== undefined && games_at_once !== 1) {
258
+ refuse('The seasonal ladder takes no games-at-once choice (war.app sends one game every 3 days), so nothing was sent.', 'Leave out `games_at_once`.');
259
+ }
260
+ gamesAtOnce = 1;
261
+ }
262
+ else {
263
+ gamesAtOnce = games_at_once ?? info.gamesAtOnce.min;
264
+ if (gamesAtOnce < info.gamesAtOnce.min || gamesAtOnce > info.gamesAtOnce.max) {
265
+ refuse(`The ${ladder} ladder takes ${info.gamesAtOnce.min} to ${info.gamesAtOnce.max} games at once, not ${gamesAtOnce}, so nothing was sent.`, `Pass \`games_at_once\` from ${info.gamesAtOnce.min} to ${info.gamesAtOnce.max}.`);
266
+ }
267
+ }
268
+ const me = await requireMe(ctx);
269
+ const seasonId = await resolveSeason(ctx, ladder, undefined);
270
+ const page = await readSeasonPage(ctx, seasonId);
271
+ if (page.me?.participating) {
272
+ refuse(`You are already on the ${ladder} ladder (${page.me.gamesAtOnce} game${page.me.gamesAtOnce === 1 ? '' : 's'} at once), so nothing was sent.`, 'warapp_get_ladder shows your standing; leave with warapp_leave_ladder first to join again.');
273
+ }
274
+ return {
275
+ gate: {
276
+ action: 'warapp.join_ladder',
277
+ summary: `Join the war.app ${ladder} ladder (season ${seasonId}) with ${gamesAtOnce} game${gamesAtOnce === 1 ? '' : 's'} at once`,
278
+ account: writeAccount(me),
279
+ target: `ladder:${info.id}`,
280
+ payload: { method: 'JoinLadder', ladder: info.id, gamesAtOnce },
281
+ willSend: { ladder, ladderId: info.id, gamesAtOnce },
282
+ preview: {
283
+ warning: `This joins the ${ladder} ladder: war.app starts creating games for you that you cannot decline.`,
284
+ account: shownAccount(undefined, me),
285
+ ladder: ladderInfo(ladder),
286
+ season: { id: seasonId, number: page.season.number, state: page.season.state, templateId: page.season.templateId, template: shownName(page.template), gamesInSeason: page.season.gamesInSeason },
287
+ gamesAtOnce,
288
+ commitsTo: joinCommitments(ladder, gamesAtOnce, page),
289
+ playerCount: page.playerCount,
290
+ untrusted: UNTRUSTED_PREVIEW_NOTE,
291
+ unverified: LADDERS_UNVERIFIED,
292
+ },
293
+ },
294
+ state: { ladder, seasonId, me, gamesAtOnce },
295
+ };
296
+ },
297
+ async execute({ ladder, seasonId, me, gamesAtOnce }) {
298
+ await requireApprovedAccount(ctx, writeAccount(me));
299
+ const info = LADDERS[ladder];
300
+ const base = { ladder, seasonId, gamesAtOnce };
301
+ let vacationEnded = null;
302
+ return sendAndVerify({
303
+ send: async () => {
304
+ const env = await ctx.rpc.call('JoinLadder', Method.JoinLadder, (w) => writeJoinLadderParams(w, { ladder: info.id, gamesAtOnce: gamesAtOnce ?? 1 }));
305
+ vacationEnded = readJoinLadderResult(env.body);
306
+ },
307
+ refused: worded(LADDER_ERRORS),
308
+ unanswered: (failure) => ({
309
+ status: 'unknown',
310
+ outcome: 'unknown',
311
+ ...base,
312
+ warning: `war.app did not confirm the join (${failure}), so you may be on the ladder already. Check with warapp_get_ladder before trying again.`,
313
+ }),
314
+ readBack: async () => (await readSeasonPage(ctx, seasonId)).me,
315
+ unreadable: (failure) => ({ status: 'unconfirmed', outcome: 'unconfirmed', ...base, warning: `The join was sent, but the ladder could not be read back (${failure}).` }),
316
+ classify: (after) => after?.participating
317
+ ? {
318
+ status: 'joined',
319
+ outcome: 'confirmed',
320
+ ...base,
321
+ readBack: { gamesAtOnce: after.gamesAtOnce, rank: after.rank, rating: after.rating },
322
+ ...(vacationEnded ? { vacationEnded: true, vacationNote: 'Joining ended your vacation: you become bootable in an hour, so take your turns.' } : {}),
323
+ }
324
+ : {
325
+ status: 'unconfirmed',
326
+ outcome: 'unconfirmed',
327
+ ...base,
328
+ warning: 'war.app accepted the join, but the season page does not show you on the ladder yet. Check with warapp_get_ladder before trying again.',
329
+ },
330
+ });
331
+ },
332
+ });
333
+ }
334
+ /** What leaving does (war.app's own help, in the client; in our words). */
335
+ const LEAVE_EFFECTS = [
336
+ 'Leaving is not counted as a loss: every ladder game you are already in keeps going, and you still play it out.',
337
+ 'Those games still count toward your ladder rating; war.app only stops creating new ones.',
338
+ "Weekly rank rewards go only to players on the ladder the whole week before they are given out: leaving (and rejoining) costs you that week's.",
339
+ ];
340
+ function registerLeaveLadder(server, ctx) {
341
+ defineGatedWrite(server, {
342
+ title: 'Leave a war.app ladder',
343
+ _meta: mintMeta('change', ['leave ladder', 'quit ladder']),
344
+ }, {
345
+ name: 'warapp_leave_ladder',
346
+ description: "Leave a war.app (Warzone) ladder (war.app's LeaveLadder): war.app stops creating ladder games for you. It is not a loss — " +
347
+ 'war.app keeps every ladder game you are in, you play them out and they still count toward your rating — but leaving costs ' +
348
+ "that week's rank reward. `ladder`: `1v1`, `2v2`, `3v3` or `seasonal`. Refuses a ladder you are not on. Always as the " +
349
+ 'signed-in war.app account; read back from the season page (`left` → `confirmed`, else `unconfirmed`); war.app saying you ' +
350
+ 'are not on it is read back too; no answer is `unknown` — never resend blindly. Read from war.app\'s client code, UNVERIFIED ' +
351
+ `live. ${BRIDGE_NOTE} ${CONFIRM_INJECTION_RULE}`,
352
+ annotations: toolAnnotations({ title: 'Leave a war.app ladder', readOnly: false, destructive: false, idempotent: true, openWorld: true }),
353
+ inputSchema: z.object({ ladder: ladderArg }),
354
+ async plan({ ladder }) {
355
+ const info = LADDERS[ladder];
356
+ const me = await requireMe(ctx);
357
+ const seasonId = await resolveSeason(ctx, ladder, undefined);
358
+ const page = await readSeasonPage(ctx, seasonId);
359
+ if (!page.me?.participating) {
360
+ refuse(`You are not on the ${ladder} ladder, so there is nothing to leave and nothing was sent.`, 'warapp_get_ladders shows your standings.');
361
+ }
362
+ return {
363
+ gate: {
364
+ action: 'warapp.leave_ladder',
365
+ summary: `Leave the war.app ${ladder} ladder (season ${seasonId})`,
366
+ account: writeAccount(me),
367
+ target: `ladder:${info.id}`,
368
+ payload: { method: 'LeaveLadder', ladder: info.id },
369
+ willSend: { ladder, ladderId: info.id },
370
+ preview: {
371
+ warning: `This leaves the ${ladder} ladder: war.app stops creating new ladder games for you.`,
372
+ account: shownAccount(undefined, me),
373
+ ladder: ladderInfo(ladder),
374
+ standing: { rank: page.me.rank, rating: page.me.rating, gamesAtOnce: page.me.gamesAtOnce },
375
+ effects: LEAVE_EFFECTS,
376
+ countsAsLoss: false,
377
+ unverified: LADDERS_UNVERIFIED,
378
+ },
379
+ },
380
+ state: { ladder, seasonId, me },
381
+ };
382
+ },
383
+ async execute({ ladder, seasonId, me }) {
384
+ await requireApprovedAccount(ctx, writeAccount(me));
385
+ const info = LADDERS[ladder];
386
+ const base = { ladder, seasonId };
387
+ return sendAndVerify({
388
+ send: async () => {
389
+ await ctx.rpc.call('LeaveLadder', Method.LeaveLadder, (w) => writeLeaveLadderParams(w, { ladder: info.id }));
390
+ },
391
+ // CannotLeaveLadderNotIn: the client treats it as already left; read back like an accepted leave.
392
+ refused: (e) => (e.code === NOT_IN_LADDER ? 'ignore' : worded(LADDER_ERRORS)(e)),
393
+ unanswered: (failure) => ({
394
+ status: 'unknown',
395
+ outcome: 'unknown',
396
+ ...base,
397
+ warning: `war.app did not confirm the leave (${failure}), so you may already be off the ladder. Check with warapp_get_ladder before trying again.`,
398
+ }),
399
+ readBack: async () => (await readSeasonPage(ctx, seasonId)).me,
400
+ unreadable: (failure) => ({ status: 'unconfirmed', outcome: 'unconfirmed', ...base, warning: `The leave was sent, but the ladder could not be read back (${failure}).` }),
401
+ classify: (after, ignored) => !after?.participating
402
+ ? {
403
+ status: 'left',
404
+ outcome: 'confirmed',
405
+ ...base,
406
+ ...(ignored ? { alreadyOff: true, alreadyOffNote: 'war.app said you were not on the ladder (error 287): nothing changed.' } : {}),
407
+ detail: 'Off the ladder: no new ladder games; the ones you are in keep going and still count.',
408
+ }
409
+ : {
410
+ status: 'unconfirmed',
411
+ outcome: 'unconfirmed',
412
+ ...base,
413
+ warning: 'war.app accepted the leave, but the season page still shows you on the ladder. Check with warapp_get_ladder before trying again.',
414
+ },
415
+ });
416
+ },
417
+ });
418
+ }
@@ -1,10 +1,15 @@
1
1
  // warapp_leave_game: give up the signed-in account's seat in a game that has not started
2
- // (`WaitingForPlayers`) with the web client's DeclineGame (method 64) — the lobby's Decline
3
- // button, gated on the user's confirmation (#217). The encoding is read from the client bundle's
2
+ // (`WaitingForPlayers`), or decline an invitation to one (#652), with the web client's DeclineGame
3
+ // (method 65) — the lobby's Decline button, gated on the user's confirmation (#217). The encoding is read from the client bundle's
4
4
  // writer, verified live 2026-11-14 for an open-seat lobby (docs/WEB-PROTOCOL.md "DeclineGame"). The game is read from GameFeed
5
5
  // first (refused once started, for a seat the account does not hold, and for mod games), and the
6
6
  // leave is reported only once GameFeed (else GetMyGames) shows the account no longer seated —
7
7
  // never from the reply, whose one bool says whether war.app removed the account's chat.
8
+ //
9
+ // Declining an invitation (#652) is the same call: the client's lobby offers its one Decline button to a seat
10
+ // that is Invited or Playing alike, and sends the same parameters (the game id, the mod-hook flag) either way
11
+ // (read from the 6.09 bundle; UNVERIFIED live for an invitation). An invitation holds no seat, so its read-back
12
+ // is GetMyGames: declined once my seat there is no longer Invited, or the whole list no longer carries the game.
8
13
  import { CONFIRM_INJECTION_RULE, toolAnnotations } from '@chrischall/mcp-utils';
9
14
  import { z } from 'zod';
10
15
  import { parseGameId } from '../client.js';
@@ -35,14 +40,15 @@ const LEAVE_ERRORS = {
35
40
  * state decides rather than a guessed wording.
36
41
  */
37
42
  const READ_BACK_ERRORS = new Set([17, 4, 7]);
43
+ const INVITED = 'Invited';
38
44
  /** The signed-in account's seat in lobby `game`, refused unless the account holds one there. */
39
45
  function leavable(game, token) {
40
46
  if (game.state !== LOBBY) {
41
47
  refuse(`Game ${game.id} is not a lobby (game state: ${game.state}): only a game still ${LOBBY} can be left, so nothing was sent.`, 'A game that has started is surrendered with warapp_surrender, not left.');
42
48
  }
43
49
  const seat = mySeat(game, token);
44
- if (!holdsSeat(seat.state)) {
45
- refuse(`You hold no seat in game ${game.id} (your state: ${seat.state ?? 'unknown'}), so there is nothing to leave.`, 'An invitation is declined in war.app; check warapp_my_games.');
50
+ if (!holdsSeat(seat.state) && seat.state !== INVITED) {
51
+ refuse(`You hold no seat in game ${game.id} (your state: ${seat.state ?? 'unknown'}), so there is nothing to leave.`, 'Check warapp_my_games: an open invitation (your seat Invited) is declined with this tool too.');
46
52
  }
47
53
  // Unread settings are treated as possibly modded: the mod-hook flag is sent false, which a
48
54
  // mod game could refuse or mishandle.
@@ -83,18 +89,40 @@ async function confirmLeft(ctx, gameId, me) {
83
89
  return false;
84
90
  }
85
91
  }
92
+ /**
93
+ * #652: whether GetMyGames shows the invitation to `gameId` declined: my seat there no longer Invited (and not
94
+ * seated), or the game gone from a list that is not partial. Nothing read is `false`.
95
+ */
96
+ async function confirmDeclined(ctx, gameId) {
97
+ try {
98
+ const { me, games, partial } = await fetchMyGames(ctx);
99
+ const game = games.find((g) => g.id === gameId);
100
+ if (!game)
101
+ return !partial;
102
+ const seat = game.players.find((p) => p.id === me);
103
+ if (!seat)
104
+ return true;
105
+ const state = playerStateName(seat.stateCode);
106
+ return state !== INVITED && !holdsSeat(state);
107
+ }
108
+ catch {
109
+ return false;
110
+ }
111
+ }
86
112
  export function registerLeaveGameTool(server, ctx) {
87
113
  defineGatedWrite(server, {
88
- title: 'Leave a war.app game that has not started',
89
- _meta: mintMeta('change', ['leave game', 'leave a lobby', 'back out of a game', 'quit a lobby']),
114
+ title: 'Leave a war.app game that has not started, or decline an invitation',
115
+ _meta: mintMeta('change', ['leave game', 'leave a lobby', 'back out of a game', 'quit a lobby', 'decline invitation', 'decline invite']),
90
116
  }, {
91
117
  name: 'warapp_leave_game',
92
118
  description: 'Leave a war.app (Warzone) game that has not started — a lobby still WaitingForPlayers — giving up your ' +
93
119
  "seat (war.app's DeclineGame, the lobby's Decline button; verified live for a lobby joined through an open " +
94
- 'seat). Refuses a game that has started (surrender it with warapp_surrender), a lobby you ' +
95
- 'hold no seat in, and mod games. Always as the signed-in war.app account; reported `left` only once ' +
96
- 'GameFeed (or your games list) no longer shows you seated — `unconfirmed` otherwise, or `unknown` when ' +
97
- `war.app did not answer (never resend blindly). ${BRIDGE_NOTE} ${CONFIRM_INJECTION_RULE}`,
120
+ 'seat). It also declines an invitation to such a game (your seat Invited, as warapp_my_games lists it): the ' +
121
+ "same call, the lobby's same Decline button (UNVERIFIED live for an invitation), reported `declined` once " +
122
+ 'your games list no longer shows the invitation. Refuses a game that has started (surrender it with ' +
123
+ 'warapp_surrender), a lobby you hold no seat or invitation in, and mod games. Always as the signed-in war.app ' +
124
+ 'account; reported `left` only once GameFeed (or your games list) no longer shows you seated — `unconfirmed` ' +
125
+ `otherwise, or \`unknown\` when war.app did not answer (never resend blindly). ${BRIDGE_NOTE} ${CONFIRM_INJECTION_RULE}`,
98
126
  annotations: toolAnnotations({
99
127
  title: 'Leave a war.app lobby',
100
128
  readOnly: false,
@@ -108,6 +136,33 @@ export function registerLeaveGameTool(server, ctx) {
108
136
  const token = await requireMe(ctx);
109
137
  const seat = leavable(game, token);
110
138
  const teamGame = isTeamGame(game.players);
139
+ const gameView = {
140
+ id: game.id,
141
+ name: game.name === undefined ? null : untrustedText(game.name),
142
+ state: game.state,
143
+ players: game.players.filter((p) => holdsSeat(p.state)).length,
144
+ };
145
+ if (seat.state === INVITED) {
146
+ return {
147
+ gate: {
148
+ action: 'warapp.decline_invite',
149
+ summary: `Decline the invitation to war.app game ${game.id}, which has not started`,
150
+ account: writeAccount(seat.id),
151
+ target: game.id,
152
+ payload: { method: 'DeclineGame', gameId: game.id },
153
+ willSend: { game: game.id, player: untrustedText(seat.name) },
154
+ preview: {
155
+ warning: `This declines your invitation to game ${game.id}; only the host can invite you again.` +
156
+ (teamGame ? ' It is a team game: declining can leave the team you were invited to a player short.' : ''),
157
+ account: shownAccount(seat.name, seat.id),
158
+ game: gameView,
159
+ unverified: 'Declining an invitation with DeclineGame is read from the client bundle, UNVERIFIED live.',
160
+ untrusted: UNTRUSTED_PREVIEW_NOTE,
161
+ },
162
+ },
163
+ state: { gameId: game.id, name: game.name ?? `game ${game.id}`, me: seat.id, invitation: true },
164
+ };
165
+ }
111
166
  return {
112
167
  gate: {
113
168
  action: 'warapp.leave_game',
@@ -122,19 +177,14 @@ export function registerLeaveGameTool(server, ctx) {
122
177
  'still free, and war.app may remove the chat messages you sent to the game.' +
123
178
  (teamGame ? ' It is a team game: leaving can leave your teammates a player short.' : ''),
124
179
  account: shownAccount(seat.name, seat.id),
125
- game: {
126
- id: game.id,
127
- name: game.name === undefined ? null : untrustedText(game.name),
128
- state: game.state,
129
- players: game.players.filter((p) => holdsSeat(p.state)).length,
130
- },
180
+ game: gameView,
131
181
  untrusted: UNTRUSTED_PREVIEW_NOTE,
132
182
  },
133
183
  },
134
184
  state: { gameId: game.id, name: game.name ?? `game ${game.id}`, me: seat.id },
135
185
  };
136
186
  },
137
- async execute({ gameId, name, me }) {
187
+ async execute({ gameId, name, me, invitation }) {
138
188
  await requireApprovedAccount(ctx, writeAccount(me));
139
189
  const game = { id: gameId, name };
140
190
  let chatRemoved;
@@ -163,18 +213,26 @@ export function registerLeaveGameTool(server, ctx) {
163
213
  warning: `war.app did not confirm the leave (${failure}), so you may already have left. ${check}`,
164
214
  }),
165
215
  // Never throws: nothing read is "not shown".
166
- readBack: () => confirmLeft(ctx, gameId, me),
216
+ readBack: () => (invitation ? confirmDeclined(ctx, gameId) : confirmLeft(ctx, gameId, me)),
167
217
  unreadable: () => ({ status: 'unconfirmed', outcome: 'unconfirmed', game, warning: check }),
168
218
  classify: (left) => left
169
- ? { status: 'left', outcome: 'confirmed', game, ...extra() }
170
- : {
171
- status: 'unconfirmed',
172
- outcome: 'unconfirmed',
173
- game,
174
- ...extra(),
175
- warning: 'war.app accepted the request, but GameFeed still shows you seated (or could not be read, and ' +
176
- `your games list does not show the seat given up), so the leave could not be confirmed. ${check}`,
177
- },
219
+ ? { status: invitation ? 'declined' : 'left', outcome: 'confirmed', game, ...extra() }
220
+ : invitation
221
+ ? {
222
+ status: 'unconfirmed',
223
+ outcome: 'unconfirmed',
224
+ game,
225
+ ...extra(),
226
+ warning: `war.app accepted the request, but your games list still shows the invitation (or could not be read), so the decline could not be confirmed. ${check}`,
227
+ }
228
+ : {
229
+ status: 'unconfirmed',
230
+ outcome: 'unconfirmed',
231
+ game,
232
+ ...extra(),
233
+ warning: 'war.app accepted the request, but GameFeed still shows you seated (or could not be read, and ' +
234
+ `your games list does not show the seat given up), so the leave could not be confirmed. ${check}`,
235
+ },
178
236
  });
179
237
  },
180
238
  });
@@ -327,8 +327,8 @@ function beginFirstError(game) {
327
327
  export async function loadLiveTerritories(ctx, game) {
328
328
  return (await loadLiveGame(ctx, game)).territories;
329
329
  }
330
- /** The issue tracking the move to the client war.app now serves (protocol 243), named in the window-closed error. */
331
- export const PROTOCOL_UPDATE_ISSUE = 'https://github.com/chrischall/warapp-mcp/issues/340';
330
+ /** The issue tracking the move to the client war.app now serves (protocol 244), named in the window-closed error. */
331
+ export const PROTOCOL_UPDATE_ISSUE = 'https://github.com/chrischall/warapp-mcp/issues/626';
332
332
  /**
333
333
  * One line for a tool's warnings while a stand-in decodes: war.app ships a client this server cannot read
334
334
  * yet, so an older build it still answers is decoding, since when. `undefined` without a stand-in.