@g33ks/foundryvtt-mcp 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +468 -2
  3. package/dist/character/manager.js +208 -0
  4. package/dist/cli/checks.js +307 -0
  5. package/dist/cli/config-file.js +120 -0
  6. package/dist/cli/init.js +410 -0
  7. package/dist/cli/prompt.js +117 -0
  8. package/dist/cli/snippets.js +49 -0
  9. package/dist/combat/manager.js +371 -0
  10. package/dist/config/env-layers.js +49 -0
  11. package/dist/config/index.js +298 -0
  12. package/dist/config/sources.js +201 -0
  13. package/dist/core.js +415 -0
  14. package/dist/diagnostics/client.js +353 -0
  15. package/dist/diagnostics/types.js +94 -0
  16. package/dist/foundry/auth.js +220 -0
  17. package/dist/foundry/browser-detect.js +170 -0
  18. package/dist/foundry/client.js +5555 -0
  19. package/dist/foundry/dice-formula.js +154 -0
  20. package/dist/foundry/event-log.js +299 -0
  21. package/dist/foundry/headless-gm-session.js +740 -0
  22. package/dist/foundry/journal-history.js +90 -0
  23. package/dist/foundry/journal-integrity.js +306 -0
  24. package/dist/foundry/module-bridge.js +413 -0
  25. package/dist/foundry/types.js +52 -0
  26. package/dist/foundry/world-cache.js +386 -0
  27. package/dist/index.js +107 -0
  28. package/dist/mcp-server.js +63 -0
  29. package/dist/server.js +159 -0
  30. package/dist/shared/build-order.js +134 -0
  31. package/dist/shared/config-hash.js +62 -0
  32. package/dist/shared/config-notice.js +55 -0
  33. package/dist/shared/control.js +255 -0
  34. package/dist/shared/daemon-link.js +135 -0
  35. package/dist/shared/daemon.js +313 -0
  36. package/dist/shared/ipc-client.js +200 -0
  37. package/dist/shared/ipc-server.js +316 -0
  38. package/dist/shared/paths.js +79 -0
  39. package/dist/shared/protocol.js +230 -0
  40. package/dist/shared/relay-config.js +65 -0
  41. package/dist/shared/relay.js +120 -0
  42. package/dist/shared/rotating-log.js +57 -0
  43. package/dist/shared/spawn.js +39 -0
  44. package/dist/shared/state-file.js +33 -0
  45. package/dist/shared/token.js +62 -0
  46. package/dist/shared/version.js +57 -0
  47. package/dist/tools/base.js +74 -0
  48. package/dist/tools/definitions.js +3109 -0
  49. package/dist/tools/handlers/actor-mutations.js +128 -0
  50. package/dist/tools/handlers/actors.js +114 -0
  51. package/dist/tools/handlers/chat-mutations.js +49 -0
  52. package/dist/tools/handlers/chat.js +36 -0
  53. package/dist/tools/handlers/combat-mutations.js +215 -0
  54. package/dist/tools/handlers/combat-order.js +94 -0
  55. package/dist/tools/handlers/combat.js +51 -0
  56. package/dist/tools/handlers/compendium.js +83 -0
  57. package/dist/tools/handlers/diagnostics.js +438 -0
  58. package/dist/tools/handlers/dice.js +54 -0
  59. package/dist/tools/handlers/effects.js +103 -0
  60. package/dist/tools/handlers/events.js +50 -0
  61. package/dist/tools/handlers/generation.js +258 -0
  62. package/dist/tools/handlers/item-mutations.js +132 -0
  63. package/dist/tools/handlers/items.js +53 -0
  64. package/dist/tools/handlers/journal-mutations.js +230 -0
  65. package/dist/tools/handlers/journals.js +80 -0
  66. package/dist/tools/handlers/module-bridge.js +421 -0
  67. package/dist/tools/handlers/placeable-mutations.js +272 -0
  68. package/dist/tools/handlers/resources.js +203 -0
  69. package/dist/tools/handlers/roll-tables.js +97 -0
  70. package/dist/tools/handlers/scene-mutations.js +159 -0
  71. package/dist/tools/handlers/scenes.js +355 -0
  72. package/dist/tools/handlers/settings.js +53 -0
  73. package/dist/tools/handlers/tile-mutations.js +56 -0
  74. package/dist/tools/handlers/token-mutations.js +356 -0
  75. package/dist/tools/handlers/users.js +59 -0
  76. package/dist/tools/handlers/utils.js +47 -0
  77. package/dist/tools/handlers/wall-mutations.js +98 -0
  78. package/dist/tools/handlers/world-documents.js +222 -0
  79. package/dist/tools/handlers/world.js +92 -0
  80. package/dist/tools/index.js +25 -0
  81. package/dist/tools/new-router.js +97 -0
  82. package/dist/tools/registry.js +79 -0
  83. package/dist/tools/resources.js +63 -0
  84. package/dist/tools/router.js +688 -0
  85. package/dist/tools/write-tools.js +97 -0
  86. package/dist/utils/cache-instance.js +30 -0
  87. package/dist/utils/cache.js +205 -0
  88. package/dist/utils/diagnostics.js +332 -0
  89. package/dist/utils/guards.js +17 -0
  90. package/dist/utils/image-size.js +160 -0
  91. package/dist/utils/log-args.js +47 -0
  92. package/dist/utils/logger.js +203 -0
  93. package/dist/utils/refusal.js +30 -0
  94. package/dist/utils/sanitize.js +22 -0
  95. package/dist/utils/serial-queue.js +22 -0
  96. package/package.json +124 -4
