@g33ks/foundryvtt-mcp 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,51 @@
3
3
  */
4
4
  import { getTurnOrder } from './combat-order.js';
5
5
  import { withToolError } from './utils.js';
6
+ /**
7
+ * A combatant's display name. v14 leaves `Combatant.name` empty unless it was
8
+ * set explicitly (the UI falls back to the token), so do the same: the
9
+ * combatant's own name, then its token's, then its actor's.
10
+ */
11
+ export function combatantName(c, combat, foundryClient) {
12
+ if (c.name) {
13
+ return c.name;
14
+ }
15
+ const sceneId = combatantSceneId(c, combat);
16
+ const token = c.tokenId ? foundryClient.findToken(c.tokenId, sceneId)?.token : undefined;
17
+ if (token && typeof token.name === 'string' && token.name) {
18
+ return token.name;
19
+ }
20
+ const actor = c.actorId ? foundryClient.getRawActor(c.actorId) : undefined;
21
+ return actor?.name ?? 'Unknown combatant';
22
+ }
23
+ function combatantSceneId(c, combat) {
24
+ const own = c.sceneId;
25
+ return own ?? combat.scene ?? undefined;
26
+ }
27
+ /**
28
+ * " HP: v/max AC: n" for a combatant, read from its token's own actor so each
29
+ * unlinked copy of a monster shows its own HP. AC is left out when absent.
30
+ */
31
+ function combatantHpAc(c, combat, foundryClient) {
32
+ const sceneId = combatantSceneId(c, combat);
33
+ const system = c.tokenId
34
+ ? foundryClient.getTokenActorSystem(c.tokenId, sceneId)
35
+ : c.actorId
36
+ ? foundryClient.getRawActor(c.actorId)?.system
37
+ : undefined;
38
+ const attributes = system?.attributes;
39
+ const hpData = attributes?.hp;
40
+ const acData = attributes?.ac;
41
+ let text = '';
42
+ if (hpData) {
43
+ text += ` HP: ${hpData.value ?? '?'}/${hpData.max ?? '?'}`;
44
+ }
45
+ const ac = acData?.value;
46
+ if (ac !== undefined && ac !== null) {
47
+ text += ` AC: ${ac}`;
48
+ }
49
+ return text;
50
+ }
6
51
  export async function handleGetCombatState(_args, foundryClient) {
7
52
  return withToolError('get combat state', async () => {
8
53
  const combat = foundryClient.getCombatState();
@@ -19,23 +64,9 @@ export async function handleGetCombatState(_args, foundryClient) {
19
64
  const current = combat.turn === i ? ' <-- CURRENT' : '';
20
65
  const status = c.defeated ? ' [DEFEATED]' : c.hidden ? ' [HIDDEN]' : '';
21
66
  const init = c.initiative !== null ? c.initiative.toString() : '?';
22
- // Try to get HP/AC from worldData if actor is linked
23
- let hpAc = '';
24
- if (c.actorId) {
25
- const actor = foundryClient.getRawActor(c.actorId);
26
- if (actor) {
27
- const hp = actor.system?.attributes;
28
- const hpData = hp?.hp;
29
- const acData = hp?.ac;
30
- if (hpData) {
31
- hpAc += ` HP: ${hpData.value ?? '?'}/${hpData.max ?? '?'}`;
32
- }
33
- if (acData) {
34
- hpAc += ` AC: ${acData.value ?? '?'}`;
35
- }
36
- }
37
- }
38
- return `${i + 1}. [${init}] **${c.name}**${hpAc}${status}${current}`;
67
+ const hpAc = combatantHpAc(c, combat, foundryClient);
68
+ const token = c.tokenId ? ` (token ${c.tokenId})` : '';
69
+ return `${i + 1}. [${init}] **${combatantName(c, combat, foundryClient)}**${token}${hpAc}${status}${current}`;
39
70
  })
40
71
  .join('\n');
41
72
  return {
@@ -367,7 +367,7 @@ export async function handleGetHealthStatus(_args, foundryClient, diagnosticsCli
367
367
  }
368
368
  else if (moduleBridge) {
369
369
  if (moduleBridge.isConnected()) {
370
- moduleBridgeSection = `✅ Connected — authenticated module (protocol v${BRIDGE_PROTOCOL_VERSION})`;
370
+ moduleBridgeSection = `✅ Connected — authenticated module ${moduleBridge.describeModuleVersion()} (protocol v${BRIDGE_PROTOCOL_VERSION})`;
371
371
  }
372
372
  else if (headlessGmSession) {
373
373
  moduleBridgeSection = `❌ Not connected — no authenticated module (protocol v${BRIDGE_PROTOCOL_VERSION}); see the headless GM session below`;
@@ -7,27 +7,19 @@
7
7
  * real `changes`/`duration`.
8
8
  */
9
9
  import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
10
+ import { actorParentUuid, isUnlinkedToken, resolveActorTarget, tokenHeaderLine, } from './actor-target.js';
10
11
  import { withToolError } from './utils.js';
11
12
  /**
12
13
  * Resolves the `ActiveEffect` parent UUID from an actor reference.
13
14
  *
14
15
  * `actorId` is always required. `sceneId` and `tokenId` are an optional
15
- * pair — supplying only one of the two is rejected — that, when present,
16
- * select the unlinked-token-actor UUID form instead of the plain
17
- * `Actor.<actorId>` form.
16
+ * pair — supplying only one of the two is rejected — naming the token whose
17
+ * actor to change: its world actor when the token is linked, its own
18
+ * (synthetic) actor when it is not. The token must be cached and carry
19
+ * `actorId`.
18
20
  */
19
- function resolveActorUuid(ref) {
20
- if (!ref.actorId || typeof ref.actorId !== 'string') {
21
- throw new McpError(ErrorCode.InvalidParams, 'actorId is required and must be a string');
22
- }
23
- const hasScene = ref.sceneId !== undefined;
24
- const hasToken = ref.tokenId !== undefined;
25
- if (hasScene !== hasToken) {
26
- throw new McpError(ErrorCode.InvalidParams, 'sceneId and tokenId must be supplied together (for an unlinked token actor) or not at all');
27
- }
28
- return hasScene
29
- ? `Scene.${ref.sceneId}.Token.${ref.tokenId}.Actor.${ref.actorId}`
30
- : `Actor.${ref.actorId}`;
21
+ function resolveActorUuid(ref, foundryClient) {
22
+ return actorParentUuid(resolveActorTarget(ref, foundryClient, { actorRequired: true }));
31
23
  }
32
24
  function formatEffect(effect) {
33
25
  const parts = [`**ID:** ${effect._id}`, `**Name:** ${effect.name}`];
@@ -43,7 +35,7 @@ function formatEffect(effect) {
43
35
  return parts.join('\n');
44
36
  }
45
37
  export async function handleCreateActorEffect(args, foundryClient) {
46
- const parentActorUuid = resolveActorUuid(args);
38
+ const parentActorUuid = resolveActorUuid(args, foundryClient);
47
39
  if (!args.name || typeof args.name !== 'string') {
48
40
  throw new McpError(ErrorCode.InvalidParams, 'name is required and must be a string');
49
41
  }
@@ -55,7 +47,7 @@ export async function handleCreateActorEffect(args, foundryClient) {
55
47
  });
56
48
  }
57
49
  export async function handleUpdateActorEffect(args, foundryClient) {
58
- const parentActorUuid = resolveActorUuid(args);
50
+ const parentActorUuid = resolveActorUuid(args, foundryClient);
59
51
  if (!args.effectId || typeof args.effectId !== 'string') {
60
52
  throw new McpError(ErrorCode.InvalidParams, 'effectId is required and must be a string');
61
53
  }
@@ -67,7 +59,7 @@ export async function handleUpdateActorEffect(args, foundryClient) {
67
59
  });
68
60
  }
69
61
  export async function handleDeleteActorEffect(args, foundryClient) {
70
- const parentActorUuid = resolveActorUuid(args);
62
+ const parentActorUuid = resolveActorUuid(args, foundryClient);
71
63
  if (!args.effectId || typeof args.effectId !== 'string') {
72
64
  throw new McpError(ErrorCode.InvalidParams, 'effectId is required and must be a string');
73
65
  }
@@ -78,15 +70,22 @@ export async function handleDeleteActorEffect(args, foundryClient) {
78
70
  };
79
71
  });
80
72
  }
73
+ /**
74
+ * Lists a world actor's effects, or one token's: for an unlinked token, its
75
+ * base actor's and its delta's merged (see `FoundryClient.getTokenActorEffects`).
76
+ */
81
77
  export async function handleListActorEffects(args, foundryClient) {
82
- if (!args.actorId || typeof args.actorId !== 'string') {
83
- throw new McpError(ErrorCode.InvalidParams, 'actorId is required and must be a string');
84
- }
78
+ const target = resolveActorTarget(args, foundryClient);
85
79
  return withToolError('list actor effects', async () => {
86
- const effects = foundryClient.listActorEffects(args.actorId);
80
+ const effects = isUnlinkedToken(target)
81
+ ? (foundryClient.getTokenActorEffects(target.tokenId, target.sceneId) ?? [])
82
+ : foundryClient.listActorEffects(target.actorId);
83
+ const header = tokenHeaderLine(target);
87
84
  if (effects.length === 0) {
88
85
  return {
89
- content: [{ type: 'text', text: '✨ **No active effects on this actor.**' }],
86
+ content: [
87
+ { type: 'text', text: `${header}✨ **No active effects on this actor.**` },
88
+ ],
90
89
  };
91
90
  }
92
91
  const lines = effects.map((effect) => `- ${formatEffect(effect)}`.replace(/\n/g, ' | '));
@@ -94,7 +93,7 @@ export async function handleListActorEffects(args, foundryClient) {
94
93
  content: [
95
94
  {
96
95
  type: 'text',
97
- text: `✨ **Active Effects** (${effects.length})\n${lines.join('\n')}`,
96
+ text: `${header}✨ **Active Effects** (${effects.length})\n${lines.join('\n')}`,
98
97
  },
99
98
  ],
100
99
  };
@@ -8,16 +8,20 @@
8
8
  * `activities.{id}.consumption.targets`.
9
9
  */
10
10
  import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
11
+ import { isUnlinkedToken, resolveActorTarget, tokenHeaderLine, } from './actor-target.js';
11
12
  import { withToolError } from './utils.js';
13
+ /** The token to pass to the client: only an unlinked one has an actor of its own. */
14
+ function tokenOf(target) {
15
+ return isUnlinkedToken(target) ? { sceneId: target.sceneId, tokenId: target.tokenId } : undefined;
16
+ }
12
17
  /**
13
18
  * Handles creating an item on an actor from a compendium reference or an inline
14
- * item document.
19
+ * item document. `actorId`, or `sceneId` + `tokenId`, names the actor (see
20
+ * actor-target.ts); an unlinked token gets the item on its own actor only.
15
21
  */
16
22
  export async function handleCreateActorItem(args, foundryClient, moduleBridge = null) {
17
- const { actorId, source } = args;
18
- if (!actorId || typeof actorId !== 'string') {
19
- throw new McpError(ErrorCode.InvalidParams, 'actorId is required and must be a string');
20
- }
23
+ const { source } = args;
24
+ const target = resolveActorTarget(args, foundryClient);
21
25
  if (!source || typeof source !== 'object') {
22
26
  throw new McpError(ErrorCode.InvalidParams, 'source is required and must be an object');
23
27
  }
@@ -49,7 +53,7 @@ export async function handleCreateActorItem(args, foundryClient, moduleBridge =
49
53
  delete cleanDoc._stats;
50
54
  effectiveSource = { type: 'inline', item: cleanDoc };
51
55
  }
52
- const newItem = await foundryClient.createActorItem(actorId, effectiveSource);
56
+ const newItem = await foundryClient.createActorItem(target.actorId, effectiveSource, tokenOf(target));
53
57
  const origin = source.type === 'compendium'
54
58
  ? `compendium ${source.compendiumId} / ${source.itemId}`
55
59
  : 'inline definition';
@@ -58,7 +62,7 @@ export async function handleCreateActorItem(args, foundryClient, moduleBridge =
58
62
  {
59
63
  type: 'text',
60
64
  text: `⚔️ **Item Created**
61
- **Actor:** ${actorId}
65
+ ${tokenHeaderLine(target)}**Actor:** ${target.actorId}
62
66
  **Item:** ${newItem.name} (${newItem.type})
63
67
  **Item ID:** ${newItem._id}
64
68
  **Source:** ${origin}
@@ -71,13 +75,12 @@ _Canonical target: D&D 5e v4+ activity schema._`,
71
75
  }
72
76
  /**
73
77
  * Handles applying a JSON merge patch to an item's `system` data. Supports
74
- * nested paths (e.g. `activities.{id}.consumption.targets`).
78
+ * nested paths (e.g. `activities.{id}.consumption.targets`). An unlinked
79
+ * token's item changes on that token only.
75
80
  */
76
81
  export async function handleUpdateActorItem(args, foundryClient) {
77
- const { actorId, itemId, patch } = args;
78
- if (!actorId || typeof actorId !== 'string') {
79
- throw new McpError(ErrorCode.InvalidParams, 'actorId is required and must be a string');
80
- }
82
+ const { itemId, patch } = args;
83
+ const target = resolveActorTarget(args, foundryClient);
81
84
  if (!itemId || typeof itemId !== 'string') {
82
85
  throw new McpError(ErrorCode.InvalidParams, 'itemId is required and must be a string');
83
86
  }
@@ -85,13 +88,13 @@ export async function handleUpdateActorItem(args, foundryClient) {
85
88
  throw new McpError(ErrorCode.InvalidParams, 'patch is required and must be an object');
86
89
  }
87
90
  return withToolError('update item', async () => {
88
- const updatedItem = await foundryClient.updateActorItem(actorId, itemId, patch);
91
+ const updatedItem = await foundryClient.updateActorItem(target.actorId, itemId, patch, tokenOf(target));
89
92
  return {
90
93
  content: [
91
94
  {
92
95
  type: 'text',
93
96
  text: `⚔️ **Item Updated**
94
- **Actor:** ${actorId}
97
+ ${tokenHeaderLine(target)}**Actor:** ${target.actorId}
95
98
  **Item:** ${updatedItem.name} (${updatedItem.type})
96
99
  **Item ID:** ${updatedItem._id}
97
100
  **Patched keys:** ${Object.keys(patch).join(', ') || '(none)'}
@@ -103,24 +106,23 @@ _JSON merge patch applied to item.system. Canonical target: D&D 5e v4+ activity
103
106
  });
104
107
  }
105
108
  /**
106
- * Handles deleting an item owned by an actor.
109
+ * Handles deleting an item owned by an actor. An unlinked token loses the
110
+ * item on its own actor only.
107
111
  */
108
112
  export async function handleDeleteActorItem(args, foundryClient) {
109
- const { actorId, itemId } = args;
110
- if (!actorId || typeof actorId !== 'string') {
111
- throw new McpError(ErrorCode.InvalidParams, 'actorId is required and must be a string');
112
- }
113
+ const { itemId } = args;
114
+ const target = resolveActorTarget(args, foundryClient);
113
115
  if (!itemId || typeof itemId !== 'string') {
114
116
  throw new McpError(ErrorCode.InvalidParams, 'itemId is required and must be a string');
115
117
  }
116
118
  return withToolError('delete item', async () => {
117
- await foundryClient.deleteActorItem(actorId, itemId);
119
+ await foundryClient.deleteActorItem(target.actorId, itemId, tokenOf(target));
118
120
  return {
119
121
  content: [
120
122
  {
121
123
  type: 'text',
122
124
  text: `🗑️ **Item Deleted**
123
- **Actor:** ${actorId}
125
+ ${tokenHeaderLine(target)}**Actor:** ${target.actorId}
124
126
  **Item ID:** ${itemId}
125
127
 
126
128
  _Canonical target: D&D 5e v4+ activity schema._`,
@@ -6,6 +6,8 @@
6
6
  import { readFile } from 'node:fs/promises';
7
7
  import { extname } 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
  };
@@ -264,6 +301,98 @@ export async function handleSetTarget(args, moduleBridge) {
264
301
  function isGetTargetsResult(value) {
265
302
  return (typeof value === 'object' && value !== null && Array.isArray(value.users));
266
303
  }
304
+ /** Default and largest `maxBytes` of get_actor_stats: the compact JSON it returns. */
305
+ export const ACTOR_STATS_DEFAULT_MAX_BYTES = 32_768;
306
+ export const ACTOR_STATS_MAX_MAX_BYTES = 65_536;
307
+ const ACTOR_STATS_MAX_PATHS = 50;
308
+ /** Keys named in a too-large error; the rest are counted. */
309
+ const TOO_LARGE_LISTED_KEYS = 15;
310
+ function formatBytes(bytes) {
311
+ return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KiB`;
312
+ }
313
+ /** The sizes of an object's top-level entries as compact JSON, largest first. */
314
+ function topLevelSizes(data) {
315
+ if (!isRecord(data)) {
316
+ return [];
317
+ }
318
+ return Object.entries(data)
319
+ .map(([key, value]) => ({ key, bytes: Buffer.byteLength(JSON.stringify(value) ?? '') }))
320
+ .sort((a, b) => b.bytes - a.bytes);
321
+ }
322
+ function isKeySizes(value) {
323
+ return (Array.isArray(value) &&
324
+ value.every((v) => isRecord(v) && typeof v.key === 'string' && typeof v.bytes === 'number'));
325
+ }
326
+ /** The error for an answer over maxBytes: its size, its largest keys, and what to do. */
327
+ function tooLargeError(bytes, maxBytes, sizes, byPath) {
328
+ const listed = sizes
329
+ .slice(0, TOO_LARGE_LISTED_KEYS)
330
+ .map((s) => `${s.key} (${formatBytes(s.bytes)})`)
331
+ .join(', ');
332
+ const more = sizes.length > TOO_LARGE_LISTED_KEYS
333
+ ? `, and ${sizes.length - TOO_LARGE_LISTED_KEYS} more`
334
+ : '';
335
+ return new McpError(ErrorCode.InvalidRequest, `The answer is ${bytes} bytes of JSON, over maxBytes ${maxBytes}. ` +
336
+ `${byPath ? 'Requested paths' : 'Top-level keys of system'}, largest first: ${listed || '(none)'}${more}. ` +
337
+ `Pass paths to read only what you need${byPath ? ' (fewer or deeper ones)' : ''}, e.g. ["${sizes[0]?.key ?? 'key'}"]` +
338
+ (maxBytes < ACTOR_STATS_MAX_MAX_BYTES
339
+ ? `, or raise maxBytes (at most ${ACTOR_STATS_MAX_MAX_BYTES}).`
340
+ : '.'));
341
+ }
342
+ /**
343
+ * Handles reading one actor's prepared `system` data through the companion
344
+ * module: a world actor by `actorId`, or one token's actor by `sceneId` +
345
+ * `tokenId`. The target is checked against the cache before anything is sent.
346
+ * Returns compact JSON; `paths` narrows it, `maxBytes` bounds it.
347
+ */
348
+ export async function handleGetActorStats(args, foundryClient, moduleBridge) {
349
+ const { paths } = args;
350
+ if (paths !== undefined &&
351
+ (!Array.isArray(paths) ||
352
+ paths.length === 0 ||
353
+ paths.length > ACTOR_STATS_MAX_PATHS ||
354
+ !paths.every((p) => typeof p === 'string' && p.length > 0))) {
355
+ throw new McpError(ErrorCode.InvalidParams, `paths must be an array of 1 to ${ACTOR_STATS_MAX_PATHS} dot paths into system`);
356
+ }
357
+ const maxBytes = args.maxBytes ?? ACTOR_STATS_DEFAULT_MAX_BYTES;
358
+ if (typeof maxBytes !== 'number' ||
359
+ !Number.isInteger(maxBytes) ||
360
+ maxBytes < 1 ||
361
+ maxBytes > ACTOR_STATS_MAX_MAX_BYTES) {
362
+ throw new McpError(ErrorCode.InvalidParams, `maxBytes must be an integer from 1 to ${ACTOR_STATS_MAX_MAX_BYTES}`);
363
+ }
364
+ const target = resolveActorTarget(args, foundryClient);
365
+ if (!moduleBridge) {
366
+ throw new McpError(ErrorCode.InvalidRequest, 'The module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');
367
+ }
368
+ const moduleTarget = target.kind === 'actor'
369
+ ? { actorId: target.actorId }
370
+ : { sceneId: target.sceneId, tokenId: target.tokenId, actorId: target.actorId };
371
+ return withToolError('get actor stats', async () => {
372
+ const answer = await moduleBridge.send('get_actor_stats', {
373
+ targets: [moduleTarget],
374
+ ...(paths === undefined ? {} : { paths }),
375
+ maxBytes,
376
+ });
377
+ const results = isRecord(answer) ? answer.results : undefined;
378
+ const entry = Array.isArray(results) && results.length === 1 ? results[0] : undefined;
379
+ if (!isRecord(answer) || !isRecord(entry)) {
380
+ throw new McpError(ErrorCode.InternalError, 'Module returned an unexpected get_actor_stats shape');
381
+ }
382
+ if (answer.tooLarge === true) {
383
+ throw tooLargeError(typeof answer.bytes === 'number' ? answer.bytes : 0, maxBytes, isKeySizes(entry.topLevel) ? entry.topLevel : [], paths !== undefined);
384
+ }
385
+ if (typeof entry.error === 'string') {
386
+ throw new Error(entry.error);
387
+ }
388
+ const text = JSON.stringify({ ...entry, truncated: answer.truncated === true });
389
+ const bytes = Buffer.byteLength(text);
390
+ if (bytes > maxBytes) {
391
+ throw tooLargeError(bytes, maxBytes, topLevelSizes(paths === undefined ? entry.system : entry.values), paths !== undefined);
392
+ }
393
+ return { content: [{ type: 'text', text }] };
394
+ });
395
+ }
267
396
  export async function handleGetTargets(_args, moduleBridge) {
268
397
  if (!moduleBridge) {
269
398
  throw new McpError(ErrorCode.InvalidRequest, 'The module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');