@g33ks/foundryvtt-mcp 3.0.1 → 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
@@ -93,7 +93,7 @@ When something fails, the message says why; [TROUBLESHOOTING.md](https://github.
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
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.
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.
97
97
 
98
98
  ## Documentation
99
99
 
@@ -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',
@@ -5,9 +5,12 @@
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
16
  import { deletionNote, withToolError } from './utils.js';
@@ -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
@@ -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.1",
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"