@chrischall/warapp-mcp 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,7 +10,9 @@
10
10
  // {@link DirectBridge} is that direct leg: it reads the AuthToken from the
11
11
  // session store (src/direct/session.ts) per call and issues an HTTPS request
12
12
  // through mcp-utils netguard `fetchPublic` (pinned to public addresses, so a
13
- // name that resolves or rebinds inward is refused). Every hop must be the exact
13
+ // name that resolves or rebinds inward is refused) — or, with an egress proxy
14
+ // configured (HTTPS_PROXY, mcp-host's only way out), through a proxy agent for
15
+ // it (src/direct/egress.ts), the proxy holding the address table. Every hop must be the exact
14
16
  // origin https://war.app; a non-GET follows no redirect at all, so its body (the
15
17
  // account email, the orders) is never re-sent anywhere
16
18
  // ({@link directFetchOptions}). It maps the reply into the same
@@ -31,27 +33,38 @@
31
33
  // errors are scrubbed BY VALUE ({@link scrubError}: message, hint, stack and
32
34
  // cause chain). The direct leg refuses to attach the cookie to any host but
33
35
  // war.app itself (no subdomain), so the token can never be sent elsewhere.
34
- // Direct mode is LOCAL-ONLY, enforced here: on a hosted child (src/hosted.ts)
35
- // {@link createDirectFirstBridge} pins the router to the browser bridge
36
- // whatever WARAPP_TRANSPORT says, and its session store reads as empty.
36
+ // Hosted (src/hosted.ts), the direct leg serves only from the AuthToken
37
+ // mcp-host captured at sign-in (WARAPP_AUTH_TOKEN, src/direct/session.ts
38
+ // `hostedSession`, in memory, never stored), with the bridge as its fallback
39
+ // exactly as locally; without that token {@link createDirectFirstBridge} pins
40
+ // the router to the browser bridge whatever WARAPP_TRANSPORT says and its
41
+ // session store reads as empty, as before (#333).
37
42
  import { detectEdgeBlock, EdgeBlockedError, McpToolError } from '@chrischall/mcp-utils';
38
43
  import { createDirectFirstTransport, readTransportMode, } from '@chrischall/mcp-utils/fetchproxy';
39
44
  import { fetchPublic } from '@chrischall/mcp-utils/netguard';
45
+ import { egressDispatcher } from './egress.js';
40
46
  import { isHosted } from '../hosted.js';
41
- import { SESSION_HOST, scrubError } from './session.js';
47
+ import { hostedSession, SESSION_HOST, scrubError } from './session.js';
42
48
  /** The env var pinning the transport: `direct` | `fetchproxy` | `auto` (default). */
43
49
  export const TRANSPORT_ENV = 'WARAPP_TRANSPORT';
44
50
  /** The byte cap on a direct reply (a board/standing reply is a few KB; pages tens of KB). */
45
51
  const MAX_DIRECT_BODY_BYTES = 16 * 1024 * 1024;
46
52
  /** The deadline over a direct request and its body read. */
47
53
  const DIRECT_TIMEOUT_MS = 30_000;
54
+ /**
55
+ * What to do about a signed-out host-captured session: mcp-host runs the sign-in again. Until then the
56
+ * router falls back to the browser bridge, so a paired war.app tab still serves the connection.
57
+ */
58
+ export const HOST_SIGN_IN_ADVICE = 'Use "Sign in" on this war.app connection, or reconnect it (mcp-host signs in to war.app again and captures a ' +
59
+ 'new session). Meanwhile, a war.app tab signed in and paired with the browser bridge works, since calls fall ' +
60
+ 'back to it.';
48
61
  /** No war.app session is linked — the router (in `auto`) falls back to the bridge. */
49
62
  export class SessionNotLinkedError extends McpToolError {
50
63
  name = 'SessionNotLinkedError';
51
- constructor() {
52
- super('No war.app session is linked for the direct transport. Run warapp_link_session to capture one.', {
53
- kind: 'no_credential',
54
- });
64
+ constructor(opts = {}) {
65
+ super(opts.hostSignIn
66
+ ? `This connection has no war.app session. ${HOST_SIGN_IN_ADVICE}`
67
+ : 'No war.app session is linked for the direct transport. Run warapp_link_session to capture one.', { kind: 'no_credential' });
55
68
  }
56
69
  }
57
70
  /** The linked session is no longer signed in — the router (in `auto`) falls back to the bridge. */
@@ -59,13 +72,19 @@ export class SessionExpiredError extends McpToolError {
59
72
  name = 'SessionExpiredError';
60
73
  /** When the expired session was captured (non-secret), so a relink can be told apart. */
61
74
  capturedAt;
75
+ /** The session was the one mcp-host captured: the remedy is its Sign in, not warapp_link_session. */
76
+ hostSignIn;
62
77
  constructor(opts = {}) {
63
- super('The linked war.app session is no longer signed in. ' +
78
+ const remedy = opts.hostSignIn ? HOST_SIGN_IN_ADVICE : 'Run warapp_link_session to relink.';
79
+ super((opts.hostSignIn
80
+ ? 'The war.app session this connection signed in with is no longer signed in. '
81
+ : 'The linked war.app session is no longer signed in. ') +
64
82
  (opts.notResent
65
83
  ? 'The request had already reached war.app, so it was not re-sent over the browser bridge (a write must ' +
66
- 'never be sent twice); later calls use the bridge. Retry, or run warapp_link_session to relink.'
67
- : 'Run warapp_link_session to relink.'), { kind: 'session_expired' });
84
+ `never be sent twice); later calls use the bridge. Retry, or: ${remedy}`
85
+ : remedy), { kind: 'session_expired' });
68
86
  this.capturedAt = opts.capturedAt;
87
+ this.hostSignIn = opts.hostSignIn ?? false;
69
88
  }
70
89
  }
