@g33ks/foundryvtt-mcp 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +21 -29
  2. package/dist/cli/init.js +5 -1
  3. package/dist/cli/snippets.js +16 -1
  4. package/dist/core.js +104 -14
  5. package/dist/diagnostics/client.js +36 -98
  6. package/dist/foundry/auth.js +4 -0
  7. package/dist/foundry/client.js +750 -157
  8. package/dist/foundry/event-log.js +2 -3
  9. package/dist/foundry/headless-gm-session.js +119 -2
  10. package/dist/foundry/journal-conflicts.js +141 -0
  11. package/dist/foundry/journal-integrity.js +20 -4
  12. package/dist/foundry/message-author.js +19 -0
  13. package/dist/foundry/module-bridge.js +153 -6
  14. package/dist/foundry/world-cache.js +206 -8
  15. package/dist/mcp-server.js +5 -3
  16. package/dist/shared/control.js +47 -6
  17. package/dist/shared/daemon.js +2 -4
  18. package/dist/shared/protocol.js +14 -10
  19. package/dist/tools/definitions.js +128 -31
  20. package/dist/tools/handlers/actor-mutations.js +13 -7
  21. package/dist/tools/handlers/actor-target.js +80 -0
  22. package/dist/tools/handlers/actors.js +25 -12
  23. package/dist/tools/handlers/chat.js +3 -1
  24. package/dist/tools/handlers/combat-mutations.js +3 -2
  25. package/dist/tools/handlers/combat.js +48 -17
  26. package/dist/tools/handlers/diagnostics.js +14 -2
  27. package/dist/tools/handlers/effects.js +23 -24
  28. package/dist/tools/handlers/item-mutations.js +23 -21
  29. package/dist/tools/handlers/module-bridge.js +131 -2
  30. package/dist/tools/handlers/token-mutations.js +151 -16
  31. package/dist/tools/handlers/utils.js +3 -2
  32. package/dist/tools/router.js +6 -23
  33. package/dist/tools/tool-dependencies.js +207 -0
  34. package/dist/utils/mcp-errors.js +47 -0
  35. package/package.json +5 -5
@@ -17,6 +17,7 @@
17
17
  */
18
18
  import { isRecord } from '../utils/guards.js';
19
19
  import { stripHtml } from '../utils/sanitize.js';
20
+ import { messageAuthorId } from './message-author.js';
20
21
  /** Longest chat excerpt carried in a summary line, in characters. */
21
22
  const MAX_SUMMARY_TEXT = 200;
