@chrischall/warapp-mcp 0.24.0 → 0.26.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.
@@ -2,6 +2,7 @@
2
2
  // (`GetChat=true`, channels unknown), with what is new since the messages were last marked seen; send
3
3
  // through the web-client protocol (`SendChat`) publicly, to my team or privately, gated on the user's
4
4
  // confirmation — a message reaches other players and cannot be unsent.
5
+ import { WarappServerError } from '../protocol/rpc.js';
5
6
  import { CONFIRM_INJECTION_RULE, McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
6
7
  import { z } from 'zod';
7
8
  import { CHAT_CHANNELS, feedChatLines, fillFromFeed, mergeChatLines, oldestId, readCreateGameGroupReply, readGameGroups, readGameRefreshChat, readMessageHistoryReply, readSendChatReply, } from '../chat.js';
@@ -9,7 +10,7 @@ import { advanceCursor, markedChannels, markNew, readChatCursor, unreadCounts, w
9
10
  import { parseGameId } from '../client.js';
10
11
  import { inGameId, inGameOf, playersByInGameId } from '../live.js';
11
12
  import { decodeChatLinks, encodeChatLinks, hasChatLinkMarkers } from '../chat-links.js';
12
- import { CHAT_CHANNEL_PUBLIC, Method, writeGameRefreshParams, writeRetrieveChatParams, writeCreateGameGroupParams, writeRetrievePrivateMessageHistoryParams, writeSendChatParams, } from '../protocol/methods.js';
13
+ import { CHAT_CHANNEL_PUBLIC, Method, writeGameRefreshParams, writeRetrieveChatParams, writeCreateGameGroupParams, writeRetrieveGameGroupMessageHistoryParams, writeRetrievePrivateMessageHistoryParams, writeSendChatParams, } from '../protocol/methods.js';
13
14
  import { carriesTeam } from '../teams.js';
14
15
  import { gameIdArg, readAnnotations, respond, UNTRUSTED_PREVIEW_NOTE, untrustedBody, untrustedDescription, untrustedText, } from './common.js';
15
16
  import { checkMessageCommitments, commitmentsArg, COMMITMENTS_NOTE, DEFAULT_PLAN_CHECKED } from './commitments.js';
@@ -28,29 +29,128 @@ const MAX_CHAT_LENGTH = 2000;
28
29
  export const MAX_GROUP_RECIPIENTS = 10;
29
30
  /** The most characters of a new game group's name. */
30
31
  const MAX_GROUP_NAME = 50;
31
- /** A new game group's name when none is given: it is shown to the members. */
32
+ /** A new game group's name when no other can be made (the members' names unreadable): it is shown to the members. */
32
33
  export const DEFAULT_GROUP_NAME = 'Group chat';
34
+ /**
35
+ * The waits before resending a message to a game group this call just created, after war.app refused it with 752
36
+ * (NotInGameGroup). Live 2026-11-30: right after CreateGameGroup war.app refused a message to the new group's right id
37
+ * (read back from the chat), and took the same message minutes later. A refusal posts nothing, so resending is safe.
38
+ * Mutable for tests only.
39
+ */
40
+ export const GROUP_SEND_RETRY = { delaysMs: [2_000, 4_000, 8_000, 16_000] };
41
+ const NOT_IN_GAME_GROUP = 752;
42
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
43
+ const CONTROL_CHARS = /\p{Cc}/gu;
44
+ /** A name for war.app: control characters out, whitespace runs one space, trimmed. */
45
+ const cleanName = (name) => name.replace(CONTROL_CHARS, '').replace(/\s+/g, ' ').trim();
46
+ /** `text` cut to MAX_GROUP_NAME characters with an ellipsis, never splitting a surrogate pair. */
47
+ function cutName(text) {
48
+ if (text.length <= MAX_GROUP_NAME)
49
+ return text;
50
+ let end = MAX_GROUP_NAME - 1;
51
+ const code = text.charCodeAt(end - 1);
52
+ if (code >= 0xd800 && code <= 0xdbff)
53
+ end -= 1;
54
+ return `${text.slice(0, end)}…`;
55
+ }
56
+ /**
57
+ * A new game group's default name from its members' names, the first (me) first: "Ann, Bob and Cat". Over
58
+ * {@link MAX_GROUP_NAME} characters it names as many as fit, then "and N more"; still too long, it is cut to 49 and an
59
+ * ellipsis. The raw names (war.app shows the name; only the preview delimits it), control characters stripped; with
60
+ * fewer than two names left, {@link DEFAULT_GROUP_NAME}.
61
+ */
62
+ export function defaultGroupName(names) {
63
+ const clean = names.map(cleanName).filter((n) => n !== '');
64
+ if (clean.length < 2)
65
+ return DEFAULT_GROUP_NAME;
66
+ const and = (first, last) => `${first.join(', ')} and ${last}`;
67
+ const full = and(clean.slice(0, -1), clean.at(-1));
68
+ if (full.length <= MAX_GROUP_NAME)
69
+ return full;
70
+ for (let k = clean.length - 1; k >= 1; k--) {
71
+ const some = and(clean.slice(0, k), `${clean.length - k} more`);
72
+ if (some.length <= MAX_GROUP_NAME)
73
+ return some;
74
+ }
75
+ return cutName(and(clean.slice(0, 1), `${clean.length - 1} more`));
76
+ }
77
+ /** What the preview says of a new group's name: it cannot be changed. */
78
+ const GROUP_NAME_NOTE = 'war.app cannot rename or delete a game group, and the members see its name and a creation line in the game chat, ' +
79
+ 'so choose the name now (`group_name`).';
33
80
  /** CreateGameGroup's refusals as the client words them. */
34
81
  const GROUP_REFUSALS = {
35
82
  227: 'a player in it has blocked you',
36
83
  751: 'this game does not allow game groups',
84
+ 752: 'you are not in that group',
85
+ 753: 'you do not moderate that group',
37
86
  };
38
87
  /** Ids as "1, 2 and 3". */
39
88
  const listIds = (ids) => (ids.length > 1 ? `${ids.slice(0, -1).join(', ')} and ${ids.at(-1)}` : String(ids[0]));
89
+ /** Whether a group holds exactly me and `members` (in-game ids). */
90
+ const sameMembers = (g, meInGame, members) => {
91
+ const want = new Set([meInGame, ...members]);
92
+ return g.members !== null && new Set(g.members).size === want.size && g.members.every((m) => want.has(m));
93
+ };
94
+ /**
95
+ * The id of the group this call just created, from the chat GameRefresh (the read warapp_get_chat makes): the game's
96
+ * newest group of exactly me and `members` under `name` when the reply lists the groups, else the newest line in a
97
+ * group with no sender whose text names it (the creation line). Live 2026-11-30 the id read from CreateGameGroup's
98
+ * reply was refused (752), and the chat's id worked. `undefined` when neither shows it or the read fails. Never throws.
99
+ */
100
+ async function createdGroupInChat(ctx, gameId, lobby, meInGame, members, name, replyId) {
101
+ try {
102
+ const env = await ctx.rpc.call('GameRefresh', Method.GameRefresh, (w) => writeGameRefreshParams(w, { gameId, chat: true, nonChat: false, lobby }));
103
+ const bundle = await ctx.bundle();
104
+ const groups = readGameGroups(bundle, env.body.fork());
105
+ const group = groups
106
+ ?.filter((g) => g.gameId === gameId && g.name === name && sameMembers(g, meInGame, members))
107
+ .sort((a, b) => b.id - a.id)[0];
108
+ if (group)
109
+ return group.id;
110
+ // Message ids are decimal text, past a double's precision: the newest is the longest, then the greatest; else the last.
111
+ const newer = (a, b) => {
112
+ const [x, y] = [a.id ?? '', b.id ?? ''];
113
+ return x.length !== y.length ? x.length > y.length : x >= y;
114
+ };
115
+ // #682: a creation line only names the group by its name, which an older group may share. War.app numbers groups
116
+ // upwards (live: 11193, then 11194), so only the line of the game's highest group read, at or above the reply's id,
117
+ // can be the new group's: else the line is an older group's, and its players must not get the message.
118
+ const lines = readGameRefreshChat(bundle, env.body) ?? [];
119
+ const highest = Math.max(-Infinity, ...lines.flatMap((l) => (l.group !== undefined ? [l.group] : [])));
120
+ let line;
121
+ for (const l of lines) {
122
+ if (l.group !== undefined && l.sender === null && l.text.includes(name) && (!line || newer(l, line)))
123
+ line = l;
124
+ }
125
+ if (line?.group === undefined || line.group !== highest || (replyId !== undefined && line.group < replyId))
126
+ return undefined;
127
+ return line.group;
128
+ }
129
+ catch {
130
+ return undefined;
131
+ }
132
+ }
40
133
  /**
41
134
  * The game's newest group holding exactly me and `members` (in-game ids), from one GameRefresh with the game details.
42
135
  * `read: false` when the groups could not be read (a failed request, or a reply without them). Never throws.
43
136
  */
44
137
  async function existingGroup(ctx, game, meInGame, members) {
138
+ // Which GameRefresh carries the groups is UNVERIFIED live (live, the details-only read did not): the chat read
139
+ // warapp_get_chat makes first, then the details read.
140
+ const read = async (chat) => {
141
+ try {
142
+ const env = await ctx.rpc.call('GameRefresh', Method.GameRefresh, (w) => writeGameRefreshParams(w, { gameId: game.id, chat, nonChat: !chat, lobby: game.state === 'WaitingForPlayers' }));
143
+ return readGameGroups(await ctx.bundle(), env.body);
144
+ }
145
+ catch {
146
+ return undefined;
147
+ }
148
+ };
45
149
  try {
46
- const env = await ctx.rpc.call('GameRefresh', Method.GameRefresh, (w) => writeGameRefreshParams(w, { gameId: game.id, chat: false, nonChat: true, lobby: game.state === 'WaitingForPlayers' }));
47
- const groups = readGameGroups(await ctx.bundle(), env.body);
150
+ const groups = (await read(true)) ?? (await read(false));
48
151
  if (!groups)
49
152
  return { read: false };
50
- const want = new Set([meInGame, ...members]);
51
- const same = groups
52
- .filter((g) => g.gameId === game.id && g.members !== null && new Set(g.members).size === want.size && g.members.every((m) => want.has(m)))
53
- .sort((a, b) => b.id - a.id);
153
+ const same = groups.filter((g) => g.gameId === game.id && sameMembers(g, meInGame, members)).sort((a, b) => b.id - a.id);
54
154
  return same[0] ? { read: true, group: same[0] } : { read: true };
55
155
  }
56
156
  catch {
@@ -94,9 +194,11 @@ export async function readChat(ctx, game, me) {
94
194
  if (me) {
95
195
  try {
96
196
  const env = await ctx.rpc.call('GameRefresh', Method.GameRefresh, (w) => writeGameRefreshParams(w, { gameId: game.id, chat: true, nonChat: false, lobby: game.state === 'WaitingForPlayers' }));
97
- const refreshed = readGameRefreshChat(await ctx.bundle(), env.body);
197
+ const bundle = await ctx.bundle();
198
+ const groups = readGameGroups(bundle, env.body.fork());
199
+ const refreshed = readGameRefreshChat(bundle, env.body);
98
200
  if (refreshed) {
99
- const { lines, olderUnread } = await withOlder(ctx, game, me, refreshed);
201
+ const { lines, olderUnread } = await withOlder(ctx, game, me, refreshed, groups);
100
202
  const read = lines.length < (feed?.length ?? 0) ? withFeed(lines, feed) : { source: 'web', lines };
101
203
  return olderUnread.length ? { ...read, olderUnread } : read;
102
204
  }
@@ -109,6 +211,19 @@ export async function readChat(ctx, game, me) {
109
211
  }
110
212
  /** The most private conversations whose history one chat read asks for (one request each). */
111
213
  export const MAX_PRIVATE_HISTORY = 8;
214
+ /** The most game groups whose history one chat read asks for (one request each, #697). */
215
+ export const MAX_GROUP_HISTORY = 8;
216
+ /**
217
+ * The ids of the game's groups I am in, newest first (#697): those the chat lines name, and those a groups list
218
+ * names (a group whose members cannot be read is kept: war.app lists a player's own groups).
219
+ */
220
+ export function myGroupIds(lines, groups, gameId, meInGame) {
221
+ const ids = new Set(lines.flatMap((l) => (l.group !== undefined ? [l.group] : [])));
222
+ for (const g of groups ?? [])
223
+ if (g.gameId === gameId && (g.members === null || g.members.includes(meInGame)))
224
+ ids.add(g.id);
225
+ return [...ids].sort((a, b) => b - a);
226
+ }
112
227
  /**
113
228
  * GameRefresh's chat with the messages it leaves out added (#363, #387). Sent `-1` markers (as the client
114
229
  * sends on a first load), GameRefresh leaves out messages war.app counts as seen — live, an own team message
@@ -118,7 +233,7 @@ export const MAX_PRIVATE_HISTORY = 8;
118
233
  * private one per other human seat with an in-game id (at most {@link MAX_PRIVATE_HISTORY}) unless the game
119
234
  * turns private messaging off. A read that fails or does not decode adds nothing and names its channels.
120
235
  */
121
- async function withOlder(ctx, game, me, refreshed) {
236
+ async function withOlder(ctx, game, me, refreshed, groupsRead) {
122
237
  let lines = refreshed;
123
238
  const olderUnread = [];
124
239
  const history = async (name, method, write) => {
@@ -158,8 +273,45 @@ async function withOlder(ctx, game, me, refreshed) {
158
273
  if (failed)
159
274
  olderUnread.push('private');
160
275
  }
276
+ // #697: GameRefresh leaves out a game group's messages once war.app counts them as seen (live 2026-12-01: a group
277
+ // message the client showed was missing). The group's history button sends RetrieveGameGroupMessageHistory (47),
278
+ // per group I am in. The chat read names a group only by its lines, so when it names none and no groups list came
279
+ // with it, one details read (GameRefresh, chat off) gives the game's groups. Groups are private conversations of
280
+ // several players, so a game that turns private messaging off, or with fewer than two other human seats, is not asked.
281
+ const others = game.players.filter((p) => !p.isAI && inGameOf(p) !== undefined && inGameOf(p) !== me.inGameId).length;
282
+ if (game.settings?.privateMessaging !== false && others >= 2) {
283
+ let groups = groupsRead;
284
+ let ids = myGroupIds(lines, groups, game.id, me.inGameId);
285
+ if (!ids.length && groups === undefined) {
286
+ try {
287
+ const env = await ctx.rpc.call('GameRefresh', Method.GameRefresh, (w) => writeGameRefreshParams(w, { gameId: game.id, chat: false, nonChat: true, lobby: game.state === 'WaitingForPlayers' }));
288
+ groups = readGameGroups(await ctx.bundle(), env.body);
289
+ }
290
+ catch {
291
+ // No groups read: none asked.
292
+ }
293
+ ids = myGroupIds(lines, groups, game.id, me.inGameId);
294
+ }
295
+ let failed = false;
296
+ for (const group of ids.slice(0, MAX_GROUP_HISTORY)) {
297
+ const got = await history('RetrieveGameGroupMessageHistory', Method.RetrieveGameGroupMessageHistory, (w) => writeRetrieveGameGroupMessageHistoryParams(w, { gameId: game.id, before: oldestId(lines, (l) => l.group === group), group }));
298
+ // A history line names its group; one that does not (read as public: the client sends a group message on channel
299
+ // -1) is the group asked for.
300
+ if (got)
301
+ lines = mergeChatLines(lines, got.map((l) => (l.group === undefined && l.to === undefined ? inGroup(l, group) : l)));
302
+ else
303
+ failed = true;
304
+ }
305
+ if (failed)
306
+ olderUnread.push('unknown');
307
+ }
161
308
  return { lines, olderUnread };
162
309
  }
310
+ /** A line of a group's history that does not name its group, as a message in it. */
311
+ function inGroup(l, group) {
312
+ const { team: _team, ...rest } = l;
313
+ return { ...rest, channel: 'unknown', group };
314
+ }
163
315
  /** A web read shorter than GameFeed's list, filled from it (#313). */
164
316
  function withFeed(web, feed) {
165
317
  const counts = `The web client's read returned fewer messages (${web.length}) than GameFeed's chat (${feed.length})`;
@@ -351,6 +503,8 @@ export function shown(line, isNew, players, byInGame, me, map) {
351
503
  channel: line.channel,
352
504
  ...(line.team !== undefined ? { team: line.team } : {}),
353
505
  ...(to ? { to } : {}),
506
+ // A game-group message's group id (warapp_send_chat's `group_id` sends into it).
507
+ ...(line.group !== undefined ? { group: line.group } : {}),
354
508
  // #387: a private message addressed to me, so a watcher can flag diplomacy the moment it arrives.
355
509
  ...(line.channel === 'private' && me !== undefined && line.to === me.inGameId ? { toMe: true } : {}),
356
510
  // #634: what the sender shared and who reacted, all their own words (delimited).
@@ -363,13 +517,15 @@ export function shown(line, isNew, players, byInGame, me, map) {
363
517
  }
364
518
  /** A message's #415 fields: its `intent`, and `advice` when it was advised on; none for mine or a system line. */
365
519
  export const readingFields = (r) => r ? { intent: r.intent, ...(r.advice ? { advice: r.advice } : {}) } : {};
366
- const CHANNEL_ARGS = ['all', ...CHAT_CHANNELS];
520
+ // #697: `group` picks the game-group messages (their channel is `unknown`, each with its `group`).
521
+ const CHANNEL_ARGS = ['all', ...CHAT_CHANNELS, 'group'];
367
522
  export function registerChatTools(server, ctx, opts = {}) {
368
523
  server.registerTool('warapp_get_chat', {
369
524
  title: 'Read a war.app game chat',
370
525
  description: untrustedDescription('Read the chat of a war.app (Warzone) game: the most recent messages, oldest first, each with its sender ' +
371
526
  '(`from`, a delimited name; `fromId`, the GameFeed id), `text` (delimited), `time` (plus `localTime` when WARAPP_TIMEZONE is set), `turn`, `channel` ' +
372
- '(`public`, `team` with its `team`, `private` with its recipient `to`, or `unknown`), `mine`, and `new` ' +
527
+ '(`public`, `team` with its `team`, `private` with its recipient `to`, or `unknown`; a game-group message is `unknown` ' +
528
+ 'with its `group` id), `mine`, and `new` ' +
373
529
  '(not yet marked seen, and not mine), plus `unread` per channel over the whole chat. The chat is read ' +
374
530
  "through your signed-in war.app tab or linked session (the web client's GameRefresh, which tells the " +
375
531
  'channels apart), else from GameFeed (channels `unknown`); when the web read has fewer messages than ' +
@@ -394,7 +550,7 @@ export function registerChatTools(server, ctx, opts = {}) {
394
550
  .max(1000)
395
551
  .optional()
396
552
  .describe(`Most recent messages to return (default ${DEFAULT_LIMIT}).`),
397
- channel: z.enum(CHANNEL_ARGS).optional().describe('Only this channel: public, team, private or unknown (default all).'),
553
+ channel: z.enum(CHANNEL_ARGS).optional().describe('Only this channel: public, team, private, unknown, or group (the game-group messages, part of unknown) (default all).'),
398
554
  mark_seen: z
399
555
  .boolean()
400
556
  .optional()
@@ -416,13 +572,13 @@ export function registerChatTools(server, ctx, opts = {}) {
416
572
  }
417
573
  const { fresh, unread, cursor } = await chatUnread(ctx, game.id, me, read.lines);
418
574
  const byInGame = playersByInGameId(game.players);
419
- const wanted = (l) => channel === undefined || channel === 'all' || l.channel === channel;
575
+ const wanted = (l) => channel === undefined || channel === 'all' || (channel === 'group' ? l.group !== undefined : l.channel === channel);
420
576
  const picked = read.lines.map((l, i) => [l, fresh[i], i]).filter(([l]) => wanted(l));
421
577
  // #415: each message another player sent is labelled, and an unread one advised on (this machine's logs only).
422
578
  const reading = chatReader(read.lines, game, me, await chatAdviceContext(ctx, game, me));
423
579
  const messages = picked.slice(-n).map(([l, isNew, i]) => ({ ...shown(l, isNew, game.players, byInGame, me, game.map), ...readingFields(reading(i, isNew)) }));
424
580
  const marked = mark_seen
425
- ? await markChatSeen(ctx, game.id, me, read, cursor, channel === undefined || channel === 'all' ? [...CHAT_CHANNELS] : [channel])
581
+ ? await markChatSeen(ctx, game.id, me, read, cursor, channel === undefined || channel === 'all' ? [...CHAT_CHANNELS] : [channel === 'group' ? 'unknown' : channel])
426
582
  : undefined;
427
583
  // Unread messages the mark covered that `limit` kept out of `messages`.
428
584
  const markedUnshown = marked ? picked.slice(0, Math.max(0, picked.length - n)).filter(([, isNew]) => isNew).length : 0;
@@ -471,7 +627,9 @@ export function registerChatTools(server, ctx, opts = {}) {
471
627
  name: 'warapp_send_chat',
472
628
  description: 'Post a chat message in a war.app (Warzone) game — to the whole game, to your team (`channel: "team"`, in ' +
473
629
  'a team game), or privately to one named player (`to`), or to several together (`to` as a list: a war.app game ' +
474
- 'group, reused when one of exactly you and them exists, else created first, named by `group_name`; UNVERIFIED live); ' +
630
+ 'group, reused when one of exactly you and them exists, else created first in the same call, named by `group_name` or ' +
631
+ "by default the members' names, yours first — war.app cannot rename or delete a group, so choose the name — and its id " +
632
+ 'read back from the game chat before the message goes to it; UNVERIFIED live); ' +
475
633
  'private sends are refused when the game turns private messages off. The message reaches other players and cannot be unsent. Sent through your signed-in war.app tab ' +
476
634
  '(ContextMint Bridge); the game is read from GameFeed first, so the GameFeed credentials are needed too. ' +
477
635
  "The result's `outcome` is `confirmed` when war.app's reply lists it as your newest message on that " +
@@ -481,12 +639,15 @@ export function registerChatTools(server, ctx, opts = {}) {
481
639
  'orders already submitted) and the agreement ledger, a commitment they do not carry refuses the send, and once ' +
482
640
  'the message is confirmed or accepted they are recorded in the ledger as yours (a propose or accept creates or ' +
483
641
  'advances the agreement, a notice moves it to notice-by-me); warapp_submit_turn warns when later orders break one. ' +
642
+ 'An n-way truce (a pact "p<n>"): propose or accept with `players`, or accept/notice by its id — every party must read ' +
643
+ 'the message (a game group holding all of them, or public), and a notice on one of three or more needs `rest` (ask the owner). ' +
484
644
  'Pass `automated: true` for a reply the owner did not tell you to send (e.g. an advice\'s `send`): it is refused ' +
485
645
  'unless WARAPP_CHAT_AUTOMATION is on (off by default: the owner sends replies), and even then it is confirm-gated. ' +
486
646
  'Link a territory or bonus as players see it in the official client with `[[t:<id or name>]]` / `[[b:<id or name>]]` ' +
487
647
  'in the message, or set `link_territories` to link every territory name it mentions: names resolve against the ' +
488
648
  "game's map (exact, case-insensitive; an unknown or shared name is refused, listing the ids), and the preview shows " +
489
- 'the message as rendered with its `links`. ' +
649
+ 'the message as rendered with its `links`. Every send is confirmed with the two-step preview and `confirmToken`, ' +
650
+ 'never an elicitation prompt (live, a client accepted one the owner never saw). ' +
490
651
  `${CONFIRM_INJECTION_RULE}`,
491
652
  annotations: toolAnnotations({
492
653
  title: 'Send a war.app chat message',
@@ -524,8 +685,17 @@ export function registerChatTools(server, ctx, opts = {}) {
524
685
  .min(1)
525
686
  .max(MAX_GROUP_NAME)
526
687
  .optional()
527
- .describe(`A list \`to\` only: the name of the game group if one has to be created (default "${DEFAULT_GROUP_NAME}"; the members see it). ` +
528
- 'An existing group of exactly these players is reused, keeping its name.'),
688
+ .describe('A list `to` only (a list of one player with it makes a group of you and that player): the name of the game group if one has to be created (default: the members\' names, yours first, ' +
689
+ `e.g. "Ann, Bob and Cat", or "Ann, Bob and 2 more" past ${MAX_GROUP_NAME} characters). The members see it, and ` +
690
+ 'war.app cannot rename or delete a group: choose it before confirming. An existing group of exactly these players ' +
691
+ 'is reused, keeping its name.'),
692
+ group_id: z
693
+ .number()
694
+ .int()
695
+ .positive()
696
+ .optional()
697
+ .describe('A list `to` only (a list of one player with it sends to a group of you and that player): send into this existing game group (its id, as warapp_get_chat shows a group message\'s `group`) ' +
698
+ 'instead of finding or creating one. war.app refuses it when you are not in that group.'),
529
699
  commitments: commitmentsArg,
530
700
  automated: z
531
701
  .boolean()
@@ -533,7 +703,7 @@ export function registerChatTools(server, ctx, opts = {}) {
533
703
  .describe('true when you send a reply the owner did not tell you to send (an automated reply). Refused unless ' +
534
704
  'WARAPP_CHAT_AUTOMATION is on; default false (a send the owner asked for).'),
535
705
  }),
536
- async plan({ game_id, message, channel, to, group_name, commitments, automated, link_territories }) {
706
+ async plan({ game_id, message, channel, to, group_name, group_id, commitments, automated, link_territories }) {
537
707
  // #415: an automated reply is refused with the gate off, before any request.
538
708
  const auto = automated === true;
539
709
  if (auto && (ctx.chatAutomation ?? chatAutomationMode(opts.env ?? process.env)) !== 'on') {
@@ -542,9 +712,10 @@ export function registerChatTools(server, ctx, opts = {}) {
542
712
  });
543
713
  }
544
714
  const gameId = parseGameId(game_id);
545
- // A list `to` of two or more players is a game group; a list of one is a private message to that player.
715
+ // A list `to` of two or more players is a game group; a list of one is a private message to that player,
716
+ // unless `group_name` or `group_id` asks for a game group (of me and that player).
546
717
  const toList = Array.isArray(to) ? to.filter((x) => String(x).trim() !== '') : undefined;
547
- const grouped = toList !== undefined && toList.length >= 2;
718
+ const grouped = toList !== undefined && (toList.length >= 2 || (toList.length === 1 && (group_name !== undefined || group_id !== undefined)));
548
719
  const single = toList ? (toList.length === 1 ? toList[0] : undefined) : Array.isArray(to) ? undefined : to;
549
720
  const privately = grouped || (single !== undefined && String(single).trim() !== '');
550
721
  if (toList !== undefined && toList.length === 0) {
@@ -555,6 +726,16 @@ export function registerChatTools(server, ctx, opts = {}) {
555
726
  hint: 'Pass `to` as a list of the players to message together, or drop `group_name`.',
556
727
  });
557
728
  }
729
+ if (group_id !== undefined && !grouped) {
730
+ throw new McpToolError('`group_id` names a game group, which only a list of two or more players in `to` uses: nothing was sent.', {
731
+ hint: 'Pass `to` as the list of the players in that group (not you), or drop `group_id`.',
732
+ });
733
+ }
734
+ if (group_id !== undefined && group_name !== undefined) {
735
+ throw new McpToolError('`group_name` is for a group this call creates, and `group_id` sends into an existing one: nothing was sent.', {
736
+ hint: 'Drop `group_name` (the group keeps its name) or drop `group_id`.',
737
+ });
738
+ }
558
739
  if (privately && channel === 'team') {
559
740
  throw new McpToolError('A private message (`to`) cannot also go to the team channel: nothing was sent.', {
560
741
  hint: 'Omit `to` to message your team, or omit `channel` to message one player privately.',
@@ -621,13 +802,25 @@ export function registerChatTools(server, ctx, opts = {}) {
621
802
  }
622
803
  kind = 'group';
623
804
  const members = people.map((p) => inGameId(p));
624
- const found = await existingGroup(ctx, game, meInGame, members);
625
- groupsRead = found.read;
626
- group = {
627
- ...(found.group ? { id: found.group.id, name: untrustedText(found.group.name) } : { name: group_name ?? DEFAULT_GROUP_NAME }),
628
- members,
629
- recipients: people.map((p) => ({ id: p.id, name: untrustedText(p.name) })),
630
- };
805
+ const recipients = people.map((p) => ({ id: p.id, name: untrustedText(p.name) }));
806
+ if (group_id !== undefined) {
807
+ // The caller names the group: no read, nothing created; war.app checks I am in it.
808
+ group = { id: group_id, name: '', members, recipients, given: true };
809
+ }
810
+ else {
811
+ const found = await existingGroup(ctx, game, meInGame, members);
812
+ groupsRead = found.read;
813
+ // A new group's name: the one given, else the members' names, mine first (raw: war.app shows it).
814
+ const given = group_name === undefined ? '' : cleanName(group_name);
815
+ const name = given || defaultGroupName([seat?.name ?? '', ...people.map((p) => p.name)]);
816
+ group = {
817
+ ...(found.group
818
+ ? { id: found.group.id, name: untrustedText(found.group.name) }
819
+ : { name, lobby: game.state === 'WaitingForPlayers' }),
820
+ members,
821
+ recipients,
822
+ };
823
+ }
631
824
  }
632
825
  else if (privately) {
633
826
  const p = resolvePlayer(game.players, single);
@@ -670,7 +863,7 @@ export function registerChatTools(server, ctx, opts = {}) {
670
863
  }
671
864
  const groupIds = group ? listIds(group.recipients.map((r) => r.id)) : '';
672
865
  const words = kind === 'group'
673
- ? `privately to players ${groupIds} only, in a game group (${group.id !== undefined ? `group ${group.id}, which exists` : 'created first'})`
866
+ ? `privately to ${group.recipients.length === 1 ? 'player' : 'players'} ${groupIds} only, in a game group (${group.id !== undefined ? `group ${group.id}, which exists` : 'created first'})`
674
867
  : kind === 'private'
675
868
  ? `privately to player ${shownRecipient.id} only`
676
869
  : kind === 'team'
@@ -680,8 +873,11 @@ export function registerChatTools(server, ctx, opts = {}) {
680
873
  return {
681
874
  gate: {
682
875
  action: 'warapp.send_chat',
876
+ // Live 2026-11-30 a client accepted the elicitation with no prompt shown to the owner: every send is the
877
+ // two-step preview + confirmToken, never an elicitation (every other confirm setting still applies).
878
+ env: { ...(opts.env ?? process.env), MCP_CONFIRM_ELICITATION: 'off' },
683
879
  summary: kind === 'group'
684
- ? `Send a group chat message to players ${groupIds} in game ${gameId}`
880
+ ? `Send a group chat message to ${group.recipients.length === 1 ? 'player' : 'players'} ${groupIds} in game ${gameId}`
685
881
  : kind === 'private'
686
882
  ? `Send a private chat message to player ${shownRecipient.id} in game ${gameId}`
687
883
  : kind === 'team'
@@ -719,15 +915,23 @@ export function registerChatTools(server, ctx, opts = {}) {
719
915
  ...(group
720
916
  ? {
721
917
  recipients: group.recipients,
722
- group: group.id !== undefined
723
- ? { id: group.id, name: group.name, reused: true }
724
- : { create: true, name: untrustedText(group.name) },
725
- groupNote: (group.id !== undefined
726
- ? `The game's group ${group.id} holds exactly you and these players: the message goes there.`
727
- : groupsRead
728
- ? 'No game group of exactly you and these players exists: one is created first, named as shown (the members see the name).'
729
- : "The game's groups could not be read, so a new group is created first, named as shown (the members see the name), even if one of exactly these players exists.") +
918
+ group: group.given
919
+ ? { id: group.id, given: true }
920
+ : group.id !== undefined
921
+ ? { id: group.id, name: group.name, reused: true }
922
+ : { create: true, name: untrustedText(group.name) },
923
+ groupNote: (group.given
924
+ ? `The message goes into game group ${group.id}, as given (its members are not read here: war.app refuses it when you are not in that group).`
925
+ : group.id !== undefined
926
+ ? `The game's group ${group.id} holds exactly you and these players: the message goes there.`
927
+ : groupsRead
928
+ ? 'No game group of exactly you and these players exists: one is created first, named as shown, and the message goes to it.'
929
+ : "The game's groups could not be read, so a new group is created first, named as shown, and the message goes to it, even if one of exactly these players exists.") +
930
+ (group.id === undefined
931
+ ? " The new group's id is read back from the game's chat before the message goes (war.app's reply's id was refused live)."
932
+ : '') +
730
933
  ` ${GROUP_UNVERIFIED}`,
934
+ ...(group.id === undefined ? { nameNote: GROUP_NAME_NOTE } : {}),
731
935
  }
732
936
  : {}),
733
937
  ...(links
@@ -778,8 +982,20 @@ export function registerChatTools(server, ctx, opts = {}) {
778
982
  await requireApprovedAccount(ctx, account);
779
983
  const to = group?.recipients ?? recipient?.name ?? (kind === 'team' ? `your team (team ${channel})` : 'everyone in the game');
780
984
  const marked = automated ? { automated: true } : {};
781
- // A group message: the group first (created when none of exactly these players exists), then the message to it.
985
+ // Like an unconfirmed send, a result whose message never left says what became of the commitments.
986
+ const withNotSentCommitments = (r) => commitments
987
+ ? {
988
+ ...r,
989
+ commitments: {
990
+ recorded: [],
991
+ why: 'The message was NOT sent (the game group could not be confirmed), so its commitments were not made: nothing to record.',
992
+ },
993
+ }
994
+ : r;
995
+ // A group message: the group first (created when none of exactly these players exists), its id read back from
996
+ // the game's chat, then the message to it.
782
997
  let groupId = group?.id;
998
+ let created;
783
999
  if (group && groupId === undefined) {
784
1000
  let createReply;
785
1001
  const notSent = (warning) => ({
@@ -789,54 +1005,97 @@ export function registerChatTools(server, ctx, opts = {}) {
789
1005
  channel: kind,
790
1006
  to,
791
1007
  ...marked,
792
- group: { id: null, created: 'unknown' },
1008
+ group: { id: null, created: 'unknown', name: untrustedText(group.name) },
793
1009
  warning,
794
1010
  });
1011
+ const findIt = 'Look for it with warapp_get_chat (a group message, or its creation line, shows its `group`), then send with ' +
1012
+ '`group_id` and the same `to`, so no other group is made.';
795
1013
  const made = await sendAndVerify({
796
1014
  send: async () => {
797
1015
  createReply = await ctx.rpc.call('CreateGameGroup', Method.CreateGameGroup, (w) => writeCreateGameGroupParams(w, { gameId, name: group.name, members: group.members }));
798
1016
  },
799
1017
  refused: (e) => new McpToolError(`war.app refused to create the game group (${GROUP_REFUSALS[e.code] ?? e.message}; war.app error ${e.code}): nothing was sent.`, { hint: 'Message each player privately instead, or post to the whole game.' }),
800
- unanswered: (failure) => notSent(`war.app did not answer the game group's creation (${failure}), so a group may now exist, but the message was NOT sent. ` +
801
- "Look at the game's groups in the web client before sending again."),
1018
+ unanswered: (failure) => notSent(`war.app did not answer the game group's creation (${failure}), so a group may now exist, but the message was NOT sent. ${findIt}`),
1019
+ // Both ids: the reply's, and the chat's (preferred: live 2026-11-30 the reply's was refused with 752).
802
1020
  readBack: async () => {
803
- const id = createReply ? readCreateGameGroupReply(await ctx.bundle(), createReply.body) : undefined;
804
- if (id === undefined)
805
- throw new Error('its reply named no group');
806
- return id;
1021
+ const replyId = createReply ? readCreateGameGroupReply(await ctx.bundle(), createReply.body) : undefined;
1022
+ return { replyId, chatId: await createdGroupInChat(ctx, gameId, group.lobby ?? false, meInGame, group.members, group.name, replyId) };
807
1023
  },
808
- unreadable: (failure) => notSent(`war.app accepted the game group's creation, but ${failure}, so the message was NOT sent. ` +
809
- "Look at the game's groups in the web client, then send it again (an existing group of exactly these players is reused)."),
810
- classify: (id) => id,
1024
+ unreadable: (failure) => notSent(`war.app accepted the game group's creation, but ${failure}, so a group may now exist, but the message was NOT sent. ${findIt}`),
1025
+ classify: (ids) => ids,
811
1026
  });
812
- if (typeof made !== 'number') {
813
- // Like an unconfirmed send, the result says what became of the commitments: the message never left.
814
- return commitments
1027
+ if ('status' in made)
1028
+ return withNotSentCommitments(made);
1029
+ const { replyId, chatId } = made;
1030
+ if (chatId === undefined && replyId === undefined) {
1031
+ return withNotSentCommitments(notSent("war.app accepted the game group's creation, but neither its reply nor the game's chat names the group, so a group " +
1032
+ `may now exist, but the message was NOT sent. ${findIt}`));
1033
+ }
1034
+ groupId = chatId ?? replyId;
1035
+ created =
1036
+ chatId === undefined
815
1037
  ? {
816
- ...made,
817
- commitments: {
818
- recorded: [],
819
- why: 'The message was NOT sent (the game group could not be confirmed), so its commitments were not made: nothing to record.',
820
- },
1038
+ idFrom: 'reply',
1039
+ warning: `The chat read did not show the new group, so the message went to the id war.app's reply named (${replyId}); ` +
1040
+ 'live 2026-11-30 a reply\'s id was refused. Check the group with warapp_get_chat.',
821
1041
  }
822
- : made;
823
- }
824
- groupId = made;
1042
+ : replyId !== undefined && replyId !== chatId
1043
+ ? {
1044
+ idFrom: 'chat',
1045
+ replyId,
1046
+ warning: `war.app's reply named group ${replyId}, but the game's chat shows group ${chatId} of exactly you and these ` +
1047
+ `players under that name: the message went to group ${chatId}.`,
1048
+ }
1049
+ : { idFrom: 'chat' };
825
1050
  }
826
- const groupOut = group ? { group: { id: groupId, created: group.id === undefined } } : {};
1051
+ const groupOut = group
1052
+ ? {
1053
+ group: created
1054
+ ? { id: groupId, created: true, name: untrustedText(group.name), idFrom: created.idFrom, ...(created.replyId !== undefined ? { replyId: created.replyId } : {}) }
1055
+ : { id: groupId, created: false },
1056
+ }
1057
+ : {};
827
1058
  const base = { status: 'sent', game: gameId, channel: kind, to, ...groupOut, ...marked };
828
1059
  let reply;
1060
+ let retried = 0;
829
1061
  const result = await sendAndVerify({
830
1062
  send: async () => {
831
- reply = await ctx.rpc.call('SendChat', Method.SendChat, (w) => writeSendChatParams(w, {
832
- gameId,
833
- text,
834
- channel,
835
- ...(recipient ? { recipient: recipient.id } : {}),
836
- ...(groupId !== undefined ? { group: groupId } : {}),
837
- }));
1063
+ for (;;) {
1064
+ try {
1065
+ reply = await ctx.rpc.call('SendChat', Method.SendChat, (w) => writeSendChatParams(w, {
1066
+ gameId,
1067
+ text,
1068
+ channel,
1069
+ ...(recipient ? { recipient: recipient.id } : {}),
1070
+ ...(groupId !== undefined ? { group: groupId } : {}),
1071
+ }));
1072
+ return;
1073
+ }
1074
+ catch (e) {
1075
+ // A group this call created refuses messages for a while (752): wait and send again. Only a refusal,
1076
+ // which posts nothing, is resent; never a group given by id or found, never any other failure.
1077
+ const delay = GROUP_SEND_RETRY.delaysMs[retried];
1078
+ if (!created || !(e instanceof WarappServerError) || e.code !== NOT_IN_GAME_GROUP || delay === undefined)
1079
+ throw e;
1080
+ retried += 1;
1081
+ await wait(delay);
1082
+ }
1083
+ }
838
1084
  },
839
- // A refusal is rethrown (nothing was posted; 36, too many messages, is never retried).
1085
+ // A refusal is rethrown (nothing was posted; 36, too many messages, is never retried). A group's refusal names
1086
+ // the group, and says so when this call created it (it stays).
1087
+ ...(groupId !== undefined
1088
+ ? {
1089
+ refused: (e) => new McpToolError(`war.app refused the message to game group ${groupId} (${GROUP_REFUSALS[e.code] ?? e.message}; war.app error ${e.code})` +
1090
+ (group?.id === undefined
1091
+ ? '. The group was created and stays (its members see it), but nothing was sent.'
1092
+ : ': nothing was sent.'), {
1093
+ hint: group?.id === undefined
1094
+ ? `To try again in that group, pass \`group_id: ${groupId}\` with the same \`to\`, so no other group is made.`
1095
+ : 'Check the group id with warapp_get_chat (a group message shows its `group`).',
1096
+ }),
1097
+ }
1098
+ : {}),
840
1099
  unanswered: (failure) => ({
841
1100
  status: 'unknown',
842
1101
  outcome: 'unknown',
@@ -877,15 +1136,19 @@ export function registerChatTools(server, ctx, opts = {}) {
877
1136
  };
878
1137
  },
879
1138
  });
1139
+ // How the new group's id was read, before anything the send itself warns of.
1140
+ const warning = [created?.warning, 'warning' in result ? result.warning : undefined].filter(Boolean).join(' ');
1141
+ const sent = retried ? { ...result, retriedAfterCreate: retried } : result;
1142
+ const out = warning ? { ...sent, warning } : sent;
880
1143
  if (!commitments)
881
- return result;
1144
+ return out;
882
1145
  // B4: a message war.app confirmed or accepted made its promises: record them as mine. Otherwise
883
1146
  // whether it went out is open, and so is whether the promises were made.
884
- if (result.outcome === 'confirmed' || result.outcome === 'accepted') {
885
- return { ...result, commitments: { recorded: await recordSent(gameId, Number(account), commitments), note: COMMITMENTS_NOTE } };
1147
+ if (out.outcome === 'confirmed' || out.outcome === 'accepted') {
1148
+ return { ...out, commitments: { recorded: await recordSent(gameId, Number(account), commitments), note: COMMITMENTS_NOTE } };
886
1149
  }
887
1150
  return {
888
- ...result,
1151
+ ...out,
889
1152
  commitments: {
890
1153
  recorded: [],
891
1154
  why: 'The message is not confirmed sent, so its commitments were not recorded. Check warapp_get_chat: if it went out, ' +