71
90
  const decoder = new TextDecoder();
@@ -134,19 +153,36 @@ export function toDirectResult(res) {
134
153
  }
135
154
  return out;
136
155
  }
137
- /** The default direct leg: a real HTTPS request through netguard `fetchPublic` (public-only, war.app-only). */
138
- const fetchViaPublic = async (url, init) => {
139
- const res = await fetchPublic(url, {
140
- ...directFetchOptions(init.method),
141
- method: init.method,
142
- headers: init.headers,
143
- maxBytes: MAX_DIRECT_BODY_BYTES,
144
- timeoutMs: DIRECT_TIMEOUT_MS,
145
- ...(init.body !== undefined ? { body: init.body } : {}),
146
- ...(init.signal ? { signal: init.signal } : {}),
147
- });
148
- return toDirectResult(res);
149
- };
156
+ /**
157
+ * The default direct leg: a real HTTPS request through netguard `fetchPublic`
158
+ * (war.app-only by `allowHosts` and `stopBefore`). With an egress proxy
159
+ * configured (HTTPS_PROXY: mcp-host's only way out, src/direct/egress.ts) it
160
+ * goes through a proxy agent, built per request and closed after; else netguard
161
+ * builds its public-only dispatcher, as before. A proxy that is set but unusable
162
+ * throws before anything is sent: never a direct connection instead.
163
+ */
164
+ export function createDirectFetch(opts = {}) {
165
+ return async (url, init) => {
166
+ const proxy = egressDispatcher(opts.env ?? process.env, opts.proxyAgent);
167
+ try {
168
+ const res = await fetchPublic(url, {
169
+ ...directFetchOptions(init.method),
170
+ method: init.method,
171
+ headers: init.headers,
172
+ maxBytes: MAX_DIRECT_BODY_BYTES,
173
+ timeoutMs: DIRECT_TIMEOUT_MS,
174
+ ...(init.body !== undefined ? { body: init.body } : {}),
175
+ ...(init.signal ? { signal: init.signal } : {}),
176
+ ...(proxy ? { dispatcher: proxy } : {}),
177
+ });
178
+ return toDirectResult(res);
179
+ }
180
+ finally {
181
+ await proxy?.close().catch(() => { });
182
+ }
183
+ };
184
+ }
185
+ const fetchViaPublic = createDirectFetch();
150
186
  /**
151
187
  * Resolve a bridge path to an absolute https URL on the exact host war.app,
152
188
  * refusing any other host (a subdomain or look-alike included), userinfo and a
@@ -258,14 +294,18 @@ export function looksSignedOut(requestedUrl, res) {
258
294
  export class DirectBridge {
259
295
  store;
260
296
  fetchImpl;
261
- constructor(store, fetchImpl = fetchViaPublic) {
297
+ hostSignIn;
298
+ constructor(store, fetchImpl = fetchViaPublic,
299
+ /** A hosted child signed in by mcp-host: its signed-out errors point at Sign in. */
300
+ hostSignIn = false) {
262
301
  this.store = store;
263
302
  this.fetchImpl = fetchImpl;
303
+ this.hostSignIn = hostSignIn;
264
304
  }
265
305
  async fetch(init, signal) {
266
306
  const sess = await this.store.read();
267
307
  if (!sess)
268
- throw new SessionNotLinkedError();
308
+ throw new SessionNotLinkedError(this.hostSignIn ? { hostSignIn: true } : {});
269
309
  const token = sess.authToken;
270
310
  // warappUrl refuses a non-war.app host BEFORE the cookie is built.
271
311
  const url = warappUrl(init.path);
@@ -297,8 +337,9 @@ export class DirectBridge {
297
337
  });
298
338
  }
299
339
  }
