@g33ks/foundryvtt-mcp 2.2.0 → 3.0.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.
@@ -13,6 +13,13 @@
13
13
  * session. Foundry itself enforces the GM/owner permission (ADR-010).
14
14
  */
15
15
  const WRITE_GATE = 'WRITE: mutates the live world. Requires FOUNDRY_WRITE_ENABLED=true (default false) and an active Socket.IO connection, and is refused otherwise; Foundry additionally enforces GM/owner permission on the document.';
16
+ /**
17
+ * Write-safety clause for the tools the companion module carries out. They
18
+ * never use the Socket.IO connection, so it is not a condition; the module
19
+ * runs in a GM client. Enforced by `assertWritesEnabled()`
20
+ * (`src/tools/handlers/module-bridge.ts`).
21
+ */
22
+ const MODULE_WRITE_GATE = 'WRITE: changes the live world. Requires FOUNDRY_WRITE_ENABLED=true (default false) and the companion module, and is refused otherwise; FoundryVTT additionally enforces the GM permission.';
16
23
  /**
17
24
  * Extra clause for destructive tools (data removal that this server cannot undo).
18
25
  */
@@ -25,7 +32,7 @@ const CONFIRM_FIRST = 'DESTRUCTIVE and not undoable from this server: confirm th
25
32
  * registry class is what *executes* the tool while `getAllTools()` is what is
26
33
  * *listed*, so a divergence would be invisible.
27
34
  */
28
- export const ROLL_DICE_DESCRIPTION = 'Roll dice and return the total with a per-term breakdown. Dice terms and whole numbers joined by + or -, with whitespace allowed anywhere ("1d20+5", "1d20 + 5", "1d20+5+3", "2d6 + 1d4", "3d6"; a count-less "d20" means one die), always work and every term counts towards the total - that is the portable grammar, safe on either transport. Multiplication and Foundry modifier syntax such as "4d6kh3" or "1d20r1" are rejected on both transports, with an error naming the offending character and its position, never dropped from the total in silence. Parentheses are the one difference: with FOUNDRY_API_KEY set the formula goes to FoundryVTT\'s own Roll engine, which evaluates them, while the default Socket.IO transport rolls locally and rejects them by name - and a REST roll that cannot reach the server falls back to that same local roller, so a parenthesised formula can still fail there. Prefer the expanded form when it matters. Use when: the user asks for a check, save, attack, damage, or any random result.';
35
+ export const ROLL_DICE_DESCRIPTION = 'Roll dice and return the total with a per-term breakdown. Dice terms and whole numbers joined by + or -, with whitespace allowed anywhere ("1d20+5", "1d20 + 5", "1d20+5+3", "2d6 + 1d4", "3d6"; a count-less "d20" means one die), always work and every term counts towards the total - that is the portable grammar, safe on either transport. Multiplication and Foundry modifier syntax such as "4d6kh3" or "1d20r1" are rejected on both transports, with an error naming the offending character and its position, never dropped from the total in silence. Parentheses are the one difference: with FOUNDRY_API_KEY set the formula goes to FoundryVTT\'s own Roll engine, which evaluates them, while the default Socket.IO transport rolls locally and rejects them by name - and a REST roll that cannot reach the server falls back to that same local roller, so a parenthesised formula can still fail there. Prefer the expanded form when it matters. Use when: the user asks for a check, an attack, damage, or any random result.';
29
36
  /**
30
37
  * Dice rolling tool definitions
31
38
  */
