@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
@@ -9,7 +9,80 @@
9
9
  * needs GM/owner permission.
10
10
  */
11
11
  import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
12
+ import { isRecord } from '../../utils/guards.js';
13
+ import { refusalError } from '../../utils/refusal.js';
12
14
  import { withToolError } from './utils.js';
15
+ /** How apply_status_effect wrote, as its answer says. */
16
+ const STATUS_PATH = {
17
+ module: "game system (the system's own status effects, through the companion module)",
18
+ socket: 'socket (an ActiveEffect carrying the status)',
19
+ none: 'none (no change needed)',
20
+ };
21
+ /** Bounds of apply_status_effect's `createOptions`. */
22
+ const CREATE_OPTIONS_MAX_KEYS = 10;
23
+ const CREATE_OPTIONS_MAX_BYTES = 1024;
24
+ const CREATE_OPTION_KEY = /^[A-Za-z_$][\w$]*$/;
25
+ /**
26
+ * Creation options the core sets or reads itself (DatabaseCreateOperation,
27
+ * common/abstract/_types.mjs, and Document.create); `createOptions` may not
28
+ * carry them.
29
+ */
30
+ const RESERVED_CREATE_OPTIONS = new Set([
31
+ 'action',
32
+ 'broadcast',
33
+ 'controlObject',
34
+ 'data',
35
+ 'diff',
36
+ 'documentName',
37
+ 'dryRun',
38
+ 'extractedImages',
39
+ 'keepEmbeddedIds',
40
+ 'keepId',
41
+ 'modifiedTime',
42
+ 'noHook',
43
+ 'pack',
44
+ 'parent',
45
+ 'parentUuid',
46
+ 'recursive',
47
+ 'render',
48
+ 'renderSheet',
49
+ 'temporary',
50
+ '_createData',
51
+ '_result',
52
+ ]);
53
+ /**
54
+ * Checks apply_status_effect's `createOptions`: a plain JSON object of at most
55
+ * {@link CREATE_OPTIONS_MAX_KEYS} keys and {@link CREATE_OPTIONS_MAX_BYTES}
56
+ * bytes, no option the core reserves, and only when applying a status.
57
+ */
58
+ function validateCreateOptions(value, active) {
59
+ if (value === undefined) {
60
+ return undefined;
61
+ }
62
+ const invalid = (reason) => new McpError(ErrorCode.InvalidParams, `createOptions ${reason}`);
63
+ if (!isRecord(value) || Object.getPrototypeOf(value) !== Object.prototype) {
64
+ throw invalid('must be a JSON object');
65
+ }
66
+ if (!active) {
67
+ throw invalid('only apply when applying a status (active=true)');
68
+ }
69
+ const keys = Object.keys(value);
70
+ if (keys.length > CREATE_OPTIONS_MAX_KEYS) {
71
+ throw invalid(`may hold at most ${CREATE_OPTIONS_MAX_KEYS} keys`);
72
+ }
73
+ const badKey = keys.find((key) => !CREATE_OPTION_KEY.test(key));
74
+ if (badKey !== undefined) {
75
+ throw invalid(`key ${JSON.stringify(badKey)} is not a valid option name`);
76
+ }
77
+ const reserved = keys.filter((key) => RESERVED_CREATE_OPTIONS.has(key));
78
+ if (reserved.length > 0) {
79
+ throw invalid(`may not set the core's own creation options: ${reserved.join(', ')}`);
80
+ }
81
+ if (Buffer.byteLength(JSON.stringify(value)) > CREATE_OPTIONS_MAX_BYTES) {
82
+ throw invalid(`may hold at most ${CREATE_OPTIONS_MAX_BYTES} bytes of JSON`);
83
+ }
84
+ return value;
85
+ }
13
86
  /**
14
87
  * Moves a token to x/y coordinates on its scene (FR-019).
15
88
  *
@@ -55,9 +128,11 @@ export async function handleMoveToken(args, foundryClient) {
55
128
  * the effect is matched by its `statuses` array, so re-applying an already
56
129
  * present condition (or removing an absent one) is a no-op. Linked actors
57
130
  * resolve to `Actor.<id>`; unlinked tokens target their synthetic actor at
58
- * `Scene.<sid>.Token.<tid>.Actor.<aid>`.
131
+ * `Scene.<sid>.Token.<tid>.Actor.<aid>`, whose effects are the base actor's
132
+ * merged with the token's delta: removing an inherited status is a delete
133
+ * under the token's ActorDelta, for which FoundryVTT records a tombstone.
59
134
  */