@@ -0,0 +1,356 @@
1
+ /**
2
+ * @fileoverview Token manipulation mutation tool handlers (FR-019)
3
+ *
4
+ * Provides GM-gated token-control tools that operate on tokens placed on
5
+ * scenes: moving a token to new coordinates, and applying/removing a status
6
+ * condition (ActiveEffect) on the token's actor. All are WRITE operations —
7
+ * they require FOUNDRY_WRITE_ENABLED=true and an active Socket.IO connection
8
+ * (mutations use the core `modifyDocument` protocol), and the connected user
9
+ * needs GM/owner permission.
10
+ */
11
+ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
12
+ import { withToolError } from './utils.js';
13
+ /**
14
+ * Moves a token to x/y coordinates on its scene (FR-019).
15
+ *
16
+ * The token is resolved from the cached worldData; `sceneId` is optional and
17
+ * only scopes the lookup (the parent scene is derived from the located token).
18
+ */
19
+ export async function handleMoveToken(args, foundryClient) {
20
+ const { tokenId, x, y, sceneId } = args;
21
+ if (!tokenId || typeof tokenId !== 'string') {
22
+ throw new McpError(ErrorCode.InvalidParams, 'tokenId is required and must be a string');
23
+ }
24
+ if (typeof x !== 'number' ||
25
+ !Number.isFinite(x) ||
26
+ typeof y !== 'number' ||
27
+ !Number.isFinite(y)) {
28
+ throw new McpError(ErrorCode.InvalidParams, 'x and y are required and must be finite numbers');
29
+ }
30
+ const located = foundryClient.findToken(tokenId, sceneId);
31
+ if (!located) {
32
+ throw new McpError(ErrorCode.InvalidRequest, `Token not found: ${tokenId}${sceneId ? ` on scene ${sceneId}` : ''}`);
33
+ }
34
+ return withToolError('move token', async () => {
35
+ const tokenName = located.token.name ?? tokenId;
36
+ await foundryClient.moveToken(located.scene._id, tokenId, x, y);
37
+ return {
38
+ content: [
39
+ {
40
+ type: 'text',
41
+ text: `🚶 **Token Moved**
42
+ **Token:** ${tokenName} (${tokenId})
43
+ **Scene:** ${located.scene.name} (${located.scene._id})
44
+ **Position:** (${x}, ${y})`,
45
+ },
46
+ ],
47
+ };
48
+ });
49
+ }
50
+ /**
51
+ * Applies or removes a status condition (ActiveEffect) on a token's actor
52
+ * (FR-019).
53
+ *
54
+ * `active` defaults to `true` (apply). Mirrors `Actor#toggleStatusEffect`:
55
+ * the effect is matched by its `statuses` array, so re-applying an already
56
+ * present condition (or removing an absent one) is a no-op. Linked actors
57
+ * resolve to `Actor.<id>`; unlinked tokens target their synthetic actor at
58
+ * `Scene.<sid>.Token.<tid>.Actor.<aid>`.
59
+ */
60
+ export async function handleApplyStatusEffect(args, foundryClient) {
61
+ const { tokenId, statusId, sceneId } = args;
62
+ const active = args.active ?? true;
63
+ if (!tokenId || typeof tokenId !== 'string') {
64
+ throw new McpError(ErrorCode.InvalidParams, 'tokenId is required and must be a string');
65
+ }
66
+ if (!statusId || typeof statusId !== 'string') {
67
+ throw new McpError(ErrorCode.InvalidParams, 'statusId is required and must be a string');
68
+ }
69
+ const located = foundryClient.findToken(tokenId, sceneId);
70
+ if (!located) {
71
+ throw new McpError(ErrorCode.InvalidRequest, `Token not found: ${tokenId}${sceneId ? ` on scene ${sceneId}` : ''}`);
72
+ }
73
+ const token = located.token;
74
+ const actorId = token.actorId;
75
+ if (!actorId) {
76
+ throw new McpError(ErrorCode.InvalidRequest, `Token ${tokenId} has no associated actor; cannot apply status effects.`);
77
+ }
78
+ // Linked tokens share the world actor; unlinked tokens own a synthetic actor
79
+ // (the per-token delta) that must be addressed through the Scene→Token path.
80
+ const linked = token.actorLink === true;
81
+ const parentActorUuid = linked
82
+ ? `Actor.${actorId}`
83
+ : `Scene.${located.scene._id}.Token.${tokenId}.Actor.${actorId}`;
84
+ // Find an existing effect carrying this status (matches toggleStatusEffect).
85
+ const effects = linked
86
+ ? (foundryClient.getRawActor(actorId)?.effects ?? [])
87
+ : (token.delta?.effects ?? []);
88
+ const existing = effects.find((e) => e.statuses?.includes(statusId));
89
+ 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);
96
+ }
97
+ if (!existing) {
98
+ return statusResult(`Status effect '${statusId}' is not active on ${token.name ?? tokenId}; nothing to remove.`, tokenId, located.scene, statusId, false);
99
+ }
100
+ await foundryClient.deleteActorEffect(parentActorUuid, existing._id);
101
+ return statusResult(`Removed status effect '${statusId}' (effect ${existing._id}).`, tokenId, located.scene, statusId, false);
102
+ });
103
+ }
104
+ /** Builds the MCP text result for a status-effect mutation. */
105
+ function statusResult(summary, tokenId, scene, statusId, active) {
106
+ return {
107
+ content: [
108
+ {
109
+ type: 'text',
110
+ text: `${active ? '✨' : '🧹'} **Status Effect ${active ? 'Applied' : 'Removed'}**
111
+ **Token:** ${tokenId}
112
+ **Scene:** ${scene.name} (${scene._id})
113
+ **Status:** ${statusId}
114
+ ${summary}`,
115
+ },
116
+ ],
117
+ };
118
+ }
119
+ /**
120
+ * Places a new token for an existing actor onto a scene.
121
+ *
122
+ * Defaults `sceneId` to the current active scene when omitted.
123
+ */
124
+ export async function handleSpawnToken(args, foundryClient) {
125
+ const { actorId, x, y, name, hidden } = args;
126
+ if (!actorId || typeof actorId !== 'string') {
127
+ throw new McpError(ErrorCode.InvalidParams, 'actorId is required and must be a string');
128
+ }
129
+ if (typeof x !== 'number' ||
130
+ !Number.isFinite(x) ||
131
+ typeof y !== 'number' ||
132
+ !Number.isFinite(y)) {
133
+ throw new McpError(ErrorCode.InvalidParams, 'x and y are required and must be finite numbers');
134
+ }
135
+ let resolvedSceneId = args.sceneId;
136
+ if (!resolvedSceneId) {
137
+ const active = foundryClient.getScenes().find((s) => s.active);
138
+ if (!active) {
139
+ throw new McpError(ErrorCode.InvalidRequest, 'No active scene and no sceneId given — pass sceneId explicitly.');
140
+ }
141
+ resolvedSceneId = active._id;
142
+ }
143
+ const sceneId = resolvedSceneId;
144
+ return withToolError('spawn token', async () => {
145
+ const scenes = foundryClient.getScenes();
146
+ const scene = scenes.find((s) => s._id === sceneId);
147
+ const tokenOptions = {};
148
+ if (name) {
149
+ tokenOptions.name = name;
150
+ }
151
+ if (hidden !== undefined) {
152
+ tokenOptions.hidden = hidden;
153
+ }
154
+ const token = await foundryClient.spawnToken(sceneId, actorId, x, y, tokenOptions);
155
+ const tokenId = token && typeof token === 'object' && '_id' in token && typeof token._id === 'string'
156
+ ? token._id
157
+ : 'unknown';
158
+ return {
159
+ content: [
160
+ {
161
+ type: 'text',
162
+ text: `🧙 **Token Spawned**
163
+ **Token ID:** ${tokenId}
164
+ **Actor:** ${actorId}
165
+ **Scene:** ${scene?.name ?? sceneId} (${sceneId})
166
+ **Position:** (${x}, ${y})`,
167
+ },
168
+ ],
169
+ };
170
+ });
171
+ }
172
+ /**
173
+ * Handles removing a token from a scene (does not delete the actor).
174
+ */
175
+ export async function handleDeleteToken(args, foundryClient) {
176
+ const { tokenId, sceneId } = args;
177
+ if (!tokenId || typeof tokenId !== 'string') {
178
+ throw new McpError(ErrorCode.InvalidParams, 'tokenId is required and must be a string');
179
+ }
180
+ const located = foundryClient.findToken(tokenId, sceneId);
181
+ if (!located) {
182
+ throw new McpError(ErrorCode.InvalidRequest, `Token not found: ${tokenId}${sceneId ? ` on scene ${sceneId}` : ''}`);
183
+ }
184
+ return withToolError('delete token', async () => {
185
+ const tokenName = located.token.name ?? tokenId;
186
+ await foundryClient.deleteToken(located.scene._id, tokenId);
187
+ return {
188
+ content: [
189
+ {
190
+ type: 'text',
191
+ text: `🧹 **Token Removed**
192
+ **Token:** ${tokenName} (${tokenId})
193
+ **Scene:** ${located.scene.name} (${located.scene._id})`,
194
+ },
195
+ ],
196
+ };
197
+ });
198
+ }
199
+ /**
200
+ * Handles moving a token to (x, y), routing around walls and — unless
201
+ * openDoors is false — opening any closed doors the route needs to pass
202
+ * through.
203
+ */
204
+ export async function handleMoveTokenPathfind(args, foundryClient) {
205
+ const { tokenId, x, y, sceneId, openDoors } = args;
206
+ if (!tokenId || typeof tokenId !== 'string') {
207
+ throw new McpError(ErrorCode.InvalidParams, 'tokenId is required and must be a string');
208
+ }
209
+ if (typeof x !== 'number' ||
210
+ !Number.isFinite(x) ||
211
+ typeof y !== 'number' ||
212
+ !Number.isFinite(y)) {
213
+ throw new McpError(ErrorCode.InvalidParams, 'x and y are required and must be finite numbers');
214
+ }
215
+ const located = foundryClient.findToken(tokenId, sceneId);
216
+ if (!located) {
217
+ throw new McpError(ErrorCode.InvalidRequest, `Token not found: ${tokenId}${sceneId ? ` on scene ${sceneId}` : ''}`);
218
+ }
219
+ return withToolError('move token (pathfinding)', async () => {
220
+ const tokenName = located.token.name ?? tokenId;
221
+ const pathOptions = {};
222
+ if (openDoors !== undefined) {
223
+ pathOptions.openDoors = openDoors;
224
+ }
225
+ const result = await foundryClient.moveTokenPathfind(located.scene._id, tokenId, x, y, pathOptions);
226
+ if (result.blocked) {
227
+ return {
228
+ content: [
229
+ {
230
+ type: 'text',
231
+ text: `🚧 **No Route Found**
232
+ **Token:** ${tokenName} (${tokenId})
233
+ **Scene:** ${located.scene.name} (${located.scene._id})
234
+ No path to (${x}, ${y}) avoiding walls${openDoors === false ? '' : ' and closed doors'}.`,
235
+ },
236
+ ],
237
+ };
238
+ }
239
+ const doorsLine = result.doorsOpened.length > 0 ? `\n**Doors Opened:** ${result.doorsOpened.join(', ')}` : '';
240
+ return {
241
+ content: [
242
+ {
243
+ type: 'text',
244
+ text: `🚶 **Token Moved (pathfinding)**
245
+ **Token:** ${tokenName} (${tokenId})
246
+ **Scene:** ${located.scene.name} (${located.scene._id})
247
+ **Waypoints:** ${result.path.length}
248
+ **Destination:** (${x}, ${y})${doorsLine}`,
249
+ },
250
+ ],
251
+ };
252
+ });
253
+ }
254
+ /**
255
+ * Moves several tokens in a single call — direct (`move_token`) by default,
256
+ * or wall-aware pathfinding (`move_token_pathfind`) per move when
257
+ * `pathfind: true`. Best-effort per move, like `create_full_actor`'s item
258
+ * seeding: one bad move (an unknown tokenId, a blocked route, a rejected
259
+ * write) is reported in the failure list rather than aborting moves that
260
+ * already succeeded.
261
+ *
262
+ * `FOUNDRY_WRITE_ENABLED` is checked once up front so a fully-disabled
263
+ * batch reports one clear error instead of the same "writes disabled"
264
+ * message once per move.
265
+ */
266
+ export async function handleMoveTokens(args, foundryClient) {
267
+ const { moves } = args;
268
+ if (!Array.isArray(moves) || moves.length === 0) {
269
+ throw new McpError(ErrorCode.InvalidParams, 'moves is required and must be a non-empty array');
270
+ }
271
+ for (const [i, move] of moves.entries()) {
272
+ if (!move || typeof move !== 'object') {
273
+ throw new McpError(ErrorCode.InvalidParams, `moves[${i}] must be an object`);
274
+ }
275
+ if (!move.tokenId || typeof move.tokenId !== 'string') {
276
+ throw new McpError(ErrorCode.InvalidParams, `moves[${i}].tokenId is required and must be a string`);
277
+ }
278
+ if (typeof move.x !== 'number' ||
279
+ !Number.isFinite(move.x) ||
280
+ typeof move.y !== 'number' ||
281
+ !Number.isFinite(move.y)) {
282
+ throw new McpError(ErrorCode.InvalidParams, `moves[${i}].x and moves[${i}].y are required and must be finite numbers`);
283
+ }
284
+ }
285
+ if (!foundryClient.isWriteEnabled()) {
286
+ throw new McpError(ErrorCode.InvalidRequest, 'Write operations are disabled. Set FOUNDRY_WRITE_ENABLED=true to allow game-state mutation.');
287
+ }
288
+ return withToolError('move tokens', async () => {
289
+ const succeeded = [];
290
+ const failed = [];
291
+ for (const move of moves) {
292
+ const located = foundryClient.findToken(move.tokenId, move.sceneId);
293
+ if (!located) {
294
+ failed.push(`${move.tokenId}: token not found${move.sceneId ? ` on scene ${move.sceneId}` : ''}`);
295
+ continue;
296
+ }
297
+ const tokenName = located.token.name ?? move.tokenId;
298
+ try {
299
+ if (move.pathfind) {
300
+ const pathOptions = {};
301
+ if (move.openDoors !== undefined) {
302
+ pathOptions.openDoors = move.openDoors;
303
+ }
304
+ const result = await foundryClient.moveTokenPathfind(located.scene._id, move.tokenId, move.x, move.y, pathOptions);
305
+ if (result.blocked) {
306
+ failed.push(`${tokenName} (${move.tokenId}): no route to (${move.x}, ${move.y})`);
307
+ continue;
308
+ }
309
+ const doorsNote = result.doorsOpened.length > 0 ? `, opened ${result.doorsOpened.length} door(s)` : '';
310
+ succeeded.push(`${tokenName} (${move.tokenId}) → (${move.x}, ${move.y}) via ${result.path.length} waypoint(s)${doorsNote}`);
311
+ }
312
+ else {
313
+ await foundryClient.moveToken(located.scene._id, move.tokenId, move.x, move.y);
314
+ succeeded.push(`${tokenName} (${move.tokenId}) → (${move.x}, ${move.y})`);
315
+ }
316
+ }
317
+ catch (error) {
318
+ failed.push(`${tokenName} (${move.tokenId}): ${error instanceof Error ? error.message : String(error)}`);
319
+ }
320
+ }
321
+ const lines = [
322
+ `🚶 **Tokens Moved** (${succeeded.length}/${moves.length})`,
323
+ ...succeeded.map((s) => `- ${s}`),
324
+ ];
325
+ if (failed.length > 0) {
326
+ lines.push('', `**Failed (${failed.length}):**`, ...failed.map((f) => `- ${f}`));
327
+ }
328
+ return { content: [{ type: 'text', text: lines.join('\n') }] };
329
+ });
330
+ }
331
+ /**
332
+ * Updates a token's vision and/or light emission properties.
333
+ */
334
+ export async function handleUpdateTokenVision(args, foundryClient) {
335
+ const { tokenId, sceneId } = args;
336
+ if (!tokenId || typeof tokenId !== 'string') {
337
+ throw new McpError(ErrorCode.InvalidParams, 'tokenId is required and must be a string');
338
+ }
339
+ const located = foundryClient.findToken(tokenId, sceneId);
340
+ if (!located) {
341
+ throw new McpError(ErrorCode.InvalidRequest, `Token not found: ${tokenId}${sceneId ? ` on scene ${sceneId}` : ''}`);
342
+ }
343
+ return withToolError('update token vision', async () => {
344
+ const tokenName = located.token.name ?? tokenId;
345
+ await foundryClient.updateTokenVision(located.scene._id, tokenId, args);
346
+ return {
347
+ content: [
348
+ {
349
+ type: 'text',
350
+ text: `👁️ **Token Vision/Light Updated**\n**Token:** ${tokenName} (${tokenId})\n**Scene:** ${located.scene.name} (${located.scene._id})`,
351
+ },
352
+ ],
353
+ };
354
+ });
355
+ }
356
+ //# sourceMappingURL=token-mutations.js.map
@@ -0,0 +1,59 @@
1
+ /**
2
+ * User management tool handler
3
+ */
4
+ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
5
+ import { USER_ROLES } from '../../foundry/types.js';
6
+ import { withToolError } from './utils.js';
7
+ const ROLE_NAMES = {
8
+ 0: 'None',
9
+ 1: 'Player',
10
+ 2: 'Trusted Player',
11
+ 3: 'Assistant GM',
12
+ 4: 'Game Master',
13
+ };
14
+ export async function handleGetUsers(_args, foundryClient) {
15
+ return withToolError('get users', async () => {
16
+ const { users, activeUsers } = foundryClient.getUsers();
17
+ const activeSet = new Set(activeUsers);
18
+ const formatted = users
19
+ .map((u) => {
20
+ const online = activeSet.has(u._id) ? 'Online' : 'Offline';
21
+ const role = ROLE_NAMES[u.role] || `Role ${u.role}`;
22
+ return `- **${u.name}** (${role}) — ${online}`;
23
+ })
24
+ .join('\n');
25
+ const onlineCount = users.filter((u) => activeSet.has(u._id)).length;
26
+ return {
27
+ content: [
28
+ {
29
+ type: 'text',
30
+ text: `**Users** (${onlineCount}/${users.length} online)\n\n${formatted}`,
31
+ },
32
+ ],
33
+ };
34
+ });
35
+ }
36
+ export async function handleSetUserRole(args, foundryClient) {
37
+ const { userId, role } = args;
38
+ if (!userId || typeof userId !== 'string') {
39
+ throw new McpError(ErrorCode.InvalidParams, 'userId is required and must be a string');
40
+ }
41
+ if (!role || typeof role !== 'string' || !(role in USER_ROLES)) {
42
+ throw new McpError(ErrorCode.InvalidParams, `Invalid role "${role}": expected one of ${Object.keys(USER_ROLES).join(', ')}`);
43
+ }
44
+ return withToolError('set user role', async () => {
45
+ const { users } = foundryClient.getUsers();
46
+ const target = users.find((u) => u._id === userId);
47
+ const name = target?.name ?? userId;
48
+ await foundryClient.setUserRole(userId, role);
49
+ return {
50
+ content: [
51
+ {
52
+ type: 'text',
53
+ text: `👤 **User Role Updated**\n**User:** ${name} (\`${userId}\`)\n**Role:** ${role}`,
54
+ },
55
+ ],
56
+ };
57
+ });
58
+ }
59
+ //# sourceMappingURL=users.js.map
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Shared utilities for tool handlers
3
+ */
4
+ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
5
+ import { logger } from '../../utils/logger.js';
6
+ import { RefusedError, refusalError } from '../../utils/refusal.js';
7
+ /**
8
+ * Puts the pending journal overwrite warnings (see journal-integrity.ts) at
9
+ * the top of a journal tool's response; each is shown once.
10
+ */
11
+ export function withJournalWarnings(foundryClient, response) {
12
+ const warnings = foundryClient.drainJournalWarnings();
13
+ const first = response.content[0];
14
+ if (warnings.length === 0 || !first) {
15
+ return response;
16
+ }
17
+ return {
18
+ ...response,
19
+ content: [
20
+ { ...first, text: `${warnings.join('\n')}\n\n${first.text}` },
21
+ ...response.content.slice(1),
22
+ ],
23
+ };
24
+ }
25
+ /**
26
+ * Wraps an async handler function with standard error logging and McpError conversion.
27
+ *
28
+ * @param toolName - Label used in error log messages (e.g. 'search actors')
29
+ * @param fn - Async function containing the handler logic
30
+ */
31
+ export async function withToolError(toolName, fn) {
32
+ try {
33
+ return await fn();
34
+ }
35
+ catch (error) {
36
+ if (error instanceof McpError) {
37
+ throw error;
38
+ }
39
+ // Expected refusals are logged once, as a warning, by FoundryCore.
40
+ if (error instanceof RefusedError) {
41
+ throw refusalError(ErrorCode.InvalidRequest, `Failed to ${toolName}: ${error.message}`);
42
+ }
43
+ logger.error(`Failed to ${toolName}:`, error);
44
+ throw new McpError(ErrorCode.InternalError, `Failed to ${toolName}: ${error instanceof Error ? error.message : 'Unknown error'}`);
45
+ }
46
+ }
47
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1,98 @@
1
+ /**
2
+ * @fileoverview Wall mutation tool handlers (create/delete a Wall, and the
3
+ * door-specific set_door_state)
4
+ *
5
+ * WRITE operations — require FOUNDRY_WRITE_ENABLED=true and an active
6
+ * Socket.IO connection (mutations use the core `modifyDocument` protocol).
7
+ * `Wall` is an embedded document of `Scene` (mirrors tile mutation handlers);
8
+ * `ds` ("door state") is a plain field on it — no canvas access is required.
9
+ */
10
+ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
11
+ import { withToolError } from './utils.js';
12
+ const DOOR_STATE_NAMES = { 0: 'closed', 1: 'open', 2: 'locked' };
13
+ /**
14
+ * Handles opening, closing, or locking a door.
15
+ */
16
+ export async function handleSetDoorState(args, foundryClient) {
17
+ const { wallId, state, sceneId } = args;
18
+ if (!wallId || typeof wallId !== 'string') {
19
+ throw new McpError(ErrorCode.InvalidParams, 'wallId is required and must be a string');
20
+ }
21
+ if (state !== 0 && state !== 1 && state !== 2) {
22
+ throw new McpError(ErrorCode.InvalidParams, 'state is required and must be 0 (closed), 1 (open), or 2 (locked)');
23
+ }
24
+ const located = foundryClient.findWall(wallId, sceneId);
25
+ if (!located) {
26
+ throw new McpError(ErrorCode.InvalidRequest, `Wall not found: ${wallId}${sceneId ? ` on scene ${sceneId}` : ''}`);
27
+ }
28
+ if (located.wall.door === 0) {
29
+ throw new McpError(ErrorCode.InvalidRequest, `Wall ${wallId} is not a door`);
30
+ }
31
+ return withToolError('set door state', async () => {
32
+ await foundryClient.setDoorState(located.scene._id, wallId, state);
33
+ return {
34
+ content: [
35
+ {
36
+ type: 'text',
37
+ text: `🚪 **Door ${DOOR_STATE_NAMES[state]}**
38
+ **Wall:** ${wallId}
39
+ **Scene:** ${located.scene.name} (${located.scene._id})`,
40
+ },
41
+ ],
42
+ };
43
+ });
44
+ }
45
+ /**
46
+ * Handles creating a new Wall segment on a scene.
47
+ */
48
+ export async function handleCreateWall(args, foundryClient) {
49
+ const { sceneId, ...options } = args;
50
+ if (!sceneId || typeof sceneId !== 'string') {
51
+ throw new McpError(ErrorCode.InvalidParams, 'sceneId is required and must be a string');
52
+ }
53
+ return withToolError('create wall', async () => {
54
+ const wall = (await foundryClient.createWall(sceneId, options));
55
+ const [x1, y1, x2, y2] = wall.c ?? [];
56
+ const type = options.type ?? 'wall';
57
+ const label = {
58
+ wall: 'Wall',
59
+ door: 'Door',
60
+ secretDoor: 'Secret Door',
61
+ terrain: 'Terrain Wall',
62
+ invisible: 'Invisible Wall',
63
+ ethereal: 'Ethereal Wall',
64
+ };
65
+ return {
66
+ content: [
67
+ {
68
+ type: 'text',
69
+ text: `🧱 **${label[type]} Placed**\n**ID:** ${wall._id}\n**Segment:** (${x1}, ${y1}) → (${x2}, ${y2})`,
70
+ },
71
+ ],
72
+ };
73
+ });
74
+ }
75
+ /**
76
+ * Handles removing a Wall from a scene.
77
+ */
78
+ export async function handleDeleteWall(args, foundryClient) {
79
+ const { sceneId, wallId } = args;
80
+ if (!sceneId || typeof sceneId !== 'string') {
81
+ throw new McpError(ErrorCode.InvalidParams, 'sceneId is required and must be a string');
82
+ }
83
+ if (!wallId || typeof wallId !== 'string') {
84
+ throw new McpError(ErrorCode.InvalidParams, 'wallId is required and must be a string');
85
+ }
86
+ return withToolError('delete wall', async () => {
87
+ await foundryClient.deleteWall(sceneId, wallId);
88
+ return {
89
+ content: [
90
+ {
91
+ type: 'text',
92
+ text: `🗑️ **Wall Removed**\n**ID:** ${wallId}`,
93
+ },
94
+ ],
95
+ };
96
+ });
97
+ }
98
+ //# sourceMappingURL=wall-mutations.js.map