@g33ks/foundryvtt-mcp 2.1.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.
@@ -3,9 +3,11 @@
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
+ import { isRecord } from '../../utils/guards.js';
10
+ import { resolveActorTarget } from './actor-target.js';
9
11
  import { withToolError } from './utils.js';
10
12
  function isCaptureSceneResult(value) {
11
13
  return (typeof value === 'object' &&
@@ -42,12 +44,46 @@ export async function handleCaptureScene(_args, moduleBridge) {
42
44
  };
43
45
  });
44
46
  }
47
+ /** What a template-declared schema is, ahead of its JSON. */
48
+ const TEMPLATE_SCHEMA_NOTE = '_Declared by template.json: no schema, only default values; each type is inferred from its value (`inferred: true`)._\n';
49
+ /** The "Schema source:" line: a module before 0.6.0 sends no source and only reads DataModels. */
50
+ function schemaSourceLine(source) {
51
+ return `Schema source: ${source === 'template' ? 'template.json (types inferred)' : 'DataModel'}\n`;
52
+ }
53
+ /**
54
+ * A field description without a `min` or `max` that is not a finite number:
55
+ * an unbounded side arrives as `null` (JSON has no Infinity) and bounds
56
+ * nothing. Sub-fields (`fields`) and array elements (`element`) are cleaned
57
+ * alike; anything else is kept as sent.
58
+ */
59
+ function withFiniteBounds(node) {
60
+ if (!isRecord(node)) {
61
+ return node;
62
+ }
63
+ const out = {};
64
+ for (const [key, value] of Object.entries(node)) {
65
+ if ((key === 'min' || key === 'max') &&
66
+ !(typeof value === 'number' && Number.isFinite(value))) {
67
+ continue;
68
+ }
69
+ if (key === 'fields' && isRecord(value)) {
70
+ out.fields = Object.fromEntries(Object.entries(value).map(([name, field]) => [name, withFiniteBounds(field)]));
71
+ }
72
+ else if (key === 'element') {
73
+ out.element = withFiniteBounds(value);
74
+ }
75
+ else {
76
+ out[key] = value;
77
+ }
78
+ }
79
+ return out;
80
+ }
45
81
  function isDocumentSchemaResult(value) {
46
82
  return (typeof value === 'object' &&
47
83
  value !== null &&
48
84
  typeof value.documentType === 'string' &&
49
85
  typeof value.type === 'string' &&
50
- typeof value.fields === 'object');
86
+ isRecord(value.fields));
51
87
  }
