@chrischall/warapp-mcp 0.0.0 → 0.2.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.
Files changed (194) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +211 -9
  4. package/dist/analysis/accept-surrender.js +56 -0
  5. package/dist/analysis/award.js +159 -0
  6. package/dist/analysis/bonuses.js +98 -0
  7. package/dist/analysis/breach.js +62 -0
  8. package/dist/analysis/calibrate.js +239 -0
  9. package/dist/analysis/card-support.js +329 -0
  10. package/dist/analysis/card-threats.js +234 -0
  11. package/dist/analysis/cards-in-effect.js +130 -0
  12. package/dist/analysis/chains.js +59 -0
  13. package/dist/analysis/chokepoints.js +140 -0
  14. package/dist/analysis/combat.js +231 -0
  15. package/dist/analysis/commander-safety.js +149 -0
  16. package/dist/analysis/commitments.js +338 -0
  17. package/dist/analysis/exchange.js +155 -0
  18. package/dist/analysis/finished-game.js +136 -0
  19. package/dist/analysis/game-lessons.js +217 -0
  20. package/dist/analysis/graph.js +82 -0
  21. package/dist/analysis/guard-off.js +54 -0
  22. package/dist/analysis/guess.js +351 -0
  23. package/dist/analysis/headroom.js +241 -0
  24. package/dist/analysis/hold-diff.js +64 -0
  25. package/dist/analysis/how-lost.js +130 -0
  26. package/dist/analysis/index.js +14 -0
  27. package/dist/analysis/local-deploy.js +179 -0
  28. package/dist/analysis/lookahead.js +108 -0
  29. package/dist/analysis/opponent-profile.js +552 -0
  30. package/dist/analysis/opponents.js +1253 -0
  31. package/dist/analysis/outlook.js +695 -0
  32. package/dist/analysis/overrides.js +60 -0
  33. package/dist/analysis/picks.js +1879 -0
  34. package/dist/analysis/plan/after-leftover.js +140 -0
  35. package/dist/analysis/plan/cap-spend.js +242 -0
  36. package/dist/analysis/plan/captures.js +1195 -0
  37. package/dist/analysis/plan/commander.js +236 -0
  38. package/dist/analysis/plan/completed.js +29 -0
  39. package/dist/analysis/plan/conceded-out.js +131 -0
  40. package/dist/analysis/plan/estimates.js +715 -0
  41. package/dist/analysis/plan/guard-off.js +232 -0
  42. package/dist/analysis/plan/holds.js +1631 -0
  43. package/dist/analysis/plan/leftover.js +760 -0
  44. package/dist/analysis/plan/move-order.js +319 -0
  45. package/dist/analysis/plan/orders.js +317 -0
  46. package/dist/analysis/plan/relations.js +702 -0
  47. package/dist/analysis/plan/report.js +672 -0
  48. package/dist/analysis/plan/shared.js +1405 -0
  49. package/dist/analysis/plan/stand-still.js +823 -0
  50. package/dist/analysis/plan/state.js +44 -0
  51. package/dist/analysis/plan/strike.js +1416 -0
  52. package/dist/analysis/plan/targets.js +651 -0
  53. package/dist/analysis/plan/team.js +299 -0
  54. package/dist/analysis/plan/threats.js +1001 -0
  55. package/dist/analysis/plan/transfers.js +328 -0
  56. package/dist/analysis/plan/util.js +5 -0
  57. package/dist/analysis/plan/vacated.js +285 -0
  58. package/dist/analysis/planner.js +2927 -0
  59. package/dist/analysis/player-record.js +144 -0
  60. package/dist/analysis/player.js +268 -0
  61. package/dist/analysis/profile.js +347 -0
  62. package/dist/analysis/relations.js +1030 -0
  63. package/dist/analysis/schedule.js +88 -0
  64. package/dist/analysis/since-last.js +50 -0
  65. package/dist/analysis/static-seats.js +71 -0
  66. package/dist/analysis/stress.js +584 -0
  67. package/dist/analysis/team-brief.js +151 -0
  68. package/dist/analysis/tripwire.js +644 -0
  69. package/dist/analysis/turn-sim.js +259 -0
  70. package/dist/analysis/whereabouts.js +1112 -0
  71. package/dist/board.js +105 -0
  72. package/dist/bundle.js +121082 -36148
  73. package/dist/calibration-source.js +75 -0
  74. package/dist/cards.js +435 -0
  75. package/dist/chat-cursor.js +135 -0
  76. package/dist/chat.js +265 -0
  77. package/dist/client.js +439 -0
  78. package/dist/config.js +62 -0
  79. package/dist/direct/link.js +102 -0
  80. package/dist/direct/session.js +267 -0
  81. package/dist/direct/transport.js +424 -0
  82. package/dist/finished-store.js +357 -0
  83. package/dist/guess-salt.js +65 -0
  84. package/dist/hosted.js +24 -0
  85. package/dist/index.js +33 -0
  86. package/dist/join-color.js +140 -0
  87. package/dist/lessons-store.js +356 -0
  88. package/dist/live.js +287 -0
  89. package/dist/map-details.js +127 -0
  90. package/dist/map-stats.js +160 -0
  91. package/dist/map-store.js +242 -0
  92. package/dist/move-order.js +141 -0
  93. package/dist/my-games.js +218 -0
  94. package/dist/normalize.js +443 -0
  95. package/dist/notifications.js +143 -0
  96. package/dist/open-games.js +537 -0
  97. package/dist/outlook-log.js +165 -0
  98. package/dist/path-lock.js +22 -0
  99. package/dist/pick-list.js +193 -0
  100. package/dist/player-record-store.js +231 -0
  101. package/dist/player-states.js +31 -0
  102. package/dist/profile-store.js +727 -0
  103. package/dist/protocol/bundle.js +375 -0
  104. package/dist/protocol/codec.js +556 -0
  105. package/dist/protocol/decoded.js +12 -0
  106. package/dist/protocol/interp.js +1904 -0
  107. package/dist/protocol/methods.js +615 -0
  108. package/dist/protocol/rpc.js +202 -0
  109. package/dist/push/listener.js +393 -0
  110. package/dist/push/packets.js +66 -0
  111. package/dist/push/socketio.js +333 -0
  112. package/dist/push/websocket.js +179 -0
  113. package/dist/redact.js +62 -0
  114. package/dist/relations-store.js +242 -0
  115. package/dist/replay.js +227 -0
  116. package/dist/scalars.js +28 -0
  117. package/dist/scout.js +346 -0
  118. package/dist/stats.js +291 -0
  119. package/dist/strategy/card-clock.js +185 -0
  120. package/dist/strategy/map-notes.js +128 -0
  121. package/dist/strategy/notes.js +2223 -0
  122. package/dist/surrender-pending.js +126 -0
  123. package/dist/team-cards.js +84 -0
  124. package/dist/team-orders.js +150 -0
  125. package/dist/teams.js +19 -0
  126. package/dist/tools/accept-surrender.js +311 -0
  127. package/dist/tools/award.js +206 -0
  128. package/dist/tools/begin-turn.js +162 -0
  129. package/dist/tools/board.js +77 -0
  130. package/dist/tools/card-advice.js +256 -0
  131. package/dist/tools/card-effects.js +49 -0
  132. package/dist/tools/card-plays.js +434 -0
  133. package/dist/tools/card-support-advice.js +140 -0
  134. package/dist/tools/chat-inbox.js +158 -0
  135. package/dist/tools/chat-read-mark.js +179 -0
  136. package/dist/tools/chat.js +525 -0
  137. package/dist/tools/check-plan.js +689 -0
  138. package/dist/tools/commander-check.js +103 -0
  139. package/dist/tools/commitments.js +216 -0
  140. package/dist/tools/common.js +143 -0
  141. package/dist/tools/diplomacy.js +342 -0
  142. package/dist/tools/end-of-game.js +384 -0
  143. package/dist/tools/game.js +151 -0
  144. package/dist/tools/guess-view.js +56 -0
  145. package/dist/tools/healthcheck.js +90 -0
  146. package/dist/tools/hints.js +34 -0
  147. package/dist/tools/how-lost.js +154 -0
  148. package/dist/tools/index.js +152 -0
  149. package/dist/tools/join-game.js +327 -0
  150. package/dist/tools/leave-game.js +181 -0
  151. package/dist/tools/live-context.js +339 -0
  152. package/dist/tools/live.js +404 -0
  153. package/dist/tools/map-details.js +88 -0
  154. package/dist/tools/map-stats.js +130 -0
  155. package/dist/tools/map.js +141 -0
  156. package/dist/tools/my-games.js +193 -0
  157. package/dist/tools/notifications.js +484 -0
  158. package/dist/tools/open-games.js +104 -0
  159. package/dist/tools/opponents.js +163 -0
  160. package/dist/tools/order-options.js +135 -0
  161. package/dist/tools/past-games.js +94 -0
  162. package/dist/tools/picks.js +305 -0
  163. package/dist/tools/profile-hook.js +156 -0
  164. package/dist/tools/profile-opponents.js +121 -0
  165. package/dist/tools/profile-reads.js +99 -0
  166. package/dist/tools/push.js +445 -0
  167. package/dist/tools/relations.js +611 -0
  168. package/dist/tools/resolve.js +45 -0
  169. package/dist/tools/route.js +36 -0
  170. package/dist/tools/scout.js +87 -0
  171. package/dist/tools/session.js +163 -0
  172. package/dist/tools/strategy.js +257 -0
  173. package/dist/tools/stress-opponents.js +83 -0
  174. package/dist/tools/surrender-pending.js +74 -0
  175. package/dist/tools/surrender.js +247 -0
  176. package/dist/tools/survival.js +189 -0
  177. package/dist/tools/team-brief.js +266 -0
  178. package/dist/tools/team-source.js +222 -0
  179. package/dist/tools/team.js +178 -0
  180. package/dist/tools/turn.js +2825 -0
  181. package/dist/tools/uncommit.js +160 -0
  182. package/dist/tools/where.js +300 -0
  183. package/dist/tools/write-kit.js +164 -0
  184. package/dist/transport-bridge.js +33 -0
  185. package/dist/trend.js +577 -0
  186. package/dist/version.js +4 -0
  187. package/manifest.json +194 -4
  188. package/mint.yaml +106 -14
  189. package/package.json +11 -6
  190. package/server.json +40 -3
  191. package/skills/warapp-api/SKILL.md +95 -4
  192. package/skills/warapp-api/references/scout.mjs +348 -0
  193. package/skills/warapp-api/scripts/warapp.sh +69 -8
  194. package/skills/warapp-mcp/SKILL.md +1096 -21
