@g33ks/foundryvtt-mcp 2.2.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -209,6 +209,7 @@ The same names work in the configuration file, in an `env` block, in the system
209
209
  | `FOUNDRY_HEADLESS_GM_PASSWORD` | No | `FOUNDRY_PASSWORD` | Password of that other account (two-account mode only) |
210
210
  | `FOUNDRY_HEADLESS_GM_EXECUTABLE_PATH` | No | — | Path to any Chromium-based browser binary (Chrome, Edge, Brave, Vivaldi…), skipping auto-detection |
211
211
  | `FOUNDRY_DATA_PATH` | No | — | Local path to Foundry `Data/` for asset dimension discovery |
212
+ | `FOUNDRY_UPLOAD_SOURCE_DIR` | No | — | The one folder `upload_asset` may read a local file from (`sourcePath`); unset, it takes `contentBase64` only |
212
213
  | `FOUNDRY_API_KEY` | No | — | Optional REST API key for server diagnostics tools |
213
214
  | `FOUNDRY_EVENT_BUFFER_SIZE` | No | `500` | In-memory event log ring buffer capacity |
214
215
  | `FOUNDRY_EVENT_WAIT_MS` | No | `25000` | Default long-polling timeout for `watch_events` |
@@ -100,6 +100,11 @@ const ConfigSchema = z.object({
100
100
  */
101
101
  assets: z.object({
102
102
  dataPath: z.string().optional(),
103
+ /**
104
+ * The one folder `upload_asset` may read a `sourcePath` from. Unset, the
105
+ * tool takes `contentBase64` only: the server reads no local file for it.
106
+ */
107
+ uploadSourceDir: z.string().optional(),
103
108
  }),
104
109
  /**
105
110
  * In-memory world-event ring backing `watch_events` — the cursor-addressed
@@ -172,6 +177,7 @@ function rawConfig(v) {
172
177
  },
173
178
  assets: {
174
179
  dataPath: v.FOUNDRY_DATA_PATH,
180
+ uploadSourceDir: v.FOUNDRY_UPLOAD_SOURCE_DIR,
175
181
  },
176
182
  events: {
177
183
  bufferSize: int(v.FOUNDRY_EVENT_BUFFER_SIZE),
@@ -41,6 +41,7 @@ export const KNOWN_SETTINGS = [
41
41
  'FOUNDRY_HEADLESS_GM_PASSWORD',
42
42
  'FOUNDRY_HEADLESS_GM_EXECUTABLE_PATH',
43
43
  'FOUNDRY_DATA_PATH',
44
+ 'FOUNDRY_UPLOAD_SOURCE_DIR',
44
45
  'FOUNDRY_EVENT_BUFFER_SIZE',
45
46
  'FOUNDRY_EVENT_WAIT_MS',
46
47
  'FOUNDRY_MCP_SHARED',
package/dist/core.js CHANGED
@@ -115,6 +115,9 @@ export class FoundryCore {
115
115
  if (config.assets.dataPath) {
116
116
  clientConfig.dataPath = config.assets.dataPath;
117
117
  }
118
+ if (config.assets.uploadSourceDir) {
119
+ clientConfig.uploadSourceDir = config.assets.uploadSourceDir;
120
+ }
118
121
  // Same state directory as the shared process's daemon.json, in both modes.
119
122
  clientConfig.journalHistoryDir = path.join(defaultStateDir(), 'journal-history');
120
123
  clientConfig.journalConflictsFile = path.join(defaultStateDir(), 'journal-conflicts.json');
@@ -81,6 +81,11 @@ const FOLDER_DOCUMENT_TYPES = [
81
81
  * preset touches the exact "blocking" (NORMAL) value, which is left to the
82
82
  * server's own schema default rather than guessed.
83
83
  */
84
+ /**
85
+ * The id FoundryVTT v14 gives the Level it creates with a new scene
86
+ * (`BaseScene.metadata.defaultLevelId`).
87
+ */
88
+ const DEFAULT_LEVEL_ID = 'defaultLevel0000';
84
89
  const WALL_TYPE_PRESETS = {
85
90
  wall: {},
86
91
  door: { door: 1, ds: 0 },
@@ -1334,6 +1339,10 @@ export class FoundryClient {
1334
1339
  isWriteEnabled() {
1335
1340
  return this.config.writeEnabled === true;
1336
1341
  }
1342
+ /** The folder `upload_asset` may read a `sourcePath` from; `undefined` when none is set. */
1343
+ uploadSourceDir() {
1344
+ return this.config.uploadSourceDir;
1345
+ }
1337
1346
  /**
1338
1347
  * Returns true if worldData is available (Socket.IO mode connected).
1339
1348
  */
@@ -4306,6 +4315,19 @@ export class FoundryClient {
4306
4315
  }
4307
4316
  return size;
4308
4317
  }
4318
+ /**
4319
+ * The connected FoundryVTT generation (13, 14, ...), from the world's
4320
+ * `release`: v14 sends `generation` (and no `version`), earlier releases
4321
+ * a `version` such as "13.351". 0 when neither is known.
4322
+ */
4323
+ getCoreGeneration() {
4324
+ const release = this.worldData?.release ?? {};
4325
+ if (typeof release.generation === 'number') {
4326
+ return release.generation;
4327
+ }
4328
+ const major = Number.parseInt(String(release.version ?? ''), 10);
4329
+ return Number.isFinite(major) ? major : 0;
4330
+ }
4309
4331
  /**
4310
4332
  * Creates a new Scene document from a background image already present
4311
4333
  * under FoundryVTT's `Data` directory. Width/height default to the
@@ -4331,13 +4353,29 @@ export class FoundryClient {
4331
4353
  : this.requireImageSize(backgroundSrc);
4332
4354
  const width = options.width ?? size.width;
4333
4355
  const height = options.height ?? size.height;
4356
+ const backgroundColor = options.backgroundColor ?? '#999999';
4357
+ // v14 moved the background onto the scene's Levels: a scene created
4358
+ // without one has nothing to draw. The Foundry client adds a default
4359
+ // Level in Scene#_preCreate (client/documents/scene.mjs, 14.370:
4360
+ // 1009-1031), which a socket create never runs, so it is built here.
4361
+ const backgroundData = this.getCoreGeneration() >= 14
4362
+ ? {
4363
+ levels: [
4364
+ {
4365
+ _id: DEFAULT_LEVEL_ID,
4366
+ name: 'Level',
4367
+ background: { src: backgroundSrc, color: backgroundColor },
4368
+ },
4369
+ ],
4370
+ initialLevel: DEFAULT_LEVEL_ID,
4371
+ }
4372
+ : { background: { src: backgroundSrc }, backgroundColor };
4334
4373
  const data = {
4335
4374
  name,
4336
- background: { src: backgroundSrc },
4375
+ ...backgroundData,
4337
4376
  width,
4338
4377
  height,
4339
4378
  padding: options.padding ?? 0.25,
4340
- backgroundColor: options.backgroundColor ?? '#999999',
4341
4379
  grid: {
4342
4380
  type: options.gridType ?? 1,
4343
4381
  size: options.gridSize ?? 100,
@@ -30,6 +30,7 @@ export const IDENTITY_SETTINGS = {
30
30
  FOUNDRY_HEADLESS_GM_PASSWORD: (c) => c.headlessGm.password,
31
31
  FOUNDRY_HEADLESS_GM_EXECUTABLE_PATH: (c) => c.headlessGm.executablePath,
32
32
  FOUNDRY_DATA_PATH: (c) => c.assets.dataPath,
33
+ FOUNDRY_UPLOAD_SOURCE_DIR: (c) => c.assets.uploadSourceDir,
33
34
  };
34
35
  function identityValues(config) {
35
36
  return Object.keys(IDENTITY_SETTINGS)
@@ -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
  */
@@ -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: {
@@ -2679,7 +2687,7 @@ export const moduleBridgeTools = [
2679
2687
  {
2680
2688
  name: 'set_target',
2681
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 spell targets, or marking focus fire. " +
2682
- WRITE_GATE,
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'],
@@ -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,
@@ -461,7 +461,7 @@ export async function routeToolRequest(name, args, foundryClient, diagnosticsCli
461
461
  if (!('formula' in args) || typeof args.formula !== 'string') {
462
462
  throw new Error('Missing required parameter: formula');
463
463
  }
464
- return handleRollAndPost(args, moduleBridge);
464
+ return handleRollAndPost(args, foundryClient, moduleBridge);
465
465
  case 'import_compendium_actor':
466
466
  if (!('compendiumId' in args) || typeof args.compendiumId !== 'string') {
467
467
  throw new Error('Missing required parameter: compendiumId');
@@ -474,7 +474,7 @@ export async function routeToolRequest(name, args, foundryClient, diagnosticsCli
474
474
  if (!('tokenIds' in args) || !Array.isArray(args.tokenIds)) {
475
475
  throw new Error('Missing required parameter: tokenIds');
476
476
  }
477
- return handleSetTarget(args, moduleBridge);
477
+ return handleSetTarget(args, foundryClient, moduleBridge);
478
478
  case 'get_actor_stats':
479
479
  return handleGetActorStats(args, foundryClient, moduleBridge);
480
480
  case 'get_targets':
@@ -486,9 +486,9 @@ export async function routeToolRequest(name, args, foundryClient, diagnosticsCli
486
486
  if (!('y' in args) || typeof args.y !== 'number') {
487
487
  throw new Error('Missing required parameter: y');
488
488
  }
489
- return handlePingCanvas(args, moduleBridge);
489
+ return handlePingCanvas(args, foundryClient, moduleBridge);
490
490
  case 'set_pause':
491
- return handleSetPause(args, moduleBridge);
491
+ return handleSetPause(args, foundryClient, moduleBridge);
492
492
  case 'upload_asset':
493
493
  if (!('targetDir' in args) || typeof args.targetDir !== 'string') {
494
494
  throw new Error('Missing required parameter: targetDir');
@@ -496,7 +496,7 @@ export async function routeToolRequest(name, args, foundryClient, diagnosticsCli
496
496
  if (!('filename' in args) || typeof args.filename !== 'string') {
497
497
  throw new Error('Missing required parameter: filename');
498
498
  }
499
- return handleUploadAsset(args, moduleBridge);
499
+ return handleUploadAsset(args, foundryClient, moduleBridge);
500
500
  // World-event tools (read-only)
501
501
  case 'watch_events':
502
502
  return handleWatchEvents(args, foundryClient);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@g33ks/foundryvtt-mcp",
3
- "version": "2.2.0",
3
+ "version": "2.2.1",
4
4
  "description": "Model Context Protocol server for FoundryVTT integration",
5
5
  "bin": {
6
6
  "foundryvtt-mcp": "dist/index.js"