@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.
@@ -4,6 +4,7 @@
4
4
  * Handles searching for actors and retrieving detailed actor information.
5
5
  */
6
6
  import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
7
+ import { isUnlinkedToken, resolveActorTarget, tokenHeaderLine, } from './actor-target.js';
7
8
  import { withToolError } from './utils.js';
8
9
  /**
9
10
  * Handles actor search requests
@@ -43,15 +44,19 @@ ${actorList || 'No actors found matching the criteria.'}
43
44
  });
44
45
  }
45
46
  /**
46
- * Handles detailed actor information requests
47
+ * Handles detailed actor information requests: a world actor by `actorId`,
48
+ * or one token's actor by `sceneId` + `tokenId` (an unlinked token's own
49
+ * HP and stats, base actor and delta merged).
47
50
  */
48
51
  export async function handleGetActorDetails(args, foundryClient) {
49
- const { actorId } = args;
50
- if (!actorId || typeof actorId !== 'string') {
52
+ if (args.actorId !== undefined && (typeof args.actorId !== 'string' || !args.actorId)) {
51
53
  throw new McpError(ErrorCode.InvalidParams, 'Actor ID is required and must be a string');
52
54
  }
55
+ const target = resolveActorTarget(args, foundryClient);
53
56
  return withToolError('get actor details', async () => {
54
- const actor = await foundryClient.getActor(actorId);
57
+ const actor = isUnlinkedToken(target)
58
+ ? foundryClient.getTokenActor(target.tokenId, target.sceneId)
59
+ : await foundryClient.getActor(target.actorId);
55
60
  const abilities = actor.abilities
56
61
  ? Object.entries(actor.abilities)
57
62
  .map(([key, ability]) => `**${key.toUpperCase()}:** ${ability.value} (${ability.mod >= 0 ? '+' : ''}${ability.mod})`)
@@ -62,7 +67,7 @@ export async function handleGetActorDetails(args, foundryClient) {
62
67
  {
63
68
  type: 'text',
64
69
  text: `🎭 **Actor Details: ${actor.name}**
65
- **Type:** ${actor.type}
70
+ ${tokenHeaderLine(target)}**Type:** ${actor.type}
66
71
  **Level:** ${actor.level || 'Unknown'}
67
72
  **Hit Points:** ${actor.hp?.value || 'Unknown'}/${actor.hp?.max || 'Unknown'}
68
73
  **Armor Class:** ${actor.ac?.value || 'Unknown'}
@@ -81,17 +86,25 @@ ${abilities}
81
86
  *
82
87
  * Reads full `system` data from the cached worldData, unlike
83
88
  * `get_actor_details`, which only reports the actor's own top-level stats.
89
+ * For an unlinked token, the items are its base actor's and its delta's
90
+ * merged (see `FoundryClient.getTokenActorItems`).
84
91
  */
85
92
  export async function handleGetActorInventory(args, foundryClient) {
86
- const { actorId } = args;
87
- if (!actorId || typeof actorId !== 'string') {
88
- throw new McpError(ErrorCode.InvalidParams, 'actorId is required and must be a string');
89
- }
93
+ const target = resolveActorTarget(args, foundryClient);
90
94
  return withToolError('get actor inventory', async () => {
91
- const items = foundryClient.getActorItems(actorId);
95
+ const items = isUnlinkedToken(target)
96
+ ? (foundryClient.getTokenActorItems(target.tokenId, target.sceneId) ?? [])
97
+ : foundryClient.getActorItems(target.actorId);
92
98
  if (items.length === 0) {
93
99
  return {
94
- content: [{ type: 'text', text: `Actor ${actorId} owns no items.` }],
100
+ content: [
101
+ {
102
+ type: 'text',
103
+ text: isUnlinkedToken(target)
104
+ ? `${tokenHeaderLine(target)}Token ${target.tokenId}'s actor owns no items.`
105
+ : `Actor ${target.actorId} owns no items.`,
106
+ },
107
+ ],
95
108
  };
96
109
  }
97
110
  const formatted = items
@@ -105,7 +118,7 @@ export async function handleGetActorInventory(args, foundryClient) {
105
118
  content: [
106
119
  {
107
120
  type: 'text',
108
- text: `🎒 **Actor Inventory** (${items.length} item${items.length !== 1 ? 's' : ''})\n\n${formatted}`,
121
+ text: `🎒 **Actor Inventory** (${items.length} item${items.length !== 1 ? 's' : ''})\n${tokenHeaderLine(target)}\n${formatted}`,
109
122
  },
110
123
  ],
111
124
  };
@@ -8,6 +8,7 @@
8
8
  * protocol), and the connected user needs GM/owner permission.
9
9
  */
10
10
  import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
11
+ import { combatantName } from './combat.js';
11
12
  import { getCurrentCombatant, getTurnOrder, turnIndexAfterInitiativeChange, } from './combat-order.js';
12
13
  import { withToolError } from './utils.js';
13
14
  /**
@@ -66,7 +67,7 @@ export async function handleNextTurn(args, foundryClient) {
66
67
  const { turn, round } = computeNextTurn(combat, skipDefeated);
67
68
  await foundryClient.updateCombat(combat._id, { turn, round });
68
69
  const current = getTurnOrder(combat)[turn];
69
- const currentName = current ? current.name : 'unknown';
70
+ const currentName = current ? combatantName(current, combat, foundryClient) : 'unknown';
70
71
  return {
71
72
  content: [
72
73
  {
@@ -142,7 +143,7 @@ export async function handleSetInitiative(args, foundryClient) {
142
143
  if (turn !== undefined && turn !== combat.turn) {
143
144
  await foundryClient.updateCombat(resolvedCombatId, { turn });
144
145
  reanchored = `
145
- **Still acting:** ${acting.name} (turn ${turn + 1} of ${combat.combatants.length})`;
146
+ **Still acting:** ${combatantName(acting, combat, foundryClient)} (turn ${turn + 1} of ${combat.combatants.length})`;
146
147
  }
147
148
  }
148
149
  return {
@@ -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._`,