@@ -55,7 +62,7 @@ export const diceTools = [
55
62
  export const actorTools = [
56
63
  {
57
64
  name: 'search_actors',
58
- description: "Search actors (player characters, NPCs) by name, optionally filtered by type. Returns a summary line per match: name, type, level and current/max HP. Use when: checking whether an actor exists, or getting a quick roster with HP. Do not use when: you already have the actorId and want that actor's ability scores - use get_actor_details; or you need the actorId itself, which this tool does not print - read the foundry://actors resource, whose JSON lists up to the first 100 actors with their _id (not exhaustive in larger worlds).",
65
+ description: "Search actors (player characters, NPCs) by name, optionally filtered by type. Returns a summary line per match: name, type, and the level and current/max hit points when the actor stores them at details.level and attributes.hp. Use when: checking whether an actor exists, or getting a quick roster. Do not use when: you already have the actorId and want more of that actor's values - use get_actor_details; or you need the actorId itself, which this tool does not print - read the foundry://actors resource, whose JSON lists up to the first 100 actors with their _id (not exhaustive in larger worlds).",
59
66
  inputSchema: {
60
67
  type: 'object',
61
68
  properties: {
@@ -81,7 +88,7 @@ export const actorTools = [
81
88
  },
82
89
  {
83
90
  name: 'get_actor_details',
84
- description: 'Get details for one actor by id: type, level, current/max HP, AC and ability scores; no biography or description text is returned (the description line always reads "No description available."). Use when: you have an actorId and need its current HP or ability scores - notably as the read-before-write step for update_actor_attributes. For one token on a map, give sceneId + tokenId instead of actorId: an unlinked token (a copy of a monster with its own HP) reports its own values, a linked token the values of its world actor. Do not use when: you only have a name - run search_actors first; or you need the ids of items the actor owns, which this tool does not return - get_actor_inventory lists them.',
91
+ description: 'Get details for one actor by id: type, and the level, current/max hit points, armour class and ability values the actor stores at details.level, attributes.hp, attributes.ac and abilities (a game system that stores them elsewhere shows fewer fields; get_actor_stats returns all of its data); no biography or description text is returned (the description line always reads "No description available."). Use when: you have an actorId and need its current values - notably as the read-before-write step for update_actor_attributes. For one token on a map, give sceneId + tokenId instead of actorId: an unlinked token (a copy of a creature with its own values) reports its own values, a linked token the values of its world actor. Do not use when: you only have a name - run search_actors first; or you need the ids of items the actor owns, which this tool does not return - get_actor_inventory lists them.',
85
92
  inputSchema: {
86
93
  type: 'object',
87
94
  properties: {
@@ -103,7 +110,7 @@ export const actorTools = [
103
110
  },
104
111
  {
105
112
  name: 'get_actor_inventory',
106
- description: "List an actor's owned items (equipment, spells, features) with full system data per item, unlike get_actor_details which only reports the actor's own top-level stats. Use when: checking what a character or NPC carries or knows before an attack, spell, or trade. For one token on a map, give sceneId + tokenId instead of actorId: an unlinked token lists its own items (those it inherits from its base actor and its own, without the ones removed from it), a linked token its world actor's. Do not use when: you only need the actor's HP/AC/abilities - use get_actor_details.",
113
+ description: "List an actor's owned items (equipment, features, abilities…) with full system data per item, unlike get_actor_details which only reports the actor's own top-level stats. Use when: checking what a character or NPC carries or knows before an action or a trade. For one token on a map, give sceneId + tokenId instead of actorId: an unlinked token lists its own items (those it inherits from its base actor and its own, without the ones removed from it), a linked token its world actor's. Do not use when: you only need the actor's own values - use get_actor_details.",
107
114
  inputSchema: {
108
115
  type: 'object',
109
116
  properties: {
@@ -133,7 +140,7 @@ export const actorTools = [
133
140
  export const actorMutationTools = [
134
141
  {
135
142
  name: 'update_actor_attributes',
136
- description: 'Update fields on an actor\'s system data. Patch keys are dot-paths into actor.system (e.g. "attributes.hp.value", "attributes.hp.temp", "currency.gp", "resources.primary.value", "spells.spell1.value", "attributes.exhaustion") and values are absolute target values, never relative deltas. Validates HP <= max + temp, spell slots <= max, and exhaustion within 0-10 (2024) or 0-6 (2014), and returns the post-update value for every patched path. Use when: applying damage or healing, spending a spell slot or resource, or adjusting currency on a known actorId. For one token on a map - an unlinked copy of a monster, which has its own HP - give sceneId + tokenId instead of actorId: only that token changes, not the base actor or its other copies. Write only stored fields: a field the game system computes from others is accepted and saved by the server, but has no effect in play. Do not use when: changing an item the actor owns (use update_actor_item) or only reading current values (use get_actor_details). ' +
143
+ description: 'Update fields on an actor\'s system data. Patch keys are dot-paths into actor.system (e.g. "attributes.health.value", "resources.primary.value", "details.notes") and values are absolute target values, never relative deltas. If the actor stores a value at one of these paths, it is range-checked: attributes.hp.value against max + temp, spells.<key>.value against the max of that entry, and attributes.exhaustion against 0-10 (0-6 when the data of the actor marks older rules). Returns the post-update value for every patched path. Use when: applying damage or healing, spending a resource, or adjusting a stored value on a known actorId. For one token on a map - an unlinked copy of a creature, which has its own values - give sceneId + tokenId instead of actorId: only that token changes, not the base actor or its other copies. Write only stored fields: a field the game system computes from others is accepted and saved by the server, but has no effect in play. Do not use when: changing an item the actor owns (use update_actor_item) or only reading current values (use get_actor_details). ' +
137
144
  WRITE_GATE,
138
145
  inputSchema: {
139
146
  type: 'object',
@@ -153,7 +160,7 @@ export const actorMutationTools = [
153
160
  patch: {
154
161
  type: 'object',
155
162
  description: 'Map of dot-path → value, where each dot-path addresses a field under actor.system ' +
156
- '(e.g. {"attributes.hp.value": 30, "currency.gp": 12}). Values must be number, string, or boolean.',
163
+ '(e.g. {"attributes.health.value": 30, "resources.primary.value": 2}). Values must be number, string, or boolean.',
157
164
  additionalProperties: {
158
165
  type: ['number', 'string', 'boolean'],
159
166
  },
@@ -195,7 +202,7 @@ export const actorMutationTools = [
195
202
  },
196
203
  {
197
204
  name: 'create_full_actor',
198
- description: "Create a new top-level Actor document AND seed it with starting items (skills, gear, weapons, cyberware, …) in one call, instead of create_world_actor followed by one create_actor_item per item. Pairs with get_document_schema: call that once per Actor/Item type to learn the real field names for `system`, then build the whole character here in a single call. The actor is always created first - a failure there aborts the whole call. Item creation is best-effort per item, not atomic: a bad item (e.g. a typo'd type) is reported in the response's item-failures list rather than losing the actor or the items that did succeed. Use when: standing up a fully-statted PC or NPC (correct ability scores/attributes plus starting equipment/skills) in one round trip. Do not use when: the actor already exists - use create_actor_item to add items to it; or a bare/generic actor is enough - use create_world_actor. " +
205
+ description: "Create a new top-level Actor document AND seed it with starting items (gear, weapons, features, …) in one call, instead of create_world_actor followed by one create_actor_item per item. Pairs with get_document_schema: call that once per Actor/Item type to learn the real field names for `system`, then build the whole character here in a single call. The actor is always created first - a failure there aborts the whole call. Item creation is best-effort per item, not atomic: a bad item (e.g. a typo'd type) is reported in the response's item-failures list rather than losing the actor or the items that did succeed. Use when: standing up a fully-statted PC or NPC (correct attributes plus starting equipment and features) in one round trip. Do not use when: the actor already exists - use create_actor_item to add items to it; or a bare/generic actor is enough - use create_world_actor. " +
199
206
  WRITE_GATE,
200
207
  inputSchema: {
201
208
  type: 'object',
@@ -218,7 +225,7 @@ export const actorMutationTools = [
218
225
  },
219
226
  items: {
220
227
  type: 'array',
221
- description: 'Optional starting items (skills, weapons, gear, cyberware, …) to create on the actor immediately after it exists',
228
+ description: 'Optional starting items (weapons, gear, features, …) to create on the actor immediately after it exists',
222
229
  items: {
223
230
  type: 'object',
224
231
  properties: {
@@ -228,7 +235,7 @@ export const actorMutationTools = [
228
235
  },
229
236
  type: {
230
237
  type: 'string',
231
- description: 'Game-system item type (e.g. "weapon", "skill") - use get_document_schema("Item", type) to learn the real field names first',
238
+ description: 'Game-system item type (e.g. "weapon", "feature") - use get_document_schema("Item", type) to learn the real field names first',
232
239
  },
233
240
  system: {
234
241
  type: 'object',
@@ -301,7 +308,7 @@ export const itemTools = [
301
308
  export const compendiumTools = [
302
309
  {
303
310
  name: 'search_compendium',
304
- description: 'Search FoundryVTT compendium packs by name and metadata; searches all enabled packs unless compendiumId scopes it to one pack. Use when: looking up spells, monsters, or equipment that are not yet present in the world. Do not use when: the document already exists in the world - use search_items or search_world. Requires the REST API module (FOUNDRY_API_KEY); without it the search returns no results instead of failing.',
311
+ description: 'Search FoundryVTT compendium packs by name and metadata; searches all enabled packs unless compendiumId scopes it to one pack. Use when: looking up creatures, items or rules that are not yet present in the world. Do not use when: the document already exists in the world - use search_items or search_world. Requires the REST API module (FOUNDRY_API_KEY); without it the search returns no results instead of failing.',
305
312
  inputSchema: {
306
313
  type: 'object',
307
314
  properties: {
@@ -323,7 +330,7 @@ export const compendiumTools = [
323
330
  },
324
331
  itemType: {
325
332
  type: 'string',
326
- description: 'Item type filter (spell, weapon, feat, etc.)',
333
+ description: 'Item type filter (e.g. weapon, equipment, feature)',
327
334
  },
328
335
  spellLevel: {
329
336
  type: 'number',
@@ -359,7 +366,7 @@ export const compendiumTools = [
359
366
  export const itemMutationTools = [
360
367
  {
361
368
  name: 'create_actor_item',
362
- description: 'Create an item on an actor from an inline item document (type, name, system) or by referencing a compendium pack entry (compendium sources require the companion Foundry module). Use when: adding a new weapon, spell, feature, or piece of equipment to a known actorId. For one token on a map, give sceneId + tokenId (an actorId given as well must be the actor of the token): an unlinked token gets the item on that token only, a linked token on its world actor. Do not use when: editing an item the actor already owns - use update_actor_item. Replacing an item is not atomic: create the replacement first and delete the old one second. Canonical target: D&D 5e v4+ activity schema. ' +
369
+ description: 'Create an item on an actor from an inline item document (type, name, system) or by referencing a compendium pack entry (compendium sources require the companion Foundry module). Use when: adding a new weapon, feature, or piece of equipment to a known actorId. For one token on a map, give sceneId + tokenId (an actorId given as well must be the actor of the token): an unlinked token gets the item on that token only, a linked token on its world actor. Do not use when: editing an item the actor already owns - use update_actor_item. Replacing an item is not atomic: create the replacement first and delete the old one second. Canonical target: D&D 5e v4+ activity schema. ' +
363
370
  WRITE_GATE,
364
371
  inputSchema: {
365
372
  type: 'object',
@@ -503,7 +510,7 @@ export const sceneMutationTools = [
503
510
  },
504
511
  backgroundSrc: {
505
512
  type: 'string',
506
- description: 'Data-relative path to the background image (e.g. "assets/cyberpunk/maps/v1/x.jpg"), as returned by list_scene_assets',
513
+ description: 'Data-relative path to the background image (e.g. "assets/maps/v1/x.jpg"), as returned by list_scene_assets',
507
514
  },
508
515
  width: {
509
516
  type: 'number',
@@ -579,7 +586,7 @@ export const sceneMutationTools = [
579
586
  },
580
587
  {
581
588
  name: 'set_scene_lighting',
582
- description: "Set a scene's ambient darkness level (0-1) and/or global illumination fields (globalLight, globalLightThreshold). Plain Scene document fields - no canvas access required. Use when: transitioning to night, dimming a room, or lighting a torch-lit area. Do not use when: you only need to read current lighting - use get_scene_info. " +
589
+ description: "Set a scene's ambient darkness level (0-1) and/or global illumination (globalLight, globalLightThreshold). Written to the Scene document's environment fields (environment.darknessLevel, environment.globalLight) - no canvas access required. Use when: transitioning to night, dimming a room, or lighting a torch-lit area. Do not use when: you only need to read current lighting - use get_scene_info. " +
583
590
  WRITE_GATE,
584
591
  inputSchema: {
585
592
  type: 'object',
@@ -839,7 +846,7 @@ export const tileTools = [
839
846
  export const tileMutationTools = [
840
847
  {
841
848
  name: 'create_tile',
842
- description: "Place a decorative Tile on a scene from an image already present under FoundryVTT's Data directory (see list_scene_assets). Width/height default to the image's real pixel dimensions when not given. Position is either explicit pixel x/y (top-left corner) or a gridCol/gridRow cell (the tile is centred in that cell - see find_open_cells for candidates). By default refuses to place a tile whose bounding box crosses a scene wall; pass allowWallOverlap: true to place anyway (e.g. a wall-mounted prop). Use when: decorating a scene with scenery (crates, dumpsters, vehicles, graffiti) that is not a creature or NPC. Do not use when: the object is a creature/NPC that should have HP and act in combat - use create_world_actor + spawn_token instead. " +
849
+ description: "Place a decorative Tile on a scene from an image already present under FoundryVTT's Data directory (see list_scene_assets). Width/height default to the image's real pixel dimensions when not given. Position is either explicit pixel x/y (top-left corner) or a gridCol/gridRow cell (the tile is centred in that cell - see find_open_cells for candidates). By default refuses to place a tile whose bounding box crosses a scene wall; pass allowWallOverlap: true to place anyway (e.g. a wall-mounted prop). Use when: decorating a scene with scenery (crates, dumpsters, vehicles, graffiti) that is not a creature or NPC. Do not use when: the object is a creature/NPC that should have its own statistics and act in combat - use create_world_actor + spawn_token instead. " +
843
850
  WRITE_GATE,
844
851
  inputSchema: {
845
852
  type: 'object',
@@ -975,7 +982,7 @@ export const placeableTools = [
975
982
  },
976
983
  {
977
984
  name: 'list_templates',
978
- description: 'List the Measured Templates (AOE spell/effect shapes) placed on a scene (id, template type, position, distance, direction, angle, width, colors, hidden), defaulting to the active scene when sceneId is omitted. Read from cached worldData - no canvas access needed. Use when: inspecting active spell areas or finding a templateId for delete_template.',
985
+ description: 'List the Measured Templates (area-of-effect shapes) placed on a scene (id, template type, position, distance, direction, angle, width, colors, hidden), defaulting to the active scene when sceneId is omitted. Read from cached worldData - no canvas access needed. Use when: inspecting active areas of effect or finding a templateId for delete_template.',
979
986
  inputSchema: {
980
987
  type: 'object',
981
988
  properties: {
@@ -1301,7 +1308,7 @@ export const placeableMutationTools = [
1301
1308
  },
1302
1309
  {
1303
1310
  name: 'create_template',
1304
- description: 'Place a Measured Template (spell/area-of-effect shape: "circle", "cone", "rect", "ray") on a scene at pixel x/y or a gridCol/gridRow cell. Distance is specified in scene grid units (e.g. metres or feet). ' +
1311
+ description: 'Place a Measured Template (area-of-effect shape: "circle", "cone", "rect", "ray") on a scene at pixel x/y or a gridCol/gridRow cell. Distance is specified in scene grid units (e.g. metres or feet). ' +
1305
1312
  WRITE_GATE,
1306
1313
  inputSchema: {
1307
1314
  type: 'object',
@@ -1369,7 +1376,7 @@ export const placeableMutationTools = [
1369
1376
  export const generationTools = [
1370
1377
  {
1371
1378
  name: 'generate_npc',
1372
- description: 'Generate a random NPC (name, race, class, HP, ability scores, background) as text. Use when: the user needs a throwaway NPC on the spot. Do not use when: the NPC must exist in FoundryVTT - this creates no documents, and the result still has to be entered into the world by hand.',
1379
+ description: 'Generate a random fantasy-style NPC as text, from built-in lists that do not depend on the game system of the world (name, people, profession, hit points, ability values, background). Use when: the user needs a throwaway NPC on the spot. Do not use when: the NPC must exist in FoundryVTT - this creates no documents, and the result still has to be entered into the world by hand.',
1373
1380
  inputSchema: {
1374
1381
  type: 'object',
1375
1382
  properties: {
@@ -1393,13 +1400,13 @@ export const generationTools = [
1393
1400
  },
1394
1401
  {
1395
1402
  name: 'generate_loot',
1396
- description: "Generate random treasure for an encounter as text. Only the currency amounts vary: they scale with the challenge rating, while the item list is fixed (a Healing Potion and a Silver Ring) and the treasureType argument is accepted but not used. Use when: the user wants a quick coin total for an encounter. Do not use when: the loot should end up in an actor's inventory - this creates no documents; use create_actor_item for that.",
1403
+ description: "Generate random fantasy-style treasure for an encounter as text, from built-in tables that do not depend on the game system of the world. Only the coin amounts vary: they scale with challengeRating, while the item list is fixed (a healing potion and a silver ring) and the treasureType argument is accepted but not used. Use when: the user wants a quick coin total for an encounter. Do not use when: the loot should end up in an actor's inventory - this creates no documents; use create_actor_item for that.",
1397
1404
  inputSchema: {
1398
1405
  type: 'object',
1399
1406
  properties: {
1400
1407
  challengeRating: {
1401
1408
  type: 'number',
1402
- description: 'Challenge rating for loot generation',
1409
+ description: 'Difficulty of the encounter; the coin amounts scale with it',
1403
1410
  minimum: 0,
1404
1411
  maximum: 30,
1405
1412
  },
@@ -1519,7 +1526,7 @@ export const diagnosticsTools = [
1519
1526
  export const combatTools = [
1520
1527
  {
1521
1528
  name: 'get_combat_state',
1522
- description: "Get the active combat encounter: initiative order with each combatant's name, initiative, HP and AC, plus the current round and which combatant is up. Use when: reporting whose turn it is, or checking whether a combat is already running before start_combat. Do not use when: you need a combatantId for set_initiative - this prints names and ordinals, not ids; read the foundry://combat resource, whose JSON includes each combatant's _id and lists combatants in this same initiative order, so the Nth entry printed here is that resource's combatants[N-1] and combat.turn indexes it directly.",
1529
+ description: "Get the active combat encounter: initiative order with each combatant's name and initiative, its hit points and armour class when its actor stores them at attributes.hp and attributes.ac, plus the current round and which combatant is up. Use when: reporting whose turn it is, or checking whether a combat is already running before start_combat. Do not use when: you need a combatantId for set_initiative - this prints names and ordinals, not ids; read the foundry://combat resource, whose JSON includes each combatant's _id and lists combatants in this same initiative order, so the Nth entry printed here is that resource's combatants[N-1] and combat.turn indexes it directly.",
1523
1530
  inputSchema: {
1524
1531
  type: 'object',
1525
1532
  properties: {},
@@ -1658,7 +1665,7 @@ export const tokenMutationTools = [
1658
1665
  },
1659
1666
  {
1660
1667
  name: 'apply_status_effect',
1661
- description: 'Apply or remove a status condition (e.g. "prone", "stunned") on a token\'s actor. Set active=false to remove. Matches by status id, so re-applying or clearing-when-absent is a no-op. With the module bridge enabled, it first waits up to 10 s for the companion module if it is still connecting. With module 0.6.0 or later, the status goes through the game system\'s own status effects, so the system recognises the effect as its condition; effects carrying the status that were written earlier over the socket are reported when applying and removed with active=false. Some game systems ask for a value when a status is created; pass it in createOptions, under the option name the system documents. Without it, the call fails at once and nothing is created. createOptions need that path: they are refused when it is not available (no module 0.6.0, or writes disabled), and ignored when the status is already active. Otherwise, or if the module does not come, an effect carrying the status is written over the socket (its icon always shown), which a game system that defines its own statuses with fixed effect ids may not recognise. The answer names the path used. On an unlinked token only that token changes: a status it inherits from its base actor is found and can be removed from that token alone. Use when: a condition is gained or lost. Do not use when: changing numeric state such as HP - use update_actor_attributes. ' +
1668
+ description: 'Apply or remove a status condition (e.g. "prone", "stunned") on a token\'s actor. Set active=false to remove. Matches by status id, so re-applying or clearing-when-absent is a no-op. With the module bridge enabled, it first waits up to 10 s for the companion module if it is still connecting. With module 0.6.0 or later, the status goes through the game system\'s own status effects, so the system recognises the effect as its condition; effects carrying the status that were written earlier over the socket are reported when applying and removed with active=false. Some game systems ask for a value when a status is created; pass it in createOptions, under the option name the system documents. Without it, the call fails at once and nothing is created. createOptions need that path: they are refused when it is not available (no module 0.6.0, or writes disabled), and ignored when the status is already active. Otherwise, or if the module does not come, an effect carrying the status is written over the socket (its icon always shown), which a game system that defines its own statuses with fixed effect ids may not recognise. The answer names the path used. On an unlinked token only that token changes: a status it inherits from its base actor is found and can be removed from that token alone. Use when: a condition is gained or lost. Do not use when: changing numeric state such as hit points - use update_actor_attributes. ' +
1662
1669
  WRITE_GATE +
1663
1670
  ' Exception: the no-op cases (applying an already-present status, or clearing an absent one) report success without attempting a write, so they also return normally while writes are disabled.',
1664
1671
  inputSchema: {
@@ -1691,7 +1698,7 @@ export const tokenMutationTools = [
1691
1698
  },
1692
1699
  {
1693
1700
  name: 'spawn_token',
1694
- description: "Place a new token for an existing actor onto a scene at given x/y pixel coordinates, defaulting to the active scene when sceneId is omitted. Base display fields (texture, size, vision) are seeded from the actor's prototypeToken. Use when: a monster, NPC, or reinforcement needs to appear on the map. Do not use when: repositioning a token that is already on the scene - use move_token. " +
1701
+ description: "Place a new token for an existing actor onto a scene at given x/y pixel coordinates, defaulting to the active scene when sceneId is omitted. Base display fields (texture, size, vision) are seeded from the actor's prototypeToken. Use when: a creature, NPC, or reinforcement needs to appear on the map. Do not use when: repositioning a token that is already on the scene - use move_token. " +
1695
1702
  WRITE_GATE,
1696
1703
  inputSchema: {
1697
1704
  type: 'object',
@@ -1726,7 +1733,7 @@ export const tokenMutationTools = [
1726
1733
  },
1727
1734
  {
1728
1735
  name: 'delete_token',
1729
- description: "Remove a token from a scene without deleting the underlying actor. Use when: a monster is defeated and removed from the battle, or a token was placed by mistake. Do not use when: the actor document itself should be deleted - use delete_world_actor; this only removes the token's placement on the map. " +
1736
+ description: "Remove a token from a scene without deleting the underlying actor. Use when: a creature is defeated and removed from the battle, or a token was placed by mistake. Do not use when: the actor document itself should be deleted - use delete_world_actor; this only removes the token's placement on the map. " +
1730
1737
  WRITE_GATE,
1731
1738
  inputSchema: {
1732
1739
  type: 'object',
@@ -2524,7 +2531,7 @@ export const rollTableTools = [
2524
2531
  export const settingsTools = [
2525
2532
  {
2526
2533
  name: 'get_world_setting',
2527
- description: 'Read a world setting by its namespaced key (e.g. "cyberpunk-red-core.customSetting" or "simple-calendar.year"). If the setting has never been modified from its system/module default, exists will be false. Use when: inspecting world configuration.',
2534
+ description: 'Read a world setting by its namespaced key (e.g. "my-module.customSetting" or "simple-calendar.year"). If the setting has never been modified from its system/module default, exists will be false. Use when: inspecting world configuration.',
2528
2535
  inputSchema: {
2529
2536
  type: 'object',
2530
2537
  properties: {
@@ -2538,7 +2545,7 @@ export const settingsTools = [
2538
2545
  },
2539
2546
  {
2540
2547
  name: 'set_world_setting',
2541
- description: 'Update or create a world setting value for a system or module namespace (e.g. "cyberpunk-red-core.settingName"). Refuses writes to the "core.*" namespace (core settings control the Foundry client itself and can break the world; change those in the UI). ' +
2548
+ description: 'Update or create a world setting value for a system or module namespace (e.g. "my-module.settingName"). Refuses writes to the "core.*" namespace (core settings control the Foundry client itself and can break the world; change those in the UI). ' +
2542
2549
  CONFIRM_FIRST +
2543
2550
  ' ' +
2544
2551
  WRITE_GATE,
@@ -2587,7 +2594,7 @@ export const moduleBridgeTools = [
2587
2594
  },
2588
2595
  type: {
2589
2596
  type: 'string',
2590
- description: 'The Actor or Item type to introspect (e.g. "character", "npc", "weapon", "spell") - system-specific; list valid types by trying an obviously-wrong one, or check get_world_summary/the system documentation',
2597
+ description: 'The Actor or Item type to introspect (e.g. "character", "npc", "weapon") - system-specific; list valid types by trying an obviously-wrong one, or check get_world_summary/the system documentation',
2591
2598
  },
2592
2599
  },
2593
2600
  required: ['documentType', 'type'],
@@ -2618,7 +2625,8 @@ export const moduleBridgeTools = [
2618
2625
  },
2619
2626
  {
2620
2627
  name: 'roll_and_post',
2621
- description: 'Evaluate a dice formula using Foundry\'s native Roll engine and post it directly to chat as a rendered, clickable roll card. Supports full Foundry dice syntax (e.g. "4d6kh3", "1d20r1", exploding dice) that the local parser rejects. Requires the companion Foundry module.',
2628
+ description: 'Evaluate a dice formula using Foundry\'s native Roll engine and post it directly to chat as a rendered, clickable roll card. Supports full Foundry dice syntax (e.g. "4d6kh3", "1d20r1", exploding dice) that the local parser rejects. Requires the companion Foundry module. ' +
2629
+ MODULE_WRITE_GATE,
2622
2630
  inputSchema: {
2623
2631
  type: 'object',
2624
2632
  properties: {
@@ -2651,14 +2659,14 @@ export const moduleBridgeTools = [
2651
2659
  },
2652
2660
  {
2653
2661
  name: 'import_compendium_actor',
2654
- description: 'Import a compendium Actor (with its embedded items and effects) as a new top-level world Actor - the gap spawn_token cannot close alone, since it requires an actor that already exists in the world. Best-effort on embedded items: if the game system rejects embedded documents on create, the actor is recreated without them and each item is seeded individually, reporting per-item failures rather than losing the whole import. Requires the companion Foundry module. Use when: adding a monster or NPC from a compendium to the world before spawning its token. Do not use when: the actor already exists in the world - use spawn_token directly.' +
2662
+ description: 'Import a compendium Actor (with its embedded items and effects) as a new top-level world Actor - the gap spawn_token cannot close alone, since it requires an actor that already exists in the world. Best-effort on embedded items: if the game system rejects embedded documents on create, the actor is recreated without them and each item is seeded individually, reporting per-item failures rather than losing the whole import. Requires the companion Foundry module. Use when: adding a creature or NPC from a compendium to the world before spawning its token. Do not use when: the actor already exists in the world - use spawn_token directly.' +
2655
2663
  WRITE_GATE,
2656
2664
  inputSchema: {
2657
2665
  type: 'object',
2658
2666
  properties: {
2659
2667
  compendiumId: {
2660
2668
  type: 'string',
2661
- description: 'Compendium pack id the actor lives in (e.g. "dnd5e.monsters")',
2669
+ description: 'Compendium pack id the actor lives in (e.g. "world.creatures")',
2662
2670
  },
2663
2671
  actorId: {
2664
2672
  type: 'string',
@@ -2678,8 +2686,8 @@ export const moduleBridgeTools = [
2678
2686
  },
2679
2687
  {
2680
2688
  name: 'set_target',
2681
- description: "Set or clear this GM user's target selection on the active canvas (renders the targeting reticle in connected player browsers). tokenIds are token document IDs on the currently viewed scene. Requires the companion Foundry module. Use when: directing player attention, declaring spell targets, or marking focus fire. " +
2682
- WRITE_GATE,
2689
+ description: "Set or clear this GM user's target selection on the active canvas (renders the targeting reticle in connected player browsers). tokenIds are token document IDs on the currently viewed scene. Requires the companion Foundry module. Use when: directing player attention, declaring targets, or marking a shared target. " +
2690
+ MODULE_WRITE_GATE,
2683
2691
  inputSchema: {
2684
2692
  type: 'object',
2685
2693
  properties: {
@@ -2743,7 +2751,7 @@ export const moduleBridgeTools = [
2743
2751
  {
2744
2752
  name: 'ping_canvas',
2745
2753
  description: "Emit an animated canvas ping at specific pixel coordinates on the active scene's view, drawing every connected player's camera and attention to that exact location. Requires the companion Foundry module. Use when: pointing out a trap, landmark, or hidden detail on the map. " +
2746
- WRITE_GATE,
2754
+ MODULE_WRITE_GATE,
2747
2755
  inputSchema: {
2748
2756
  type: 'object',
2749
2757
  properties: {
@@ -2760,7 +2768,7 @@ export const moduleBridgeTools = [
2760
2768
  {
2761
2769
  name: 'set_pause',
2762
2770
  description: 'Pause or unpause the game clock. When paused, token movement and real-time combat timers freeze for players. Requires the companion Foundry module. Use when: stepping away, narrating a long cutscene, or resolving a complex rules question. ' +
2763
- WRITE_GATE,
2771
+ MODULE_WRITE_GATE,
2764
2772
  inputSchema: {
2765
2773
  type: 'object',
2766
2774
  properties: {
@@ -2773,18 +2781,18 @@ export const moduleBridgeTools = [
2773
2781
  },
2774
2782
  {
2775
2783
  name: 'upload_asset',
2776
- description: "Upload a file (image, audio, etc.) into FoundryVTT's Data storage via the GM browser's FilePicker, returning the Foundry-relative path to feed directly into create_scene (backgroundSrc), create_tile (src), or create_sound (path). Provide exactly one of contentBase64 (base64-encoded file content) or sourcePath (an absolute path readable by this MCP server, which base64-encodes it server-side). Rejects payloads over 8 MiB. Requires the companion Foundry module. Use when: adding new map art, tokens, or audio the world does not already have. " +
2777
- WRITE_GATE,
2784
+ description: "Upload a file (image, audio, etc.) into FoundryVTT's Data storage via the GM browser's FilePicker, returning the Foundry-relative path to feed directly into create_scene (backgroundSrc), create_tile (src), or create_sound (path). Provide exactly one of contentBase64 (base64-encoded file content) or sourcePath (a file inside the folder named by FOUNDRY_UPLOAD_SOURCE_DIR, which the server reads; refused when that setting is unset). Only media files: .png, .jpg, .jpeg, .webp, .gif, .mp3, .ogg, .wav, .m4a, .webm, .mp4, and filename must have the source file's extension. targetDir is a folder relative to the Data storage (no \"..\", no absolute path) and filename a plain file name. Rejects files over 8 MiB. Requires the companion Foundry module. Use when: adding new map art, tokens, or audio the world does not already have. " +
2785
+ MODULE_WRITE_GATE,
2778
2786
  inputSchema: {
2779
2787
  type: 'object',
2780
2788
  properties: {
2781
2789
  targetDir: {
2782
2790
  type: 'string',
2783
- description: 'Data-relative destination folder (e.g. "assets/uploads")',
2791
+ description: 'Destination folder relative to the Data storage (e.g. "assets/uploads"); no ".." and no absolute path',
2784
2792
  },
2785
2793
  filename: {
2786
2794
  type: 'string',
2787
- description: 'Destination filename, including extension',
2795
+ description: 'Destination file name with a media extension (e.g. "map.png"), no folder',
2788
2796
  },
2789
2797
  contentBase64: {
2790
2798
  type: 'string',
@@ -2792,11 +2800,11 @@ export const moduleBridgeTools = [
2792
2800
  },
2793
2801
  sourcePath: {
2794
2802
  type: 'string',
2795
- description: 'Absolute filesystem path readable by this MCP server. Mutually exclusive with contentBase64.',
2803
+ description: 'Path of a file inside the FOUNDRY_UPLOAD_SOURCE_DIR folder (refused when that setting is unset). Mutually exclusive with contentBase64.',
2796
2804
  },
2797
2805
  mimeType: {
2798
2806
  type: 'string',
2799
- description: 'Optional MIME type override; inferred from the filename extension if omitted',
2807
+ description: 'Optional MIME type; must be the one of the filename extension, which is used when omitted',
2800
2808
  },
2801
2809
  },
2802
2810
  required: ['targetDir', 'filename'],
@@ -2814,7 +2822,7 @@ export const moduleBridgeTools = [
2814
2822
  export const effectTools = [
2815
2823
  {
2816
2824
  name: 'create_actor_effect',
2817
- description: 'Create a general-purpose ActiveEffect on an actor with mechanical changes (attribute modifiers) and/or a duration - not just a status toggle (use apply_status_effect for that). Give actorId alone for a world actor, or actorId plus the sceneId+tokenId pair for one token: a linked token writes its world actor, an unlinked token only that token (its own copy of the actor), never the base actor or its other tokens. The token must carry actorId. changes[].mode is a named FoundryVTT ACTIVE_EFFECT_MODES combine rule (add/multiply/override/upgrade/downgrade/custom), not a raw number. Use when: applying a spell buff, a debuff, or an equipment bonus with a real mechanical effect. Do not use when: toggling a simple named condition (prone, stunned) - use apply_status_effect. ' +
2825
+ description: 'Create a general-purpose ActiveEffect on an actor with mechanical changes (attribute modifiers) and/or a duration - not just a status toggle (use apply_status_effect for that). Give actorId alone for a world actor, or actorId plus the sceneId+tokenId pair for one token: a linked token writes its world actor, an unlinked token only that token (its own copy of the actor), never the base actor or its other tokens. The token must carry actorId. changes[].mode is a named FoundryVTT ACTIVE_EFFECT_MODES combine rule (add/multiply/override/upgrade/downgrade/custom), not a raw number. Use when: applying a buff, a debuff, or an equipment bonus with a real mechanical effect. Do not use when: toggling a simple named condition (prone, stunned) - use apply_status_effect. ' +
2818
2826
  WRITE_GATE,
2819
2827
  inputSchema: {
2820
2828
  type: 'object',
@@ -2859,7 +2867,7 @@ export const effectTools = [
2859
2867
  properties: {
2860
2868
  key: {
2861
2869
  type: 'string',
2862
- description: 'Dot-path into the actor being modified (e.g. "system.attributes.hp.max")',
2870
+ description: 'Dot-path into the actor being modified (e.g. "system.attributes.health.max")',
2863
2871
  },
2864
2872
  mode: {
2865
2873
  type: 'string',
@@ -3,8 +3,8 @@
3
3
  * Foundry module over {@link ModuleBridge} rather than FoundryVTT's own
4
4
  * Socket.IO document API — see module-bridge.ts for why.
5
5
  */
6
- import { readFile } from 'node:fs/promises';
7
- import { extname } from 'node:path';
6
+ import { readFile, realpath, stat } from 'node:fs/promises';
7
+ import { extname, isAbsolute, relative, sep } from 'node:path';
8
8
  import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
9
9
  import { isRecord } from '../../utils/guards.js';
10
10
  import { resolveActorTarget } from './actor-target.js';
@@ -160,11 +160,22 @@ function isRollAndPostResult(value) {
160
160
  typeof value.formula === 'string' &&
161
161
  typeof value.total === 'number');
162
162
  }
163
- export async function handleRollAndPost(args, moduleBridge) {
163
+ /**
164
+ * Refuses a tool that changes the world while FOUNDRY_WRITE_ENABLED is off.
165
+ * The module tools never reach `FoundryClient.assertWriteable()`, so they
166
+ * check here, before anything is sent to the module or read from disk.
167
+ */
168
+ function assertWritesEnabled(foundryClient) {
169
+ if (!foundryClient.isWriteEnabled()) {
170
+ throw new McpError(ErrorCode.InvalidRequest, 'Write operations are disabled. Set FOUNDRY_WRITE_ENABLED=true to allow game-state mutation.');
171
+ }
172
+ }
173
+ export async function handleRollAndPost(args, foundryClient, moduleBridge) {
164
174
  const { formula } = args;
165
175
  if (!formula || typeof formula !== 'string') {
166
176
  throw new McpError(ErrorCode.InvalidParams, 'formula is required and must be a string');
167
177
  }
178
+ assertWritesEnabled(foundryClient);
168
179
  if (!moduleBridge) {
169
180
  throw new McpError(ErrorCode.InvalidRequest, 'The module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');
170
181
  }
@@ -202,6 +213,8 @@ export async function handleImportCompendiumActor(args, foundryClient, moduleBri
202
213
  if (!actorId || typeof actorId !== 'string') {
203
214
  throw new McpError(ErrorCode.InvalidParams, 'actorId is required and must be a string');
204
215
  }
216
+ // Before the compendium document is read through the module.
217
+ assertWritesEnabled(foundryClient);
205
218
  if (!moduleBridge) {
206
219
  throw new McpError(ErrorCode.InvalidRequest, 'The module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');
207
220
  }
@@ -277,7 +290,8 @@ function isSetTargetResult(value) {
277
290
  typeof value.targeted === 'boolean' &&
278
291
  typeof value.count === 'number');
279
292
  }
280
- export async function handleSetTarget(args, moduleBridge) {
293
+ export async function handleSetTarget(args, foundryClient, moduleBridge) {
294
+ assertWritesEnabled(foundryClient);
281
295
  if (!moduleBridge) {
282
296
  throw new McpError(ErrorCode.InvalidRequest, 'The module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');
283
297
  }
@@ -419,10 +433,11 @@ function isPingCanvasResult(value) {
419
433
  typeof value.x === 'number' &&
420
434
  typeof value.y === 'number');
421
435
  }
422
- export async function handlePingCanvas(args, moduleBridge) {
436
+ export async function handlePingCanvas(args, foundryClient, moduleBridge) {
423
437
  if (typeof args.x !== 'number' || typeof args.y !== 'number') {
424
438
  throw new McpError(ErrorCode.InvalidParams, 'x and y coordinates are required and must be numbers');
425
439
  }
440
+ assertWritesEnabled(foundryClient);
426
441
  if (!moduleBridge) {
427
442
  throw new McpError(ErrorCode.InvalidRequest, 'The module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');
428
443
  }
@@ -446,7 +461,8 @@ function isSetPauseResult(value) {
446
461
  value !== null &&
447
462
  typeof value.paused === 'boolean');
448
463
  }
449
- export async function handleSetPause(args, moduleBridge) {
464
+ export async function handleSetPause(args, foundryClient, moduleBridge) {
465
+ assertWritesEnabled(foundryClient);
450
466
  if (!moduleBridge) {
451
467
  throw new McpError(ErrorCode.InvalidRequest, 'The module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');
452
468
  }
@@ -470,12 +486,16 @@ function isUploadAssetResult(value) {
470
486
  value !== null &&
471
487
  typeof value.path === 'string');
472
488
  }
473
- const MIME_EXTENSIONS = {
489
+ /**
490
+ * The media types `upload_asset` accepts, by extension: images, audio and
491
+ * video. No SVG (it can carry script, served from FoundryVTT's origin), and
492
+ * nothing that is not media.
493
+ */
494
+ const MEDIA_TYPES = {
474
495
  '.png': 'image/png',
475
496
  '.jpg': 'image/jpeg',
476
497
  '.jpeg': 'image/jpeg',
477
498
  '.webp': 'image/webp',
478
- '.svg': 'image/svg+xml',
479
499
  '.gif': 'image/gif',
480
500
  '.mp3': 'audio/mpeg',
481
501
  '.ogg': 'audio/ogg',
@@ -483,11 +503,72 @@ const MIME_EXTENSIONS = {
483
503
  '.m4a': 'audio/mp4',
484
504
  '.webm': 'video/webm',
485
505
  '.mp4': 'video/mp4',
486
- '.json': 'application/json',
487
- '.pdf': 'application/pdf',
488
506
  };
489
507
  const MAX_UPLOAD_BYTES = 8 * 1024 * 1024; // 8 MiB
490
- export async function handleUploadAsset(args, moduleBridge) {
508
+ const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
509
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what it refuses
510
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/;
511
+ function invalidUpload(message) {
512
+ return new McpError(ErrorCode.InvalidParams, message);
513
+ }
514
+ /** A folder relative to FoundryVTT's Data storage: no root, drive, scheme or `..`. */
515
+ function checkTargetDir(targetDir) {
516
+ if (CONTROL_CHARACTERS.test(targetDir) ||
517
+ targetDir.startsWith('/') ||
518
+ targetDir.includes('\\') ||
519
+ targetDir.includes(':')) {
520
+ throw invalidUpload(`targetDir must be a folder relative to FoundryVTT's Data storage, such as "assets/maps": ${JSON.stringify(targetDir)}`);
521
+ }
522
+ if (targetDir.split('/').includes('..')) {
523
+ throw invalidUpload(`targetDir must not contain "..": ${JSON.stringify(targetDir)}`);
524
+ }
525
+ }
526
+ /** A plain file name: no folder, no drive, not hidden. */
527
+ function checkFilename(filename) {
528
+ if (CONTROL_CHARACTERS.test(filename) || /[/\\:]/.test(filename) || filename.startsWith('.')) {
529
+ throw invalidUpload(`filename must be a plain file name such as "map.png", with no folder, ":" or leading ".": ${JSON.stringify(filename)}`);
530
+ }
531
+ }
532
+ /**
533
+ * Reads `sourcePath` for an upload: only a regular file inside
534
+ * FOUNDRY_UPLOAD_SOURCE_DIR (links resolved), with `extension`, within the
535
+ * size limit — checked before the file is read.
536
+ */
537
+ async function readUploadSource(sourcePath, extension, sourceDir) {
538
+ if (!sourceDir) {
539
+ throw invalidUpload('sourcePath is disabled: set FOUNDRY_UPLOAD_SOURCE_DIR to the folder files may be uploaded from, or send contentBase64 instead.');
540
+ }
541
+ if (extname(sourcePath).toLowerCase() !== extension) {
542
+ throw invalidUpload(`The extension of filename (${extension}) must match the source file's: ${sourcePath}`);
543
+ }
544
+ let root;
545
+ let file;
546
+ try {
547
+ root = await realpath(sourceDir);
548
+ }
549
+ catch (error) {
550
+ throw invalidUpload(`FOUNDRY_UPLOAD_SOURCE_DIR cannot be read: ${error.message}`);
551
+ }
552
+ try {
553
+ file = await realpath(sourcePath);
554
+ }
555
+ catch (error) {
556
+ throw invalidUpload(`sourcePath cannot be read: ${error.message}`);
557
+ }
558
+ const inside = relative(root, file);
559
+ if (inside === '' || inside === '..' || inside.startsWith(`..${sep}`) || isAbsolute(inside)) {
560
+ throw invalidUpload(`sourcePath is outside FOUNDRY_UPLOAD_SOURCE_DIR (${root}): ${sourcePath}`);
561
+ }
562
+ const info = await stat(file);
563
+ if (!info.isFile()) {
564
+ throw invalidUpload(`sourcePath is not a regular file: ${sourcePath}`);
565
+ }
566
+ if (info.size > MAX_UPLOAD_BYTES) {
567
+ throw invalidUpload(`File size (${info.size} bytes) exceeds the 8 MiB upload limit`);
568
+ }
569
+ return readFile(file);
570
+ }
571
+ export async function handleUploadAsset(args, foundryClient, moduleBridge) {
491
572
  const { targetDir, filename, contentBase64, sourcePath } = args;
492
573
  if (!targetDir || typeof targetDir !== 'string') {
493
574
  throw new McpError(ErrorCode.InvalidParams, 'targetDir is required and must be a string');
@@ -500,22 +581,33 @@ export async function handleUploadAsset(args, moduleBridge) {
500
581
  if ((!hasBase64 && !hasSource) || (hasBase64 && hasSource)) {
501
582
  throw new McpError(ErrorCode.InvalidParams, 'Exactly one of contentBase64 or sourcePath must be provided');
502
583
  }
584
+ // Before anything is read from disk or sent to the module.
585
+ assertWritesEnabled(foundryClient);
503
586
  if (!moduleBridge) {
504
587
  throw new McpError(ErrorCode.InvalidRequest, 'The module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');
505
588
  }
589
+ checkTargetDir(targetDir);
590
+ checkFilename(filename);
591
+ const extension = extname(filename).toLowerCase();
592
+ const mimeType = MEDIA_TYPES[extension];
593
+ if (!mimeType) {
594
+ throw invalidUpload(`filename must end with a media file type (${Object.keys(MEDIA_TYPES).join(', ')}): ${JSON.stringify(filename)}`);
595
+ }
596
+ if (args.mimeType !== undefined && args.mimeType !== mimeType) {
597
+ throw invalidUpload(`mimeType ${JSON.stringify(args.mimeType)} does not match ${extension} (${mimeType})`);
598
+ }
599
+ if (hasBase64 && !BASE64.test(contentBase64 ?? '')) {
600
+ throw invalidUpload('contentBase64 is not base64');
601
+ }
506
602
  return withToolError('upload asset', async () => {
507
603
  let base64Payload;
508
- let mimeType = args.mimeType;
509
604
  if (hasSource && sourcePath) {
510
- const buffer = await readFile(sourcePath);
605
+ const buffer = await readUploadSource(sourcePath, extension, foundryClient.uploadSourceDir());
606
+ // The file may have grown since it was checked.
511
607
  if (buffer.byteLength > MAX_UPLOAD_BYTES) {
512
608
  throw new McpError(ErrorCode.InvalidParams, `File size (${buffer.byteLength} bytes) exceeds the 8 MiB upload limit`);
513
609
  }
514
610
  base64Payload = buffer.toString('base64');
515
- if (!mimeType) {
516
- const ext = extname(sourcePath).toLowerCase();
517
- mimeType = MIME_EXTENSIONS[ext] ?? 'application/octet-stream';
518
- }
519
611
  }
520
612
  else {
521
613
  base64Payload = contentBase64 ?? '';
@@ -523,10 +615,6 @@ export async function handleUploadAsset(args, moduleBridge) {
523
615
  if (estimatedBytes > MAX_UPLOAD_BYTES) {
524
616
  throw new McpError(ErrorCode.InvalidParams, `Estimated payload size (${estimatedBytes} bytes) exceeds the 8 MiB upload limit`);
525
617
  }
526
- if (!mimeType) {
527
- const ext = extname(filename).toLowerCase();
528
- mimeType = MIME_EXTENSIONS[ext] ?? 'application/octet-stream';
529
- }
530
618
  }
531
619
  const result = await moduleBridge.send('upload_asset', {
532
620
  targetDir,