@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.
Files changed (177) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +199 -8
  4. package/dist/analysis/award.js +159 -0
  5. package/dist/analysis/bonuses.js +98 -0
  6. package/dist/analysis/breach.js +62 -0
  7. package/dist/analysis/card-support.js +329 -0
  8. package/dist/analysis/card-threats.js +234 -0
  9. package/dist/analysis/cards-in-effect.js +130 -0
  10. package/dist/analysis/chains.js +59 -0
  11. package/dist/analysis/chokepoints.js +140 -0
  12. package/dist/analysis/combat.js +231 -0
  13. package/dist/analysis/commander-safety.js +149 -0
  14. package/dist/analysis/commitments.js +338 -0
  15. package/dist/analysis/exchange.js +155 -0
  16. package/dist/analysis/graph.js +82 -0
  17. package/dist/analysis/guard-off.js +54 -0
  18. package/dist/analysis/guess.js +351 -0
  19. package/dist/analysis/headroom.js +241 -0
  20. package/dist/analysis/hold-diff.js +64 -0
  21. package/dist/analysis/how-lost.js +130 -0
  22. package/dist/analysis/index.js +14 -0
  23. package/dist/analysis/local-deploy.js +159 -0
  24. package/dist/analysis/lookahead.js +108 -0
  25. package/dist/analysis/opponent-profile.js +551 -0
  26. package/dist/analysis/opponents.js +1245 -0
  27. package/dist/analysis/outlook.js +633 -0
  28. package/dist/analysis/overrides.js +60 -0
  29. package/dist/analysis/picks.js +1879 -0
  30. package/dist/analysis/plan/after-leftover.js +140 -0
  31. package/dist/analysis/plan/cap-spend.js +242 -0
  32. package/dist/analysis/plan/captures.js +1195 -0
  33. package/dist/analysis/plan/commander.js +236 -0
  34. package/dist/analysis/plan/completed.js +29 -0
  35. package/dist/analysis/plan/conceded-out.js +131 -0
  36. package/dist/analysis/plan/estimates.js +715 -0
  37. package/dist/analysis/plan/guard-off.js +232 -0
  38. package/dist/analysis/plan/holds.js +1631 -0
  39. package/dist/analysis/plan/leftover.js +760 -0
  40. package/dist/analysis/plan/move-order.js +319 -0
  41. package/dist/analysis/plan/orders.js +317 -0
  42. package/dist/analysis/plan/relations.js +702 -0
  43. package/dist/analysis/plan/report.js +672 -0
  44. package/dist/analysis/plan/shared.js +1218 -0
  45. package/dist/analysis/plan/stand-still.js +823 -0
  46. package/dist/analysis/plan/state.js +44 -0
  47. package/dist/analysis/plan/strike.js +1416 -0
  48. package/dist/analysis/plan/targets.js +651 -0
  49. package/dist/analysis/plan/team.js +299 -0
  50. package/dist/analysis/plan/threats.js +927 -0
  51. package/dist/analysis/plan/transfers.js +328 -0
  52. package/dist/analysis/plan/util.js +5 -0
  53. package/dist/analysis/plan/vacated.js +285 -0
  54. package/dist/analysis/planner.js +2922 -0
  55. package/dist/analysis/player-record.js +144 -0
  56. package/dist/analysis/player.js +268 -0
  57. package/dist/analysis/profile.js +347 -0
  58. package/dist/analysis/relations.js +1030 -0
  59. package/dist/analysis/schedule.js +88 -0
  60. package/dist/analysis/since-last.js +50 -0
  61. package/dist/analysis/static-seats.js +71 -0
  62. package/dist/analysis/stress.js +577 -0
  63. package/dist/analysis/team-brief.js +151 -0
  64. package/dist/analysis/tripwire.js +644 -0
  65. package/dist/analysis/turn-sim.js +259 -0
  66. package/dist/analysis/whereabouts.js +1109 -0
  67. package/dist/board.js +105 -0
  68. package/dist/bundle.js +117959 -36172
  69. package/dist/cards.js +435 -0
  70. package/dist/chat-cursor.js +135 -0
  71. package/dist/chat.js +192 -0
  72. package/dist/client.js +361 -0
  73. package/dist/config.js +62 -0
  74. package/dist/direct/link.js +102 -0
  75. package/dist/direct/session.js +267 -0
  76. package/dist/direct/transport.js +424 -0
  77. package/dist/guess-salt.js +65 -0
  78. package/dist/hosted.js +24 -0
  79. package/dist/index.js +33 -0
  80. package/dist/join-color.js +140 -0
  81. package/dist/live.js +278 -0
  82. package/dist/map-stats.js +152 -0
  83. package/dist/map-store.js +204 -0
  84. package/dist/move-order.js +141 -0
  85. package/dist/my-games.js +180 -0
  86. package/dist/normalize.js +411 -0
  87. package/dist/open-games.js +537 -0
  88. package/dist/outlook-log.js +138 -0
  89. package/dist/path-lock.js +22 -0
  90. package/dist/pick-list.js +193 -0
  91. package/dist/player-record-store.js +229 -0
  92. package/dist/player-states.js +31 -0
  93. package/dist/profile-store.js +677 -0
  94. package/dist/protocol/bundle.js +375 -0
  95. package/dist/protocol/codec.js +556 -0
  96. package/dist/protocol/decoded.js +12 -0
  97. package/dist/protocol/interp.js +1904 -0
  98. package/dist/protocol/methods.js +531 -0
  99. package/dist/protocol/rpc.js +202 -0
  100. package/dist/push/listener.js +393 -0
  101. package/dist/push/packets.js +66 -0
  102. package/dist/push/socketio.js +333 -0
  103. package/dist/push/websocket.js +179 -0
  104. package/dist/redact.js +62 -0
  105. package/dist/relations-store.js +242 -0
  106. package/dist/replay.js +215 -0
  107. package/dist/scalars.js +28 -0
  108. package/dist/scout.js +346 -0
  109. package/dist/stats.js +269 -0
  110. package/dist/strategy/card-clock.js +185 -0
  111. package/dist/strategy/map-notes.js +128 -0
  112. package/dist/strategy/notes.js +2168 -0
  113. package/dist/team-cards.js +84 -0
  114. package/dist/team-orders.js +150 -0
  115. package/dist/teams.js +19 -0
  116. package/dist/tools/award.js +206 -0
  117. package/dist/tools/begin-turn.js +162 -0
  118. package/dist/tools/board.js +77 -0
  119. package/dist/tools/card-advice.js +256 -0
  120. package/dist/tools/card-effects.js +49 -0
  121. package/dist/tools/card-plays.js +434 -0
  122. package/dist/tools/card-support-advice.js +140 -0
  123. package/dist/tools/chat-inbox.js +146 -0
  124. package/dist/tools/chat.js +483 -0
  125. package/dist/tools/check-plan.js +688 -0
  126. package/dist/tools/commander-check.js +102 -0
  127. package/dist/tools/commitments.js +216 -0
  128. package/dist/tools/common.js +143 -0
  129. package/dist/tools/diplomacy.js +342 -0
  130. package/dist/tools/game.js +126 -0
  131. package/dist/tools/guess-view.js +56 -0
  132. package/dist/tools/healthcheck.js +90 -0
  133. package/dist/tools/hints.js +34 -0
  134. package/dist/tools/how-lost.js +154 -0
  135. package/dist/tools/index.js +142 -0
  136. package/dist/tools/join-game.js +327 -0
  137. package/dist/tools/leave-game.js +181 -0
  138. package/dist/tools/live-context.js +339 -0
  139. package/dist/tools/live.js +404 -0
  140. package/dist/tools/map-stats.js +117 -0
  141. package/dist/tools/map.js +133 -0
  142. package/dist/tools/my-games.js +123 -0
  143. package/dist/tools/open-games.js +104 -0
  144. package/dist/tools/opponents.js +151 -0
  145. package/dist/tools/order-options.js +135 -0
  146. package/dist/tools/picks.js +292 -0
  147. package/dist/tools/profile-hook.js +156 -0
  148. package/dist/tools/profile-opponents.js +121 -0
  149. package/dist/tools/profile-reads.js +99 -0
  150. package/dist/tools/push.js +385 -0
  151. package/dist/tools/relations.js +611 -0
  152. package/dist/tools/resolve.js +45 -0
  153. package/dist/tools/route.js +36 -0
  154. package/dist/tools/scout.js +87 -0
  155. package/dist/tools/session.js +163 -0
  156. package/dist/tools/strategy.js +200 -0
  157. package/dist/tools/stress-opponents.js +83 -0
  158. package/dist/tools/surrender.js +240 -0
  159. package/dist/tools/survival.js +189 -0
  160. package/dist/tools/team-brief.js +266 -0
  161. package/dist/tools/team-source.js +222 -0
  162. package/dist/tools/team.js +182 -0
  163. package/dist/tools/turn.js +2761 -0
  164. package/dist/tools/uncommit.js +160 -0
  165. package/dist/tools/where.js +275 -0
  166. package/dist/tools/write-kit.js +158 -0
  167. package/dist/transport-bridge.js +33 -0
  168. package/dist/trend.js +452 -0
  169. package/dist/version.js +4 -0
  170. package/manifest.json +174 -4
  171. package/mint.yaml +101 -14
  172. package/package.json +11 -6
  173. package/server.json +40 -3
  174. package/skills/warapp-api/SKILL.md +95 -4
  175. package/skills/warapp-api/references/scout.mjs +348 -0
  176. package/skills/warapp-api/scripts/warapp.sh +69 -8
  177. package/skills/warapp-mcp/SKILL.md +969 -21