22
23
  /**
@@ -255,9 +256,7 @@ function renderSummary(broadcast, first, changed, ids, worldData) {
255
256
  if (type === 'ChatMessage' && action === 'create' && first) {
256
257
  const speaker = isRecord(first.speaker) ? first.speaker : undefined;
257
258
  const alias = speaker && typeof speaker.alias === 'string' ? speaker.alias : undefined;
258
- const author = alias ??
259
- userName(worldData, typeof first.user === 'string' ? first.user : broadcast.userId) ??
260
- 'Unknown';
259
+ const author = alias ?? userName(worldData, messageAuthorId(first) ?? broadcast.userId) ?? 'Unknown';
261
260
  const raw = typeof first.content === 'string' ? first.content : '';
262
261
  const text = truncate(stripHtml(raw));
263
262
  const flavor = typeof first.flavor === 'string' ? truncate(stripHtml(first.flavor)) : '';
@@ -155,6 +155,71 @@ export const HEADLESS_BROWSER_ARGS = [
155
155
  'BraveLocalhostAccessPermission',
156
156
  ].join(',')}`,
157
157
  ];
158
+ /**
159
+ * Size of the headless GM page. Playwright's default, 1280x720, is below
160
+ * FoundryVTT's 1366x768 minimum: Foundry warns, and canvas work such as
161
+ * `capture_scene` misbehaves.
162
+ */
163
+ export const HEADLESS_VIEWPORT = { width: 1920, height: 1080 };
164
+ /** Where the companion module's scripts are served from. */
165
+ const BRIDGE_SCRIPT_PATH = '/modules/foundryvtt-mcp-bridge/';
166
+ /** The prefixes the companion module puts on its console lines. */
167
+ const BRIDGE_CONSOLE_PREFIXES = ['FoundryVTT MCP Bridge | ', 'foundryvtt-mcp-bridge | '];
168
+ const BRIDGE_CONSOLE_MAX_LENGTH = 500;
169
+ const BRIDGE_PAGE_ERROR_MAX_LENGTH = 200;
170
+ /** A stack frame (Chromium format) inside one of the module's scripts. */
171
+ const BRIDGE_STACK_FRAME = /^\s+at .*\/modules\/foundryvtt-mcp-bridge\//m;
172
+ function isBridgeScript(url) {
173
+ try {
174
+ return new URL(url).pathname.startsWith(BRIDGE_SCRIPT_PATH);
175
+ }
176
+ catch {
177
+ return false;
178
+ }
179
+ }
180
+ /**
181
+ * The part of a page console message worth copying to the log: a companion
182
+ * module line, printed by one of the module's own scripts, reduced to its
183
+ * first argument. Further arguments (a received command, an error) and
184
+ * every other script's lines stay out of the log, so no page, document or
185
+ * command content reaches it. `msg.text()` is never used: it renders every
186
+ * argument, including an object's own fields.
187
+ *
188
+ * @returns the line, cut to {@link BRIDGE_CONSOLE_MAX_LENGTH}, or `null`
189
+ */
190
+ export async function bridgeConsoleText(message) {
191
+ if (!isBridgeScript(message.location().url)) {
192
+ return null;
193
+ }
194
+ const first = message.args()[0];
195
+ if (!first) {
196
+ return null;
197
+ }
198
+ let value;
199
+ try {
200
+ value = await first.jsonValue();
201
+ }
202
+ catch {
203
+ // The page navigated away before the argument could be read.
204
+ return null;
205
+ }
206
+ if (typeof value !== 'string' || !BRIDGE_CONSOLE_PREFIXES.some((p) => value.startsWith(p))) {
207
+ return null;
208
+ }
209
+ return value.slice(0, BRIDGE_CONSOLE_MAX_LENGTH);
210
+ }
211
+ /**
212
+ * `name: message` of an uncaught page error thrown from the companion
213
+ * module's code (a stack frame in its scripts), without the stack.
214
+ *
215
+ * @returns the text, cut to {@link BRIDGE_PAGE_ERROR_MAX_LENGTH}, or `null`
216
+ */
217
+ export function bridgePageErrorText(error) {
218
+ if (!BRIDGE_STACK_FRAME.test(error.stack ?? '')) {
219
+ return null;
220
+ }
221
+ return `${error.name}: ${error.message}`.slice(0, BRIDGE_PAGE_ERROR_MAX_LENGTH);
222
+ }
158
223
  /** Page binding behind `window.foundryMcpBridge`; see {@link BRIDGE_INIT_SCRIPT}. */
159
224
  const BRIDGE_BINDING = '__foundryMcpBridgeCall';
160
225
  /**
@@ -238,6 +303,10 @@ export class HeadlessGmSession {
238
303
  lastError = null;
239
304
  retryDelayMs = BASE_RETRY_MS;
240
305
  retryTimer = null;
306
+ /** When {@link active} last became true. */
307
+ activeSince = null;
308
+ /** Shared mode: the connector could not get a new session; it retries on its own. */
309
+ reauthFailed = false;
241
310
  watchdogTimer = null;
242
311
  bridgeDownTicks = 0;
243
312
  stopped = false;
