@g33ks/foundryvtt-mcp 3.0.0 → 3.0.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.
package/README.md CHANGED
@@ -92,6 +92,8 @@ When something fails, the message says why; [TROUBLESHOOTING.md](https://github.
92
92
  - **Some changes stay yours**: the connector does not promote anyone to Gamemaster nor change the world's permission settings.
93
93
  - **After FoundryVTT restarts, launch the world again.** The connector waits for it and reconnects by itself.
94
94
  - **After an update, restart your MCP client**: a client started earlier keeps the previous list of tools.
95
+ - **A deletion can, rarely, go unanswered**: FoundryVTT deletes the document, but its answer never reaches the connector. It has not been reproduced on demand. The connector then reads the document back: the tool succeeds with a note when the document is gone, and reports the timeout otherwise. If such an error still happens, note the time, call `refresh_world_data`, and keep the connector's log lines from that time ([where the log is](https://github.com/G33ks/foundryvtt-mcp/blob/main/docs/architecture.md#the-state-directory)).
96
+ - **A combat created by `start_combat` may not show in the combat tracker.** Some game systems define a combat's own data in code that only the browsers load; the connector creates the combat on the server without that data, and the browsers reject it. The fix needs a future version of the companion module.
95
97
 
96
98
  ## Documentation
97
99
 
@@ -298,6 +298,27 @@ export function gamemasterAccountWarning(shared, account) {
298
298
  'it: that page may become the active GM instead of a human Gamemaster (equal roles go to ' +
299
299
  'the smaller user id) and run the game system automations. Make this account an Assistant GM.');
300
300
  }
