@g33ks/foundryvtt-mcp 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
+ - **Before companion module 0.7.0, 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; without the module 0.7.0, the connector creates the combat on the server without that data, and open browsers reject it until each user reloads FoundryVTT (F5); later updates then show live. With the module 0.7.0 or later, the combat is created in the module's browser session and shows at once.
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
@@ -40,6 +40,11 @@
40
40
  * not cover it; it only decides which commands the server tries to send (see
41
41
  * {@link ModuleBridge.send}). An older module omits it, and is then sent only
42
42
  * {@link LEGACY_COMMANDS}.
43
+ *
44
+ * Since module 0.7.0, an error response may also carry `refusal: true` (and a
45
+ * `code`): the command turned the call down by design, and {@link
46
+ * ModuleBridge.send} rejects with a {@link RefusedError}. `error` stays the
47
+ * message either way.
43
48
  */
44
49
  import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
45
50
  import { WebSocket, WebSocketServer } from 'ws';
@@ -80,6 +85,7 @@ export const LEGACY_COMMANDS = [
80
85
  export const COMMAND_SINCE = {
81
86
  get_actor_stats: '0.6.0',
82
87
  toggle_status_effect: '0.6.0',
88
+ create_combat: '0.7.0',
83
89
  };
84
90
  /**
85
91
  * Bounds of the `module` announcement in `auth_response`: at worst (100
@@ -550,7 +556,8 @@ export class ModuleBridge {
550
556
  this.pending.delete(parsed.id);
551
557
  clearTimeout(pending.timeout);
552
558
  if (parsed.error !== undefined) {
553
- pending.reject(new Error(typeof parsed.error === 'string' ? parsed.error : 'Module error'));
559
+ const message = typeof parsed.error === 'string' ? parsed.error : 'Module error';
560
+ pending.reject(parsed.refusal === true ? new RefusedError(message) : new Error(message));
554
561
  }
555
562
  else {
556
563
  pending.resolve(parsed.result);
@@ -1591,7 +1591,7 @@ export const combatMutationTools = [
1591
1591
  },
1592
1592
  {
1593
1593
  name: 'start_combat',
1594
- description: 'Start a new combat encounter, seeding combatants from tokens: pass explicit tokenIds, or omit them to seed every token on the scene. Defaults to the active scene when sceneId is omitted. The encounter begins at round 1, turn 0, as when the GM clicks Begin Combat in Foundry. Use when: a fight begins and no combat is running. Do not use when: a combat is already active - check get_combat_state first, since this always creates an additional encounter. ' +
1594
+ description: 'Start a new combat encounter, seeding combatants from tokens: pass explicit tokenIds, or omit them to seed every token on the scene. Defaults to the active scene when sceneId is omitted. The encounter begins at round 1, turn 0, as when the GM clicks Begin Combat in Foundry. With the companion module 0.7.0 or later, the combat is created in its browser session, so the game system prepares the combat and its combatants; without it, the combat is created over the socket, and when the game system defines combat types of its own, open browsers reject it until each user reloads FoundryVTT (F5); later updates then show live. Use when: a fight begins and no combat is running. Do not use when: a combat is already active - check get_combat_state first, since this always creates an additional encounter. ' +
1595
1595
  WRITE_GATE,
1596
1596
  inputSchema: {
1597
1597
  type: 'object',
@@ -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
  }
@@ -5,12 +5,15 @@
5
5
  * advancing the turn, ending the encounter, and setting a combatant's
6
6
  * initiative. All are WRITE operations — they require FOUNDRY_WRITE_ENABLED=true
7
7
  * and an active Socket.IO connection (mutations use the core `modifyDocument`
8
- * protocol), and the connected user needs GM/owner permission.
8
+ * protocol), and the connected user needs GM/owner permission. Starting a
9
+ * combat goes through the companion module when it serves `create_combat`.
9
10
  */
10
11
  import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
12
+ import { isRecord } from '../../utils/guards.js';
13
+ import { logger } from '../../utils/logger.js';
11
14
  import { combatantName } from './combat.js';
12
15
  import { getCurrentCombatant, getTurnOrder, turnIndexAfterInitiativeChange, } from './combat-order.js';
13
- import { withToolError } from './utils.js';
16
+ import { deletionNote, withToolError } from './utils.js';
14
17
  /**
15
18
  * Computes the next `{ turn, round }` for an active combat.
16
19
  *
@@ -90,14 +93,14 @@ export async function handleEndCombat(_args, foundryClient) {
90
93
  throw new McpError(ErrorCode.InvalidRequest, 'No active combat to end.');
91
94
  }
92
95
  return withToolError('end combat', async () => {
93
- await foundryClient.endCombat(combat._id);
96
+ const note = await foundryClient.endCombat(combat._id);
94
97
  return {
95
98
  content: [
96
99
  {
97
100
  type: 'text',
98
101
  text: `āš”ļø **Combat Ended**
99
102
  **Encounter:** ${combat._id}
100
- The active combat encounter has been removed.`,
103
+ The active combat encounter has been removed.${deletionNote(note)}`,
101
104
  },
102
105
  ],
103
106
  };
@@ -159,14 +162,99 @@ export async function handleSetInitiative(args, foundryClient) {
159
162
  };
160
163
  });
161
164
  }
165
+ /** How long start_combat waits for the cache to show a combat the module created. */
166
+ export const CACHED_COMBAT_WAIT_MS = 2000;
167
+ const CACHED_COMBAT_POLL_MS = 25;
168
+ /**
169
+ * The sub-types the world's game system declares for `Combat` or
170
+ * `Combatant`, other than `base`: from the world payload's `model` (what the
171
+ * browsers build `game.documentTypes` from), else from its system manifest's
172
+ * `documentTypes`. Such a system may define data of its own for them, which
173
+ * only code loaded by the browsers fills in.
174
+ */
175
+ export function declaredCombatTypes(world) {
176
+ if (!world) {
177
+ return [];
178
+ }
179
+ const typesOf = (documentName) => {
180
+ const fromModel = isRecord(world.model) ? world.model[documentName] : undefined;
181
+ if (isRecord(fromModel)) {
182
+ return Object.keys(fromModel);
183
+ }
184
+ const manifestTypes = isRecord(world.system) ? world.system.documentTypes : undefined;
185
+ const fromManifest = isRecord(manifestTypes) ? manifestTypes[documentName] : undefined;
186
+ return isRecord(fromManifest) ? Object.keys(fromManifest) : [];
187
+ };
188
+ return [...new Set([...typesOf('Combat'), ...typesOf('Combatant')])].filter((type) => type !== 'base');
189
+ }
190
+ /**
191
+ * Waits, up to {@link CACHED_COMBAT_WAIT_MS}, for the cache to show a combat
192
+ * the module created, begun and with its combatants. The module answers once
193
+ * its own page has the combat; FoundryVTT broadcasts it to the connector's
194
+ * socket at the same time, but nothing orders the two.
195
+ *
196
+ * Logs one info line with the time waited and the number of polls (waits of
197
+ * {@link CACHED_COMBAT_POLL_MS}): 0 polls means the cache already had it.
198
+ *
199
+ * @returns false when the time ran out first
200
+ */
201
+ async function waitForCachedCombat(foundryClient, combatId, combatantCount) {
202
+ const started = Date.now();
203
+ const deadline = started + CACHED_COMBAT_WAIT_MS;
204
+ for (let polls = 0;; polls++) {
205
+ const combat = foundryClient.getWorldData()?.combats.find((c) => c._id === combatId);
206
+ const cached = combat !== undefined && combat.round >= 1 && combat.combatants.length >= combatantCount;
207
+ if (cached || Date.now() >= deadline) {
208
+ logger.info(`combat ${combatId} ${cached ? 'in' : 'not yet in'} the cache after ${Date.now() - started} ms (${polls} polls)${cached ? '' : '; answered with a note'}`);
209
+ return cached;
210
+ }
211
+ await new Promise((resolve) => setTimeout(resolve, CACHED_COMBAT_POLL_MS));
212
+ }
213
+ }
214
+ function parseModuleCombat(outcome) {
215
+ if (!isRecord(outcome) ||
216
+ typeof outcome.combatId !== 'string' ||
217
+ !Array.isArray(outcome.combatantIds) ||
218
+ !outcome.combatantIds.every((id) => typeof id === 'string') ||
219
+ (outcome.incomplete !== undefined && typeof outcome.incomplete !== 'string')) {
220
+ throw new McpError(ErrorCode.InternalError, 'Module returned an unexpected create_combat shape');
221
+ }
222
+ return {
223
+ combatId: outcome.combatId,
224
+ combatantIds: outcome.combatantIds,
225
+ ...(outcome.incomplete !== undefined ? { incomplete: outcome.incomplete } : {}),
226
+ };
227
+ }
228
+ function startedResult(combatId, scene, combatantCount, createdBy, note = '') {
229
+ return {
230
+ content: [
231
+ {
232
+ type: 'text',
233
+ text: `āš”ļø **Combat Started**
234
+ **Encounter:** ${combatId}
235
+ **Scene:** ${scene.name} (${scene._id})
236
+ **Combatants:** ${combatantCount}
237
+ **Created by:** ${createdBy}${note}`,
238
+ },
239
+ ],
240
+ };
241
+ }
162
242
  /**
163
243
  * Starts a new combat encounter, seeding combatants from tokens (FR-018, laurigates/foundryvtt-mcp#172).
164
244
  *
165
245
  * Resolves the target scene (explicit `sceneId`, else the active scene), then
166
246
  * builds combatant seeds from the requested `tokenIds` (or every token on the
167
- * scene when none are given) and delegates the two-step create to the client.
247
+ * scene when none are given).
248
+ *
249
+ * With writes enabled and a companion module that serves `create_combat`
250
+ * (0.7.0 or later; FoundryCore waited for one on its way), the module creates
251
+ * and begins the combat in the headless GM page, so the game system prepares
252
+ * it. Otherwise the client creates it over the socket; when the world's game
253
+ * system declares combat sub-types ({@link declaredCombatTypes}), the
254
+ * open browsers reject that combat until each user reloads, and the answer
255
+ * says so.
168
256
  */
169
- export async function handleStartCombat(args, foundryClient) {
257
+ export async function handleStartCombat(args, foundryClient, moduleBridge = null) {
170
258
  const { tokenIds, sceneId } = args ?? {};
171
259
  const scenes = foundryClient.getScenes();
172
260
  const scene = sceneId
@@ -199,18 +287,29 @@ export async function handleStartCombat(args, foundryClient) {
199
287
  }
200
288
  }
201
289
  return withToolError('start combat', async () => {
290
+ const writeEnabled = foundryClient.isWriteEnabled();
291
+ if (writeEnabled && moduleBridge?.supports('create_combat')) {
292
+ const created = parseModuleCombat(await moduleBridge.send('create_combat', {
293
+ sceneId: scene._id,
294
+ combatants: seeds.map(({ tokenId, actorId }) => ({
295
+ tokenId,
296
+ ...(actorId ? { actorId } : {}),
297
+ })),
298
+ }));
299
+ if (created.incomplete !== undefined) {
300
+ throw new Error(`Combat ${created.combatId} was created on scene ${scene.name} (${scene._id}), but ${created.incomplete}. It was left in place; end_combat removes it.`);
301
+ }
302
+ const cached = await waitForCachedCombat(foundryClient, created.combatId, created.combatantIds.length);
303
+ return startedResult(created.combatId, scene, created.combatantIds.length, 'the companion module (the game system prepared it)', cached
304
+ ? ''
305
+ : `\n\nāš ļø The connector's cache had not caught up with this combat after ${CACHED_COMBAT_WAIT_MS / 1000} s; get_combat_state may show it a moment later.`);
306
+ }
307
+ // Writes disabled: the socket path below turns the call down as every write does.
308
+ const declared = writeEnabled ? declaredCombatTypes(foundryClient.getWorldData()) : [];
202
309
  const { combatId, combatantCount } = await foundryClient.startCombat(scene._id, seeds);
203
- return {
204
- content: [
205
- {
206
- type: 'text',
207
- text: `āš”ļø **Combat Started**
208
- **Encounter:** ${combatId}
209
- **Scene:** ${scene.name} (${scene._id})
210
- **Combatants:** ${combatantCount}`,
211
- },
212
- ],
213
- };
310
+ return startedResult(combatId, scene, combatantCount, 'the socket', declared.length > 0
311
+ ? `\n\nāš ļø This world's game system defines its own combat data (types: ${declared.join(', ')}), which only the companion module 0.7.0 or later can create. Created without it, the combat is rejected by open browsers until each user reloads FoundryVTT (F5); later updates then show live.`
312
+ : '');
214
313
  });
215
314
  }
216
315
  //# sourceMappingURL=combat-mutations.js.map
@@ -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
  };