300
- if (looksSignedOut(url, res))
301
- throw new SessionExpiredError({ capturedAt: sess.capturedAt });
340
+ if (looksSignedOut(url, res)) {
341
+ throw new SessionExpiredError({ capturedAt: sess.capturedAt, hostSignIn: this.hostSignIn || sess.origin === 'host' });
342
+ }
302
343
  return { status: res.status, body: res.body, url: res.url };
303
344
  }
304
345
  }
@@ -316,14 +357,21 @@ export const RELINK_CHECK_MS = 5_000;
316
357
  * is lifted when a NEW session is linked, so the direct leg is retried.
317
358
  */
318
359
  export function createDirectFirstBridge(opts) {
319
- // LOCAL-ONLY: a hosted child never rides the direct leg nor reads a stored
320
- // session, whatever WARAPP_TRANSPORT (or `mode`) says.
321
- const hosted = isHosted(opts.env ?? process.env);
322
- const mode = hosted
360
+ // A hosted child never reads a stored session. With the token mcp-host
361
+ // captured at sign-in it rides the direct leg from that token alone (the
362
+ // given store is not consulted) and resolves its mode as a local process
363
+ // does; without one it is pinned to the browser bridge whatever
364
+ // WARAPP_TRANSPORT (or `mode`) says.
365
+ const env = opts.env ?? process.env;
366
+ const hosted = isHosted(env);
367
+ const hostSession = hosted ? hostedSession(env) : null;
368
+ const pinned = hosted && !hostSession;
369
+ const mode = pinned
323
370
  ? 'fetchproxy'
324
371
  : (opts.mode ?? readTransportMode(TRANSPORT_ENV, opts.env ? { env: opts.env } : {}));
325
- const store = hosted ? { read: async () => null } : opts.store;
326
- const direct = new DirectBridge(store, opts.directFetch);
372
+ const store = hosted ? { read: async () => hostSession } : opts.store;
373
+ const hostSignIn = hostSession !== null;
374
+ const direct = new DirectBridge(store, opts.directFetch ?? createDirectFetch({ env }), hostSignIn);
327
375
  const log = opts.log ?? ((m) => console.error(m));
328
376
  const now = opts.now ?? Date.now;
329
377
  let wall = null;
@@ -343,7 +391,13 @@ export function createDirectFirstBridge(opts) {
343
391
  : 'the site edge refused the direct request';
344
392
  log(`[warapp-mcp] Direct transport unavailable (${why}) — switching to the ContextMint Bridge browser bridge. ` +
345
393
  `Keep a ${SESSION_HOST} tab open and approve the pairing prompt in the extension if one appears` +
346
- (next.kind === 'session' && !hosted ? '; run warapp_link_session to return to the direct transport.' : '.'));
394
+ (next.kind !== 'session'
395
+ ? '.'
396
+ : hostSignIn
397
+ ? `. ${HOST_SIGN_IN_ADVICE}`
398
+ : hosted
399
+ ? '.'
400
+ : '; run warapp_link_session to return to the direct transport.'));
347
401
  };
348
402
  const build = () => createDirectFirstTransport({
349
403
  direct,
@@ -400,8 +454,9 @@ export function createDirectFirstBridge(opts) {
400
454
  throw err;
401
455
  }
402
456
  }
403
- if (reached)
404
- throw new SessionExpiredError({ capturedAt: reached.capturedAt, notResent: true });
457
+ if (reached) {
458
+ throw new SessionExpiredError({ capturedAt: reached.capturedAt, notResent: true, hostSignIn: reached.hostSignIn });
459
+ }
405
460
  return leg.ready().then((t) => t.fetch(init));
406
461
  });
407
462
  };
package/dist/hosted.js CHANGED
@@ -3,10 +3,12 @@
3
3
  // mcp-host gives this server no explicit "hosted" flag, so a hosted child is
4
4
  // recognised by the variables only the host sets ({@link HOSTED_MARKERS}).
5
5
  // Consulted by the map statistics (always off when hosted, src/stats.ts) and by
6
- // the direct transport, which is LOCAL-ONLY: when hosted the session store
7
- // reads as empty and refuses writes (src/direct/session.ts), the router is
8
- // pinned to the browser bridge (src/direct/transport.ts), and
9
- // warapp_link_session is not registered (src/tools/session.ts).
6
+ // the direct transport: when hosted no session file is ever read or written
7
+ // (src/direct/session.ts) and warapp_link_session is not registered
8
+ // (src/tools/session.ts). The direct leg then serves only from the AuthToken
9
+ // mcp-host captured at sign-in (WARAPP_AUTH_TOKEN, in memory, #333), the
10
+ // bridge its fallback; without one the router is pinned to the browser bridge
11
+ // (src/direct/transport.ts).
10
12
  import { readEnvVar } from '@chrischall/mcp-utils';