52
88
  /**
53
89
  * Handles introspecting a game system's real DataModel schema for an Actor
@@ -71,11 +107,12 @@ export async function handleGetDocumentSchema(args, moduleBridge) {
71
107
  if (!isDocumentSchemaResult(result)) {
72
108
  throw new McpError(ErrorCode.InternalError, 'Module returned an unexpected get_document_schema shape');
73
109
  }
110
+ const fields = Object.fromEntries(Object.entries(result.fields).map(([name, field]) => [name, withFiniteBounds(field)]));
74
111
  return {
75
112
  content: [
76
113
  {
77
114
  type: 'text',
78
- text: `🧬 **${result.documentType} Schema: ${result.type}**\n\`\`\`json\n${JSON.stringify(result.fields, null, 2)}\n\`\`\``,
115
+ text: `🧬 **${result.documentType} Schema: ${result.type}**\n${schemaSourceLine(result.source)}${result.source === 'template' ? TEMPLATE_SCHEMA_NOTE : ''}\`\`\`json\n${JSON.stringify(fields, null, 2)}\n\`\`\``,
79
116
  },
80
117
  ],
81
118
  };
@@ -123,11 +160,22 @@ function isRollAndPostResult(value) {
123
160
  typeof value.formula === 'string' &&
124
161
  typeof value.total === 'number');
125
162
  }
126
- 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) {
127
174
  const { formula } = args;
128
175
  if (!formula || typeof formula !== 'string') {
129
176
  throw new McpError(ErrorCode.InvalidParams, 'formula is required and must be a string');
130
177
  }
178
+ assertWritesEnabled(foundryClient);
131
179
  if (!moduleBridge) {
132
180
  throw new McpError(ErrorCode.InvalidRequest, 'The module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');
133
181
  }
@@ -165,6 +213,8 @@ export async function handleImportCompendiumActor(args, foundryClient, moduleBri
165
213
  if (!actorId || typeof actorId !== 'string') {
166
214
  throw new McpError(ErrorCode.InvalidParams, 'actorId is required and must be a string');
167
215
  }
216
+ // Before the compendium document is read through the module.
217
+ assertWritesEnabled(foundryClient);
168
218
  if (!moduleBridge) {
169
219
  throw new McpError(ErrorCode.InvalidRequest, 'The module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');
170
220
  }
@@ -240,7 +290,8 @@ function isSetTargetResult(value) {
240
290
  typeof value.targeted === 'boolean' &&
241
291
  typeof value.count === 'number');
242
292
  }
243
- export async function handleSetTarget(args, moduleBridge) {
293
+ export async function handleSetTarget(args, foundryClient, moduleBridge) {
294
+ assertWritesEnabled(foundryClient);
244
295
  if (!moduleBridge) {
245
296
  throw new McpError(ErrorCode.InvalidRequest, 'The module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');
246
297
  }
@@ -264,6 +315,98 @@ export async function handleSetTarget(args, moduleBridge) {
264
315
  function isGetTargetsResult(value) {
265
316
  return (typeof value === 'object' && value !== null && Array.isArray(value.users));
266
317
  }
318
+ /** Default and largest `maxBytes` of get_actor_stats: the compact JSON it returns. */
319
+ export const ACTOR_STATS_DEFAULT_MAX_BYTES = 32_768;
320
+ export const ACTOR_STATS_MAX_MAX_BYTES = 65_536;
321
+ const ACTOR_STATS_MAX_PATHS = 50;
322
+ /** Keys named in a too-large error; the rest are counted. */
323
+ const TOO_LARGE_LISTED_KEYS = 15;
324
+ function formatBytes(bytes) {
325
+ return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KiB`;
326
+ }
327
+ /** The sizes of an object's top-level entries as compact JSON, largest first. */
328
+ function topLevelSizes(data) {
329
+ if (!isRecord(data)) {
330
+ return [];
331
+ }
332
+ return Object.entries(data)
333
+ .map(([key, value]) => ({ key, bytes: Buffer.byteLength(JSON.stringify(value) ?? '') }))
334
+ .sort((a, b) => b.bytes - a.bytes);
335
+ }
336
+ function isKeySizes(value) {
337
+ return (Array.isArray(value) &&
338
+ value.every((v) => isRecord(v) && typeof v.key === 'string' && typeof v.bytes === 'number'));
339
+ }
340
+ /** The error for an answer over maxBytes: its size, its largest keys, and what to do. */
341
+ function tooLargeError(bytes, maxBytes, sizes, byPath) {
342
+ const listed = sizes
343
+ .slice(0, TOO_LARGE_LISTED_KEYS)
344
+ .map((s) => `${s.key} (${formatBytes(s.bytes)})`)
345
+ .join(', ');
346
+ const more = sizes.length > TOO_LARGE_LISTED_KEYS
347
+ ? `, and ${sizes.length - TOO_LARGE_LISTED_KEYS} more`
348
+ : '';
349
+ return new McpError(ErrorCode.InvalidRequest, `The answer is ${bytes} bytes of JSON, over maxBytes ${maxBytes}. ` +
350
+ `${byPath ? 'Requested paths' : 'Top-level keys of system'}, largest first: ${listed || '(none)'}${more}. ` +
351
+ `Pass paths to read only what you need${byPath ? ' (fewer or deeper ones)' : ''}, e.g. ["${sizes[0]?.key ?? 'key'}"]` +
352
+ (maxBytes < ACTOR_STATS_MAX_MAX_BYTES
353
+ ? `, or raise maxBytes (at most ${ACTOR_STATS_MAX_MAX_BYTES}).`
354
+ : '.'));
355
+ }
356
+ /**
357
+ * Handles reading one actor's prepared `system` data through the companion
358
+ * module: a world actor by `actorId`, or one token's actor by `sceneId` +
359
+ * `tokenId`. The target is checked against the cache before anything is sent.
360
+ * Returns compact JSON; `paths` narrows it, `maxBytes` bounds it.
361
+ */
362
+ export async function handleGetActorStats(args, foundryClient, moduleBridge) {
363
+ const { paths } = args;
364
+ if (paths !== undefined &&
365
+ (!Array.isArray(paths) ||
366
+ paths.length === 0 ||
367
+ paths.length > ACTOR_STATS_MAX_PATHS ||
368
+ !paths.every((p) => typeof p === 'string' && p.length > 0))) {
369
+ throw new McpError(ErrorCode.InvalidParams, `paths must be an array of 1 to ${ACTOR_STATS_MAX_PATHS} dot paths into system`);
370
+ }
371
+ const maxBytes = args.maxBytes ?? ACTOR_STATS_DEFAULT_MAX_BYTES;
372
+ if (typeof maxBytes !== 'number' ||
373
+ !Number.isInteger(maxBytes) ||
374
+ maxBytes < 1 ||
375
+ maxBytes > ACTOR_STATS_MAX_MAX_BYTES) {
376
+ throw new McpError(ErrorCode.InvalidParams, `maxBytes must be an integer from 1 to ${ACTOR_STATS_MAX_MAX_BYTES}`);
377
+ }
378
+ const target = resolveActorTarget(args, foundryClient);
379
+ if (!moduleBridge) {
380
+ throw new McpError(ErrorCode.InvalidRequest, 'The module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');
381
+ }
382
+ const moduleTarget = target.kind === 'actor'
383
+ ? { actorId: target.actorId }
384
+ : { sceneId: target.sceneId, tokenId: target.tokenId, actorId: target.actorId };
385
+ return withToolError('get actor stats', async () => {
386
+ const answer = await moduleBridge.send('get_actor_stats', {
387
+ targets: [moduleTarget],
388
+ ...(paths === undefined ? {} : { paths }),
389
+ maxBytes,
390
+ });
391
+ const results = isRecord(answer) ? answer.results : undefined;
392
+ const entry = Array.isArray(results) && results.length === 1 ? results[0] : undefined;
393
+ if (!isRecord(answer) || !isRecord(entry)) {
394
+ throw new McpError(ErrorCode.InternalError, 'Module returned an unexpected get_actor_stats shape');
395
+ }
396
+ if (answer.tooLarge === true) {
397
+ throw tooLargeError(typeof answer.bytes === 'number' ? answer.bytes : 0, maxBytes, isKeySizes(entry.topLevel) ? entry.topLevel : [], paths !== undefined);
398
+ }
399
+ if (typeof entry.error === 'string') {
400
+ throw new Error(entry.error);
401
+ }
402
+ const text = JSON.stringify({ ...entry, truncated: answer.truncated === true });
403
+ const bytes = Buffer.byteLength(text);
404
+ if (bytes > maxBytes) {
405
+ throw tooLargeError(bytes, maxBytes, topLevelSizes(paths === undefined ? entry.system : entry.values), paths !== undefined);
406
+ }
407
+ return { content: [{ type: 'text', text }] };
408
+ });
409
+ }
267
410
  export async function handleGetTargets(_args, moduleBridge) {
268
411
  if (!moduleBridge) {
269
412
  throw new McpError(ErrorCode.InvalidRequest, 'The module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');
@@ -290,10 +433,11 @@ function isPingCanvasResult(value) {
290
433
  typeof value.x === 'number' &&
291
434
  typeof value.y === 'number');
292
435
  }
293
- export async function handlePingCanvas(args, moduleBridge) {
436
+ export async function handlePingCanvas(args, foundryClient, moduleBridge) {
294
437
  if (typeof args.x !== 'number' || typeof args.y !== 'number') {
295
438
  throw new McpError(ErrorCode.InvalidParams, 'x and y coordinates are required and must be numbers');
296
439
  }
440
+ assertWritesEnabled(foundryClient);
297
441
  if (!moduleBridge) {
298
442
  throw new McpError(ErrorCode.InvalidRequest, 'The module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');
299
443
  }
@@ -317,7 +461,8 @@ function isSetPauseResult(value) {
317
461
  value !== null &&
318
462
  typeof value.paused === 'boolean');
319
463
  }
320
- export async function handleSetPause(args, moduleBridge) {
464
+ export async function handleSetPause(args, foundryClient, moduleBridge) {
465
+ assertWritesEnabled(foundryClient);
321
466
  if (!moduleBridge) {
322
467
  throw new McpError(ErrorCode.InvalidRequest, 'The module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');
323
468
  }
@@ -341,12 +486,16 @@ function isUploadAssetResult(value) {
341
486
  value !== null &&
342
487
  typeof value.path === 'string');
343
488
  }
344
- 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 = {
345
495
  '.png': 'image/png',
346
496
  '.jpg': 'image/jpeg',
347
497
  '.jpeg': 'image/jpeg',
348
498
  '.webp': 'image/webp',
349
- '.svg': 'image/svg+xml',
350
499
  '.gif': 'image/gif',
351
500
  '.mp3': 'audio/mpeg',
352
501
  '.ogg': 'audio/ogg',
@@ -354,11 +503,72 @@ const MIME_EXTENSIONS = {
354
503
  '.m4a': 'audio/mp4',
355
504
  '.webm': 'video/webm',
356
505
  '.mp4': 'video/mp4',
357
- '.json': 'application/json',
358
- '.pdf': 'application/pdf',
359
506
  };
360
507
  const MAX_UPLOAD_BYTES = 8 * 1024 * 1024; // 8 MiB
361
- 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) {
362
572
  const { targetDir, filename, contentBase64, sourcePath } = args;
363
573
  if (!targetDir || typeof targetDir !== 'string') {
364
574
  throw new McpError(ErrorCode.InvalidParams, 'targetDir is required and must be a string');
@@ -371,22 +581,33 @@ export async function handleUploadAsset(args, moduleBridge) {
371
581
  if ((!hasBase64 && !hasSource) || (hasBase64 && hasSource)) {
372
582
  throw new McpError(ErrorCode.InvalidParams, 'Exactly one of contentBase64 or sourcePath must be provided');
373
583
  }
584
+ // Before anything is read from disk or sent to the module.
585
+ assertWritesEnabled(foundryClient);
374
586
  if (!moduleBridge) {
375
587
  throw new McpError(ErrorCode.InvalidRequest, 'The module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');
376
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
+ }
377
602
  return withToolError('upload asset', async () => {
378
603
  let base64Payload;
379
- let mimeType = args.mimeType;
380
604
  if (hasSource && sourcePath) {
381
- const buffer = await readFile(sourcePath);
605
+ const buffer = await readUploadSource(sourcePath, extension, foundryClient.uploadSourceDir());
606
+ // The file may have grown since it was checked.
382
607
  if (buffer.byteLength > MAX_UPLOAD_BYTES) {
383
608
  throw new McpError(ErrorCode.InvalidParams, `File size (${buffer.byteLength} bytes) exceeds the 8 MiB upload limit`);
384
609
  }
385
610
  base64Payload = buffer.toString('base64');
386
- if (!mimeType) {
387
- const ext = extname(sourcePath).toLowerCase();
388
- mimeType = MIME_EXTENSIONS[ext] ?? 'application/octet-stream';
389
- }
390
611
  }
391
612
  else {
392
613
  base64Payload = contentBase64 ?? '';
@@ -394,10 +615,6 @@ export async function handleUploadAsset(args, moduleBridge) {
394
615
  if (estimatedBytes > MAX_UPLOAD_BYTES) {
395
616
  throw new McpError(ErrorCode.InvalidParams, `Estimated payload size (${estimatedBytes} bytes) exceeds the 8 MiB upload limit`);
396
617
  }
397
- if (!mimeType) {
398
- const ext = extname(filename).toLowerCase();
399
- mimeType = MIME_EXTENSIONS[ext] ?? 'application/octet-stream';
400
- }
401
618
  }
402
619
  const result = await moduleBridge.send('upload_asset', {
403
620
  targetDir,
@@ -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
  ],