@@ -306,7 +306,7 @@ export async function routeToolRequest(name, args, foundryClient, diagnosticsCli
306
306
  }
307
307
  return handleSetInitiative(args, foundryClient);
308
308
  case 'start_combat':
309
- return handleStartCombat(args, foundryClient);
309
+ return handleStartCombat(args, foundryClient, moduleBridge);
310
310
  // Token tools (read) — pure reads over cached worldData, no write gate.
311
311
  case 'list_tokens':
312
312
  return handleListTokens(args, foundryClient);
@@ -154,7 +154,7 @@ const TOOL_DEPENDENCIES = new Map([
154
154
  * but never refuses the call because of it; the tool then falls back to the
155
155
  * socket.
156
156
  */
157
- const PREFERS_BRIDGE_TOOLS = new Set(['apply_status_effect']);
157
+ const PREFERS_BRIDGE_TOOLS = new Set(['apply_status_effect', 'start_combat']);
158
158
  /** Every `foundry://` resource reads the cache, except the REST diagnostics. */
159
159
  const RESOURCE_DEPENDENCIES = new Map([
160
160
  ['foundry://actors', 'socket'],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@g33ks/foundryvtt-mcp",
3
- "version": "3.0.0",
3
+ "version": "3.1.0",
4
4
  "description": "Model Context Protocol server for FoundryVTT integration",
5
5
  "bin": {
6
6
  "foundryvtt-mcp": "dist/index.js"