@@ -0,0 +1,36 @@
1
+ import { McpToolError } from '@chrischall/mcp-utils';
2
+ import { z } from 'zod';
3
+ import { shortestPath } from '../analysis/index.js';
4
+ import { gameIdArg, graphOf, readAnnotations, respond, untrustedDescription, untrustedText } from './common.js';
5
+ import { lookupMeta } from './hints.js';
6
+ import { mapOf } from './map.js';
7
+ import { resolveTerritory } from './resolve.js';
8
+ const territoryArg = (end) => z.union([z.string(), z.number()]).describe(`The ${end} territory: its id, its name, or a unique part of its name.`);
9
+ export function registerRouteTool(server, client) {
10
+ server.registerTool('warapp_plan_route', {
11
+ title: 'Plan a route between two war.app territories',
12
+ description: untrustedDescription('Find the shortest path between two territories on a war.app (Warzone) game\'s map — how many moves apart ' +
13
+ 'they are and every territory on the way, by name. Territories can be given by id or by name. ' +
14
+ 'Map-only (ignores who holds what). Read-only.'),
15
+ _meta: lookupMeta(['warzone route', 'path between territories', 'how far is']),
16
+ annotations: readAnnotations('Plan a war.app route'),
17
+ inputSchema: z.object({ game_id: gameIdArg, from: territoryArg('starting'), to: territoryArg('destination') }),
18
+ }, async ({ game_id, from, to }) => {
19
+ const game = await client.getGame(game_id);
20
+ const map = mapOf(game);
21
+ const a = resolveTerritory(map, from);
22
+ const b = resolveTerritory(map, to);
23
+ const path = shortestPath(graphOf(map), a.id, b.id);
24
+ // Territory and map names are map-maker text: delimited, since errors sit outside the untrusted envelope.
25
+ if (!path) {
26
+ throw new McpToolError(`No route connects ${untrustedText(a.name)} (${a.id}) and ${untrustedText(b.name)} (${b.id}) on map ${map.id} (${untrustedText(map.name)}).`);
27
+ }
28
+ const byId = new Map(map.territories.map((t) => [t.id, t.name]));
29
+ return respond(undefined, ['compact'], () => ({
30
+ from: { id: a.id, name: a.name },
31
+ to: { id: b.id, name: b.name },
32
+ hops: path.length - 1,
33
+ path: path.map((id) => ({ id, name: byId.get(id) })),
34
+ }));
35
+ });
36
+ }
@@ -0,0 +1,87 @@
1
+ // warapp_scout_player: an opponent's public stats and my head-to-head record
2
+ // with them, from war.app's Profile and CommonGames pages (GETs through the
3
+ // signed-in tab). Only allowlisted fields leave src/scout.ts — never location
4
+ // or any other personal detail.
5
+ import { McpToolError } from '@chrischall/mcp-utils';
6
+ import { z } from 'zod';
7
+ import { commonGamesUrl, isProfile, parseCommonGames, parseProfile, profileUrl } from '../scout.js';
8
+ import { gameIdArg, readAnnotations, respond, untrustedDescription } from './common.js';
9
+ import { lookupMeta } from './hints.js';
10
+ import { metRead } from './profile-reads.js';
11
+ import { resolvePlayer } from './resolve.js';
12
+ /**
13
+ * The player's invite token (= GameFeed player id), looked up in a game or given raw, and the numeric
14
+ * id the profile store keys it by (a raw token read as GameFeed ids are).
15
+ */
16
+ async function tokenOf(ctx, gameId, player) {
17
+ const raw = String(player).trim();
18
+ if (gameId === undefined) {
19
+ if (/^\d{5,20}$/.test(raw))
20
+ return { token: raw, id: Number(raw) };
21
+ throw new McpToolError(`Pass game_id to look up ${JSON.stringify(raw)} by name, or pass the player's id.`, {
22
+ hint: 'warapp_get_game lists each player with their id; warapp_my_games lists game ids.',
23
+ });
24
+ }
25
+ const game = await ctx.client.getGame(gameId, { map: false });
26
+ const p = resolvePlayer(game.players, raw);
27
+ return { token: p.feedId ?? String(p.id), id: p.id };
28
+ }
29
+ async function page(ctx, url, what) {
30
+ try {
31
+ return await ctx.fetchPage(url);
32
+ }
33
+ catch (e) {
34
+ throw new McpToolError(`Could not read the player's ${what} page: ${e instanceof Error ? e.message : String(e)}`, {
35
+ kind: 'unknown',
36
+ hint: 'Make sure a signed-in war.app tab is open and paired (reload or focus it if it is frozen), then retry.',
37
+ cause: e,
38
+ });
39
+ }
40
+ }
41
+ export function registerScoutTool(server, ctx, opts = {}) {
42
+ const env = opts.env ?? process.env;
43
+ server.registerTool('warapp_scout_player', {
44
+ title: 'Scout a war.app player',
45
+ description: untrustedDescription('Scout a war.app (Warzone) player: name, level, multi-player games played and real-time share, when last ' +
46
+ 'seen, boot count and boot rate, ranked totals and per-format records ({format, wins, games, pct}), and your ' +
47
+ 'head-to-head — the games you share with them (id, name, started, teams, your state) with your wins, ' +
48
+ 'losses (games without teams only: in a team game they may have been your teammate, so those are counted ' +
49
+ 'as `teamGames`) and games in progress. Name the player with game_id + player (name or id), or pass just their ' +
50
+ 'player id. Reads war.app pages through your signed-in tab (ContextMint Bridge). Fields a new player ' +
51
+ 'lacks are null. When your earlier finished games with them are in the opponent-profile record (WARAPP_PLAYER_PROFILE), ' +
52
+ '`met` gives how many you met them in and the read from those games (each habit with its value, n, confidence and ' +
53
+ 'basis, and the labels): a likelihood, never a certainty, and never to be quoted to them. Read-only.'),
54
+ _meta: lookupMeta(['scout player', 'opponent stats', 'warzone player', 'head to head', 'who am i playing']),
55
+ annotations: readAnnotations('Scout a war.app player'),
56
+ inputSchema: z.object({
57
+ game_id: gameIdArg.optional(),
58
+ player: z
59
+ .union([z.string(), z.number()])
60
+ .describe('The player: a name (or part of one) in game_id, or their player id (GameFeed id / invite token).'),
61
+ }),
62
+ }, async ({ game_id, player }) => {
63
+ const { token, id } = await tokenOf(ctx, game_id, player);
64
+ const [profileHtml, commonHtml] = await Promise.all([
65
+ page(ctx, profileUrl(token), 'profile'),
66
+ page(ctx, commonGamesUrl(token), 'common games'),
67
+ ]);
68
+ const profile = parseProfile(profileHtml);
69
+ if (!isProfile(profile)) {
70
+ throw new McpToolError(`war.app's page for player ${token} is not a player profile.`, {
71
+ kind: 'unknown',
72
+ hint: 'Either the war.app tab is signed out (sign in, or reload or focus the tab if it is frozen) or no ' +
73
+ 'player has this id — check it with warapp_get_game.',
74
+ });
75
+ }
76
+ const headToHead = parseCommonGames(commonHtml);
77
+ const { name, ...stats } = profile;
78
+ // Part D (docs/PLAN-PROFILES.md section 11): the cross-game read, when the record has the player.
79
+ const met = await metRead(ctx.dataDir, env, id).catch(() => undefined);
80
+ return respond(undefined, ['compact'], () => ({
81
+ player: { id: token, name },
82
+ profile: stats,
83
+ headToHead,
84
+ ...(met ? { met } : {}),
85
+ }));
86
+ });
87
+ }
@@ -0,0 +1,163 @@
1
+ // The direct-transport session tools:
2
+ //
3
+ // - `warapp_link_session` (write, confirm-gated, owner-only intent) captures
4
+ // the signed-in war.app session cookie once through the browser bridge and
5
+ // stores it, so later calls skip Chrome (src/direct/link.ts). It reports only
6
+ // success + when it was captured + the active transport — NEVER the token.
7
+ // - `warapp_session_status` (read) reports whether a session is linked, when it
8
+ // was captured and how old it is, and which leg (direct vs the browser
9
+ // bridge) is serving calls now — again never the token. While the direct leg's
10
+ // last answer was a `SessionExpiredError`, it surfaces "session expired — run
11
+ // warapp_link_session" so the owner relinks; a relink clears it.
12
+ //
13
+ // LOCAL-ONLY: on a hosted child (src/hosted.ts) `warapp_link_session` is not
14
+ // registered, and `warapp_session_status` reports `hosted: true` and the
15
+ // browser bridge without reading the store or suggesting a link.
16
+ //
17
+ // SECURITY: the AuthToken is a full-account credential. Neither tool returns,
18
+ // logs, or previews it; the status output carries only `capturedAt`/`host`/age.
19
+ import { CONFIRM_INJECTION_RULE, toolAnnotations } from '@chrischall/mcp-utils';
20
+ import { z } from 'zod';
21
+ import { linkSession } from '../direct/link.js';
22
+ import { readSession, SESSION_HOST } from '../direct/session.js';
23
+ import { isHosted } from '../hosted.js';
24
+ import { lookupMeta, mintMeta } from './hints.js';
25
+ import { readAnnotations, respond, untrustedDescription } from './common.js';
26
+ import { defineGatedWrite } from './write-kit.js';
27
+ const HINT_NOT_LINKED = 'No war.app session is linked. Run warapp_link_session to use the direct (no-browser) transport; the browser ' +
28
+ 'bridge is used until then.';
29
+ const NOTE_HOSTED = 'This server is hosted: the direct (no-browser) transport is local-only, so war.app calls go through the browser ' +
30
+ 'bridge and your signed-in war.app tab.';
31
+ const HINT_EXPIRED = 'The linked war.app session is signed out (war.app answered a direct call signed-out this run). Run ' +
32
+ 'warapp_link_session to relink.';
33
+ /**
34
+ * The sentence other tools' descriptions carry about the direct transport —
35
+ * empty on a hosted child, where there is no session to link.
36
+ */
37
+ export function noBrowserNote(hosted) {
38
+ return hosted ? '' : ' Works without a browser once a session is linked (warapp_link_session).';
39
+ }
40
+ export function registerSessionTools(server, deps) {
41
+ const read = deps.read ?? (() => readSession(deps.env));
42
+ const link = deps.link ?? ((opts) => linkSession({ ...(deps.env ? { env: deps.env } : {}), ...opts }));
43
+ const now = deps.now ?? Date.now;
44
+ const hosted = deps.hosted ?? isHosted(deps.env ?? process.env);
45
+ /** The board decoder, once a live tool has loaded the client bundle (#148). */
46
+ const decoderView = () => {
47
+ if (!deps.decoder)
48
+ return {};
49
+ const d = deps.decoder();
50
+ // Not loaded yet in this process: say so rather than leave the field out.
51
+ if (!d)
52
+ return {
53
+ decoder: {
54
+ checked: false,
55
+ note: "Not checked yet: no live board has been decoded in this process. The check runs when war.app's client first loads (any live tool).",
56
+ },
57
+ };
58
+ return {
59
+ decoder: {
60
+ ...d,
61
+ ...(d.fallback
62
+ ? { note: "A cached copy of war.app's client is decoding boards: the current version could not be looked up." }
63
+ : {}),
64
+ },
65
+ };
66
+ };
67
+ server.registerTool('warapp_session_status', {
68
+ title: 'war.app direct-transport session status',
69
+ description: untrustedDescription(hosted
70
+ ? 'Report which transport serves war.app calls on this hosted server (always the browser bridge: the ' +
71
+ 'direct, no-browser transport is local-only) and which transport the turn-notification push socket ' +
72
+ 'rides (websocket or xhr-polling) once it has run, and, once a live board has been read, which client ' +
73
+ 'bundle decodes boards (a cached stand-in or not) and which of its reader helpers were verified. Read-only.'
74
+ : 'Report whether a signed-in war.app session is linked for the direct (no-browser) transport, when it was ' +
75
+ 'captured and how old it is, which transport is currently active (direct, or the browser bridge), and ' +
76
+ 'which transport the turn-notification push socket rides (websocket or xhr-polling) once it has run, ' +
77
+ 'and, once a live board has been read, which client bundle decodes boards (a cached stand-in or not) and ' +
78
+ 'which of its reader helpers were verified. ' +
79
+ 'Never shows the session cookie. Read-only; use warapp_link_session to link or relink.'),
80
+ _meta: lookupMeta(['war.app session', 'is war.app linked', 'direct transport status']),
81
+ annotations: readAnnotations('war.app session status'),
82
+ inputSchema: z.object({}),
83
+ }, async () => {
84
+ if (hosted) {
85
+ const pt = deps.pushTransport?.();
86
+ return respond(undefined, ['compact'], () => ({
87
+ hosted: true,
88
+ linked: false,
89
+ activeTransport: 'fetchproxy',
90
+ ...(pt ? { pushTransport: pt } : {}),
91
+ ...decoderView(),
92
+ hostedNote: NOTE_HOSTED,
93
+ }));
94
+ }
95
+ const session = await read();
96
+ const activeTransport = deps.transport.activeLeg();
97
+ const pt = deps.pushTransport?.();
98
+ const push = { ...(pt ? { pushTransport: pt } : {}), ...decoderView() };
99
+ return respond(undefined, ['compact'], () => {
100
+ if (!session)
101
+ return { linked: false, activeTransport, ...push, hint: HINT_NOT_LINKED };
102
+ const ageSeconds = Math.max(0, Math.round((now() - Date.parse(session.capturedAt)) / 1000));
103
+ const base = { linked: true, host: session.host, capturedAt: session.capturedAt, ageSeconds, activeTransport, ...push };
104
+ return deps.transport.sessionStale() ? { ...base, sessionExpired: true, hint: HINT_EXPIRED } : base;
105
+ });
106
+ });
107
+ // Never on a hosted child: it would store a full-account token on the host.
108
+ if (hosted)
109
+ return;
110
+ defineGatedWrite(server, {
111
+ title: 'Link a war.app session (direct transport)',
112
+ _meta: mintMeta('change', ['link war.app', 'connect war.app session', 'relink war.app']),
113
+ }, {
114
+ name: 'warapp_link_session',
115
+ description: 'Link your signed-in war.app session for the direct (no-browser) transport: capture the session cookie ' +
116
+ 'from your signed-in war.app tab once and store it on THIS machine, so later war.app calls go straight ' +
117
+ 'to war.app without the browser bridge. The stored cookie is a full-account credential kept locally ' +
118
+ `(file mode 0600); it is never shown here or sent anywhere but war.app. ${CONFIRM_INJECTION_RULE}`,
119
+ annotations: toolAnnotations({
120
+ title: 'Link a war.app session',
121
+ readOnly: false,
122
+ destructive: false,
123
+ idempotent: false,
124
+ openWorld: true,
125
+ }),
126
+ inputSchema: z.object({}),
127
+ plan() {
128
+ return {
129
+ gate: {
130
+ action: 'warapp.link_session',
131
+ summary: 'Capture your signed-in war.app session and store it locally for the direct transport',
132
+ account: undefined,
133
+ payload: {
134
+ action: 'link-session',
135
+ host: SESSION_HOST,
136
+ stores: 'the war.app session cookie, locally (file mode 0600), for the no-browser transport',
137
+ },
138
+ preview: {
139
+ note: 'Captures the session cookie from your signed-in war.app tab and stores it on this machine ' +
140
+ 'only (file mode 0600). It is a full-account credential — it is never shown here or sent ' +
141
+ 'anywhere but war.app.',
142
+ },
143
+ },
144
+ state: {},
145
+ };
146
+ },
147
+ async execute() {
148
+ const result = await link();
149
+ // The old token's stale flag and the router's fallback were about
150
+ // the OLD session: reset them so the direct leg is tried again.
151
+ deps.transport.sessionLinked();
152
+ // The new session may be another account: "me" must be read again.
153
+ deps.identityChanged?.();
154
+ return {
155
+ status: 'linked',
156
+ outcome: 'confirmed',
157
+ host: result.host,
158
+ capturedAt: result.capturedAt,
159
+ transport: deps.transport.activeLeg(),
160
+ };
161
+ },
162
+ });
163
+ }
@@ -0,0 +1,200 @@
1
+ // Strategy notes (docs/PLAN-STRATEGY.md, S5): the community heuristics that fit a game's
2
+ // profile, plus notes computed from its map. Read-only: one GameFeed read with a game,
3
+ // none without. Also served as MCP resources: `warapp://strategy` (every general note)
4
+ // and `warapp://strategy/map/{mapId}` (a map this process has loaded).
5
+ import { McpToolError } from '@chrischall/mcp-utils';
6
+ import { ResourceTemplate } from '@modelcontextprotocol/server';
7
+ import { z } from 'zod';
8
+ import { mapNotes, mapNotesMarkdown } from '../strategy/map-notes.js';
9
+ import { feedProfile, generalNotes, hasCostlyBonus, NOTE_TOPICS, noteContext, notesFor, notesMarkdown, TOPIC_TITLES, } from '../strategy/notes.js';
10
+ import { cardClock } from '../strategy/card-clock.js';
11
+ import { cardRules } from '../cards.js';
12
+ import { gameIdArg, graphOf, readAnnotations, respond, untrustedDescription, viewArg, WARAPP_UNTRUSTED_NOTE } from './common.js';
13
+ import { lookupMeta } from './hints.js';
14
+ import { DEFAULT_TERRITORY_LIMIT, PICK_PHASE_STATE, pickSettings } from './picks.js';
15
+ import { mapOf } from './map.js';
16
+ import { currentTurn } from './turn.js';
17
+ const VIEWS = ['compact', 'full'];
18
+ const STRATEGY_URI = 'warapp://strategy';
19
+ const STRATEGY_MAP_URI = 'warapp://strategy/map/{mapId}';
20
+ const mapIdArg = z.coerce
21
+ .number()
22
+ .int()
23
+ .min(1)
24
+ .max(2 ** 31 - 1)
25
+ .optional()
26
+ .describe('A war.app map id (the game settings\' Map). Alone, it works for a map this server has already loaded with a game.');
27
+ function mapNotLoaded(mapId) {
28
+ return new McpToolError(`Map ${mapId} has not been loaded yet.`, {
29
+ hint: 'war.app serves a map only with a game: pass the game_id of a game on that map (warapp_strategy or warapp_get_map loads it).',
30
+ });
31
+ }
32
+ const noteView = (full) => (n) => ({
33
+ id: n.id,
34
+ topic: n.topic,
35
+ text: n.text,
36
+ source: n.source,
37
+ ...(full ? { basis: n.basis, encoded: n.encoded ?? null } : {}),
38
+ });
39
+ const mapView = (map, n, full) => ({
40
+ id: map.id,
41
+ name: map.name,
42
+ bonuses: n.bonuses.map((b) => ({
43
+ ...b,
44
+ entryPoints: full ? b.entryPoints : b.entryPoints.map((e) => e.name),
45
+ })),
46
+ bonusesShown: `${n.bonuses.length} of ${n.bonusesRanked}`,
47
+ chokepoints: full ? n.chokepoints : n.chokepoints.map(({ territoryId, name, connects }) => ({ territoryId, name, connects })),
48
+ ...(n.incomeTargets ? { incomeTargets: n.incomeTargets } : {}),
49
+ assumptions: n.assumptions,
50
+ });
51
+ /**
52
+ * The map notes of a game: its settings, and an opening simulation while picks are open — over
53
+ * the territories GameFeed's standing lists as pickable (#132; none listed, no income targets).
54
+ */
55
+ function gameMapNotes(game, map) {
56
+ const picking = game.state === PICK_PHASE_STATE;
57
+ const playing = game.players.filter((p) => (p.state ?? 'Playing') === 'Playing').length;
58
+ const limit = game.settings?.territoryLimit;
59
+ const board = game.standing?.territories ?? [];
60
+ const pickable = board.filter((t) => t.owner.kind === 'available').map((t) => t.territoryId);
61
+ const neutralArmies = new Map(board.flatMap((t) => (t.owner.kind === 'neutral' && t.armies !== null ? [[t.territoryId, t.armies]] : [])));
62
+ return mapNotes({
63
+ graph: graphOf(map),
64
+ settings: pickSettings(game.settings),
65
+ ...(game.settings?.overriddenBonusesUnparsed ? { overridesUnparsed: true } : {}),
66
+ ...(picking
67
+ ? {
68
+ opening: {
69
+ players: Math.max(2, playing || game.players.length),
70
+ territoryLimit: limit && limit > 0 ? limit : DEFAULT_TERRITORY_LIMIT,
71
+ pickable,
72
+ ...(neutralArmies.size ? { neutralArmies } : {}),
73
+ },
74
+ }
75
+ : {}),
76
+ });
77
+ }
78
+ const MAP_ONLY_NOTE = "Bonus values are the map's own; a game can override them (pass its game_id to see its values).";
79
+ export function registerStrategyTool(server, client) {
80
+ server.registerTool('warapp_strategy', {
81
+ title: 'war.app strategy notes for a game or a map',
82
+ description: untrustedDescription('Strategy notes for war.app (Warzone), each a short heuristic in our own words with the community guide or ' +
83
+ 'wiki page it comes from, by topic: format (1v1, free-for-all, teams), settings (attack sizes, luck, ' +
84
+ 'commanders, the guard, income, Local Deployment, No-Split), cards (each card, and when cards arrive), ' +
85
+ 'reading the game (fog, picks, counting armies), opening (picks and the first turns), timing (the order ' +
86
+ 'of orders within a turn), fighting (stacks in contact, ahead and behind) and the map. With `game_id`: ' +
87
+ 'the notes that fit the game (its format, phase, fog, move order, distribution, kill rates and the cards ' +
88
+ 'in play, read from GameFeed — standing is left to warapp_plan_turn), its `cardClock` (per card: pieces, ' +
89
+ 'and the first turn it can be played, fastest and guaranteed) and map notes: bonuses ranked by value per ' +
90
+ 'army to take at its settings with their entry points, chokepoints, and in the picking stage income ' +
91
+ "targets by turn from the pick advisor's opening over the territories the game lists as pickable. With " +
92
+ 'only `map_id` (a map already loaded with a game): the map notes. With neither: the topics, and ' +
93
+ '`notes` as ids and topics only (pass `topic` for its notes, or view "full" for every note). Read-only.'),
94
+ _meta: lookupMeta(['warzone strategy', 'strategy tips', 'how to play this map', 'warzone advice']),
95
+ annotations: readAnnotations('war.app strategy notes'),
96
+ inputSchema: z.object({
97
+ game_id: gameIdArg.optional(),
98
+ map_id: mapIdArg,
99
+ topic: z.enum(NOTE_TOPICS).optional().describe('Only notes on this topic; any topic but "map" leaves the map notes out.'),
100
+ view: viewArg(VIEWS, 'compact (default) gives each note\'s id, topic, text and source, and the map notes with entry points by name; ' +
101
+ '"full" adds whether each note is stated by its source or our reasoning from it, where the server acts on it, ' +
102
+ 'the whole profile and the chokepoints\' reasons.'),
103
+ }),
104
+ }, async ({ game_id, map_id, topic, view }) => {
105
+ const withMap = topic === undefined || topic === 'map';
106
+ if (game_id === undefined && map_id === undefined) {
107
+ return respond(view, VIEWS, (rung) =>
108
+ // Every note at once is a long read: with no topic the compact answer is the index. `notes`
109
+ // stays in every answer (#168): here each entry is the id and topic alone.
110
+ topic === undefined && rung !== 'full'
111
+ ? {
112
+ scope: 'general',
113
+ topics: NOTE_TOPICS.map((t) => ({ topic: t, title: TOPIC_TITLES[t], notes: generalNotes(t).length })),
114
+ notes: generalNotes().map((n) => ({ id: n.id, topic: n.topic })),
115
+ next: 'Pass `topic` for one topic\'s notes, `game_id` for the notes that fit a game, or view "full" for every note.',
116
+ }
117
+ : { scope: 'general', notes: generalNotes(topic).map(noteView(rung === 'full')) });
118
+ }
119
+ if (game_id === undefined) {
120
+ const map = client.cachedMap(map_id);
121
+ if (!map)
122
+ throw mapNotLoaded(map_id);
123
+ const notes = mapNotes({ graph: graphOf(map) });
124
+ notes.assumptions.push(MAP_ONLY_NOTE);
125
+ return respond(view, VIEWS, (rung) => ({
126
+ scope: 'map',
127
+ notes: generalNotes('map').map(noteView(rung === 'full')),
128
+ map: mapView(map, notes, rung === 'full'),
129
+ }));
130
+ }
131
+ const game = await client.getGame(game_id, { settings: true });
132
+ const map = mapOf(game);
133
+ if (map_id !== undefined && map_id !== map.id) {
134
+ throw new McpToolError(`Game ${game.id} is played on map ${map.id}, not map ${map_id}.`, {
135
+ hint: 'Omit map_id when you pass a game_id: the game names its map.',
136
+ });
137
+ }
138
+ const s = game.settings;
139
+ const profile = feedProfile({
140
+ graph: graphOf(map),
141
+ players: game.players.map((p) => ({
142
+ id: p.id,
143
+ ...(p.team !== undefined ? { team: p.team } : {}),
144
+ ...(p.state !== undefined ? { state: p.state } : {}),
145
+ })),
146
+ settings: {
147
+ ...(s?.luckModifier !== undefined ? { luckModifier: s.luckModifier } : {}),
148
+ ...(s?.roundingMode !== undefined ? { roundingMode: s.roundingMode } : {}),
149
+ cards: cardRules(s).inPlay.length > 0,
150
+ ...(s?.localDeployments !== undefined ? { localDeployments: s.localDeployments } : {}),
151
+ ...(s?.noSplit !== undefined ? { noSplit: s.noSplit } : {}),
152
+ ...(s?.commanders !== undefined ? { commanders: s.commanders } : {}),
153
+ ...(s?.fog !== undefined ? { fog: s.fog } : {}),
154
+ ...(s?.offensiveKillRate !== undefined ? { offensiveKillRate: s.offensiveKillRate } : {}),
155
+ ...(s?.defensiveKillRate !== undefined ? { defensiveKillRate: s.defensiveKillRate } : {}),
156
+ ...(s?.oneArmyStandsGuard !== undefined ? { oneArmyStandsGuard: s.oneArmyStandsGuard } : {}),
157
+ },
158
+ turn: currentTurn(game),
159
+ picking: game.state === PICK_PHASE_STATE,
160
+ ...(game.standing ? { board: game.standing } : {}),
161
+ });
162
+ // The map is the game's own (bonus overrides applied), so a bonus made negative here counts.
163
+ const notes = notesFor(profile, topic, { ...noteContext(s), negativeBonus: hasCostlyBonus(graphOf(map)) });
164
+ const clock = topic === undefined || topic === 'cards' ? cardClock(s) : undefined;
165
+ const mapped = withMap ? gameMapNotes(game, map) : undefined;
166
+ return respond(view, VIEWS, (rung) => ({
167
+ scope: 'game',
168
+ game: { id: game.id, name: game.name ?? null, state: game.state, turn: currentTurn(game) },
169
+ profile: rung === 'full'
170
+ ? profile
171
+ : { format: profile.format, opponents: profile.opponents, phase: profile.phase, standing: profile.standing },
172
+ notes: notes.map(noteView(rung === 'full')),
173
+ // When each card can first be in a hand, from the game's card settings (absent with no cards).
174
+ ...(clock ? { cardClock: clock } : {}),
175
+ ...(mapped ? { map: mapView(map, mapped, rung === 'full') } : {}),
176
+ }));
177
+ });
178
+ server.registerResource('warapp-strategy', STRATEGY_URI, {
179
+ title: 'war.app strategy notes',
180
+ description: 'Every general war.app (Warzone) strategy note, by topic, each with its source link (markdown).',
181
+ mimeType: 'text/markdown',
182
+ }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: 'text/markdown', text: notesMarkdown(generalNotes()) }] }));
183
+ server.registerResource('warapp-strategy-map', new ResourceTemplate(STRATEGY_MAP_URI, { list: undefined }), {
184
+ title: 'war.app map strategy notes',
185
+ description: 'Notes computed from a war.app map this server has loaded with a game: bonuses by value per army, entry ' +
186
+ 'points, chokepoints (markdown). Bonus and territory names are written by the map designer.',
187
+ mimeType: 'text/markdown',
188
+ }, async (uri, variables) => {
189
+ const raw = variables.mapId;
190
+ const mapId = Number(Array.isArray(raw) ? raw[0] : raw);
191
+ const map = Number.isInteger(mapId) && mapId > 0 ? client.cachedMap(mapId) : undefined;
192
+ if (!map) {
193
+ throw new Error(`Map ${String(raw)} has not been loaded yet: call warapp_strategy (or warapp_get_map) with a game on that map first.`);
194
+ }
195
+ const notes = mapNotes({ graph: graphOf(map) });
196
+ notes.assumptions.push(MAP_ONLY_NOTE);
197
+ const text = `> ${WARAPP_UNTRUSTED_NOTE}\n\n${mapNotesMarkdown(map.name, notes)}`;
198
+ return { contents: [{ uri: uri.href, mimeType: 'text/markdown', text }] };
199
+ });
200
+ }
@@ -0,0 +1,83 @@
1
+ // Who the stress test tries, and with what deploy: the same per-opponent estimates
2
+ // warapp_plan_turn works from. Shared by warapp_check_plan and warapp_submit_turn's commander
3
+ // check (#274), so both size a reply alike.
4
+ import { incomeDetail, planEnemyEstimates, symmetricStart, trackGame, trackOpponents, unevenStart } from '../analysis/index.js';
5
+ import { neutralizeSeats, seatEndRules, staticSeats } from '../analysis/static-seats.js';
6
+ import { carriesTeam } from '../teams.js';
7
+ import { opponentReinforcement } from './card-advice.js';
8
+ import { boardCardsInEffect } from './card-effects.js';
9
+ export function stressOpponents(input) {
10
+ const { graph, map, game, me, seen, turn, settings, hand, info } = input;
11
+ // #270: a player out of the game whose seat no AI plays deploys and attacks nothing: its
12
+ // territories are neutrals (static armies), and it is tried as no opponent.
13
+ const seats = staticSeats(game.players, game.endRules, me.id);
14
+ const board = neutralizeSeats(input.board, seats);
15
+ const previous = input.previous ? neutralizeSeats(input.previous, seats) : undefined;
16
+ const tracks = turn !== null
17
+ ? trackOpponents(graph, [...input.boards, { turn, board: seen }], me.id, settings, trackGame(game.players, game.settings, map, game.endRules))
18
+ : undefined;
19
+ // #253: what the army cap leaves me and what I earn before the cut.
20
+ const incomeOnBoard = incomeDetail(graph, board, me.id, game.settings);
21
+ const income = incomeOnBoard.income;
22
+ const earnedIncome = incomeOnBoard.cap ? incomeOnBoard.cap.uncapped : income;
23
+ // PLAN-TEAMS D3: the cards in effect the decoder is sure of.
24
+ const effect = boardCardsInEffect(game, me, turn, info);
25
+ const previousOrders = previous && turn !== null ? input.boards.find((b) => b.turn === turn - 1)?.orders : undefined;
26
+ const { estimates } = planEnemyEstimates({
27
+ graph,
28
+ board,
29
+ me: me.id,
30
+ income,
31
+ ...(incomeOnBoard.cap ? { incomeCap: incomeOnBoard.cap } : {}),
32
+ settings,
33
+ ...(previous ? { previousBoard: previous } : {}),
34
+ // #226: my orders on that turn, when this server sent them.
35
+ ...(previousOrders ? { previousOrders } : {}),
36
+ ...(tracks ? { tracks } : {}),
37
+ // The fog prior in a 1v1 that started even (#119) and the turn (#128), as warapp_plan_turn has them.
38
+ game: {
39
+ players: game.players.map((p) => ({
40
+ id: p.id,
41
+ ...(p.team !== undefined ? { team: p.team } : {}),
42
+ ...(p.state !== undefined ? { state: p.state } : {}),
43
+ ...(p.humanTurnedIntoAI ? { humanTurnedIntoAI: true } : {}),
44
+ })),
45
+ ...(game.endRules && Object.keys(seatEndRules(game.endRules)).length ? { endRules: seatEndRules(game.endRules) } : {}),
46
+ turn,
47
+ symmetricStart: symmetricStart(game.settings),
48
+ ...(unevenStart(game.settings) ? { unevenStart: unevenStart(game.settings) } : {}),
49
+ ...(input.opening ? { opening: input.opening } : {}),
50
+ ...(game.settings?.fog !== undefined ? { fog: game.settings.fog } : {}),
51
+ ...(opponentReinforcement(game.settings, hand) ? { reinforcement: opponentReinforcement(game.settings, hand) } : {}),
52
+ },
53
+ turn,
54
+ ...(effect.sanctionsOnOthers.length ? { sanctions: effect.sanctionsOnOthers } : {}),
55
+ });
56
+ const myTeam = carriesTeam(me.team) ? me.team : undefined;
57
+ const teamOf = new Map(game.players.map((p) => [p.id, p.team]));
58
+ const friend = (id) => id === me.id || (myTeam !== undefined && teamOf.get(id) === myTeam);
59
+ // Whoever holds a stack on the board can use it, whatever GameFeed says of the player (a booted
60
+ // seat may be an AI): every owner in view, then every other player still in the game. A static
61
+ // seat's territories are neutral on `board` (#270), so it is never among them.
62
+ const onBoard = new Set(board.territories.flatMap((t) => (t.owner.kind === 'player' ? [t.owner.playerId] : [])));
63
+ const stillIn = game.players.filter((p) => (p.state ?? 'Playing') === 'Playing').map((p) => p.id);
64
+ const base = settings.baseIncome ?? 0;
65
+ const estimateOf = (id) => estimates.find((x) => x.playerId === id)?.estimate ?? base;
66
+ const opponents = [...new Set([...onBoard, ...stillIn])]
67
+ .filter((id) => !friend(id))
68
+ .sort((a, b) => a - b)
69
+ .map((id) => {
70
+ const e = estimates.find((x) => x.playerId === id);
71
+ return { id, deploy: input.enemyDeploy ?? e?.estimate ?? base, base: e?.base ?? base };
72
+ });
73
+ const teams = new Map();
74
+ for (const p of game.players)
75
+ if (carriesTeam(p.team))
76
+ teams.set(p.id, p.team);
77
+ const inView = new Set(board.territories.flatMap((t) => (t.owner.kind === 'player' && t.armies !== null ? [t.owner.playerId] : [])));
78
+ // #180: in a free-for-all I lead when my income beats every estimate of an opponent in view
79
+ // (two at least; enemy_deploy is a what-if, not the game's standing).
80
+ const rivals = opponents.filter((o) => inView.has(o.id));
81
+ const leader = teams.size === 0 && rivals.length >= 2 && rivals.every((o) => earnedIncome > estimateOf(o.id));
82
+ return { board, seats, tracks, incomeOnBoard, income, earnedIncome, effect, estimates, estimateOf, friend, opponents, teams, inView, leader };
83
+ }