11
13
  /**
12
14
  * Variables only a hosted child sees: mcp-host's own (its child-env contract —
@@ -1,3 +1,4 @@
1
+ import { egressProxyConfigured } from '../direct/egress.js';
1
2
  import { scrubToken } from '../direct/session.js';
2
3
  import { DirectBridge } from '../direct/transport.js';
3
4
  import { parseHandshake, parsePacket, SOCKET_URL } from './packets.js';
@@ -37,10 +38,16 @@ export function websocketUrl(sid) {
37
38
  * The leg for the process's direct-first bridge: the WebSocket is selected
38
39
  * only while the active transport is `direct` (pinned `direct`, or `auto`
39
40
  * still on the direct leg); otherwise the push stays on xhr-polling.
41
+ *
42
+ * Never with an egress proxy configured (HTTPS_PROXY: mcp-host's only way out,
43
+ * src/direct/egress.ts). Node's built-in WebSocket opens its own socket, which
44
+ * the proxy would not carry (a direct socket is silently dropped there), so the
45
+ * push stays on xhr-polling over the direct-first router, whose direct leg goes
46
+ * through the proxy. Read on each attempt.
40
47
  */
41
- export function pushWebSocketLeg(bridge, readSession, seams = {}) {
48
+ export function pushWebSocketLeg(bridge, readSession, seams = {}, env = process.env) {
42
49
  return {
43
- select: () => bridge.status().transport === 'direct',
50
+ select: () => bridge.status().transport === 'direct' && !egressProxyConfigured(env),
44
51
  session: readSession,
45
52
  ...seams,
46
53
  };
@@ -75,7 +75,7 @@ export function registerMarkChatReadTool(server, ctx) {
75
75
  // The gate binds the account read fresh (the write rules); its in-game id keys the private marks.
76
76
  const me = await ctx.myIdentity({ fresh: true }).catch(() => undefined);
77
77
  if (!me)
78
- throw accountUnknown(ctx.hosted);
78
+ throw accountUnknown(ctx);
79
79
  const read = await readChat(ctx, game, me);
80
80
  // A filled web read (#313) still carries the web messages' ids; GameFeed's added lines carry none and mark nothing.
81
81
  if (!read || read.source === 'gamefeed') {
@@ -26,11 +26,17 @@ export { PROBE_GAME_ID };
26
26
  const PROBE_PATH = `/API/GameFeed?GameID=${PROBE_GAME_ID}&GetMap=false`;
27
27
  /** The page the bridge arm round-trips through the user's war.app tab. */
28
28
  export const BRIDGE_PROBE_PATH = '/';
29
- /** The non-secret facts about the linked direct session — never the token. */
29
+ /**
30
+ * The non-secret facts about the linked direct session — never the token. The
31
+ * session mcp-host captured at sign-in (hosted, #333) is `linked: true` with `linkedBy: 'host'` (`linked` stays a boolean), with
32
+ * no capture time or age: this process does not know them.
33
+ */
30
34
  function sessionSummary(env, now) {
31
35
  const s = readSessionSync(env);
32
36
  if (!s)
33
37
  return { linked: false };
38
+ if (s.origin === 'host')
39
+ return { linked: true, linkedBy: 'host' };
34
40
  const ageSeconds = Math.max(0, Math.round((now() - Date.parse(s.capturedAt)) / 1000));
35
41
  return { linked: true, capturedAt: s.capturedAt, ageSeconds };
36
42
  }
@@ -40,6 +40,7 @@ import { pushWebSocketLeg } from '../push/websocket.js';
40
40
  import { readSession } from '../direct/session.js';
41
41
  import { createDirectFirstBridge } from '../direct/transport.js';
42
42
  import { isHosted } from '../hosted.js';
43
+ import { registerSignInTool } from './sign-in.js';
43
44
  import { createWarappBridge } from '../transport-bridge.js';
44
45
  /** Every tool this server serves. index.ts and the tests share this list. */
45
46
  export function registerAllTools(server, deps = {}) {
@@ -56,9 +57,10 @@ export function registerAllTools(server, deps = {}) {
56
57
  // browser bridge otherwise (WARAPP_TRANSPORT: auto default | direct |
57
58
  // fetchproxy). WarappRpc, the page fetches, the healthcheck and the push
58
59
  // socket all take this one bridge, so they all gain direct mode at once.
59
- // Direct mode is LOCAL-ONLY (src/hosted.ts): on a hosted child the router is
60
- // pinned to the browser bridge, the session store reads as empty and
61
- // warapp_link_session is not registered.
60
+ // Hosted (src/hosted.ts) no session file is read or written and
61
+ // warapp_link_session is not registered: the direct leg serves only from the
62
+ // AuthToken mcp-host captured at sign-in (WARAPP_AUTH_TOKEN, in memory,
63
+ // #333), and without one the router is pinned to the browser bridge.
62
64
  const hosted = isHosted(env ?? process.env);
63
65
  const bridge = createDirectFirstBridge({
64
66
  store: { read: () => readSession(deps.env) },
@@ -133,7 +135,7 @@ export function registerAllTools(server, deps = {}) {
133
135
  const push = deps.push ??
134
136
  pushListenerFor(fetchproxy, {
135
137
  transport: () => bridge.ready(),
136
- webSocket: pushWebSocketLeg(bridge, () => readSession(deps.env)),
138
+ webSocket: pushWebSocketLeg(bridge, () => readSession(deps.env), {}, deps.env ?? process.env),
137
139
  extras: () => live.rpc.extras,
138
140
  });
139
141
  registerSessionTools(server, {
@@ -149,4 +151,8 @@ export function registerAllTools(server, deps = {}) {
149
151
  ...(env ? { env } : {}),
150
152
  });
151
153
  registerPushTools(server, live, push, deps.env ? { env: deps.env } : {});
154
+ // Hosted only: the war.app sign-in mcp-host's authFlow captures the AuthToken from (#333 part B).
155
+ // Locally warapp_link_session stays the way to the direct transport.
156
+ if (hosted)
157
+ registerSignInTool(server, deps.signIn ? { signIn: deps.signIn } : {});
152
158
  }
@@ -225,7 +225,7 @@ export function registerJoinGameTool(server, ctx) {
225
225
  // acts as the signed-in account, so it is refused when that cannot be read (#133).
226
226
  const [html, me] = await Promise.all([openGamesPage(ctx), ctx.myIdentity({ fresh: true })]);
227
227
  if (me === undefined)
228
- throw accountUnknown(ctx.hosted);
228
+ throw accountUnknown(ctx);
229
229
  const { token, inGameId: myId } = me;
230
230
  const bundle = await ctx.bundle();
231
231
  const parsed = parseOpenGamesPage(html, bundle);
@@ -8,6 +8,7 @@ import { BUNDLE_FETCH_TIMEOUT_MS, BUNDLE_MAX_BYTES, BundleProvider } from '../pr
8
8
  import { Method, readTerritoryPicks, writeGetLatestGameInfoParams, writeGetTerritoryPicksParams, } from '../protocol/methods.js';
9
9
  import { WarappRpc } from '../protocol/rpc.js';
10
10
  import { BRIDGE_DOMAINS } from '../transport-bridge.js';
11
+ import { hostedSession } from '../direct/session.js';
11
12
  import { isHosted } from '../hosted.js';
12
13
  /**
13
14
  * The token from war.app's `/InviteToken` page ("Your invite token is N"), as text — the
@@ -220,6 +221,7 @@ export function createLiveContext(opts) {
220
221
  fetchPage: fetchText,
221
222
  dataDir: dir,
222
223
  hosted: isHosted(opts.env ?? process.env),
224
+ hostSignIn: hostedSession(opts.env ?? process.env) !== null,
223
225
  client: opts.client,
224
226
  rpc,
225
227
  decoderReport: () => lastBundle?.report?.(),
@@ -64,7 +64,7 @@ export async function listMyGames(read, windows = MY_GAMES_WINDOWS) {
64
64
  async function myInGameId(ctx) {
65
65
  const me = await ctx.myInGameId();
66
66
  if (me === undefined) {
67
- throw accountUnknown(ctx.hosted, 'its games cannot be listed');
67
+ throw accountUnknown(ctx, 'its games cannot be listed');
68
68
  }
69
69
  return me;
70
70
  }
@@ -5,6 +5,7 @@ import { McpToolError } from '@chrischall/mcp-utils';
5
5
  import { z } from 'zod';
6
6
  import { filterOpenGames, joiningPolicy, lotteryOf, lotteryShape, markJoined, withLottery, OPEN_GAMES_URL, parseOpenGamesPage, } from '../open-games.js';
7
7
  import { readAnnotations, respond, untrustedDescription } from './common.js';
8
+ import { HOST_SIGN_IN_ADVICE } from '../direct/transport.js';
8
9
  import { noBrowserNote } from './session.js';
9
10
  import { lookupMeta } from './hints.js';
10
11
  /** The OpenGames page as text, or a tool error with a hint. */
@@ -15,8 +16,10 @@ export async function openGamesPage(ctx) {
15
16
  catch (e) {
16
17
  throw new McpToolError(`Could not read war.app's open games page: ${e instanceof Error ? e.message : String(e)}`, {
17
18
  kind: 'unknown',
18
- hint: (ctx.hosted ? 'Make sure' : 'Link a session with warapp_link_session to read it without a browser, or make sure') +
19
- ' a signed-in war.app tab is open and paired (reload or focus it if it is frozen), then retry.',
19
+ hint: ctx.hosted && ctx.hostSignIn
20
+ ? `${HOST_SIGN_IN_ADVICE} Then retry.`
21
+ : (ctx.hosted ? 'Make sure' : 'Link a session with warapp_link_session to read it without a browser, or make sure') +
22
+ ' a signed-in war.app tab is open and paired (reload or focus it if it is frozen), then retry.',
20
23
  cause: e,
21
24
  });
22
25
  }
@@ -10,24 +10,35 @@
10
10
  // last answer was a `SessionExpiredError`, it surfaces "session expired — run
11
11
  // warapp_link_session" so the owner relinks; a relink clears it.
12
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.
13
+ // Hosted (src/hosted.ts) `warapp_link_session` is never registered: a hosted
14
+ // child stores no session. Its session, when it has one, is the AuthToken
15
+ // mcp-host captured at sign-in (WARAPP_AUTH_TOKEN, #333): `warapp_session_status`
16
+ // then reports `hosted: true`, `linked: true`, `linkedBy: 'host'` and the active leg (no
17
+ // capture time, no age), and a signed-out one points at the connection's
18
+ // "Sign in". Without it the status reports the browser bridge, as before,
19
+ // without suggesting a link.
16
20
  //
17
21
  // SECURITY: the AuthToken is a full-account credential. Neither tool returns,
18
22
  // logs, or previews it; the status output carries only `capturedAt`/`host`/age.
19
23
  import { CONFIRM_INJECTION_RULE, toolAnnotations } from '@chrischall/mcp-utils';
20
24
  import { z } from 'zod';
21
25
  import { linkSession } from '../direct/link.js';
22
- import { readSession, SESSION_HOST } from '../direct/session.js';
26
+ import { hostedTokenState, readSession, SESSION_HOST } from '../direct/session.js';
27
+ import { HOST_SIGN_IN_ADVICE } from '../direct/transport.js';
23
28
  import { isHosted } from '../hosted.js';
24
29
  import { lookupMeta, mintMeta } from './hints.js';
25
30
  import { readAnnotations, respond, untrustedDescription } from './common.js';
26
31
  import { defineGatedWrite } from './write-kit.js';
27
32
  const HINT_NOT_LINKED = 'No war.app session is linked. Run warapp_link_session to use the direct (no-browser) transport; the browser ' +
28
33
  '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.';
34
+ const NOTE_HOSTED = 'This server is hosted: it reaches war.app directly only from the session captured at sign-in, and this ' +
35
+ 'connection has none, so war.app calls go through the browser bridge and your signed-in war.app tab. ' +
36
+ HOST_SIGN_IN_ADVICE;
37
+ const NOTE_HOSTED_DIRECT = 'This server is hosted and signed in to war.app by mcp-host: war.app calls go directly to war.app with the ' +
38
+ 'session captured at sign-in, and fall back to the browser bridge only when that session stops working.';
39
+ const NOTE_HOSTED_MALFORMED = 'This server is hosted, and the war.app session mcp-host passed it is not usable, so war.app calls go through ' +
40
+ `the browser bridge and your signed-in war.app tab. ${HOST_SIGN_IN_ADVICE}`;
41
+ const HINT_HOST_EXPIRED = `The war.app session this connection signed in with is signed out. ${HOST_SIGN_IN_ADVICE}`;
31
42
  const HINT_EXPIRED = 'The linked war.app session is signed out (war.app answered a direct call signed-out this run). Run ' +
32
43
  'warapp_link_session to relink.';
33
44
  /**
@@ -42,6 +53,7 @@ export function registerSessionTools(server, deps) {
42
53
  const link = deps.link ?? ((opts) => linkSession({ ...(deps.env ? { env: deps.env } : {}), ...opts }));
43
54
  const now = deps.now ?? Date.now;
44
55
  const hosted = deps.hosted ?? isHosted(deps.env ?? process.env);
56
+ const hostToken = hosted ? (deps.hostToken ?? hostedTokenState(deps.env ?? process.env)) : 'none';
45
57
  /** The board decoder, once a live tool has loaded the client bundle (#148). */
46
58
  const decoderView = () => {
47
59
  if (!deps.decoder)
@@ -66,21 +78,41 @@ export function registerSessionTools(server, deps) {
66
78
  };
67
79
  server.registerTool('warapp_session_status', {
68
80
  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.'),
81
+ description: untrustedDescription(hosted && hostToken === 'ok'
82
+ ? 'Report which transport serves war.app calls on this hosted server (direct to war.app with the session ' +
83
+ 'mcp-host captured at sign-in, or the browser bridge after that session stops working) and which ' +
84
+ 'transport the turn-notification push socket rides (websocket or xhr-polling) once it has run, and, once ' +
85
+ 'a live board has been read, which client bundle decodes boards (a cached stand-in or not) and which of ' +
86
+ 'its reader helpers were verified. Never shows the session cookie. Read-only.'
87
+ : hosted
88
+ ? 'Report which transport serves war.app calls on this hosted server (the browser bridge: hosted, the ' +
89
+ 'direct, no-browser transport runs only from the session captured at sign-in, and this connection ' +
90
+ 'has none) and which transport the turn-notification push socket ' +
91
+ 'rides (websocket or xhr-polling) once it has run, and, once a live board has been read, which client ' +
92
+ 'bundle decodes boards (a cached stand-in or not) and which of its reader helpers were verified. Read-only.'
93
+ : 'Report whether a signed-in war.app session is linked for the direct (no-browser) transport, when it was ' +
94
+ 'captured and how old it is, which transport is currently active (direct, or the browser bridge), and ' +
95
+ 'which transport the turn-notification push socket rides (websocket or xhr-polling) once it has run, ' +
96
+ 'and, once a live board has been read, which client bundle decodes boards (a cached stand-in or not) and ' +
97
+ 'which of its reader helpers were verified. ' +
98
+ 'Never shows the session cookie. Read-only; use warapp_link_session to link or relink.'),
80
99
  _meta: lookupMeta(['war.app session', 'is war.app linked', 'direct transport status']),
81
100
  annotations: readAnnotations('war.app session status'),
82
101
  inputSchema: z.object({}),
83
102
  }, async () => {
103
+ if (hosted && hostToken === 'ok') {
104
+ const pt = deps.pushTransport?.();
105
+ const base = {
106
+ hosted: true,
107
+ linked: true,
108
+ linkedBy: 'host',
109
+ activeTransport: deps.transport.activeLeg(),
110
+ ...(pt ? { pushTransport: pt } : {}),
111
+ ...decoderView(),
112
+ hostedNote: NOTE_HOSTED_DIRECT,
113
+ };
114
+ return respond(undefined, ['compact'], () => deps.transport.sessionStale() ? { ...base, sessionExpired: true, hint: HINT_HOST_EXPIRED } : base);
115
+ }
84
116
  if (hosted) {
85
117
  const pt = deps.pushTransport?.();
86
118
  return respond(undefined, ['compact'], () => ({
@@ -89,7 +121,7 @@ export function registerSessionTools(server, deps) {
89
121
  activeTransport: 'fetchproxy',
90
122
  ...(pt ? { pushTransport: pt } : {}),
91
123
  ...decoderView(),
92
- hostedNote: NOTE_HOSTED,
124
+ hostedNote: hostToken === 'malformed' ? NOTE_HOSTED_MALFORMED : NOTE_HOSTED,
93
125
  }));
94
126
  }
95
127
  const session = await read();
@@ -0,0 +1,56 @@
1
+ // `warapp_sign_in` — the war.app sign-in mcp-host's hosted authFlow calls as its
2
+ // `capture` (#333 part B, docs/examples/warapp-auth-flow.json).
3
+ //
4
+ // Registered ONLY on a hosted child (src/hosted.ts). Locally the way to the
5
+ // direct transport stays warapp_link_session, which takes the cookie off the
6
+ // signed-in tab and never returns it.
7
+ //
8
+ // THE ONE DOCUMENTED EXCEPTION to "the AuthToken is never in a tool result":
9
+ // this tool's result is `{ authToken }`, because mcp-host's `capture` reads the
10
+ // credential out of the capture tool's result (`path: authToken`) and seals it
11
+ // as the per-user secret WARAPP_AUTH_TOKEN. The caller already holds the
12
+ // account's email and password, so the result grants it nothing it did not
13
+ // have. Nothing else about the account is returned, and a refusal's text never
14
+ // holds the email, the password or a cookie value (src/direct/sign-in.ts).
15
+ // Hiding it from the connector's tool menu (mcp-host `enabledTools`) is the
16
+ // owner's choice, not a default: a flow's step and capture calls are never
17
+ // checked against that allowlist, so the sign-in would still run, but the gate
18
+ // is fail-closed — once set, the connection's resources (warapp://strategy) and
19
+ // prompts are gone, and every tool a later release adds stays hidden until the
20
+ // list is edited by hand (docs/PLAN-DIRECT.md, registration change step 3).
21
+ //
22
+ // Not confirm-gated: the flow calls it with exactly the arguments its document
23
+ // declares, and a gate would need another argument there. It is not read-only
24
+ // (it signs in, creating a war.app session), it reaches no player, and it is
25
+ // not idempotent (each call is a sign-in attempt war.app may count).
26
+ import { toolAnnotations } from '@chrischall/mcp-utils';
27
+ import { z } from 'zod';
28
+ import { signIn } from '../direct/sign-in.js';
29
+ import { mintMeta } from './hints.js';
30
+ export function registerSignInTool(server, deps = {}) {
31
+ const run = deps.signIn ?? signIn;
32
+ server.registerTool('warapp_sign_in', {
33
+ title: 'Sign in to war.app (host sign-in flow)',
34
+ description: "For the host's sign-in flow only, not for chat use: signs in to war.app once with the account's email " +
35
+ 'and password and returns the session cookie war.app sets, as `authToken`, which the host keeps as this ' +
36
+ "connection's own secret so later calls reach war.app without a browser. The password is used for this one " +
37
+ 'sign-in and never stored. A refusal (wrong email or password, a captcha or bot check, a network failure) ' +
38
+ 'is an error that says which, and is never retried, because war.app may count failed sign-ins.',
39
+ _meta: mintMeta('other', ['sign in to war.app']),
40
+ annotations: toolAnnotations({
41
+ title: 'Sign in to war.app',
42
+ readOnly: false,
43
+ destructive: false,
44
+ idempotent: false,
45
+ openWorld: true,
46
+ }),
47
+ inputSchema: z.object({
48
+ email: z.string().min(1).max(320).describe("The war.app account's email."),
49
+ password: z.string().min(1).max(1024).describe("The war.app account's password, used once and never stored."),
50
+ }),
51
+ }, async ({ email, password }, ctx) => {
52
+ const { authToken } = await run({ email, password }, { signal: ctx.mcpReq.signal });
53
+ // The capture reads this top-level key; nothing else about the account is returned.
54
+ return { content: [{ type: 'text', text: JSON.stringify({ authToken }) }] };
55
+ });
56
+ }
@@ -67,7 +67,7 @@ export function registerTeamBriefTool(server, ctx) {
67
67
  const gameId = parseGameId(game_id);
68
68
  const identity = await ctx.myIdentity().catch(() => undefined);
69
69
  if (!identity)
70
- throw accountUnknown(ctx.hosted, 'your team brief cannot be read');
70
+ throw accountUnknown(ctx, 'your team brief cannot be read');
71
71
  const feed = await ctx.client.getGame(gameId, { settings: true });
72
72
  if (feed.state !== PLAYING && feed.state !== DISTRIBUTING) {
73
73
  throw new McpToolError(`Game ${feed.id} is not being picked or played (game state: ${feed.state}), so there is nothing to brief.`, {
@@ -67,7 +67,7 @@ export function registerTeamTool(server, ctx) {
67
67
  const gameId = parseGameId(game_id);
68
68
  const identity = await ctx.myIdentity().catch(() => undefined);
69
69
  if (!identity)
70
- throw accountUnknown(ctx.hosted, 'your team cannot be read');
70
+ throw accountUnknown(ctx, 'your team cannot be read');
71
71
  const read = await ctx.client.getGame(gameId, { settings: true, chat: true });
72
72
  const { game, source } = await resolveTeams(ctx, read);
73
73
  const me = game.players.find((p) => p.id === identity.token);
@@ -39,14 +39,21 @@ import { defineWrite, McpToolError, registerWrite, } from '@chrischall/mcp-utils
39
39
  import { notSent, WarappServerError } from '../protocol/rpc.js';
40
40
  import { respond, untrustedText } from './common.js';
41
41
  import { withToolConfig } from './hints.js';
42
+ import { HOST_SIGN_IN_ADVICE } from '../direct/transport.js';
42
43
  import { failureText } from './live-context.js';
43
44
  import { resolvePlayer } from './resolve.js';
44
45
  /** Refuse a write (or a read) before anything is sent. */
45
46
  export function refuse(message, hint) {
46
47
  throw new McpToolError(message, { kind: 'unknown', hint });
47
48
  }
48
- /** The hint when the signed-in account cannot be told: linking a session is suggested only locally. */
49
- function signedInHint(hosted) {
49
+ /**
50
+ * The hint when the signed-in account cannot be told: linking a session is suggested only locally, and a
51
+ * hosted connection mcp-host signed in to war.app is pointed at its "Sign in" (a paired tab meanwhile).
52
+ */
53
+ function signedInHint(view) {
54
+ const { hosted, hostSignIn } = typeof view === 'object' ? view : { hosted: view, hostSignIn: false };
55
+ if (hosted && hostSignIn)
56
+ return `${HOST_SIGN_IN_ADVICE} Then retry.`;
50
57
  return hosted
51
58
  ? 'Make sure a war.app tab signed in to your account is open and paired (reload or focus it if it is frozen), then retry.'
52
59
  : 'Make sure a war.app tab signed in to your account is open and paired (reload or focus it if it is frozen), or link ' +
@@ -67,7 +74,7 @@ export function accountUnknown(hosted, consequence = 'nothing was sent') {
67
74
  export async function requireMe(ctx, opts = {}) {
68
75
  const token = await ctx.myInviteToken({ fresh: opts.fresh ?? true });
69
76
  if (token === undefined)
70
- throw accountUnknown(ctx.hosted, opts.consequence);
77
+ throw accountUnknown(ctx, opts.consequence);
71
78
  return token;
72
79
  }
73
80
  /** The seat of account `token` in `game`; refused when it holds none. */
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // Single source of truth for the server version. release-please bumps the
2
2
  // literal on the marked line (registered in release-please-config.json
3
3
  // extra-files); every other module imports VERSION from here.
4
- export const VERSION = '0.2.0'; // x-release-please-version
4
+ export const VERSION = '0.3.1'; // x-release-please-version