301
+ /** A Socket.IO request whose acknowledgement did not arrive within the timeout. */
302
+ class AckTimeoutError extends Error {
303
+ }
304
+ /** Response note of a deletion that only a re-read could confirm. */
305
+ export const DELETE_VERIFIED_NOTE = 'FoundryVTT deleted the document but its acknowledgement timed out; verified by re-reading it.';
306
+ /** Action, document type and id of a `modifyDocument` request, for the log. */
307
+ function describeAckRequest(payload) {
308
+ if (!isRecord(payload)) {
309
+ return {};
310
+ }
311
+ const operation = isRecord(payload.operation) ? payload.operation : {};
312
+ const first = (list) => (Array.isArray(list) ? list[0] : undefined);
313
+ const data = first(operation.data) ?? first(operation.updates);
314
+ const query = isRecord(operation.query) ? operation.query : {};
315
+ const id = first(operation.ids) ?? (isRecord(data) ? data._id : undefined) ?? query._id;
316
+ return {
317
+ ...(typeof payload.action === 'string' ? { action: payload.action } : {}),
318
+ ...(typeof payload.type === 'string' ? { type: payload.type } : {}),
319
+ ...(typeof id === 'string' ? { id } : {}),
320
+ };
321
+ }
301
322
  export class FoundryClient {
302
323
  http;
303
324
  socket = null;
@@ -342,6 +363,10 @@ export class FoundryClient {
342
363
  outage = null;
343
364
  /** Counts socket drops: a reload that saw one leaves the cache stale. */
344
365
  socketDrops = 0;
366
+ /** When the server's last ping reached the socket; `null` since it connected. */
367
+ lastPingAt = null;
368
+ /** Socket.IO requests still waiting for their acknowledgement within their timeout. */
369
+ pendingAcks = 0;
345
370
  /**
346
371
  * Last observed outcome of a REST request: false once one failed to reach
347
372
  * FoundryVTT at all (laurigates/foundryvtt-mcp#217). Unused in Socket.IO mode.
@@ -761,13 +786,22 @@ export class FoundryClient {
761
786
  socket.on('userActivity', this.onUserActivity);
762
787
  // Collaborative-editor autosaves bypass `modifyDocument` entirely.
763
788
  socket.on('pm.autosave', this.onEditorAutosave);
789
+ // The server's pings, for the age logged when a request times out
790
+ // (test doubles have no manager).
791
+ this.lastPingAt = null;
792
+ socket.io?.on('ping', this.onServerPing);
764
793
  }
765
794
  detachDataListeners(socket) {
766
795
  socket.off('modifyDocument', this.onDocumentBroadcast);
767
796
  socket.off('modifyDocumentBatch', this.onDocumentBatchBroadcast);
768
797
  socket.off('userActivity', this.onUserActivity);
769
798
  socket.off('pm.autosave', this.onEditorAutosave);
799
+ socket.io?.off('ping', this.onServerPing);
770
800
  }
801
+ /** Bound field rather than a method so the same reference reaches `off()`. */
802
+ onServerPing = () => {
803
+ this.lastPingAt = Date.now();
804
+ };
771
805
  /** The handshake: FoundryVTT's first `session` event must name a user. */
772
806
  waitForSessionUser(socket, timeoutMs, timeoutMessage) {
773
807
  return new Promise((resolve, reject) => {
@@ -1122,6 +1156,7 @@ export class FoundryClient {
1122
1156
  // Only the transport is back: FoundryVTT may not know the session any
1123
1157
  // more (a server restart forgets every session). `onSessionEvent` decides.
1124
1158
  this.awaitingSession = true;
1159
+ this.lastPingAt = null;
1125
1160
  logger.debug('FoundryVTT socket transport reconnected — waiting for its session');
1126
1161
  };
1127
1162
  /**
@@ -2133,6 +2168,10 @@ export class FoundryClient {
2133
2168
  * Emits a Socket.IO event with an acknowledgement callback, resolving the
2134
2169
  * server's response and rejecting on timeout. Mirrors the ack pattern used by
2135
2170
  * the `world` event in {@link connectAndLoadWorld}/{@link refreshWorldData}.
2171
+ *
2172
+ * The timeout error carries the age of the server's last ping, the socket's
2173
+ * state and the requests still waiting; an acknowledgement that arrives
2174
+ * after it is logged and otherwise ignored.
2136
2175
  */
2137
2176
  emitWithAck(event, payload) {
2138
2177
  return new Promise((resolve, reject) => {
@@ -2149,9 +2188,30 @@ export class FoundryClient {
2149
2188
  return;
2150
2189
  }
2151
2190
  const timeoutMs = this.config.timeout || 10000;
2152
- const timeout = setTimeout(() => reject(new Error(`Timeout waiting for '${event}' response (${timeoutMs}ms)`)), timeoutMs);
2191
+ const sentAt = Date.now();
2192
+ let timedOut = false;
2193
+ this.pendingAcks += 1;
2194
+ const timeout = setTimeout(() => {
2195
+ timedOut = true;
2196
+ const lastPing = this.lastPingAt === null
2197
+ ? 'none since connect'
2198
+ : `${Date.now() - this.lastPingAt} ms ago`;
2199
+ reject(new AckTimeoutError(`Timeout waiting for '${event}' response (${timeoutMs}ms) ` +
2200
+ `[last ping: ${lastPing}; socket: ${socket.connected ? 'connected' : 'disconnected'}; ` +
2201
+ `pending requests: ${this.pendingAcks}]`));
2202
+ this.pendingAcks -= 1;
2203
+ }, timeoutMs);
2153
2204
  socket.emit(event, payload, (response) => {
2205
+ if (timedOut) {
2206
+ logger.warn(`Late acknowledgement for '${event}' ignored`, {
2207
+ ...describeAckRequest(payload),
2208
+ delayMs: Date.now() - sentAt,
2209
+ timeoutMs,
2210
+ });
2211
+ return;
2212
+ }
2154
2213
  clearTimeout(timeout);
2214
+ this.pendingAcks -= 1;
2155
2215
  resolve(response);
2156
2216
  });
2157
2217
  });
@@ -2213,6 +2273,63 @@ export class FoundryClient {
2213
2273
  this.changeCache((worldData) => applyDocumentBroadcast(worldData, ownWrite));
2214
2274
  return result;
2215
2275
  }
2276
+ /**
2277
+ * Deletes one world document. When the acknowledgement times out, reads
2278
+ * the document back once over the socket instead of reporting a failure
2279
+ * FoundryVTT may not have had: gone means deleted (the cache is updated as
2280
+ * an acknowledgement would have); still there, or the read failing, keeps
2281
+ * the timeout error. Never sends the deletion again. A scene confirmed this
2282
+ * way also marks the cache stale: FoundryVTT deletes its combats with it,
2283
+ * and their deletion was never received.
2284
+ *
2285
+ * @returns a note for the response when only the re-read confirmed the deletion
2286
+ */
2287
+ async deleteWorldDocument(type, id) {
2288
+ try {
2289
+ await this.modifyDocument(type, 'delete', { ids: [id] });
2290
+ return undefined;
2291
+ }
2292
+ catch (error) {
2293
+ if (!(error instanceof AckTimeoutError)) {
2294
+ throw error;
2295
+ }
2296
+ let exists;
2297
+ try {
2298
+ exists = await this.worldDocumentExists(type, id);
2299
+ }
2300
+ catch (readError) {
2301
+ const reason = readError instanceof Error ? readError.message : String(readError);
2302
+ throw new Error(`${error.message} (re-reading the document to check failed: ${reason})`);
2303
+ }
2304
+ if (exists) {
2305
+ throw error;
2306
+ }
2307
+ logger.warn('Deletion acknowledgement timed out, but re-reading shows the document is gone', {
2308
+ type,
2309
+ id,
2310
+ });
2311
+ this.changeCache((worldData) => applyDocumentBroadcast(worldData, { type, action: 'delete', result: [id] }));
2312
+ if (type === 'Scene') {
2313
+ this.markWorldDataStale(true, 'a scene deletion was only confirmed by re-reading it; its combats may still be cached');
2314
+ }
2315
+ return DELETE_VERIFIED_NOTE;
2316
+ }
2317
+ }
2318
+ /** Whether the server still has this world document (`modifyDocument` `get`). */
2319
+ async worldDocumentExists(type, id) {
2320
+ const response = await this.emitWithAck('modifyDocument', {
2321
+ type,
2322
+ action: 'get',
2323
+ operation: { query: { _id: id }, pack: null },
2324
+ });
2325
+ if (response?.error) {
2326
+ throw new Error(response.error.message || 'unknown error');
2327
+ }
2328
+ if (!Array.isArray(response?.result)) {
2329
+ throw new Error('unexpected answer');
2330
+ }
2331
+ return response.result.length > 0;
2332
+ }
2216
2333
  // ==========================================================================
2217
2334
  // Item mutation methods (WRITE — Socket.IO modifyDocument)
2218
2335
  // ==========================================================================
@@ -2344,13 +2461,14 @@ export class FoundryClient {
2344
2461
  * Ends (deletes) the active combat encounter (FR-018).
2345
2462
  *
2346
2463
  * @param combatId - 16-char alphanumeric Combat document id
2464
+ * @returns a note when only a re-read confirmed the deletion ({@link deleteWorldDocument})
2347
2465
  */
2348
2466
  async endCombat(combatId) {
2349
2467
  this.assertWriteable();
2350
2468
  if (!FOUNDRY_ID_PATTERN.test(combatId)) {
2351
2469
  throw new Error(`Invalid combatId format: ${combatId}`);
2352
2470
  }
2353
- await this.modifyDocument('Combat', 'delete', { ids: [combatId] });
2471
+ return this.deleteWorldDocument('Combat', combatId);
2354
2472
  }
2355
2473
  /**
2356
2474
  * Sets a combatant's initiative (FR-018).
@@ -3540,25 +3658,27 @@ export class FoundryClient {
3540
3658
  * Permanently deletes a top-level Actor document (mirrors {@link createWorldActor}).
3541
3659
  *
3542
3660
  * @param actorId - 16-char alphanumeric Actor document id to delete
3661
+ * @returns a note when only a re-read confirmed the deletion ({@link deleteWorldDocument})
3543
3662
  */
3544
3663
  async deleteWorldActor(actorId) {
3545
3664
  this.assertWriteable();
3546
3665
  if (!FOUNDRY_ID_PATTERN.test(actorId)) {
3547
3666
  throw new Error(`Invalid actorId format: ${actorId}`);
3548
3667
  }
3549
- await this.modifyDocument('Actor', 'delete', { ids: [actorId] });
3668
+ return this.deleteWorldDocument('Actor', actorId);
3550
3669
  }
3551
3670
  /**
3552
3671
  * Permanently deletes a Scene document (mirrors {@link switchScene}).
3553
3672
  *
3554
3673
  * @param sceneId - 16-char alphanumeric Scene document id to delete
3674
+ * @returns a note when only a re-read confirmed the deletion ({@link deleteWorldDocument})
3555
3675
  */
3556
3676
  async deleteScene(sceneId) {
3557
3677
  this.assertWriteable();
3558
3678
  if (!FOUNDRY_ID_PATTERN.test(sceneId)) {
3559
3679
  throw new Error(`Invalid sceneId format: ${sceneId}`);
3560
3680
  }
3561
- await this.modifyDocument('Scene', 'delete', { ids: [sceneId] });
3681
+ return this.deleteWorldDocument('Scene', sceneId);
3562
3682
  }
3563
3683
  /**
3564
3684
  * Updates document ownership permissions for users.
@@ -3608,13 +3728,14 @@ export class FoundryClient {
3608
3728
  * Permanently deletes a JournalEntry document (mirrors {@link createJournalEntry}).
3609
3729
  *
3610
3730
  * @param journalId - 16-char alphanumeric JournalEntry document id to delete
3731
+ * @returns a note when only a re-read confirmed the deletion ({@link deleteWorldDocument})
3611
3732
  */
3612
3733
  async deleteJournalEntry(journalId) {
3613
3734
  this.assertWriteable();
3614
3735
  if (!FOUNDRY_ID_PATTERN.test(journalId)) {
3615
3736
  throw new Error(`Invalid journalId format: ${journalId}`);
3616
3737
  }
3617
- await this.modifyDocument('JournalEntry', 'delete', { ids: [journalId] });
3738
+ return this.deleteWorldDocument('JournalEntry', journalId);
3618
3739
  }
3619
3740
  // ==========================================================================
3620
3741
  // Roll tables (read + local weighted draw)
@@ -3742,7 +3863,7 @@ export class FoundryClient {
3742
3863
  if (!FOUNDRY_ID_PATTERN.test(tableId)) {
3743
3864
  throw new Error(`Invalid tableId format: ${tableId}`);
3744
3865
  }
3745
- await this.modifyDocument('RollTable', 'delete', { ids: [tableId] });
3866
+ return this.deleteWorldDocument('RollTable', tableId);
3746
3867
  }
3747
3868
  // ==========================================================================
3748
3869
  // Folder methods
@@ -3852,7 +3973,7 @@ export class FoundryClient {
3852
3973
  if (!FOUNDRY_ID_PATTERN.test(macroId)) {
3853
3974
  throw new Error(`Invalid macroId format: ${macroId}`);
3854
3975
  }
3855
- await this.modifyDocument('Macro', 'delete', { ids: [macroId] });
3976
+ return this.deleteWorldDocument('Macro', macroId);
3856
3977
  }
3857
3978
  // ==========================================================================
3858
3979
  // Playlist methods
@@ -3965,7 +4086,7 @@ export class FoundryClient {
3965
4086
  if (!FOUNDRY_ID_PATTERN.test(playlistId)) {
3966
4087
  throw new Error(`Invalid playlistId format: ${playlistId}`);
3967
4088
  }
3968
- await this.modifyDocument('Playlist', 'delete', { ids: [playlistId] });
4089
+ return this.deleteWorldDocument('Playlist', playlistId);
3969
4090
  }
3970
4091
  // ==========================================================================
3971
4092
  // World settings methods
@@ -6,7 +6,7 @@
6
6
  * connection (mutations use the core `modifyDocument` protocol).
7
7
  */
8
8
  import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
9
- import { withToolError } from './utils.js';
9
+ import { deletionNote, withToolError } from './utils.js';
10
10
  /**
11
11
  * Handles actor attribute update requests.
12
12
  *
@@ -125,9 +125,11 @@ export async function handleDeleteWorldActor(args, foundryClient) {
125
125
  throw new McpError(ErrorCode.InvalidParams, 'actorId is required and must be a string');
126
126
  }
127
127
  return withToolError('delete actor', async () => {
128
- await foundryClient.deleteWorldActor(actorId);
128
+ const note = await foundryClient.deleteWorldActor(actorId);
129
129
  return {
130
- content: [{ type: 'text', text: `🗑️ **Actor Deleted**\n**ID:** ${actorId}` }],
130
+ content: [
131
+ { type: 'text', text: `🗑️ **Actor Deleted**\n**ID:** ${actorId}${deletionNote(note)}` },
132
+ ],
131
133
  };
132
134
  });
133
135
  }
@@ -10,7 +10,7 @@
10
10
  import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
11
11
  import { combatantName } from './combat.js';
12
12
  import { getCurrentCombatant, getTurnOrder, turnIndexAfterInitiativeChange, } from './combat-order.js';
13
- import { withToolError } from './utils.js';
13
+ import { deletionNote, withToolError } from './utils.js';
14
14
  /**
15
15
  * Computes the next `{ turn, round }` for an active combat.
16
16
  *
@@ -90,14 +90,14 @@ export async function handleEndCombat(_args, foundryClient) {
90
90
  throw new McpError(ErrorCode.InvalidRequest, 'No active combat to end.');
91
91
  }
92
92
  return withToolError('end combat', async () => {
93
- await foundryClient.endCombat(combat._id);
93
+ const note = await foundryClient.endCombat(combat._id);
94
94
  return {
95
95
  content: [
96
96
  {
97
97
  type: 'text',
98
98
  text: `⚔️ **Combat Ended**
99
99
  **Encounter:** ${combat._id}
100
- The active combat encounter has been removed.`,
100
+ The active combat encounter has been removed.${deletionNote(note)}`,
101
101
  },
102
102
  ],
103
103
  };
@@ -10,7 +10,7 @@ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
10
10
  import { journalVersion } from '../../foundry/journal-integrity.js';
11
11
  import { VISIBILITY_LEVELS } from '../../foundry/types.js';
12
12
  import { refusalError } from '../../utils/refusal.js';
13
- import { withJournalWarnings, withToolError } from './utils.js';
13
+ import { deletionNote, withJournalWarnings, withToolError } from './utils.js';
14
14
  /** Version token of a page body as returned by the server. */
15
15
  function pageVersion(page) {
16
16
  return journalVersion(page?.text?.content ?? '');
@@ -219,10 +219,13 @@ export async function handleDeleteJournalEntry(args, foundryClient) {
219
219
  return withToolError('delete journal entry', async () => {
220
220
  const target = foundryClient.getJournal(journalId);
221
221
  const name = target?.name ?? journalId;
222
- await foundryClient.deleteJournalEntry(journalId);
222
+ const note = await foundryClient.deleteJournalEntry(journalId);
223
223
  return withJournalWarnings(foundryClient, {
224
224
  content: [
225
- { type: 'text', text: `🗑️ **Journal Entry Deleted**\n**Entry:** ${name} (${journalId})` },
225
+ {
226
+ type: 'text',
227
+ text: `🗑️ **Journal Entry Deleted**\n**Entry:** ${name} (${journalId})${deletionNote(note)}`,
228
+ },
226
229
  ],
227
230
  });
228
231
  });
@@ -6,7 +6,7 @@
6
6
  * FOUNDRY_WRITE_ENABLED.
7
7
  */
8
8
  import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
9
- import { withToolError } from './utils.js';
9
+ import { deletionNote, withToolError } from './utils.js';
10
10
  /**
11
11
  * Handles listing the world's roll tables.
12
12
  */
@@ -83,12 +83,12 @@ export async function handleDeleteRollTable(args, foundryClient) {
83
83
  throw new McpError(ErrorCode.InvalidParams, 'tableId is required and must be a string');
84
84
  }
85
85
  return withToolError('delete roll table', async () => {
86
- await foundryClient.deleteRollTable(tableId);
86
+ const note = await foundryClient.deleteRollTable(tableId);
87
87
  return {
88
88
  content: [
89
89
  {
90
90
  type: 'text',
91
- text: `🗑️ **Roll Table Deleted**\n**ID:** ${tableId}`,
91
+ text: `🗑️ **Roll Table Deleted**\n**ID:** ${tableId}${deletionNote(note)}`,
92
92
  },
93
93
  ],
94
94
  };
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
8
8
  import { resolveSceneId } from './scenes.js';
9
- import { withToolError } from './utils.js';
9
+ import { deletionNote, withToolError } from './utils.js';
10
10
  /**
11
11
  * Handles creating a new Scene document from a background image on disk.
12
12
  */
@@ -66,9 +66,14 @@ export async function handleDeleteScene(args, foundryClient) {
66
66
  return withToolError('delete scene', async () => {
67
67
  const target = foundryClient.getScenes().find((s) => s._id === sceneId);
68
68
  const name = target?.name ?? sceneId;
69
- await foundryClient.deleteScene(sceneId);
69
+ const note = await foundryClient.deleteScene(sceneId);
70
70
  return {
71
- content: [{ type: 'text', text: `🗑️ **Scene Deleted**\n**Scene:** ${name} (${sceneId})` }],
71
+ content: [
72
+ {
73
+ type: 'text',
74
+ text: `🗑️ **Scene Deleted**\n**Scene:** ${name} (${sceneId})${deletionNote(note)}`,
75
+ },
76
+ ],
72
77
  };
73
78
  });
74
79
  }
@@ -22,6 +22,13 @@ export function withJournalWarnings(foundryClient, response) {
22
22
  ],
23
23
  };
24
24
  }
25
+ /**
26
+ * Ends a deletion's response with the client's note when only a re-read
27
+ * confirmed the deletion (see `FoundryClient.deleteScene` and the like).
28
+ */
29
+ export function deletionNote(note) {
30
+ return note ? `\n\n⚠️ ${note}` : '';
31
+ }
25
32
  /**
26
33
  * Wraps an async handler function with standard error logging and McpError conversion.
27
34
  *
@@ -2,7 +2,7 @@
2
2
  * @fileoverview World document tool handlers (folders, macros, playlists).
3
3
  */
4
4
  import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
5
- import { withToolError } from './utils.js';
5
+ import { deletionNote, withToolError } from './utils.js';
6
6
  // ============================================================================
7
7
  // Folder handlers
8
8
  // ============================================================================
@@ -98,12 +98,12 @@ export async function handleDeleteMacro(args, foundryClient) {
98
98
  throw new McpError(ErrorCode.InvalidParams, 'macroId is required and must be a string');
99
99
  }
100
100
  return withToolError('delete macro', async () => {
101
- await foundryClient.deleteMacro(macroId);
101
+ const note = await foundryClient.deleteMacro(macroId);
102
102
  return {
103
103
  content: [
104
104
  {
105
105
  type: 'text',
106
- text: `🗑️ **Macro Deleted**\n**ID:** ${macroId}`,
106
+ text: `🗑️ **Macro Deleted**\n**ID:** ${macroId}${deletionNote(note)}`,
107
107
  },
108
108
  ],
109
109
  };
@@ -181,12 +181,12 @@ export async function handleDeletePlaylist(args, foundryClient) {
181
181
  throw new McpError(ErrorCode.InvalidParams, 'playlistId is required and must be a string');
182
182
  }
183
183
  return withToolError('delete playlist', async () => {
184
- await foundryClient.deletePlaylist(playlistId);
184
+ const note = await foundryClient.deletePlaylist(playlistId);
185
185
  return {
186
186
  content: [
187
187
  {
188
188
  type: 'text',
189
- text: `🗑️ **Playlist Deleted**\n**ID:** ${playlistId}`,
189
+ text: `🗑️ **Playlist Deleted**\n**ID:** ${playlistId}${deletionNote(note)}`,
190
190
  },
191
191
  ],
192
192
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@g33ks/foundryvtt-mcp",
3
- "version": "3.0.0",
3
+ "version": "3.0.1",
4
4
  "description": "Model Context Protocol server for FoundryVTT integration",
5
5
  "bin": {
6
6
  "foundryvtt-mcp": "dist/index.js"