@chrischall/warapp-mcp 0.0.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +4 -4
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +199 -8
- package/dist/analysis/award.js +159 -0
- package/dist/analysis/bonuses.js +98 -0
- package/dist/analysis/breach.js +62 -0
- package/dist/analysis/card-support.js +329 -0
- package/dist/analysis/card-threats.js +234 -0
- package/dist/analysis/cards-in-effect.js +130 -0
- package/dist/analysis/chains.js +59 -0
- package/dist/analysis/chokepoints.js +140 -0
- package/dist/analysis/combat.js +231 -0
- package/dist/analysis/commander-safety.js +149 -0
- package/dist/analysis/commitments.js +338 -0
- package/dist/analysis/exchange.js +155 -0
- package/dist/analysis/graph.js +82 -0
- package/dist/analysis/guard-off.js +54 -0
- package/dist/analysis/guess.js +351 -0
- package/dist/analysis/headroom.js +241 -0
- package/dist/analysis/hold-diff.js +64 -0
- package/dist/analysis/how-lost.js +130 -0
- package/dist/analysis/index.js +14 -0
- package/dist/analysis/local-deploy.js +159 -0
- package/dist/analysis/lookahead.js +108 -0
- package/dist/analysis/opponent-profile.js +551 -0
- package/dist/analysis/opponents.js +1245 -0
- package/dist/analysis/outlook.js +633 -0
- package/dist/analysis/overrides.js +60 -0
- package/dist/analysis/picks.js +1879 -0
- package/dist/analysis/plan/after-leftover.js +140 -0
- package/dist/analysis/plan/cap-spend.js +242 -0
- package/dist/analysis/plan/captures.js +1195 -0
- package/dist/analysis/plan/commander.js +236 -0
- package/dist/analysis/plan/completed.js +29 -0
- package/dist/analysis/plan/conceded-out.js +131 -0
- package/dist/analysis/plan/estimates.js +715 -0
- package/dist/analysis/plan/guard-off.js +232 -0
- package/dist/analysis/plan/holds.js +1631 -0
- package/dist/analysis/plan/leftover.js +760 -0
- package/dist/analysis/plan/move-order.js +319 -0
- package/dist/analysis/plan/orders.js +317 -0
- package/dist/analysis/plan/relations.js +702 -0
- package/dist/analysis/plan/report.js +672 -0
- package/dist/analysis/plan/shared.js +1218 -0
- package/dist/analysis/plan/stand-still.js +823 -0
- package/dist/analysis/plan/state.js +44 -0
- package/dist/analysis/plan/strike.js +1416 -0
- package/dist/analysis/plan/targets.js +651 -0
- package/dist/analysis/plan/team.js +299 -0
- package/dist/analysis/plan/threats.js +927 -0
- package/dist/analysis/plan/transfers.js +328 -0
- package/dist/analysis/plan/util.js +5 -0
- package/dist/analysis/plan/vacated.js +285 -0
- package/dist/analysis/planner.js +2922 -0
- package/dist/analysis/player-record.js +144 -0
- package/dist/analysis/player.js +268 -0
- package/dist/analysis/profile.js +347 -0
- package/dist/analysis/relations.js +1030 -0
- package/dist/analysis/schedule.js +88 -0
- package/dist/analysis/since-last.js +50 -0
- package/dist/analysis/static-seats.js +71 -0
- package/dist/analysis/stress.js +577 -0
- package/dist/analysis/team-brief.js +151 -0
- package/dist/analysis/tripwire.js +644 -0
- package/dist/analysis/turn-sim.js +259 -0
- package/dist/analysis/whereabouts.js +1109 -0
- package/dist/board.js +105 -0
- package/dist/bundle.js +117959 -36172
- package/dist/cards.js +435 -0
- package/dist/chat-cursor.js +135 -0
- package/dist/chat.js +192 -0
- package/dist/client.js +361 -0
- package/dist/config.js +62 -0
- package/dist/direct/link.js +102 -0
- package/dist/direct/session.js +267 -0
- package/dist/direct/transport.js +424 -0
- package/dist/guess-salt.js +65 -0
- package/dist/hosted.js +24 -0
- package/dist/index.js +33 -0
- package/dist/join-color.js +140 -0
- package/dist/live.js +278 -0
- package/dist/map-stats.js +152 -0
- package/dist/map-store.js +204 -0
- package/dist/move-order.js +141 -0
- package/dist/my-games.js +180 -0
- package/dist/normalize.js +411 -0
- package/dist/open-games.js +537 -0
- package/dist/outlook-log.js +138 -0
- package/dist/path-lock.js +22 -0
- package/dist/pick-list.js +193 -0
- package/dist/player-record-store.js +229 -0
- package/dist/player-states.js +31 -0
- package/dist/profile-store.js +677 -0
- package/dist/protocol/bundle.js +375 -0
- package/dist/protocol/codec.js +556 -0
- package/dist/protocol/decoded.js +12 -0
- package/dist/protocol/interp.js +1904 -0
- package/dist/protocol/methods.js +531 -0
- package/dist/protocol/rpc.js +202 -0
- package/dist/push/listener.js +393 -0
- package/dist/push/packets.js +66 -0
- package/dist/push/socketio.js +333 -0
- package/dist/push/websocket.js +179 -0
- package/dist/redact.js +62 -0
- package/dist/relations-store.js +242 -0
- package/dist/replay.js +215 -0
- package/dist/scalars.js +28 -0
- package/dist/scout.js +346 -0
- package/dist/stats.js +269 -0
- package/dist/strategy/card-clock.js +185 -0
- package/dist/strategy/map-notes.js +128 -0
- package/dist/strategy/notes.js +2168 -0
- package/dist/team-cards.js +84 -0
- package/dist/team-orders.js +150 -0
- package/dist/teams.js +19 -0
- package/dist/tools/award.js +206 -0
- package/dist/tools/begin-turn.js +162 -0
- package/dist/tools/board.js +77 -0
- package/dist/tools/card-advice.js +256 -0
- package/dist/tools/card-effects.js +49 -0
- package/dist/tools/card-plays.js +434 -0
- package/dist/tools/card-support-advice.js +140 -0
- package/dist/tools/chat-inbox.js +146 -0
- package/dist/tools/chat.js +483 -0
- package/dist/tools/check-plan.js +688 -0
- package/dist/tools/commander-check.js +102 -0
- package/dist/tools/commitments.js +216 -0
- package/dist/tools/common.js +143 -0
- package/dist/tools/diplomacy.js +342 -0
- package/dist/tools/game.js +126 -0
- package/dist/tools/guess-view.js +56 -0
- package/dist/tools/healthcheck.js +90 -0
- package/dist/tools/hints.js +34 -0
- package/dist/tools/how-lost.js +154 -0
- package/dist/tools/index.js +142 -0
- package/dist/tools/join-game.js +327 -0
- package/dist/tools/leave-game.js +181 -0
- package/dist/tools/live-context.js +339 -0
- package/dist/tools/live.js +404 -0
- package/dist/tools/map-stats.js +117 -0
- package/dist/tools/map.js +133 -0
- package/dist/tools/my-games.js +123 -0
- package/dist/tools/open-games.js +104 -0
- package/dist/tools/opponents.js +151 -0
- package/dist/tools/order-options.js +135 -0
- package/dist/tools/picks.js +292 -0
- package/dist/tools/profile-hook.js +156 -0
- package/dist/tools/profile-opponents.js +121 -0
- package/dist/tools/profile-reads.js +99 -0
- package/dist/tools/push.js +385 -0
- package/dist/tools/relations.js +611 -0
- package/dist/tools/resolve.js +45 -0
- package/dist/tools/route.js +36 -0
- package/dist/tools/scout.js +87 -0
- package/dist/tools/session.js +163 -0
- package/dist/tools/strategy.js +200 -0
- package/dist/tools/stress-opponents.js +83 -0
- package/dist/tools/surrender.js +240 -0
- package/dist/tools/survival.js +189 -0
- package/dist/tools/team-brief.js +266 -0
- package/dist/tools/team-source.js +222 -0
- package/dist/tools/team.js +182 -0
- package/dist/tools/turn.js +2761 -0
- package/dist/tools/uncommit.js +160 -0
- package/dist/tools/where.js +275 -0
- package/dist/tools/write-kit.js +158 -0
- package/dist/transport-bridge.js +33 -0
- package/dist/trend.js +452 -0
- package/dist/version.js +4 -0
- package/manifest.json +174 -4
- package/mint.yaml +101 -14
- package/package.json +11 -6
- package/server.json +40 -3
- package/skills/warapp-api/SKILL.md +95 -4
- package/skills/warapp-api/references/scout.mjs +348 -0
- package/skills/warapp-api/scripts/warapp.sh +69 -8
- package/skills/warapp-mcp/SKILL.md +969 -21
package/dist/chat.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// Game chat as data: one line shape for both sources, with the channel each message was sent on.
|
|
2
|
+
//
|
|
3
|
+
// - The web client's GameRefresh (method 39) answers `warlight.shared.GameDetailsAndChat`, whose first
|
|
4
|
+
// field is the chat: a list of `warlight.shared.GameMessage`. Both are decoded by the client bundle's
|
|
5
|
+
// own readers, found by their stable registered type names; fields are taken by read order and
|
|
6
|
+
// checked by type, never by their minified names (docs/WEB-PROTOCOL.md, Chat). The SendChat reply is
|
|
7
|
+
// the same message list. UNVERIFIED live: the field meanings come from how the client's chat UI uses
|
|
8
|
+
// them (the sender, the channel, -1 public, else a team; the private counterpart; the turn).
|
|
9
|
+
// - GameFeed's `GetChat=true` list is read loosely: it is not documented, and whether it carries team
|
|
10
|
+
// or private messages, or any channel field, is unknown. A message with no channel field is `unknown`.
|
|
11
|
+
//
|
|
12
|
+
// Readers here never throw: a reply in a shape they do not understand is `undefined`, and the caller
|
|
13
|
+
// falls back (GameRefresh to GameFeed) or reports the outcome as unreadable.
|
|
14
|
+
import { fields, isObj } from './protocol/decoded.js';
|
|
15
|
+
import { parseFeedTime } from './normalize.js';
|
|
16
|
+
import { asInt } from './scalars.js';
|
|
17
|
+
export const GAME_DETAILS_AND_CHAT = 'warlight.shared.GameDetailsAndChat';
|
|
18
|
+
export const GAME_MESSAGE = 'warlight.shared.GameMessage';
|
|
19
|
+
/** GameMessage field positions in read order, and its whole field count. */
|
|
20
|
+
const GM = { date: 0, sender: 1, group: 2, id: 4, text: 5, channel: 6, to: 7, turn: 9 };
|
|
21
|
+
export const GAME_MESSAGE_FIELDS = 10;
|
|
22
|
+
/** The public channel's value (any other is a team). */
|
|
23
|
+
export const PUBLIC_CHANNEL = -1;
|
|
24
|
+
export const CHAT_CHANNELS = ['public', 'team', 'private', 'unknown'];
|
|
25
|
+
const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
|
|
26
|
+
const optInt = (v) => v === null || isInt(v);
|
|
27
|
+
/** One decoded GameMessage as a line; `undefined` when a field is not what it should be. */
|
|
28
|
+
function webLine(m) {
|
|
29
|
+
if (!isObj(m) || m.$type !== GAME_MESSAGE)
|
|
30
|
+
return undefined;
|
|
31
|
+
const f = fields(m);
|
|
32
|
+
if (f.length !== GAME_MESSAGE_FIELDS)
|
|
33
|
+
return undefined;
|
|
34
|
+
const date = f[GM.date];
|
|
35
|
+
const sender = f[GM.sender];
|
|
36
|
+
const group = f[GM.group];
|
|
37
|
+
const id = f[GM.id];
|
|
38
|
+
const text = f[GM.text];
|
|
39
|
+
const channel = f[GM.channel];
|
|
40
|
+
const to = f[GM.to];
|
|
41
|
+
const turn = f[GM.turn];
|
|
42
|
+
if (!(date === null || date instanceof Date) || !optInt(sender) || !optInt(group) || !optInt(to) || !optInt(turn))
|
|
43
|
+
return undefined;
|
|
44
|
+
if (!(id === null || typeof id === 'string' || isInt(id)) || typeof text !== 'string' || !isInt(channel))
|
|
45
|
+
return undefined;
|
|
46
|
+
const line = { sender, text, turn, channel: 'unknown' };
|
|
47
|
+
if (id !== null)
|
|
48
|
+
line.id = String(id);
|
|
49
|
+
if (date !== null && Number.isFinite(date.getTime())) {
|
|
50
|
+
line.time = date.toISOString();
|
|
51
|
+
line.timeMs = date.getTime();
|
|
52
|
+
}
|
|
53
|
+
// The client sorts a message into a tab the same way: a private counterpart first, then a game
|
|
54
|
+
// group (no channel of ours), then the channel (-1 public, else the team).
|
|
55
|
+
if (to !== null) {
|
|
56
|
+
line.channel = 'private';
|
|
57
|
+
line.to = to;
|
|
58
|
+
}
|
|
59
|
+
else if (group !== null) {
|
|
60
|
+
line.channel = 'unknown';
|
|
61
|
+
}
|
|
62
|
+
else if (channel === PUBLIC_CHANNEL) {
|
|
63
|
+
line.channel = 'public';
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
line.channel = 'team';
|
|
67
|
+
line.team = channel;
|
|
68
|
+
}
|
|
69
|
+
return line;
|
|
70
|
+
}
|
|
71
|
+
const numericId = (id) => {
|
|
72
|
+
const n = id === undefined ? Number.NaN : Number(id);
|
|
73
|
+
return Number.isFinite(n) ? n : Number.POSITIVE_INFINITY;
|
|
74
|
+
};
|
|
75
|
+
/** Oldest first: by time where both have one, else by id. */
|
|
76
|
+
function byAge(a, b) {
|
|
77
|
+
if (a.timeMs !== undefined && b.timeMs !== undefined && a.timeMs !== b.timeMs)
|
|
78
|
+
return a.timeMs - b.timeMs;
|
|
79
|
+
return numericId(a.id) - numericId(b.id);
|
|
80
|
+
}
|
|
81
|
+
/** A decoded message list as lines, oldest first; `undefined` when any message is unreadable. */
|
|
82
|
+
function webLines(list) {
|
|
83
|
+
if (!Array.isArray(list))
|
|
84
|
+
return undefined;
|
|
85
|
+
const out = [];
|
|
86
|
+
for (const m of list) {
|
|
87
|
+
if (m === null)
|
|
88
|
+
continue;
|
|
89
|
+
const line = webLine(m);
|
|
90
|
+
if (!line)
|
|
91
|
+
return undefined;
|
|
92
|
+
out.push(line);
|
|
93
|
+
}
|
|
94
|
+
return out.sort(byAge);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The chat of a GameRefresh reply (the body positioned at the result-present flag), oldest first;
|
|
98
|
+
* `undefined` when there is no result, no chat list, or a shape this server does not understand.
|
|
99
|
+
*/
|
|
100
|
+
export function readGameRefreshChat(bundle, body) {
|
|
101
|
+
try {
|
|
102
|
+
if (!body.bool())
|
|
103
|
+
return undefined;
|
|
104
|
+
const ret = bundle.readClass(GAME_DETAILS_AND_CHAT, body);
|
|
105
|
+
if (!isObj(ret) || ret.$type !== GAME_DETAILS_AND_CHAT)
|
|
106
|
+
return undefined;
|
|
107
|
+
const list = fields(ret)[0];
|
|
108
|
+
return list === null ? undefined : webLines(list);
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* The SendChat reply: the updated message list, read straight after the result-present flag (each
|
|
116
|
+
* message behind its own present flag), oldest first; `undefined` when it cannot be read.
|
|
117
|
+
*/
|
|
118
|
+
export function readSendChatReply(bundle, body) {
|
|
119
|
+
try {
|
|
120
|
+
if (!body.bool())
|
|
121
|
+
return undefined;
|
|
122
|
+
const list = body.list((r) => (r.bool() ? bundle.readClass(GAME_MESSAGE, r) : null));
|
|
123
|
+
return list === null ? undefined : webLines(list);
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
130
|
+
const pick = (r, keys) => {
|
|
131
|
+
for (const k of keys)
|
|
132
|
+
if (r[k] !== undefined && r[k] !== null)
|
|
133
|
+
return r[k];
|
|
134
|
+
return undefined;
|
|
135
|
+
};
|
|
136
|
+
const SENDER_KEYS = ['playerID', 'playerId', 'sender', 'senderID', 'from', 'player'];
|
|
137
|
+
const TEXT_KEYS = ['message', 'text', 'chat', 'msg', 'body'];
|
|
138
|
+
const TIME_KEYS = ['time', 'date', 'dateTime', 'created', 'sent', 'when'];
|
|
139
|
+
const LIST_KEYS = ['chat', 'messages', 'Chat'];
|
|
140
|
+
const TURN_KEYS = ['turn', 'turnNumber', 'Turn'];
|
|
141
|
+
// None of these has been seen in a GameFeed reply (V2 in docs/PLAN-TEAMS.md): read only to be tolerant.
|
|
142
|
+
const CHANNEL_KEYS = ['channel', 'Channel', 'teamID', 'teamId', 'team', 'Team'];
|
|
143
|
+
const RECIPIENT_KEYS = ['recipientID', 'recipientId', 'recipient', 'toPlayerID', 'toPlayerId', 'privateTo', 'to'];
|
|
144
|
+
/**
|
|
145
|
+
* GameFeed's chat as lines, in the order sent (most recent last): a message is anything with a text
|
|
146
|
+
* field, its sender an id (GameFeed's `playerID` is the in-game id) or a name. `undefined` when
|
|
147
|
+
* nothing recognisable is there, so the caller can pass the raw value through instead.
|
|
148
|
+
*/
|
|
149
|
+
export function feedChatLines(raw) {
|
|
150
|
+
let list = raw;
|
|
151
|
+
if (isRec(list))
|
|
152
|
+
list = pick(list, LIST_KEYS);
|
|
153
|
+
if (!Array.isArray(list))
|
|
154
|
+
return undefined;
|
|
155
|
+
const out = [];
|
|
156
|
+
for (const item of list) {
|
|
157
|
+
if (!isRec(item))
|
|
158
|
+
return undefined;
|
|
159
|
+
const text = pick(item, TEXT_KEYS);
|
|
160
|
+
if (typeof text !== 'string')
|
|
161
|
+
return undefined;
|
|
162
|
+
const from = pick(item, SENDER_KEYS);
|
|
163
|
+
const id = asInt(from);
|
|
164
|
+
const line = { sender: id ?? null, text, turn: asInt(pick(item, TURN_KEYS)) ?? null, channel: 'unknown' };
|
|
165
|
+
if (id === undefined && typeof from === 'string' && from !== '')
|
|
166
|
+
line.senderName = from;
|
|
167
|
+
const time = pick(item, TIME_KEYS);
|
|
168
|
+
if (typeof time === 'string' || typeof time === 'number') {
|
|
169
|
+
line.time = String(time);
|
|
170
|
+
// A feed time with no zone is UTC, as every other GameFeed time (parseFeedTime); Date.parse would read it as local time.
|
|
171
|
+
const ms = typeof time === 'string' ? (parseFeedTime(time) ?? Date.parse(time)) : Number.NaN;
|
|
172
|
+
if (Number.isFinite(ms))
|
|
173
|
+
line.timeMs = ms;
|
|
174
|
+
}
|
|
175
|
+
const to = asInt(pick(item, RECIPIENT_KEYS));
|
|
176
|
+
const channel = asInt(pick(item, CHANNEL_KEYS));
|
|
177
|
+
if (to !== undefined) {
|
|
178
|
+
line.channel = 'private';
|
|
179
|
+
line.to = to;
|
|
180
|
+
}
|
|
181
|
+
else if (channel !== undefined) {
|
|
182
|
+
if (channel === PUBLIC_CHANNEL)
|
|
183
|
+
line.channel = 'public';
|
|
184
|
+
else {
|
|
185
|
+
line.channel = 'team';
|
|
186
|
+
line.team = channel;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
out.push(line);
|
|
190
|
+
}
|
|
191
|
+
return out;
|
|
192
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
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, rememberGameMap, touchStoredMap, writeStoredMap } from './map-store.js';
|
|
29
|
+
import { scrubSecrets } from './redact.js';
|
|
30
|
+
import { asInt } from './scalars.js';
|
|
31
|
+
const BASE_URL = 'https://war.app';
|
|
32
|
+
const SERVICE = 'war.app';
|
|
33
|
+
/** A game id war.app will not have: the largest positive int32. */
|
|
34
|
+
export const PROBE_GAME_ID = 2147483647;
|
|
35
|
+
/** The hint for a rejected credential. */
|
|
36
|
+
export const AUTH_FAILED_HINT = `Check WARAPP_EMAIL is the email you sign in to war.app with, and regenerate WARAPP_API_TOKEN at ` +
|
|
37
|
+
`${TOKEN_URL} while signed in — changing your war.app password also rotates the token.`;
|
|
38
|
+
/** The game id names no game this player can load. */
|
|
39
|
+
export class WarappNotFoundError extends McpToolError {
|
|
40
|
+
code = 'not_found';
|
|
41
|
+
constructor(gameId) {
|
|
42
|
+
super(`war.app has no game ${gameId} (ServerGameKeyNotFound).`, {
|
|
43
|
+
kind: 'http',
|
|
44
|
+
status: 404,
|
|
45
|
+
hint: 'Check the game id — it is the number in the game URL (war.app/MultiPlayer?GameID=<n>).',
|
|
46
|
+
});
|
|
47
|
+
this.name = 'WarappNotFoundError';
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* A GameFeed game id: a positive whole number below 2^31. Validated locally so
|
|
52
|
+
* a bad id never costs a request (war.app answers `GameID must be an integer`).
|
|
53
|
+
*/
|
|
54
|
+
export function parseGameId(v) {
|
|
55
|
+
const n = typeof v === 'number' || (typeof v === 'string' && /^\s*\d+\s*$/.test(v)) ? asInt(v) : undefined;
|
|
56
|
+
if (n === undefined || n < 1 || n >= 2 ** 31) {
|
|
57
|
+
throw new McpToolError(`Game id must be a positive whole number below 2147483648 (got ${JSON.stringify(String(v)).slice(0, 40)}).`, {
|
|
58
|
+
hint: 'Use the number after GameID= in the game URL.',
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
return n;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Map cache: map id → map, plus game id → map id, in memory per process. Given a data directory, a
|
|
65
|
+
* miss is read back from the persistent store (src/map-store.ts) and a new map or game is written
|
|
66
|
+
* there, best effort: the disk never makes a call fail.
|
|
67
|
+
*/
|
|
68
|
+
export class MapCache {
|
|
69
|
+
#maps = new Map();
|
|
70
|
+
#gameMaps = new Map();
|
|
71
|
+
#refreshed = new Set();
|
|
72
|
+
get(mapId) {
|
|
73
|
+
return this.#maps.get(mapId);
|
|
74
|
+
}
|
|
75
|
+
set(map) {
|
|
76
|
+
this.#maps.set(map.id, map);
|
|
77
|
+
}
|
|
78
|
+
/** The cached map of a game seen before, if it is still cached. */
|
|
79
|
+
forGame(gameId) {
|
|
80
|
+
const mapId = this.#gameMaps.get(gameId);
|
|
81
|
+
return mapId === undefined ? undefined : this.#maps.get(mapId);
|
|
82
|
+
}
|
|
83
|
+
rememberGame(gameId, mapId) {
|
|
84
|
+
this.#gameMaps.set(gameId, mapId);
|
|
85
|
+
}
|
|
86
|
+
/** {@link get}, else the map stored under `dir` (then kept in memory). */
|
|
87
|
+
async load(mapId, dir) {
|
|
88
|
+
const hit = this.#maps.get(mapId);
|
|
89
|
+
if (hit && dir !== undefined)
|
|
90
|
+
await touchStoredMap(dir, hit);
|
|
91
|
+
if (hit || dir === undefined)
|
|
92
|
+
return hit;
|
|
93
|
+
const stored = await readStoredMap(dir, mapId);
|
|
94
|
+
if (stored)
|
|
95
|
+
this.set(stored);
|
|
96
|
+
return stored;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* {@link forGame}, else the map the store under `dir` names for the game (the map then kept in
|
|
100
|
+
* memory). A game found only in the stored index is not remembered here, so the caller's
|
|
101
|
+
* {@link storeGame} moves its index entry to the newest.
|
|
102
|
+
*/
|
|
103
|
+
async loadForGame(gameId, dir) {
|
|
104
|
+
const mapId = this.#gameMaps.get(gameId);
|
|
105
|
+
if (mapId !== undefined && this.#maps.has(mapId))
|
|
106
|
+
return this.load(mapId, dir);
|
|
107
|
+
if (dir === undefined)
|
|
108
|
+
return undefined;
|
|
109
|
+
const id = mapId ?? (await readGameMapId(dir, gameId));
|
|
110
|
+
return id === undefined ? undefined : this.load(id, dir);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Keep `map` in memory and, when it is new to this process (or `replace`), under `dir`; a map
|
|
114
|
+
* already known is only marked recently used there.
|
|
115
|
+
*/
|
|
116
|
+
async store(map, dir, replace = false) {
|
|
117
|
+
const known = this.#maps.has(map.id);
|
|
118
|
+
this.set(map);
|
|
119
|
+
if (dir === undefined)
|
|
120
|
+
return;
|
|
121
|
+
if (!known || replace)
|
|
122
|
+
await writeStoredMap(dir, map);
|
|
123
|
+
else
|
|
124
|
+
await touchStoredMap(dir, map);
|
|
125
|
+
}
|
|
126
|
+
/** Whether `mapId` was already downloaded again this process because the feed named land it lacked. */
|
|
127
|
+
wasRefreshed(mapId) {
|
|
128
|
+
return this.#refreshed.has(mapId);
|
|
129
|
+
}
|
|
130
|
+
markRefreshed(mapId) {
|
|
131
|
+
this.#refreshed.add(mapId);
|
|
132
|
+
}
|
|
133
|
+
/** Remember the game's map in memory and, when that is new to this process, under `dir`. */
|
|
134
|
+
async storeGame(gameId, mapId, dir) {
|
|
135
|
+
const known = this.#gameMaps.get(gameId) === mapId;
|
|
136
|
+
this.rememberGame(gameId, mapId);
|
|
137
|
+
if (!known && dir !== undefined)
|
|
138
|
+
await rememberGameMap(dir, gameId, mapId);
|
|
139
|
+
}
|
|
140
|
+
clear() {
|
|
141
|
+
this.#maps.clear();
|
|
142
|
+
this.#gameMaps.clear();
|
|
143
|
+
this.#refreshed.clear();
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/** Whether the game's standing names a territory `map` does not have. */
|
|
147
|
+
function lacksTerritory(map, game) {
|
|
148
|
+
const territories = game.standing?.territories;
|
|
149
|
+
if (!territories?.length)
|
|
150
|
+
return false;
|
|
151
|
+
const ids = new Set(map.territories.map((t) => t.id));
|
|
152
|
+
return territories.some((t) => !ids.has(t.territoryId));
|
|
153
|
+
}
|
|
154
|
+
/** The process-wide default cache. */
|
|
155
|
+
export const defaultMapCache = new MapCache();
|
|
156
|
+
export class WarappClient {
|
|
157
|
+
#env;
|
|
158
|
+
#cache;
|
|
159
|
+
#dataDir;
|
|
160
|
+
#api;
|
|
161
|
+
#secrets = [];
|
|
162
|
+
constructor(opts = {}) {
|
|
163
|
+
this.#env = opts.env;
|
|
164
|
+
this.#cache = opts.mapCache ?? defaultMapCache;
|
|
165
|
+
this.#dataDir = opts.dataDir;
|
|
166
|
+
this.#api = createApiClient({
|
|
167
|
+
baseUrl: BASE_URL,
|
|
168
|
+
serviceName: SERVICE,
|
|
169
|
+
baseHeaders: { accept: 'application/json' },
|
|
170
|
+
retry: { count: 1, delayMs: 2000, statuses: [429, 500, 502, 503, 504], honorRetryAfter: true },
|
|
171
|
+
redirect: 'same-origin',
|
|
172
|
+
...(opts.timeoutMs !== undefined ? { timeout: opts.timeoutMs } : {}),
|
|
173
|
+
...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),
|
|
174
|
+
...(opts.sleep ? { sleep: opts.sleep } : {}),
|
|
175
|
+
onUnauthorized: () => new McpToolError('war.app refused the request (HTTP 401).', {
|
|
176
|
+
kind: 'credential_rejected',
|
|
177
|
+
status: 401,
|
|
178
|
+
hint: AUTH_FAILED_HINT,
|
|
179
|
+
}),
|
|
180
|
+
onErrorResponse: ({ status, body }) => new McpToolError(`war.app GameFeed answered HTTP ${status}${body.trim() ? `: ${this.#redact(body)}` : ''}`, { kind: 'http', status }),
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
#redact(text) {
|
|
184
|
+
// Scrub by value before the shape redactor and the cut (as `values` would),
|
|
185
|
+
// over no more than truncateErrorMessage itself redacts.
|
|
186
|
+
return truncateErrorMessage(scrubSecrets(text.slice(0, ERROR_REDACTION_INPUT_MAX), this.#secrets), 300);
|
|
187
|
+
}
|
|
188
|
+
#credentials() {
|
|
189
|
+
try {
|
|
190
|
+
const creds = readCredentials(this.#env);
|
|
191
|
+
this.#secrets = [creds.token, { value: creds.email, anyCase: true }];
|
|
192
|
+
return creds;
|
|
193
|
+
}
|
|
194
|
+
catch (e) {
|
|
195
|
+
if (e instanceof WarappConfigError) {
|
|
196
|
+
throw new McpToolError(e.message, {
|
|
197
|
+
kind: 'no_credential',
|
|
198
|
+
hint: `Set WARAPP_EMAIL and WARAPP_API_TOKEN (token from ${TOKEN_URL}).`,
|
|
199
|
+
cause: e,
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
throw e;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
/** One GameFeed call. Returns the parsed body; maps `{ error }` bodies to typed errors. */
|
|
206
|
+
async #feed(gameId, flags) {
|
|
207
|
+
const { email, token } = this.#credentials();
|
|
208
|
+
let path = `/API/GameFeed?GameID=${gameId}`;
|
|
209
|
+
if (flags.history)
|
|
210
|
+
path += '&GetHistory=true';
|
|
211
|
+
if (flags.settings)
|
|
212
|
+
path += '&GetSettings=true';
|
|
213
|
+
if (flags.chat)
|
|
214
|
+
path += '&GetChat=true';
|
|
215
|
+
if (flags.noMap)
|
|
216
|
+
path += '&GetMap=false';
|
|
217
|
+
const body = await this.#api.fetchJson('POST', path, {
|
|
218
|
+
rawBody: new URLSearchParams({ Email: email, APIToken: token }).toString(),
|
|
219
|
+
contentType: 'application/x-www-form-urlencoded',
|
|
220
|
+
// A read sent as POST: safe to repeat.
|
|
221
|
+
idempotent: true,
|
|
222
|
+
expect: 'object',
|
|
223
|
+
});
|
|
224
|
+
const error = feedErrorOf(body);
|
|
225
|
+
if (error === undefined)
|
|
226
|
+
return body;
|
|
227
|
+
if (error === 'Auth failed') {
|
|
228
|
+
throw new McpToolError('war.app rejected the email + API token (Auth failed).', {
|
|
229
|
+
kind: 'credential_rejected',
|
|
230
|
+
hint: AUTH_FAILED_HINT,
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
if (/ServerGameKeyNotFound/.test(error))
|
|
234
|
+
throw new WarappNotFoundError(gameId);
|
|
235
|
+
throw new McpToolError(`war.app GameFeed error: ${this.#redact(error)}`, { kind: 'http' });
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Load a game, normalized. The map comes from the cache (memory, else the data directory's
|
|
239
|
+
* store) when this game's map is already known (fetched with GetMap=false), else from the
|
|
240
|
+
* feed (and is then cached).
|
|
241
|
+
*/
|
|
242
|
+
async getGame(id, opts = {}) {
|
|
243
|
+
const gameId = parseGameId(id);
|
|
244
|
+
const dir = this.#dir();
|
|
245
|
+
let known = await this.#cache.loadForGame(gameId, dir);
|
|
246
|
+
let body = await this.#feed(gameId, { ...opts, noMap: known !== undefined || opts.map === false });
|
|
247
|
+
let game = normalizeGame(body);
|
|
248
|
+
// GameFeed sends no map version, so an edited map shows as land the cached copy lacks: download
|
|
249
|
+
// it once more (once per map per process, in case the loose standing parser misreads an id).
|
|
250
|
+
let replace = false;
|
|
251
|
+
if (known && opts.map !== false && lacksTerritory(known, game) && !this.#cache.wasRefreshed(known.id)) {
|
|
252
|
+
this.#cache.markRefreshed(known.id);
|
|
253
|
+
// A failed refresh keeps the first read and the known map: the extra request is a check, not the read.
|
|
254
|
+
const fresher = await this.#feed(gameId, { ...opts, noMap: false }).catch(() => undefined);
|
|
255
|
+
if (fresher) {
|
|
256
|
+
body = fresher;
|
|
257
|
+
game = normalizeGame(body);
|
|
258
|
+
known = undefined;
|
|
259
|
+
replace = true;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
let map = known;
|
|
263
|
+
const rawMap = body.map;
|
|
264
|
+
if (!map && rawMap && typeof rawMap === 'object' && Array.isArray(rawMap.territories)) {
|
|
265
|
+
const fresh = normalizeMap(rawMap);
|
|
266
|
+
map = replace ? fresh : (this.#cache.get(fresh.id) ?? fresh);
|
|
267
|
+
await this.#cache.store(map, dir, replace);
|
|
268
|
+
}
|
|
269
|
+
if (!map && game.settings?.mapId !== undefined)
|
|
270
|
+
map = await this.#cache.load(game.settings.mapId, dir);
|
|
271
|
+
if (map) {
|
|
272
|
+
// The index only saves a map download for a caller that wants the map, on a game still played:
|
|
273
|
+
// a `map: false` caller always asks GetMap=false, and a finished game (map statistics read many)
|
|
274
|
+
// would only push live games out of the bounded index.
|
|
275
|
+
const index = opts.map !== false && game.state !== 'Finished';
|
|
276
|
+
await this.#cache.storeGame(gameId, map.id, index ? dir : undefined);
|
|
277
|
+
game.map = map;
|
|
278
|
+
}
|
|
279
|
+
return game;
|
|
280
|
+
}
|
|
281
|
+
/** The data directory for the map store, or `undefined` (memory only); never throws. */
|
|
282
|
+
#dir() {
|
|
283
|
+
try {
|
|
284
|
+
return this.#dataDir?.();
|
|
285
|
+
}
|
|
286
|
+
catch {
|
|
287
|
+
return undefined;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* The game ids of a ladder or tournament, from war.app's game-ID feed
|
|
292
|
+
* (`/API/GameIDFeed?LadderID=<n>` or `?TournamentID=<n>`, documented on the
|
|
293
|
+
* public wiki page "Game ID feed API": 1v1 ladder 0, 2v2 1, 3v3 4).
|
|
294
|
+
* UNVERIFIED: the wiki names neither the method, the auth nor the reply, so
|
|
295
|
+
* this POSTs the GameFeed credentials (harmless if the feed is public) and
|
|
296
|
+
* reads the ids loosely — a bare array, or `gameIDs` / `gameIds` / `games`,
|
|
297
|
+
* each a number, numeric string or `{ id | gameID }`. Distinct, newest
|
|
298
|
+
* (highest id) first.
|
|
299
|
+
*/
|
|
300
|
+
async getGameIds(source) {
|
|
301
|
+
const [key, raw] = 'ladderId' in source ? ['LadderID', source.ladderId] : ['TournamentID', source.tournamentId];
|
|
302
|
+
if (!Number.isInteger(raw) || raw < 0 || raw >= 2 ** 31) {
|
|
303
|
+
throw new McpToolError(`${key} must be a whole number from 0 (got ${String(raw).slice(0, 20)}).`, {
|
|
304
|
+
hint: 'Ladders: 1v1 is 0, 2v2 is 1, 3v3 is 4.',
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
const { email, token } = this.#credentials();
|
|
308
|
+
const body = await this.#api.fetchJson('POST', `/API/GameIDFeed?${key}=${raw}`, {
|
|
309
|
+
rawBody: new URLSearchParams({ Email: email, APIToken: token }).toString(),
|
|
310
|
+
contentType: 'application/x-www-form-urlencoded',
|
|
311
|
+
idempotent: true,
|
|
312
|
+
});
|
|
313
|
+
const error = Array.isArray(body) ? undefined : feedErrorOf(body);
|
|
314
|
+
if (error === 'Auth failed') {
|
|
315
|
+
throw new McpToolError('war.app rejected the email + API token (Auth failed).', {
|
|
316
|
+
kind: 'credential_rejected',
|
|
317
|
+
hint: AUTH_FAILED_HINT,
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
if (error !== undefined)
|
|
321
|
+
throw new McpToolError(`war.app GameIDFeed error: ${this.#redact(error)}`, { kind: 'http' });
|
|
322
|
+
return gameIdsOf(body);
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* A map this process has already loaded (with some game), by map id; `undefined`
|
|
326
|
+
* otherwise. GameFeed serves maps only with a game, so this never makes a request.
|
|
327
|
+
*/
|
|
328
|
+
cachedMap(mapId) {
|
|
329
|
+
return this.#cache.get(mapId);
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Prove the credentials work without loading a real game: ask for
|
|
333
|
+
* {@link PROBE_GAME_ID}. `ServerGameKeyNotFound` (or, improbably, a game)
|
|
334
|
+
* means authenticated; `Auth failed` throws `credential_rejected`.
|
|
335
|
+
*/
|
|
336
|
+
async probeAuth() {
|
|
337
|
+
try {
|
|
338
|
+
await this.#feed(PROBE_GAME_ID, { noMap: true });
|
|
339
|
+
}
|
|
340
|
+
catch (e) {
|
|
341
|
+
if (!(e instanceof WarappNotFoundError))
|
|
342
|
+
throw e;
|
|
343
|
+
}
|
|
344
|
+
return { authenticated: true };
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
/** Game ids out of a GameIDFeed body, in any of the plausible layouts; distinct, descending. */
|
|
348
|
+
function gameIdsOf(body) {
|
|
349
|
+
const rec = body && typeof body === 'object' && !Array.isArray(body) ? body : undefined;
|
|
350
|
+
const list = Array.isArray(body) ? body : (rec?.gameIDs ?? rec?.gameIds ?? rec?.GameIDs ?? rec?.games);
|
|
351
|
+
if (!Array.isArray(list))
|
|
352
|
+
return [];
|
|
353
|
+
const ids = new Set();
|
|
354
|
+
for (const e of list) {
|
|
355
|
+
const v = e && typeof e === 'object' ? (e.id ?? e.gameID) : e;
|
|
356
|
+
const n = asInt(v);
|
|
357
|
+
if (n !== undefined && n > 0 && n < 2 ** 31)
|
|
358
|
+
ids.add(n);
|
|
359
|
+
}
|
|
360
|
+
return [...ids].sort((a, b) => b - a);
|
|
361
|
+
}
|
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
|
+
}
|