package/dist/client.js ADDED
@@ -0,0 +1,439 @@
1
+ // WarappClient — every call to war.app's GameFeed API.
2
+ //
3
+ // POST https://war.app/API/GameFeed?GameID=<n>[&GetHistory=true][&GetSettings=true][&GetChat=true][&GetMap=false]
4
+ // body (form): Email=<email>&APIToken=<token>
5
+ //
6
+ // Failures come back as HTTP 200 JSON `{ termsOfUse, error }`, so the status
7
+ // never decides success alone: `Auth failed` is a rejected credential,
8
+ // `…ServerGameKeyNotFound` an unknown game. Transport-level trouble (429 /
9
+ // 5xx) is retried once by createApiClient.
10
+ //
11
+ // Config is deferred: credentials are read per call, so the server boots
12
+ // without them. The email and token are scrubbed by value from every upstream
13
+ // string this module surfaces — raw, JSON-escaped, percent- and form-encoded,
14
+ // the email in any letter case (src/redact.ts).
15
+ //
16
+ // Maps are large (761 territories on map 39905) and the feed's terms ask callers
17
+ // to cache — so a map is kept per process and a game whose map is cached is
18
+ // fetched with GetMap=false. With a data directory (`dataDir`, wired by
19
+ // tools/index.ts) the cache is also kept on disk (src/map-store.ts:
20
+ // `<dataDir>/maps/`, base values, LRU-bounded), so a known map is not
21
+ // downloaded again after a restart — for at most MAX_MAP_AGE_MS (30 days), since
22
+ // a map maker can edit a map under the same id and GameFeed sends no version.
23
+ // The game → map index is written only for a caller that wants the map, on a
24
+ // game not finished.
25
+ import { createApiClient, ERROR_REDACTION_INPUT_MAX, McpToolError, truncateErrorMessage, } from '@chrischall/mcp-utils';
26
+ import { readCredentials, TOKEN_URL, WarappConfigError } from './config.js';
27
+ import { feedErrorOf, normalizeGame, normalizeMap } from './normalize.js';
28
+ import { readGameMapId, readStoredMap, readStoredMapEntry, rememberGameMap, touchStoredMap, writeStoredMap, writeStoredModeTerritories } from './map-store.js';
29
+ import { scrubSecrets } from './redact.js';
30
+ import { asInt } from './scalars.js';
31
+ import { safeKeys } from './trend.js';
32
+ const BASE_URL = 'https://war.app';
33
+ const SERVICE = 'war.app';
34
+ /** A game id war.app will not have: the largest positive int32. */
35
+ export const PROBE_GAME_ID = 2147483647;
36
+ /** The hint for a rejected credential. */
37
+ export const AUTH_FAILED_HINT = `Check WARAPP_EMAIL is the email you sign in to war.app with, and regenerate WARAPP_API_TOKEN at ` +
38
+ `${TOKEN_URL} while signed in — changing your war.app password also rotates the token.`;
39
+ /** The game id names no game this player can load. */
40
+ export class WarappNotFoundError extends McpToolError {
41
+ code = 'not_found';
42
+ constructor(gameId) {
43
+ super(`war.app has no game ${gameId} (ServerGameKeyNotFound).`, {
44
+ kind: 'http',
45
+ status: 404,
46
+ hint: 'Check the game id — it is the number in the game URL (war.app/MultiPlayer?GameID=<n>).',
47
+ });
48
+ this.name = 'WarappNotFoundError';
49
+ }
50
+ }
51
+ /**
52
+ * A GameFeed game id: a positive whole number below 2^31. Validated locally so
53
+ * a bad id never costs a request (war.app answers `GameID must be an integer`).
54
+ */
55
+ export function parseGameId(v) {
56
+ const n = typeof v === 'number' || (typeof v === 'string' && /^\s*\d+\s*$/.test(v)) ? asInt(v) : undefined;
57
+ if (n === undefined || n < 1 || n >= 2 ** 31) {
58
+ throw new McpToolError(`Game id must be a positive whole number below 2147483648 (got ${JSON.stringify(String(v)).slice(0, 40)}).`, {
59
+ hint: 'Use the number after GameID= in the game URL.',
60
+ });
61
+ }
62
+ return n;
63
+ }
64
+ /**
65
+ * Map cache: map id → map, plus game id → map id, in memory per process. Given a data directory, a
66
+ * miss is read back from the persistent store (src/map-store.ts) and a new map or game is written
67
+ * there, best effort: the disk never makes a call fail.
68
+ */
69
+ export class MapCache {
70
+ #maps = new Map();
71
+ #gameMaps = new Map();
72
+ #refreshed = new Set();
73
+ #detailsTried = new Set();
74
+ get(mapId) {
75
+ return this.#maps.get(mapId);
76
+ }
77
+ set(map) {
78
+ this.#maps.set(map.id, map);
79
+ }
80
+ /** The cached map of a game seen before, if it is still cached. */
81
+ forGame(gameId) {
82
+ const mapId = this.#gameMaps.get(gameId);
83
+ return mapId === undefined ? undefined : this.#maps.get(mapId);
84
+ }
85
+ rememberGame(gameId, mapId) {
86
+ this.#gameMaps.set(gameId, mapId);
87
+ }
88
+ /** {@link get}, else the map stored under `dir` (then kept in memory). */
89
+ async load(mapId, dir) {
90
+ const hit = this.#maps.get(mapId);
91
+ if (hit && dir !== undefined)
92
+ await touchStoredMap(dir, hit);
93
+ if (hit || dir === undefined)
94
+ return hit;
95
+ const stored = await readStoredMap(dir, mapId);
96
+ if (stored)
97
+ this.set(stored);
98
+ return stored;
99
+ }
100
+ /**
101
+ * {@link forGame}, else the map the store under `dir` names for the game (the map then kept in
102
+ * memory). A game found only in the stored index is not remembered here, so the caller's
103
+ * {@link storeGame} moves its index entry to the newest.
104
+ */
105
+ async loadForGame(gameId, dir) {
106
+ const mapId = this.#gameMaps.get(gameId);
107
+ if (mapId !== undefined && this.#maps.has(mapId))
108
+ return this.load(mapId, dir);
109
+ if (dir === undefined)
110
+ return undefined;
111
+ const id = mapId ?? (await readGameMapId(dir, gameId));
112
+ return id === undefined ? undefined : this.load(id, dir);
113
+ }
114
+ /**
115
+ * Keep `map` in memory and, when it is new to this process (or `replace`), under `dir`; a map
116
+ * already known is only marked recently used there.
117
+ */
118
+ async store(map, dir, replace = false) {
119
+ const known = this.#maps.has(map.id);
120
+ // #328: a map new to this process may already be stored with its modes' territories (read from war.app's
121
+ // map details, not GameFeed): the same map within its age, so they are kept rather than read again.
122
+ const carried = !known && !replace && dir !== undefined ? await this.#withStoredModes(map, dir) : undefined;
123
+ const kept = carried?.map ?? map;
124
+ this.set(kept);
125
+ if (dir === undefined)
126
+ return;
127
+ // Carried ids keep the age of the copy they were read with, so they age out on its clock, not this download's.
128
+ if (!known || replace)
129
+ await writeStoredMap(dir, kept, carried?.storedAt);
130
+ else
131
+ await touchStoredMap(dir, kept);
132
+ }
133
+ /**
134
+ * `map` with the mode territories its stored copy carries, where it has none of its own, and that copy's
135
+ * `storedAt`; `undefined` when nothing is carried. A mode whose stored ids are not all territories of
136
+ * `map` (its maker edited it since) is not carried: it reads as not read yet, so war.app is asked again
137
+ * and the fresh reply's ids are checked (and any the map lacks dropped with a warning) as on a first read.
138
+ */
139
+ async #withStoredModes(map, dir) {
140
+ const stored = await readStoredMapEntry(dir, map.id);
141
+ if (!stored || stored.storedAt === undefined)
142
+ return undefined;
143
+ const land = new Set(map.territories.map((t) => t.id));
144
+ const byMode = new Map(stored.map.distributionModes
145
+ .filter((d) => Array.isArray(d.territories) && d.territories.length > 0 && d.territories.every((id) => land.has(id)))
146
+ .map((d) => [d.id, d.territories]));
147
+ let any = false;
148
+ const distributionModes = map.distributionModes.map((d) => {
149
+ if (d.territories !== undefined || !byMode.has(d.id))
150
+ return d;
151
+ any = true;
152
+ return { ...d, territories: byMode.get(d.id) };
153
+ });
154
+ return any ? { map: { ...map, distributionModes }, storedAt: stored.storedAt } : undefined;
155
+ }
156
+ /**
157
+ * Lay the territories read for `mapId`'s modes (#328, by mode id) on the cached base map (a new object:
158
+ * the graph cache is keyed by map object) and keep them under `dir`. Nothing when the map is not cached.
159
+ */
160
+ async setModeTerritories(mapId, given, dir) {
161
+ const base = this.#maps.get(mapId);
162
+ if (!base)
163
+ return;
164
+ // An empty list is no knowledge (unknown is never `[]`): it is neither laid on the map nor kept.
165
+ const byMode = new Map([...given].filter(([, ids]) => ids.length > 0));
166
+ if (!byMode.size)
167
+ return;
168
+ this.set({
169
+ ...base,
170
+ distributionModes: base.distributionModes.map((d) => (byMode.has(d.id) ? { ...d, territories: [...byMode.get(d.id)] } : d)),
171
+ });
172
+ if (dir !== undefined)
173
+ await writeStoredModeTerritories(dir, mapId, byMode);
174
+ }
175
+ /** Whether war.app's map details were already asked for `mapId` this process (#328: once per map, never in a loop). */
176
+ mapDetailsTried(mapId) {
177
+ return this.#detailsTried.has(mapId);
178
+ }
179
+ markMapDetailsTried(mapId) {
180
+ this.#detailsTried.add(mapId);
181
+ }
182
+ /** Whether `mapId` was already downloaded again this process because the feed named land it lacked. */
183
+ wasRefreshed(mapId) {
184
+ return this.#refreshed.has(mapId);
185
+ }
186
+ markRefreshed(mapId) {
187
+ this.#refreshed.add(mapId);
188
+ }
189
+ /** Remember the game's map in memory and, when that is new to this process, under `dir`. */
190
+ async storeGame(gameId, mapId, dir) {
191
+ const known = this.#gameMaps.get(gameId) === mapId;
192
+ this.rememberGame(gameId, mapId);
193
+ if (!known && dir !== undefined)
194
+ await rememberGameMap(dir, gameId, mapId);
195
+ }
196
+ clear() {
197
+ this.#maps.clear();
198
+ this.#gameMaps.clear();
199
+ this.#refreshed.clear();
200
+ this.#detailsTried.clear();
201
+ }
202
+ }
203
+ /** Whether the game's standing names a territory `map` does not have. */
204
+ function lacksTerritory(map, game) {
205
+ const territories = game.standing?.territories;
206
+ if (!territories?.length)
207
+ return false;
208
+ const ids = new Set(map.territories.map((t) => t.id));
209
+ return territories.some((t) => !ids.has(t.territoryId));
210
+ }
211
+ /** The process-wide default cache. */
212
+ export const defaultMapCache = new MapCache();
213
+ export class WarappClient {
214
+ #env;
215
+ #cache;
216
+ #dataDir;
217
+ #api;
218
+ /** The same client with no retry, for a request that must go out at most once (`noRetry`). */
219
+ #apiOnce;
220
+ #secrets = [];
221
+ constructor(opts = {}) {
222
+ this.#env = opts.env;
223
+ this.#cache = opts.mapCache ?? defaultMapCache;
224
+ this.#dataDir = opts.dataDir;
225
+ const build = (count) => createApiClient({
226
+ baseUrl: BASE_URL,
227
+ serviceName: SERVICE,
228
+ baseHeaders: { accept: 'application/json' },
229
+ retry: { count, delayMs: 2000, statuses: [429, 500, 502, 503, 504], honorRetryAfter: true },
230
+ redirect: 'same-origin',
231
+ ...(opts.timeoutMs !== undefined ? { timeout: opts.timeoutMs } : {}),
232
+ ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),
233
+ ...(opts.sleep ? { sleep: opts.sleep } : {}),
234
+ onUnauthorized: () => new McpToolError('war.app refused the request (HTTP 401).', {
235
+ kind: 'credential_rejected',
236
+ status: 401,
237
+ hint: AUTH_FAILED_HINT,
238
+ }),
239
+ onErrorResponse: ({ status, body }) => new McpToolError(`war.app GameFeed answered HTTP ${status}${body.trim() ? `: ${this.#redact(body)}` : ''}`, { kind: 'http', status }),
240
+ });
241
+ this.#api = build(1);
242
+ this.#apiOnce = build(0);
243
+ }
244
+ #redact(text) {
245
+ // Scrub by value before the shape redactor and the cut (as `values` would),
246
+ // over no more than truncateErrorMessage itself redacts.
247
+ return truncateErrorMessage(scrubSecrets(text.slice(0, ERROR_REDACTION_INPUT_MAX), this.#secrets), 300);
248
+ }
249
+ #credentials() {
250
+ try {
251
+ const creds = readCredentials(this.#env);
252
+ this.#secrets = [creds.token, { value: creds.email, anyCase: true }];
253
+ return creds;
254
+ }
255
+ catch (e) {
256
+ if (e instanceof WarappConfigError) {
257
+ throw new McpToolError(e.message, {
258
+ kind: 'no_credential',
259
+ hint: `Set WARAPP_EMAIL and WARAPP_API_TOKEN (token from ${TOKEN_URL}).`,
260
+ cause: e,
261
+ });
262
+ }
263
+ throw e;
264
+ }
265
+ }
266
+ /** One GameFeed call. Returns the parsed body; maps `{ error }` bodies to typed errors. */
267
+ async #feed(gameId, flags) {
268
+ const { email, token } = this.#credentials();
269
+ let path = `/API/GameFeed?GameID=${gameId}`;
270
+ if (flags.history)
271
+ path += '&GetHistory=true';
272
+ if (flags.settings)
273
+ path += '&GetSettings=true';
274
+ if (flags.chat)
275
+ path += '&GetChat=true';
276
+ if (flags.noMap)
277
+ path += '&GetMap=false';
278
+ const api = flags.noRetry ? this.#apiOnce : this.#api;
279
+ const body = await api.fetchJson('POST', path, {
280
+ rawBody: new URLSearchParams({ Email: email, APIToken: token }).toString(),
281
+ contentType: 'application/x-www-form-urlencoded',
282
+ // A read sent as POST: safe to repeat.
283
+ idempotent: true,
284
+ expect: 'object',
285
+ });
286
+ const error = feedErrorOf(body);
287
+ if (error === undefined)
288
+ return body;
289
+ if (error === 'Auth failed') {
290
+ throw new McpToolError('war.app rejected the email + API token (Auth failed).', {
291
+ kind: 'credential_rejected',
292
+ hint: AUTH_FAILED_HINT,
293
+ });
294
+ }
295
+ if (/ServerGameKeyNotFound/.test(error))
296
+ throw new WarappNotFoundError(gameId);
297
+ throw new McpToolError(`war.app GameFeed error: ${this.#redact(error)}`, { kind: 'http' });
298
+ }
299
+ /**
300
+ * Load a game, normalized. The map comes from the cache (memory, else the data directory's
301
+ * store) when this game's map is already known (fetched with GetMap=false), else from the
302
+ * feed (and is then cached).
303
+ */
304
+ async getGame(id, opts = {}) {
305
+ const gameId = parseGameId(id);
306
+ const dir = this.#dir();
307
+ let known = await this.#cache.loadForGame(gameId, dir);
308
+ let body = await this.#feed(gameId, { ...opts, noMap: known !== undefined || opts.map === false });
309
+ let game = normalizeGame(body);
310
+ // GameFeed sends no map version, so an edited map shows as land the cached copy lacks: download
311
+ // it once more (once per map per process, in case the loose standing parser misreads an id).
312
+ let replace = false;
313
+ if (known && opts.map !== false && lacksTerritory(known, game) && !this.#cache.wasRefreshed(known.id)) {
314
+ this.#cache.markRefreshed(known.id);
315
+ // A failed refresh keeps the first read and the known map: the extra request is a check, not the read.
316
+ const fresher = await this.#feed(gameId, { ...opts, noMap: false }).catch(() => undefined);
317
+ if (fresher) {
318
+ body = fresher;
319
+ game = normalizeGame(body);
320
+ known = undefined;
321
+ replace = true;
322
+ }
323
+ }
324
+ let map = known;
325
+ const rawMap = body.map;
326
+ if (!map && rawMap && typeof rawMap === 'object' && Array.isArray(rawMap.territories)) {
327
+ const fresh = normalizeMap(rawMap);
328
+ map = replace ? fresh : (this.#cache.get(fresh.id) ?? fresh);
329
+ await this.#cache.store(map, dir, replace);
330
+ // The cache may hold it with what the store kept for it (#328: its modes' territories).
331
+ map = this.#cache.get(map.id) ?? map;
332
+ }
333
+ if (!map && game.settings?.mapId !== undefined)
334
+ map = await this.#cache.load(game.settings.mapId, dir);
335
+ if (map) {
336
+ // The index only saves a map download for a caller that wants the map, on a game still played:
337
+ // a `map: false` caller always asks GetMap=false, and a finished game (map statistics read many)
338
+ // would only push live games out of the bounded index.
339
+ const index = opts.map !== false && game.state !== 'Finished';
340
+ await this.#cache.storeGame(gameId, map.id, index ? dir : undefined);
341
+ game.map = map;
342
+ }
343
+ // #302: what came instead of a history that does not read, by key name only.
344
+ if (opts.history)
345
+ game.feedKeys = safeKeys(Object.keys(body));
346
+ return game;
347
+ }
348
+ /** Keep the territories read for a map's distribution modes (#328) on the cached map and in the store. */
349
+ async keepModeTerritories(mapId, byMode) {
350
+ await this.#cache.setModeTerritories(mapId, byMode, this.#dir());
351
+ }
352
+ /** Whether war.app's map details were already asked for `mapId` this process (#328). */
353
+ mapDetailsTried(mapId) {
354
+ return this.#cache.mapDetailsTried(mapId);
355
+ }
356
+ markMapDetailsTried(mapId) {
357
+ this.#cache.markMapDetailsTried(mapId);
358
+ }
359
+ /** The data directory for the map store, or `undefined` (memory only); never throws. */
360
+ #dir() {
361
+ try {
362
+ return this.#dataDir?.();
363
+ }
364
+ catch {
365
+ return undefined;
366
+ }
367
+ }
368
+ /**
369
+ * The game ids of a ladder or tournament, from war.app's game-ID feed
370
+ * (`/API/GameIDFeed?LadderID=<n>` or `?TournamentID=<n>`, documented on the
371
+ * public wiki page "Game ID feed API": 1v1 ladder 0, 2v2 1, 3v3 4).
372
+ * UNVERIFIED: the wiki names neither the method, the auth nor the reply, so
373
+ * this POSTs the GameFeed credentials (harmless if the feed is public) and
374
+ * reads the ids loosely — a bare array, or `gameIDs` / `gameIds` / `games`,
375
+ * each a number, numeric string or `{ id | gameID }`. Distinct, newest
376
+ * (highest id) first.
377
+ */
378
+ async getGameIds(source) {
379
+ const [key, raw] = 'ladderId' in source ? ['LadderID', source.ladderId] : ['TournamentID', source.tournamentId];
380
+ if (!Number.isInteger(raw) || raw < 0 || raw >= 2 ** 31) {
381
+ throw new McpToolError(`${key} must be a whole number from 0 (got ${String(raw).slice(0, 20)}).`, {
382
+ hint: 'Ladders: 1v1 is 0, 2v2 is 1, 3v3 is 4.',
383
+ });
384
+ }
385
+ const { email, token } = this.#credentials();
386
+ const body = await this.#api.fetchJson('POST', `/API/GameIDFeed?${key}=${raw}`, {
387
+ rawBody: new URLSearchParams({ Email: email, APIToken: token }).toString(),
388
+ contentType: 'application/x-www-form-urlencoded',
389
+ idempotent: true,
390
+ });
391
+ const error = Array.isArray(body) ? undefined : feedErrorOf(body);
392
+ if (error === 'Auth failed') {
393
+ throw new McpToolError('war.app rejected the email + API token (Auth failed).', {
394
+ kind: 'credential_rejected',
395
+ hint: AUTH_FAILED_HINT,
396
+ });
397
+ }
398
+ if (error !== undefined)
399
+ throw new McpToolError(`war.app GameIDFeed error: ${this.#redact(error)}`, { kind: 'http' });
400
+ return gameIdsOf(body);
401
+ }
402
+ /**
403
+ * A map this process has already loaded (with some game), by map id; `undefined`
404
+ * otherwise. GameFeed serves maps only with a game, so this never makes a request.
405
+ */
406
+ cachedMap(mapId) {
407
+ return this.#cache.get(mapId);
408
+ }
409
+ /**
410
+ * Prove the credentials work without loading a real game: ask for
411
+ * {@link PROBE_GAME_ID}. `ServerGameKeyNotFound` (or, improbably, a game)
412
+ * means authenticated; `Auth failed` throws `credential_rejected`.
413
+ */
414
+ async probeAuth() {
415
+ try {
416
+ await this.#feed(PROBE_GAME_ID, { noMap: true });
417
+ }
418
+ catch (e) {
419
+ if (!(e instanceof WarappNotFoundError))
420
+ throw e;
421
+ }
422
+ return { authenticated: true };
423
+ }
424
+ }
425
+ /** Game ids out of a GameIDFeed body, in any of the plausible layouts; distinct, descending. */
426
+ function gameIdsOf(body) {
427
+ const rec = body && typeof body === 'object' && !Array.isArray(body) ? body : undefined;
428
+ const list = Array.isArray(body) ? body : (rec?.gameIDs ?? rec?.gameIds ?? rec?.GameIDs ?? rec?.games);
429
+ if (!Array.isArray(list))
430
+ return [];
431
+ const ids = new Set();
432
+ for (const e of list) {
433
+ const v = e && typeof e === 'object' ? (e.id ?? e.gameID) : e;
434
+ const n = asInt(v);
435
+ if (n !== undefined && n > 0 && n < 2 ** 31)
436
+ ids.add(n);
437
+ }
438
+ return [...ids].sort((a, b) => b - a);
439
+ }
package/dist/config.js ADDED
@@ -0,0 +1,62 @@
1
+ // Credential and env-file resolution. Deferred-config pattern: nothing here
2
+ // runs at import time, and a missing credential is an error on the first call
3
+ // that needs it, never a boot failure.
4
+ import { homedir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { readEnvVar, requireEnvVar } from '@chrischall/mcp-utils';
7
+ /** Where a regenerated token comes from (signed in to war.app in a browser). */
8
+ export const TOKEN_URL = 'https://war.app/API/GetAPIToken';
9
+ export class WarappConfigError extends Error {
10
+ name = 'WarappConfigError';
11
+ }
12
+ /** The optional dotenv file: `WARAPP_ENV_FILE`, else `~/.config/warapp-mcp/.env`. */
13
+ export function envFilePath(env = process.env) {
14
+ return readEnvVar('WARAPP_ENV_FILE', { env }) ?? join(homedir(), '.config', 'warapp-mcp', '.env');
15
+ }
16
+ /**
17
+ * Read `WARAPP_EMAIL` + `WARAPP_API_TOKEN`. Throws a {@link WarappConfigError}
18
+ * naming every missing variable — and never a value, so a leaked placeholder is
19
+ * not echoed back.
20
+ */
21
+ export function readCredentials(env = process.env) {
22
+ // requireEnvVar (not readEnvVar): both are required to make any call, and the
23
+ // throw is caught here so the deferred-config pattern still holds.
24
+ const required = (key) => {
25
+ try {
26
+ return requireEnvVar(key, { env });
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ };
32
+ const email = required('WARAPP_EMAIL');
33
+ const token = required('WARAPP_API_TOKEN');
34
+ if (email && token)
35
+ return { email, token };
36
+ const missing = [email ? null : 'WARAPP_EMAIL', token ? null : 'WARAPP_API_TOKEN'].filter(Boolean);
37
+ throw new WarappConfigError(`${missing.join(' and ')} ${missing.length > 1 ? 'are' : 'is'} not set. Set WARAPP_EMAIL to your war.app ` +
38
+ `sign-in email and WARAPP_API_TOKEN to the API token shown at ${TOKEN_URL} while signed in.`);
39
+ }
40
+ /**
41
+ * Read `WARAPP_EMAIL` alone — the web-client protocol's auth block carries the
42
+ * account email and nothing else (the browser's cookies authenticate the
43
+ * request). Throws a value-free {@link WarappConfigError} when it is unset.
44
+ */
45
+ export function readEmail(env = process.env) {
46
+ try {
47
+ return requireEnvVar('WARAPP_EMAIL', { env });
48
+ }
49
+ catch {
50
+ // Fall through to the live-tools wording below (requireEnvVar's is generic).
51
+ }
52
+ throw new WarappConfigError('WARAPP_EMAIL is not set. Set it to the email you sign in to war.app with — the live-game tools send it ' +
53
+ 'with each request, alongside the session of your signed-in war.app tab.');
54
+ }
55
+ /**
56
+ * Where state that should survive a restart lives (the cached client bundle):
57
+ * `MCP_DATA_DIR` (set by mcp-host for a registration with `state.dataDir`),
58
+ * else `~/.config/warapp-mcp`.
59
+ */
60
+ export function dataDir(env = process.env) {
61
+ return readEnvVar('MCP_DATA_DIR', { env }) ?? join(homedir(), '.config', 'warapp-mcp');
62
+ }
@@ -0,0 +1,102 @@
1
+ // Linking (and relinking) the chrome-less "direct" session.
2
+ //
3
+ // The direct transport (src/direct/transport.ts) authenticates every war.app
4
+ // request with the signed-in `AuthToken` cookie (live-verified 2026-11-12).
5
+ // {@link linkSession} captures that cookie ONCE off the user's signed-in
6
+ // war.app tab through the browser bridge (mcp-utils `captureBearerHeader`,
7
+ // which snapshots the `Cookie` request header via the fetchproxy server's
8
+ // `captureRequestHeader`), extracts the `AuthToken` value, and stores it with
9
+ // M1's on-disk hygiene. The bridge is touched only here, never on the hot
10
+ // path — once linked, every later call is a plain server-side HTTPS request.
11
+ //
12
+ // SECURITY: the AuthToken is a FULL-ACCOUNT credential. linkSession never
13
+ // returns it, never logs it, never puts it in an error: it returns only when
14
+ // the capture happened ({@link LinkResult} is `capturedAt` + `host`). Every
15
+ // cookie but `AuthToken` is discarded. A capture that yields no AuthToken
16
+ // throws {@link NoAuthTokenError} and stores nothing. Direct mode is
17
+ // LOCAL-ONLY — the hosted path keeps the browser bridge and stores no token.
18
+ import { McpToolError, readPortEnv } from '@chrischall/mcp-utils';
19
+ import { captureBearerHeader } from '@chrischall/mcp-utils/fetchproxy';
20
+ import { isHosted } from '../hosted.js';
21
+ import { DEFAULT_WS_PORT, SERVER_NAME, WS_PORT_ENV } from '../transport-bridge.js';
22
+ import { VERSION } from '../version.js';
23
+ import { scrubError, SESSION_HOST, writeSession } from './session.js';
24
+ /** The cookie that carries the signed-in war.app session. */
25
+ const AUTH_COOKIE = 'AuthToken';
26
+ /** The capture waits this long (ms) for the signed-in tab to make a request. */
27
+ const DEFAULT_CAPTURE_WINDOW_MS = 60_000;
28
+ /** No `AuthToken` cookie was present on the captured war.app request. */
29
+ export class NoAuthTokenError extends McpToolError {
30
+ name = 'NoAuthTokenError';
31
+ constructor() {
32
+ super(`No ${AUTH_COOKIE} cookie was found on the war.app request. Sign in to war.app in the bridged tab, then retry.`, { kind: 'no_credential' });
33
+ }
34
+ }
35
+ /**
36
+ * The `AuthToken` value from a `Cookie` header, or `null` when it is absent or
37
+ * empty. Only an exact `AuthToken` cookie counts; every other cookie (and a
38
+ * name that merely ends in `AuthToken`) is ignored.
39
+ */
40
+ export function authTokenFromCookie(cookie) {
41
+ for (const part of cookie.split(';')) {
42
+ const eq = part.indexOf('=');
43
+ if (eq < 0)
44
+ continue;
45
+ if (part.slice(0, eq).trim() !== AUTH_COOKIE)
46
+ continue;
47
+ const value = part.slice(eq + 1).trim();
48
+ return value.length > 0 ? value : null;
49
+ }
50
+ return null;
51
+ }
52
+ /** The default capture: snapshot the `Cookie` header off a war.app request through the bridge. */
53
+ function captureWarappCookie(opts) {
54
+ const env = opts.env ?? process.env;
55
+ return captureBearerHeader({
56
+ captures: [{ host: SESSION_HOST, headerName: 'Cookie' }],
57
+ domains: [SESSION_HOST],
58
+ windowMs: opts.windowMs ?? DEFAULT_CAPTURE_WINDOW_MS,
59
+ serverName: SERVER_NAME,
60
+ version: VERSION,
61
+ // The AuthToken is parsed out of the whole Cookie header ourselves, so keep
62
+ // it intact (no Bearer-stripping) and never reject on length.
63
+ minLength: 1,
64
+ normalise: (raw) => raw,
65
+ port: opts.port ?? readPortEnv(WS_PORT_ENV, DEFAULT_WS_PORT, { env }),
66
+ what: 'your war.app session',
67
+ guidance: 'Open a signed-in war.app tab (e.g. war.app/MultiPlayer) and load or click into a game so the tab sends a ' +
68
+ 'request, then retry.',
69
+ transportOptions: { env },
70
+ ...(opts.createTransport ? { createTransport: opts.createTransport } : {}),
71
+ });
72
+ }
73
+ /**
74
+ * Capture the signed-in war.app session cookie through the bridge, extract the
75
+ * `AuthToken`, and store it (M1). Returns only {@link LinkResult} — when and
76
+ * where, never the token. Throws {@link NoAuthTokenError} (storing nothing)
77
+ * when the captured cookie carries no `AuthToken`.
78
+ */
79
+ export async function linkSession(opts = {}) {
80
+ // Local-only: a hosted child never pulls the full-account cookie into memory
81
+ // (the tool is not registered there, and writeSession refuses too).
82
+ if (isHosted(opts.env ?? process.env)) {
83
+ throw new McpToolError('The direct transport is local-only: a hosted server never links a war.app session.', {
84
+ kind: 'unknown',
85
+ });
86
+ }
87
+ const cookie = await (opts.capture ?? (() => captureWarappCookie(opts)))();
88
+ const authToken = authTokenFromCookie(cookie);
89
+ if (!authToken)
90
+ throw new NoAuthTokenError();
91
+ const capturedAt = (opts.now?.() ?? new Date()).toISOString();
92
+ const session = { authToken, capturedAt, host: SESSION_HOST };
93
+ try {
94
+ await (opts.save ?? ((s) => writeSession(s, opts.env)))(session);
95
+ }
96
+ catch (err) {
97
+ // Whatever failed after the capture never carries the token or the rest
98
+ // of the captured cookie (other session cookies) out in its error.
99
+ throw scrubError(err, [authToken, cookie]);
100
+ }
101
+ return { capturedAt, host: SESSION_HOST };
102
+ }