60
- export async function handleApplyStatusEffect(args, foundryClient) {
135
+ export async function handleApplyStatusEffect(args, foundryClient, moduleBridge = null) {
61
136
  const { tokenId, statusId, sceneId } = args;
62
137
  const active = args.active ?? true;
63
138
  if (!tokenId || typeof tokenId !== 'string') {
@@ -66,6 +141,7 @@ export async function handleApplyStatusEffect(args, foundryClient) {
66
141
  if (!statusId || typeof statusId !== 'string') {
67
142
  throw new McpError(ErrorCode.InvalidParams, 'statusId is required and must be a string');
68
143
  }
144
+ const createOptions = validateCreateOptions(args.createOptions, active);
69
145
  const located = foundryClient.findToken(tokenId, sceneId);
70
146
  if (!located) {
71
147
  throw new McpError(ErrorCode.InvalidRequest, `Token not found: ${tokenId}${sceneId ? ` on scene ${sceneId}` : ''}`);
@@ -82,27 +158,85 @@ export async function handleApplyStatusEffect(args, foundryClient) {
82
158
  ? `Actor.${actorId}`
83
159
  : `Scene.${located.scene._id}.Token.${tokenId}.Actor.${actorId}`;
84
160
  // Find an existing effect carrying this status (matches toggleStatusEffect).
85
- const effects = linked
86
- ? (foundryClient.getRawActor(actorId)?.effects ?? [])
87
- : (token.delta?.effects ?? []);
161
+ const effects = foundryClient.getTokenActorEffects(tokenId, located.scene._id) ?? [];
88
162
  const existing = effects.find((e) => e.statuses?.includes(statusId));
89
163
  return withToolError('apply status effect', async () => {
90
- if (active) {
91
- if (existing) {
92
- return statusResult(`Status effect '${statusId}' is already active on ${token.name ?? tokenId}.`, tokenId, located.scene, statusId, true);
93
- }
94
- const effect = await foundryClient.createActorStatusEffect(parentActorUuid, statusId);
95
- return statusResult(`Applied status effect '${statusId}' (effect ${effect._id}).`, tokenId, located.scene, statusId, true);
164
+ // The module's path when a module announcing it is connected (FoundryCore
165
+ // waited for one on its way): the module decides itself whether the call
166
+ // changes anything. While writes are disabled, the cache decides, below.
167
+ const writeEnabled = foundryClient.isWriteEnabled();
168
+ if (writeEnabled && moduleBridge?.supports('toggle_status_effect')) {
169
+ const outcome = await moduleBridge.send('toggle_status_effect', {
170
+ target: { sceneId: located.scene._id, tokenId, actorId },
171
+ statusId,
172
+ active,
173
+ ...(createOptions ? { createOptions } : {}),
174
+ });
175
+ return statusResult(moduleStatusSummary(outcome, statusId, active, token.name ?? tokenId, createOptions !== undefined), tokenId, located.scene, statusId, active, STATUS_PATH.module);
176
+ }
177
+ // createOptions only mean something to the game system's own creation.
178
+ if (createOptions) {
179
+ const reason = !writeEnabled
180
+ ? 'writes are disabled (FOUNDRY_WRITE_ENABLED)'
181
+ : !moduleBridge
182
+ ? 'the module bridge is disabled'
183
+ : moduleBridge.isConnected()
184
+ ? moduleBridge.missingCommandMessage('toggle_status_effect')
185
+ : 'the companion module is not connected';
186
+ throw refusalError(ErrorCode.InvalidRequest, `createOptions need the game system's path, through the companion module 0.6.0 or later with writes enabled, and it is not available: ${reason}. Nothing was changed.`);
187
+ }
188
+ // The no-op cases are decided from the cache.
189
+ if (active && existing) {
190
+ return statusResult(`Status effect '${statusId}' is already active on ${token.name ?? tokenId}.`, tokenId, located.scene, statusId, true, STATUS_PATH.none);
96
191
  }
97
- if (!existing) {
98
- return statusResult(`Status effect '${statusId}' is not active on ${token.name ?? tokenId}; nothing to remove.`, tokenId, located.scene, statusId, false);
192
+ if (!active && !existing) {
193
+ return statusResult(`Status effect '${statusId}' is not active on ${token.name ?? tokenId}; nothing to remove.`, tokenId, located.scene, statusId, false, STATUS_PATH.none);
99
194
  }
100
- await foundryClient.deleteActorEffect(parentActorUuid, existing._id);
101
- return statusResult(`Removed status effect '${statusId}' (effect ${existing._id}).`, tokenId, located.scene, statusId, false);
195
+ if (!active && existing) {
196
+ await foundryClient.deleteActorEffect(parentActorUuid, existing._id);
197
+ return statusResult(`Removed status effect '${statusId}' (effect ${existing._id}).`, tokenId, located.scene, statusId, false, STATUS_PATH.socket);
198
+ }
199
+ const effect = await foundryClient.createActorStatusEffect(parentActorUuid, statusId);
200
+ return statusResult(`Applied status effect '${statusId}' (effect ${effect._id}).`, tokenId, located.scene, statusId, true, STATUS_PATH.socket);
102
201
  });
103
202
  }
203
+ function isStringArray(value) {
204
+ return Array.isArray(value) && value.every((v) => typeof v === 'string');
205
+ }
206
+ /**
207
+ * What the module's toggle_status_effect did, as one or two lines: applied or
208
+ * already there (with the earlier-version effects that also carry the
209
+ * status), removed (with their ids), or nothing to remove.
210
+ */
211
+ function moduleStatusSummary(outcome, statusId, active, name, withCreateOptions) {
212
+ const unexpected = () => new McpError(ErrorCode.InternalError, 'Module returned an unexpected toggle_status_effect shape');
213
+ if (!isRecord(outcome) || outcome.active !== active || typeof outcome.changed !== 'boolean') {
214
+ throw unexpected();
215
+ }
216
+ if (!active) {
217
+ if (!isStringArray(outcome.removed)) {
218
+ throw unexpected();
219
+ }
220
+ return outcome.removed.length > 0
221
+ ? `Removed status effect '${statusId}' (effect${outcome.removed.length > 1 ? 's' : ''} ${outcome.removed.join(', ')}).`
222
+ : `Status effect '${statusId}' is not active on ${name}; nothing to remove.`;
223
+ }
224
+ const { effectId, legacy } = outcome;
225
+ if ((effectId !== null && typeof effectId !== 'string') || !isStringArray(legacy)) {
226
+ throw unexpected();
227
+ }
228
+ const summary = outcome.changed
229
+ ? `Applied status effect '${statusId}' (effect ${effectId}).`
230
+ : effectId
231
+ ? `Status effect '${statusId}' is already active on ${name} (effect ${effectId}).` +
232
+ (withCreateOptions ? ' createOptions were ignored: nothing was created.' : '')
233
+ : `The game system did not create status effect '${statusId}' on ${name}.`;
234
+ return legacy.length > 0
235
+ ? `${summary}\nEffect(s) ${legacy.join(', ')} from an earlier version also carry this status; active=false removes them.`
236
+ : summary;
237
+ }
104
238
  /** Builds the MCP text result for a status-effect mutation. */
105
- function statusResult(summary, tokenId, scene, statusId, active) {
239
+ function statusResult(summary, tokenId, scene, statusId, active, path) {
106
240
  return {
107
241
  content: [
108
242
  {
@@ -111,6 +245,7 @@ function statusResult(summary, tokenId, scene, statusId, active) {
111
245
  **Token:** ${tokenId}
112
246
  **Scene:** ${scene.name} (${scene._id})
113
247
  **Status:** ${statusId}
248
+ **Path:** ${path}
114
249
  ${summary}`,
115
250
  },
116
251
  ],
@@ -36,9 +36,10 @@ export async function withToolError(toolName, fn) {
36
36
  if (error instanceof McpError) {
37
37
  throw error;
38
38
  }
39
- // Expected refusals are logged once, as a warning, by FoundryCore.
39
+ // Expected refusals are logged once, as a warning, by FoundryCore. Their
40
+ // message already says what was refused and why: no "Failed to …" prefix.
40
41
  if (error instanceof RefusedError) {
41
- throw refusalError(ErrorCode.InvalidRequest, `Failed to ${toolName}: ${error.message}`);
42
+ throw refusalError(ErrorCode.InvalidRequest, error.message);
42
43
  }
43
44
  logger.error(`Failed to ${toolName}:`, error);
44
45
  throw new McpError(ErrorCode.InternalError, `Failed to ${toolName}: ${error instanceof Error ? error.message : 'Unknown error'}`);
@@ -20,7 +20,7 @@ import { handleCreateActorItem, handleDeleteActorItem, handleUpdateActorItem, }
20
20
  import { handleSearchItems } from './handlers/items.js';
21
21
  import { handleAddJournalPage, handleCreateJournalEntry, handleDeleteJournalEntry, handleUpdateJournalEntry, handleUpdateJournalPage, } from './handlers/journal-mutations.js';
22
22
  import { handleGetJournal, handleSearchJournals } from './handlers/journals.js';
23
- import { handleCaptureScene, handleGetDocumentSchema, handleGetTargets, handleImportCompendiumActor, handlePingCanvas, handleRollAndPost, handleSearchCompendiumContent, handleSetPause, handleSetTarget, handleUploadAsset, } from './handlers/module-bridge.js';
23
+ import { handleCaptureScene, handleGetActorStats, handleGetDocumentSchema, handleGetTargets, handleImportCompendiumActor, handlePingCanvas, handleRollAndPost, handleSearchCompendiumContent, handleSetPause, handleSetTarget, handleUploadAsset, } from './handlers/module-bridge.js';
24
24
  import { handleCreateDrawing, handleCreateLight, handleCreateNote, handleCreateRegion, handleCreateSound, handleCreateTemplate, handleDeleteDrawing, handleDeleteLight, handleDeleteNote, handleDeleteRegion, handleDeleteSound, handleDeleteTemplate, handleUpdateLight, } from './handlers/placeable-mutations.js';
25
25
  import { handleReadResource } from './handlers/resources.js';
26
26
  import { handleCreateRollTable, handleDeleteRollTable, handleListRollTables, handleRollTable, } from './handlers/roll-tables.js';
@@ -66,22 +66,14 @@ export async function routeToolRequest(name, args, foundryClient, diagnosticsCli
66
66
  // Actor tools
67
67
  case 'search_actors':
68
68
  return handleSearchActors(args, foundryClient);
69
+ // actorId, or sceneId + tokenId: the handlers check which (actor-target.ts)
69
70
  case 'get_actor_details':
70
- if (!('actorId' in args) || typeof args.actorId !== 'string') {
71
- throw new Error('Missing required parameter: actorId');
72
- }
73
71
  return handleGetActorDetails(args, foundryClient);
74
72
  case 'get_actor_inventory':
75
- if (!('actorId' in args) || typeof args.actorId !== 'string') {
76
- throw new Error('Missing required parameter: actorId');
77
- }
78
73
  return handleGetActorInventory(args, foundryClient);
79
74
  // Actor mutation tools (laurigates/foundryvtt-mcp#143) — WRITE via the Socket.IO modifyDocument
80
75
  // protocol (foundryClient); require FOUNDRY_WRITE_ENABLED=true + a GM user.
81
76
  case 'update_actor_attributes':
82
- if (!('actorId' in args) || typeof args.actorId !== 'string') {
83
- throw new Error('Missing required parameter: actorId');
84
- }
85
77
  if (!('patch' in args) || typeof args.patch !== 'object' || args.patch === null) {
86
78
  throw new Error('Missing required parameter: patch');
87
79
  }
@@ -118,18 +110,13 @@ export async function routeToolRequest(name, args, foundryClient, diagnosticsCli
118
110
  return handleSearchCompendium(args, foundryClient);
119
111
  // Item mutation tools (WRITE) — Socket.IO modifyDocument protocol
120
112
  // (foundryClient); require FOUNDRY_WRITE_ENABLED=true + a GM user.
113
+ // actorId, or sceneId + tokenId: the handlers check which (actor-target.ts)
121
114
  case 'create_actor_item':
122
- if (!('actorId' in args) || typeof args.actorId !== 'string') {
123
- throw new Error('Missing required parameter: actorId');
124
- }
125
115
  if (!('source' in args) || typeof args.source !== 'object' || args.source === null) {
126
116
  throw new Error('Missing required parameter: source');
127
117
  }
128
118
  return handleCreateActorItem(args, foundryClient, moduleBridge);
129
119
  case 'update_actor_item':
130
- if (!('actorId' in args) || typeof args.actorId !== 'string') {
131
- throw new Error('Missing required parameter: actorId');
132
- }
133
120
  if (!('itemId' in args) || typeof args.itemId !== 'string') {
134
121
  throw new Error('Missing required parameter: itemId');
135
122
  }
@@ -138,9 +125,6 @@ export async function routeToolRequest(name, args, foundryClient, diagnosticsCli
138
125
  }
139
126
  return handleUpdateActorItem(args, foundryClient);
140
127
  case 'delete_actor_item':
141
- if (!('actorId' in args) || typeof args.actorId !== 'string') {
142
- throw new Error('Missing required parameter: actorId');
143
- }
144
128
  if (!('itemId' in args) || typeof args.itemId !== 'string') {
145
129
  throw new Error('Missing required parameter: itemId');
146
130
  }
@@ -345,7 +329,7 @@ export async function routeToolRequest(name, args, foundryClient, diagnosticsCli
345
329
  if (!('statusId' in args) || typeof args.statusId !== 'string') {
346
330
  throw new Error('Missing required parameter: statusId');
347
331
  }
348
- return handleApplyStatusEffect(args, foundryClient);
332
+ return handleApplyStatusEffect(args, foundryClient, moduleBridge);
349
333
  case 'spawn_token':
350
334
  if (!('actorId' in args) || typeof args.actorId !== 'string') {
351
335
  throw new Error('Missing required parameter: actorId');
@@ -491,6 +475,8 @@ export async function routeToolRequest(name, args, foundryClient, diagnosticsCli
491
475
  throw new Error('Missing required parameter: tokenIds');
492
476
  }
493
477
  return handleSetTarget(args, moduleBridge);
478
+ case 'get_actor_stats':
479
+ return handleGetActorStats(args, foundryClient, moduleBridge);
494
480
  case 'get_targets':
495
481
  return handleGetTargets(args, moduleBridge);
496
482
  case 'ping_canvas':
@@ -670,9 +656,6 @@ export async function routeToolRequest(name, args, foundryClient, diagnosticsCli
670
656
  }
671
657
  return handleDeleteActorEffect(args, foundryClient);
672
658
  case 'list_actor_effects':
673
- if (!('actorId' in args) || typeof args.actorId !== 'string') {
674
- throw new Error('Missing required parameter: actorId');
675
- }
676
659
  return handleListActorEffects(args, foundryClient);
677
660
  default:
678
661
  throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
@@ -0,0 +1,207 @@
1
+ /**
2
+ * @fileoverview What each tool and resource needs from FoundryVTT.
3
+ *
4
+ * Decides which calls wait for a connection being restored (see
5
+ * {@link FoundryCore}): only those that read the Socket.IO cache or go
6
+ * through the socket wait for it — a cache nobody keeps live must not answer
7
+ * during an outage. The others never touch the socket and must not wait for it.
8
+ *
9
+ * - `socket`: the cached world or a Socket.IO request (every document write).
10
+ * - `socket+bridge`: the socket and the companion module (see {@link needsBridge}).
11
+ * - `bridge`: the companion module only.
12
+ * - `rest`: the REST API module (`FOUNDRY_API_KEY`) only.
13
+ * - `rest-or-local`: the REST API module when a key is set, a local computation otherwise.
14
+ * - `local`: no FoundryVTT at all (a computation, or files under `FOUNDRY_DATA_PATH`).
15
+ * - `health`: reports the connections themselves, so waits for none.
16
+ *
17
+ * A unit test checks that every tool and resource is classified.
18
+ */
19
+ import { isRecord } from '../utils/guards.js';
20
+ const SOCKET_TOOLS = [
21
+ // Reads from the cached world (search_actors, get_actor_details,
22
+ // search_items, get_scene_info and get_world_summary ask the REST API
23
+ // module first when a key is set, then fall back to the cache).
24
+ 'search_actors',
25
+ 'get_actor_details',
26
+ 'get_actor_inventory',
27
+ 'search_items',
28
+ 'get_scene_info',
29
+ 'list_tiles',
30
+ 'list_walls',
31
+ 'list_tokens',
32
+ 'list_lights',
33
+ 'list_sounds',
34
+ 'list_notes',
35
+ 'list_drawings',
36
+ 'list_templates',
37
+ 'list_regions',
38
+ 'find_open_cells',
39
+ 'list_actor_effects',
40
+ 'get_combat_state',
41
+ 'get_chat_messages',
42
+ 'get_users',
43
+ 'search_journals',
44
+ 'search_world',
45
+ 'get_world_summary',
46
+ 'list_roll_tables',
47
+ 'roll_table',
48
+ 'list_folders',
49
+ 'list_macros',
50
+ 'list_playlists',
51
+ 'get_world_setting',
52
+ // The event log is fed by socket broadcasts: during an outage it would
53
+ // answer "nothing new", which is not true.
54
+ 'watch_events',
55
+ // The cache, plus compendium packs through the module when it is there.
56
+ 'lookup_rule',
57
+ // Requests to the server over the socket.
58
+ 'get_journal',
59
+ 'refresh_world_data',
60
+ // Writes (Socket.IO modifyDocument).
61
+ 'update_actor_attributes',
62
+ 'create_world_actor',
63
+ 'create_full_actor',
64
+ 'delete_world_actor',
65
+ 'update_actor_item',
66
+ 'delete_actor_item',
67
+ 'create_scene',
68
+ 'switch_scene',
69
+ 'delete_scene',
70
+ 'set_scene_lighting',
71
+ 'reset_fog',
72
+ 'set_scene_weather',
73
+ 'create_wall',
74
+ 'delete_wall',
75
+ 'set_door_state',
76
+ 'create_tile',
77
+ 'delete_tile',
78
+ 'create_light',
79
+ 'update_light',
80
+ 'delete_light',
81
+ 'create_sound',
82
+ 'delete_sound',
83
+ 'create_note',
84
+ 'delete_note',
85
+ 'create_drawing',
86
+ 'delete_drawing',
87
+ 'create_template',
88
+ 'delete_template',
89
+ 'create_region',
90
+ 'delete_region',
91
+ 'next_turn',
92
+ 'end_combat',
93
+ 'set_initiative',
94
+ 'start_combat',
95
+ 'move_token',
96
+ 'apply_status_effect',
97
+ 'spawn_token',
98
+ 'delete_token',
99
+ 'move_token_pathfind',
100
+ 'move_tokens',
101
+ 'update_token_vision',
102
+ 'send_chat_message',
103
+ 'create_journal_entry',
104
+ 'update_journal_page',
105
+ 'add_journal_page',
106
+ 'update_journal_entry',
107
+ 'delete_journal_entry',
108
+ 'create_folder',
109
+ 'create_macro',
110
+ 'delete_macro',
111
+ 'create_playlist',
112
+ 'set_playlist_state',
113
+ 'delete_playlist',
114
+ 'set_document_ownership',
115
+ 'create_actor_effect',
116
+ 'update_actor_effect',
117
+ 'delete_actor_effect',
118
+ 'create_roll_table',
119
+ 'delete_roll_table',
120
+ 'set_world_setting',
121
+ 'set_user_role',
122
+ ];
123
+ const TOOL_DEPENDENCIES = new Map([
124
+ ...SOCKET_TOOLS.map((name) => [name, 'socket']),
125
+ // Reads a compendium document through the module, then writes over the socket.
126
+ ['import_compendium_actor', 'socket+bridge'],
127
+ // The module only for a compendium source; see needsBridge.
128
+ ['create_actor_item', 'socket+bridge'],
129
+ // Checks its target against the cache, then reads it through the module.
130
+ ['get_actor_stats', 'socket+bridge'],
131
+ ['capture_scene', 'bridge'],
132
+ ['get_document_schema', 'bridge'],
133
+ ['search_compendium_content', 'bridge'],
134
+ ['get_targets', 'bridge'],
135
+ ['roll_and_post', 'bridge'],
136
+ ['set_target', 'bridge'],
137
+ ['ping_canvas', 'bridge'],
138
+ ['set_pause', 'bridge'],
139
+ ['upload_asset', 'bridge'],
140
+ ['search_compendium', 'rest'],
141
+ ['get_recent_logs', 'rest'],
142
+ ['search_logs', 'rest'],
143
+ ['get_system_health', 'rest'],
144
+ ['diagnose_errors', 'rest'],
145
+ ['roll_dice', 'rest-or-local'],
146
+ ['generate_npc', 'local'],
147
+ ['generate_loot', 'local'],
148
+ ['list_scene_assets', 'local'],
149
+ ['get_health_status', 'health'],
150
+ ]);
151
+ /**
152
+ * Socket tools that go through the companion module when it is there:
153
+ * FoundryCore waits for a module on its way as it does for a module tool,
154
+ * but never refuses the call because of it; the tool then falls back to the
155
+ * socket.
156
+ */
157
+ const PREFERS_BRIDGE_TOOLS = new Set(['apply_status_effect']);
158
+ /** Every `foundry://` resource reads the cache, except the REST diagnostics. */
159
+ const RESOURCE_DEPENDENCIES = new Map([
160
+ ['foundry://actors', 'socket'],
161
+ ['foundry://items', 'socket'],
162
+ ['foundry://scenes', 'socket'],
163
+ ['foundry://scenes/current', 'socket'],
164
+ ['foundry://journals', 'socket'],
165
+ ['foundry://users', 'socket'],
166
+ ['foundry://combat', 'socket'],
167
+ ['foundry://world/settings', 'socket'],
168
+ ['foundry://system/diagnostics', 'rest'],
169
+ ]);
170
+ /** The tool's dependency; `undefined` for a name nobody classified. */
171
+ export function toolDependency(name) {
172
+ return TOOL_DEPENDENCIES.get(name);
173
+ }
174
+ /** The resource's dependency; `undefined` for a URI nobody classified. */
175
+ export function resourceDependency(uri) {
176
+ return RESOURCE_DEPENDENCIES.get(uri);
177
+ }
178
+ /**
179
+ * True when the dependency involves the socket. An unclassified name counts
180
+ * as one: waiting is the safe default for something that may read the cache.
181
+ */
182
+ export function waitsForSocket(dependency) {
183
+ return dependency === undefined || dependency === 'socket' || dependency === 'socket+bridge';
184
+ }
185
+ /** True when the tool uses the companion module if it can (see {@link PREFERS_BRIDGE_TOOLS}). */
186
+ export function prefersBridge(name) {
187
+ return PREFERS_BRIDGE_TOOLS.has(name);
188
+ }
189
+ /**
190
+ * True when this call goes through the companion module: every `bridge`
191
+ * tool, `import_compendium_actor`, `get_actor_stats`, and `create_actor_item` from a
192
+ * compendium source (an inline item needs only the socket).
193
+ */
194
+ export function needsBridge(name, args) {
195
+ const dependency = toolDependency(name);
196
+ if (dependency === 'bridge') {
197
+ return true;
198
+ }
199
+ if (dependency !== 'socket+bridge') {
200
+ return false;
201
+ }
202
+ if (name === 'create_actor_item') {
203
+ return isRecord(args.source) && args.source.type === 'compendium';
204
+ }
205
+ return true;
206
+ }
207
+ //# sourceMappingURL=tool-dependencies.js.map
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @fileoverview MCP errors on their way to a client.
3
+ *
4
+ * `McpError` puts "MCP error <code>: " in front of its message, and the
5
+ * SDK's `Protocol` sends `error.message` as it is in the JSON-RPC error; the
6
+ * client's SDK then builds its own `McpError`, which adds the prefix a second
7
+ * time (G33ks/foundryvtt-mcp#15). The message
8
+ * on the wire must therefore be the bare text.
9
+ */
10
+ import { McpError } from '@modelcontextprotocol/sdk/types.js';
11
+ /** McpError prefixes its message with "MCP error <code>: "; this is the text without it. */
12
+ export function bareMessage(error) {
13
+ return error.message.replace(/^MCP error -?\d+: /, '');
14
+ }
15
+ /**
16
+ * An error as the SDK sends it: `Protocol` reads `code` (a safe integer),
17
+ * `message` and `data` from whatever a handler throws (SDK 1.32.2,
18
+ * dist/esm/shared/protocol.js:426-428), so a plain `Error` with those
19
+ * fields reaches the client unchanged.
20
+ */
21
+ export class WireError extends Error {
22
+ code;
23
+ data;
24
+ name = 'WireError';
25
+ constructor(code, message, data) {
26
+ super(message);
27
+ this.code = code;
28
+ this.data = data;
29
+ }
30
+ }
31
+ /**
32
+ * Runs a request handler; an `McpError` it throws leaves with its bare
33
+ * message, its code and its data, so the client shows one prefix. Any other
34
+ * error is left to the SDK.
35
+ */
36
+ export async function withBareErrors(handler) {
37
+ try {
38
+ return await handler();
39
+ }
40
+ catch (error) {
41
+ if (error instanceof McpError) {
42
+ throw new WireError(error.code, bareMessage(error), error.data);
43
+ }
44
+ throw error;
45
+ }
46
+ }
47
+ //# sourceMappingURL=mcp-errors.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@g33ks/foundryvtt-mcp",
3
- "version": "2.0.0",
3
+ "version": "2.2.0",
4
4
  "description": "Model Context Protocol server for FoundryVTT integration",
5
5
  "bin": {
6
6
  "foundryvtt-mcp": "dist/index.js"
@@ -76,7 +76,7 @@
76
76
  "@modelcontextprotocol/sdk": "^1.32.2",
77
77
  "ajv": "^8.20.0",
78
78
  "axios": "^1.21.0",
79
- "dotenv": "^17.4.2",
79
+ "dotenv": "^18.0.9",
80
80
  "playwright-core": "^1.63.0",
81
81
  "socket.io-client": "^4.8.3",
82
82
  "ws": "^8.21.0",
@@ -85,14 +85,14 @@
85
85
  "devDependencies": {
86
86
  "@biomejs/biome": "^2.5.0",
87
87
  "@playwright/test": "^1.61.0",
88
- "@types/node": "^25.9.4",
88
+ "@types/node": "^22.20.5",
89
89
  "@types/ws": "^8.18.1",
90
90
  "husky": "^9.1.7",
91
91
  "lint-staged": "^17.0.7",
92
92
  "rimraf": "^6.1.4",
93
93
  "tsx": "^4.22.4",
94
94
  "typescript": "^6.0.3",
95
- "vitest": "^4.1.12"
95
+ "vitest": "^5.1.0"
96
96
  },
97
97
  "engines": {
98
98
  "node": ">=22"
@@ -112,7 +112,7 @@
112
112
  "picomatch": "^4.0.4",
113
113
  "brace-expansion": "^5.0.12",
114
114
  "form-data": "^4.0.6",
115
- "ws": "^8.21.0",
115
+ "ws": "$ws",
116
116
  "qs": "^6.17.1"
117
117
  },
118
118
  "lint-staged": {