@@ -262,12 +331,22 @@ export class HeadlessGmSession {
262
331
  const { sessionSource } = this.options;
263
332
  if (sessionSource) {
264
333
  // A context of its own: the shared cookie never mixes with anything else.
265
- this.context = await this.browser.newContext();
334
+ this.context = await this.browser.newContext({ viewport: HEADLESS_VIEWPORT });
266
335
  this.page = await this.context.newPage();
267
336
  }
268
337
  else {
269
- this.page = await this.browser.newPage();
338
+ this.page = await this.browser.newPage({ viewport: HEADLESS_VIEWPORT });
270
339
  }
340
+ // The companion module reports bridge failures only in the browser console.
341
+ this.page.on('console', (message) => {
342
+ void this.logBridgeConsole(message);
343
+ });
344
+ this.page.on('pageerror', (error) => {
345
+ const text = bridgePageErrorText(error);
346
+ if (text) {
347
+ logger.warn(`Headless GM page error (bridge): ${text}`);
348
+ }
349
+ });
271
350
  if (this.options.bridgeCredentials) {
272
351
  // Before the first navigation, so the module finds it on its first `ready`.
273
352
  await this.exposeBridgeCredentials(this.page, this.options.bridgeCredentials);
@@ -348,6 +427,18 @@ export class HeadlessGmSession {
348
427
  isActive() {
349
428
  return this.active;
350
429
  }
430
+ /** When the session became logged in (epoch ms), while it still is; `null` otherwise. */
431
+ loggedInSince() {
432
+ return this.active ? this.activeSince : null;
433
+ }
434
+ /**
435
+ * True while the session is failing: a failed attempt waits for its next
436
+ * try (login, or loading /game), or the connector could not provide a new
437
+ * session. The retries go on in the background, with growing delays.
438
+ */
439
+ isRetrying() {
440
+ return (this.retryTimer !== null && this.lastError !== null) || this.reauthFailed;
441
+ }
351
442
  /** `shared`: the page reuses the connector's session; `separate`: its own account. */
352
443
  mode() {
353
444
  return this.options.sessionSource ? 'shared' : 'separate';
@@ -379,6 +470,9 @@ export class HeadlessGmSession {
379
470
  if (state === 'waiting-for-session') {
380
471
  return `⏳ Waiting for the connector's session — ${mode}`;
381
472
  }
473
+ if (state === 'loading-game') {
474
+ return `⏳ Opening /game with the connector's session — ${mode}`;
475
+ }
382
476
  if (state === 'reauthenticating') {
383
477
  return `⏳ Reauthenticating — ${mode}${this.lastError ? ` (${this.lastError})` : ''}`;
384
478
  }
@@ -425,6 +519,7 @@ export class HeadlessGmSession {
425
519
  /** Shared mode: installs a new session cookie, then (re)loads `/game`. */
426
520
  useSession(session) {
427
521
  this.reauthRequested = false;
522
+ this.reauthFailed = false;
428
523
  clearTimeout(this.retryTimer ?? undefined);
429
524
  this.retryTimer = null;
430
525
  this.sessionQueued = true;
@@ -471,6 +566,10 @@ export class HeadlessGmSession {
471
566
  this.sharedState = 'reconnecting';
472
567
  this.lastError = 'loading /game';
473
568
  }
569
+ else if (this.sharedState === 'waiting-for-session') {
570
+ // The session is in hand: what remains is the game itself.
571
+ this.sharedState = 'loading-game';
572
+ }
474
573
  try {
475
574
  const gameUrl = new URL('/game', this.options.foundryUrl).toString();
476
575
  await this.page.goto(gameUrl, { waitUntil: 'domcontentloaded' });
@@ -531,6 +630,7 @@ export class HeadlessGmSession {
531
630
  }
532
631
  const wasLoggedIn = this.sharedState === 'logged-in';
533
632
  this.active = true;
633
+ this.activeSince = Date.now();
534
634
  this.sharedState = 'logged-in';
535
635
  this.lastError = null;
536
636
  this.retryDelayMs = BASE_RETRY_MS;
@@ -584,6 +684,7 @@ export class HeadlessGmSession {
584
684
  sessionSource.reauthenticate(`headless GM page: ${reason}`).catch((error) => {
585
685
  // The connector keeps retrying on its own; the page waits for its cookie.
586
686
  this.lastError = `${reason}; reauthentication failed: ${errorText(error)}`;
687
+ this.reauthFailed = true;
587
688
  });
588
689
  }
589
690
  /**
@@ -627,6 +728,7 @@ export class HeadlessGmSession {
627
728
  }
628
729
  clearTimeout(this.retryTimer ?? undefined);
629
730
  this.retryTimer = setTimeout(() => {
731
+ this.retryTimer = null;
630
732
  this.attemptLogin().catch((error) => {
631
733
  // attemptLogin itself never throws (see its own try/catch) — this is
632
734
  // a last-resort guard so a bug there can never kill the retry loop.
@@ -682,6 +784,7 @@ export class HeadlessGmSession {
682
784
  throw new Error('Join submitted but the session never reached /game — check the password and that the world is active');
683
785
  }
684
786
  this.active = true;
787
+ this.activeSince = Date.now();
685
788
  this.lastError = null;
686
789
  this.retryDelayMs = BASE_RETRY_MS;
687
790
  logger.info(`Headless GM session logged in as ${this.options.username}`);
@@ -719,6 +822,20 @@ export class HeadlessGmSession {
719
822
  this.bridgeDownTicks = 0;
720
823
  this.reloadForBridgeRecovery();
721
824
  }
825
+ /** Copies a companion module console line to the log ({@link bridgeConsoleText}). Never throws. */
826
+ async logBridgeConsole(message) {
827
+ const text = await bridgeConsoleText(message);
828
+ if (!text) {
829
+ return;
830
+ }
831
+ const type = message.type();
832
+ if (type === 'warning' || type === 'error') {
833
+ logger.warn(`Headless GM page [bridge console.${type === 'warning' ? 'warn' : type}]: ${text}`);
834
+ }
835
+ else {
836
+ logger.info(`Headless GM page [bridge console.${type}]: ${text}`);
837
+ }
838
+ }
722
839
  /**
723
840
  * Forces a fresh page load: the Foundry session cookie survives a reload,
724
841
  * so this does not need to repeat the login form — it just re-executes
@@ -0,0 +1,141 @@
1
+ /**
2
+ * @fileoverview The list of detected journal overwrites, kept on disk so that
3
+ * `get_health_status` still lists them after the shared process restarts.
4
+ *
5
+ * `<state dir>/journal-conflicts.json`:
6
+ * `{ "version": 1, "conflicts": [{ at, journalId, pageId, journalName,
7
+ * pageName, reason, savedBy, historyPath }] }`, `at` as an ISO date. Ids,
8
+ * names, who saved and the path of the local copy: never page content (that
9
+ * stays in the copies under `journal-history/`). Written whole on every
10
+ * change, to a `.tmp` file renamed over the list, so a crash leaves the old
11
+ * list or the new one, never half of one.
12
+ */
13
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
14
+ import path from 'node:path';
15
+ import { z } from 'zod';
16
+ import { logger } from '../utils/logger.js';
17
+ const FILE_VERSION = 1;
18
+ const StoredConflictSchema = z.object({
19
+ at: z.string().refine((value) => !Number.isNaN(Date.parse(value))),
20
+ journalId: z.string(),
21
+ pageId: z.string(),
22
+ journalName: z.string(),
23
+ pageName: z.string(),
24
+ reason: z.string(),
25
+ savedBy: z.string().nullable(),
26
+ historyPath: z.string().nullable(),
27
+ });
28
+ const FileSchema = z.object({ version: z.literal(FILE_VERSION), conflicts: z.array(z.unknown()) });
29
+ const NODE_OPS = { writeFileSync, renameSync };
30
+ /** Windows: an antivirus or indexer briefly holding the file. */
31
+ const TRANSIENT_CODES = new Set(['EPERM', 'EBUSY']);
32
+ function errorCode(error) {
33
+ return typeof error === 'object' && error !== null && 'code' in error
34
+ ? String(error.code)
35
+ : undefined;
36
+ }
37
+ function errorText(error) {
38
+ return error instanceof Error ? error.message : String(error);
39
+ }
40
+ export class JournalConflictFile {
41
+ file;
42
+ ops;
43
+ constructor(file, ops = NODE_OPS) {
44
+ this.file = file;
45
+ this.ops = ops;
46
+ }
47
+ /**
48
+ * The conflicts kept in the file. A missing file is an empty list; an
49
+ * unreadable or invalid one is an empty list and one warning; an invalid
50
+ * entry is skipped. Pruning is the caller's.
51
+ */
52
+ load() {
53
+ let raw;
54
+ try {
55
+ raw = readFileSync(this.file, 'utf8');
56
+ }
57
+ catch (error) {
58
+ if (errorCode(error) !== 'ENOENT') {
59
+ logger.warn('Could not read the list of journal overwrites; starting with an empty one', {
60
+ file: this.file,
61
+ error: errorText(error),
62
+ });
63
+ }
64
+ return [];
65
+ }
66
+ let parsed;
67
+ try {
68
+ parsed = FileSchema.parse(JSON.parse(raw));
69
+ }
70
+ catch {
71
+ logger.warn('The list of journal overwrites is not valid; starting with an empty one', {
72
+ file: this.file,
73
+ });
74
+ return [];
75
+ }
76
+ const conflicts = [];
77
+ let skipped = 0;
78
+ for (const entry of parsed.conflicts) {
79
+ const stored = StoredConflictSchema.safeParse(entry);
80
+ if (!stored.success) {
81
+ skipped++;
82
+ continue;
83
+ }
84
+ conflicts.push({ ...stored.data, at: Date.parse(stored.data.at) });
85
+ }
86
+ if (skipped > 0) {
87
+ logger.warn(`Skipped ${skipped} invalid entr${skipped === 1 ? 'y' : 'ies'} of the list of journal overwrites`, {
88
+ file: this.file,
89
+ });
90
+ }
91
+ return conflicts;
92
+ }
93
+ /**
94
+ * Writes the whole list: a `.tmp` file, then a rename over the list, tried
95
+ * twice when Windows reports the file busy. A failure is one warning; the
96
+ * list in memory is unaffected.
97
+ *
98
+ * @returns whether the list was written
99
+ */
100
+ save(conflicts) {
101
+ const content = `${JSON.stringify({
102
+ version: FILE_VERSION,
103
+ conflicts: conflicts.map((conflict) => ({
104
+ at: new Date(conflict.at).toISOString(),
105
+ journalId: conflict.journalId,
106
+ pageId: conflict.pageId,
107
+ journalName: conflict.journalName,
108
+ pageName: conflict.pageName,
109
+ reason: conflict.reason,
110
+ savedBy: conflict.savedBy,
111
+ historyPath: conflict.historyPath,
112
+ })),
113
+ }, null, 2)}\n`;
114
+ const tmp = `${this.file}.tmp`;
115
+ for (let attempt = 1;; attempt++) {
116
+ try {
117
+ mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
118
+ this.ops.writeFileSync(tmp, content, { encoding: 'utf8', mode: 0o600 });
119
+ this.ops.renameSync(tmp, this.file);
120
+ return true;
121
+ }
122
+ catch (error) {
123
+ if (attempt === 1 && TRANSIENT_CODES.has(errorCode(error) ?? '')) {
124
+ continue;
125
+ }
126
+ try {
127
+ rmSync(tmp, { force: true });
128
+ }
129
+ catch {
130
+ // Left behind; the next save overwrites it.
131
+ }
132
+ logger.warn('Could not save the list of journal overwrites; it is kept in memory', {
133
+ file: this.file,
134
+ error: errorText(error),
135
+ });
136
+ return false;
137
+ }
138
+ }
139
+ }
140
+ }
141
+ //# sourceMappingURL=journal-conflicts.js.map
@@ -196,18 +196,28 @@ function pageKey(journalId, pageId) {
196
196
  return `${journalId}.${pageId}`;
197
197
  }
198
198
  /**
199
- * In-memory integrity state for journal pages: writes in flight, watched
200
- * writes, recent editor autosaves, pending warnings and recent conflicts.
199
+ * Integrity state for journal pages: writes in flight, watched writes, recent
200
+ * editor autosaves and pending warnings, in memory; the recent conflicts also
201
+ * in a file when one is given ({@link JournalConflictFile}), so they survive
202
+ * a restart.
201
203
  */
202
204
  export class JournalWatch {
203
205
  now;
206
+ conflictFile;
204
207
  watches = new Map();
205
208
  inflight = new Map();
206
209
  autosaves = new Map();
207
210
  warnings = [];
208
211
  conflicts = [];
209
- constructor(now = Date.now) {
212
+ constructor(now = Date.now, conflictFile = null) {
210
213
  this.now = now;
214
+ this.conflictFile = conflictFile;
215
+ if (conflictFile) {
216
+ this.conflicts = conflictFile.load();
217
+ if (this.pruneConflicts()) {
218
+ conflictFile.save(this.conflicts);
219
+ }
220
+ }
211
221
  }
212
222
  /** Starts collecting foreign changes to a page while a connector write is in flight. */
213
223
  beginWrite(journalId, pageId) {
@@ -284,10 +294,13 @@ export class JournalWatch {
284
294
  recordConflict(conflict) {
285
295
  this.conflicts.push(conflict);
286
296
  this.pruneConflicts();
297
+ this.conflictFile?.save(this.conflicts);
287
298
  }
288
299
  /** Conflicts detected within {@link CONFLICT_RETENTION_MS}, oldest first. */
289
300
  recentConflicts() {
290
- this.pruneConflicts();
301
+ if (this.pruneConflicts()) {
302
+ this.conflictFile?.save(this.conflicts);
303
+ }
291
304
  return [...this.conflicts];
292
305
  }
293
306
  pruneWatches() {
@@ -298,9 +311,12 @@ export class JournalWatch {
298
311
  }
299
312
  }
300
313
  }
314
+ /** @returns whether any conflict was dropped */
301
315
  pruneConflicts() {
302
316
  const cutoff = this.now() - CONFLICT_RETENTION_MS;
317
+ const before = this.conflicts.length;
303
318
  this.conflicts = this.conflicts.filter((conflict) => conflict.at > cutoff);
319
+ return this.conflicts.length !== before;
304
320
  }
305
321
  }
306
322
  //# sourceMappingURL=journal-integrity.js.map
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @fileoverview Who wrote a chat message.
3
+ *
4
+ * FoundryVTT stores the author of a chat message in `author` since v12
5
+ * (v14: common/documents/chat-message.mjs,
6
+ * `author: new fields.DocumentAuthorField(documents.BaseUser)`); `user` is
7
+ * its earlier name, kept for messages from older data (G33ks/foundryvtt-mcp#13).
8
+ */
9
+ /** The id of the user who wrote `message`: `author`, else `user`; `undefined` when neither is a string. */
10
+ export function messageAuthorId(message) {
11
+ if (typeof message.author === 'string' && message.author !== '') {
12
+ return message.author;
13
+ }
14
+ if (typeof message.user === 'string' && message.user !== '') {
15
+ return message.user;
16
+ }
17
+ return undefined;
18
+ }
19
+ //# sourceMappingURL=message-author.js.map