@g33ks/foundryvtt-mcp 0.0.0-stage → 2.1.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 (100) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +457 -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 +414 -0
  7. package/dist/cli/prompt.js +117 -0
  8. package/dist/cli/snippets.js +64 -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 +481 -0
  14. package/dist/diagnostics/client.js +291 -0
  15. package/dist/diagnostics/types.js +94 -0
  16. package/dist/foundry/auth.js +224 -0
  17. package/dist/foundry/browser-detect.js +170 -0
  18. package/dist/foundry/client.js +5874 -0
  19. package/dist/foundry/dice-formula.js +154 -0
  20. package/dist/foundry/event-log.js +298 -0
  21. package/dist/foundry/headless-gm-session.js +857 -0
  22. package/dist/foundry/journal-conflicts.js +141 -0
  23. package/dist/foundry/journal-history.js +90 -0
  24. package/dist/foundry/journal-integrity.js +322 -0
  25. package/dist/foundry/message-author.js +19 -0
  26. package/dist/foundry/module-bridge.js +441 -0
  27. package/dist/foundry/types.js +52 -0
  28. package/dist/foundry/world-cache.js +386 -0
  29. package/dist/index.js +107 -0
  30. package/dist/mcp-server.js +65 -0
  31. package/dist/server.js +159 -0
  32. package/dist/shared/build-order.js +134 -0
  33. package/dist/shared/config-hash.js +62 -0
  34. package/dist/shared/config-notice.js +55 -0
  35. package/dist/shared/control.js +291 -0
  36. package/dist/shared/daemon-link.js +135 -0
  37. package/dist/shared/daemon.js +311 -0
  38. package/dist/shared/ipc-client.js +200 -0
  39. package/dist/shared/ipc-server.js +316 -0
  40. package/dist/shared/paths.js +79 -0
  41. package/dist/shared/protocol.js +230 -0
  42. package/dist/shared/relay-config.js +65 -0
  43. package/dist/shared/relay.js +120 -0
  44. package/dist/shared/rotating-log.js +57 -0
  45. package/dist/shared/spawn.js +39 -0
  46. package/dist/shared/state-file.js +33 -0
  47. package/dist/shared/token.js +62 -0
  48. package/dist/shared/version.js +57 -0
  49. package/dist/tools/base.js +74 -0
  50. package/dist/tools/definitions.js +3109 -0
  51. package/dist/tools/handlers/actor-mutations.js +128 -0
  52. package/dist/tools/handlers/actors.js +114 -0
  53. package/dist/tools/handlers/chat-mutations.js +49 -0
  54. package/dist/tools/handlers/chat.js +38 -0
  55. package/dist/tools/handlers/combat-mutations.js +215 -0
  56. package/dist/tools/handlers/combat-order.js +94 -0
  57. package/dist/tools/handlers/combat.js +51 -0
  58. package/dist/tools/handlers/compendium.js +83 -0
  59. package/dist/tools/handlers/diagnostics.js +450 -0
  60. package/dist/tools/handlers/dice.js +54 -0
  61. package/dist/tools/handlers/effects.js +103 -0
  62. package/dist/tools/handlers/events.js +50 -0
  63. package/dist/tools/handlers/generation.js +258 -0
  64. package/dist/tools/handlers/item-mutations.js +132 -0
  65. package/dist/tools/handlers/items.js +53 -0
  66. package/dist/tools/handlers/journal-mutations.js +230 -0
  67. package/dist/tools/handlers/journals.js +80 -0
  68. package/dist/tools/handlers/module-bridge.js +421 -0
  69. package/dist/tools/handlers/placeable-mutations.js +272 -0
  70. package/dist/tools/handlers/resources.js +203 -0
  71. package/dist/tools/handlers/roll-tables.js +97 -0
  72. package/dist/tools/handlers/scene-mutations.js +159 -0
  73. package/dist/tools/handlers/scenes.js +355 -0
  74. package/dist/tools/handlers/settings.js +53 -0
  75. package/dist/tools/handlers/tile-mutations.js +56 -0
  76. package/dist/tools/handlers/token-mutations.js +356 -0
  77. package/dist/tools/handlers/users.js +59 -0
  78. package/dist/tools/handlers/utils.js +48 -0
  79. package/dist/tools/handlers/wall-mutations.js +98 -0
  80. package/dist/tools/handlers/world-documents.js +222 -0
  81. package/dist/tools/handlers/world.js +92 -0
  82. package/dist/tools/index.js +25 -0
  83. package/dist/tools/new-router.js +97 -0
  84. package/dist/tools/registry.js +79 -0
  85. package/dist/tools/resources.js +63 -0
  86. package/dist/tools/router.js +688 -0
  87. package/dist/tools/tool-dependencies.js +194 -0
  88. package/dist/tools/write-tools.js +97 -0
  89. package/dist/utils/cache-instance.js +30 -0
  90. package/dist/utils/cache.js +205 -0
  91. package/dist/utils/diagnostics.js +332 -0
  92. package/dist/utils/guards.js +17 -0
  93. package/dist/utils/image-size.js +160 -0
  94. package/dist/utils/log-args.js +47 -0
  95. package/dist/utils/logger.js +203 -0
  96. package/dist/utils/mcp-errors.js +47 -0
  97. package/dist/utils/refusal.js +30 -0
  98. package/dist/utils/sanitize.js +22 -0
  99. package/dist/utils/serial-queue.js +22 -0
  100. package/package.json +124 -4
@@ -0,0 +1,371 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { logger } from '../utils/logger.js';
3
+ export class CombatManager extends EventEmitter {
4
+ currentCombat = null;
5
+ combatHistory = [];
6
+ turnTimer;
7
+ TURN_WARNING_TIME = 30000; // 30 seconds
8
+ constructor(_foundryClient) {
9
+ super();
10
+ this.setupEventHandlers();
11
+ }
12
+ setupEventHandlers() {
13
+ this.on('combat_start', this.handleCombatStart.bind(this));
14
+ this.on('turn_start', this.handleTurnStart.bind(this));
15
+ this.on('turn_end', this.handleTurnEnd.bind(this));
16
+ this.on('round_end', this.handleRoundEnd.bind(this));
17
+ }
18
+ /**
19
+ * Destroy the combat manager and release resources
20
+ */
21
+ destroy() {
22
+ if (this.turnTimer) {
23
+ clearTimeout(this.turnTimer);
24
+ this.turnTimer = undefined;
25
+ }
26
+ this.removeAllListeners();
27
+ this.currentCombat = null;
28
+ this.combatHistory = [];
29
+ logger.info('Combat manager destroyed');
30
+ }
31
+ // Public API Methods
32
+ getCurrentCombat() {
33
+ return this.currentCombat;
34
+ }
35
+ getCombatHistory(limit = 50) {
36
+ return this.combatHistory.slice(-limit);
37
+ }
38
+ async startCombat(combatants) {
39
+ logger.info('Starting new combat encounter');
40
+ const combat = {
41
+ id: this.generateCombatId(),
42
+ round: 1,
43
+ turn: 0,
44
+ active: true,
45
+ started: false,
46
+ combatants: await this.initializeCombatants(combatants),
47
+ turnStartTime: new Date(),
48
+ roundStartTime: new Date(),
49
+ };
50
+ // Sort by initiative
51
+ combat.combatants.sort((a, b) => (b.initiative || 0) - (a.initiative || 0));
52
+ this.currentCombat = combat;
53
+ this.emitCombatEvent('combat_start', combat);
54
+ return combat;
55
+ }
56
+ async rollInitiative(combatantId) {
57
+ if (!this.currentCombat) {
58
+ throw new Error('No active combat');
59
+ }
60
+ const results = {};
61
+ const combatants = combatantId
62
+ ? this.currentCombat.combatants.filter((c) => c.id === combatantId)
63
+ : this.currentCombat.combatants;
64
+ for (const combatant of combatants) {
65
+ // Roll 1d20 + initiative modifier (simplified)
66
+ const roll = Math.floor(Math.random() * 20) + 1;
67
+ const modifier = this.getInitiativeModifier(combatant);
68
+ const total = roll + modifier;
69
+ combatant.initiative = total;
70
+ results[combatant.name] = total;
71
+ logger.debug(`${combatant.name} rolled initiative: ${total} (${roll} + ${modifier})`);
72
+ }
73
+ // Re-sort combatants by initiative
74
+ this.currentCombat.combatants.sort((a, b) => (b.initiative || 0) - (a.initiative || 0));
75
+ this.emitCombatEvent('initiative_changed', this.currentCombat, results);
76
+ return results;
77
+ }
78
+ async nextTurn() {
79
+ if (!this.currentCombat?.active) {
80
+ throw new Error('No active combat');
81
+ }
82
+ // End current turn
83
+ if (this.currentCombat.currentCombatant) {
84
+ this.emitCombatEvent('turn_end', this.currentCombat);
85
+ }
86
+ // Clear turn timer
87
+ if (this.turnTimer) {
88
+ clearTimeout(this.turnTimer);
89
+ }
90
+ // Advance to next combatant
91
+ this.currentCombat.turn++;
92
+ // Check if we need to start a new round
93
+ if (this.currentCombat.turn >= this.currentCombat.combatants.length) {
94
+ this.currentCombat.turn = 0;
95
+ this.currentCombat.round++;
96
+ this.emitCombatEvent('round_end', this.currentCombat);
97
+ // Reset turn actions for all combatants
98
+ this.currentCombat.combatants.forEach((c) => {
99
+ c.turnTaken = false;
100
+ c.actions = {
101
+ action: false,
102
+ bonus: false,
103
+ movement: 0,
104
+ reaction: false,
105
+ };
106
+ });
107
+ }
108
+ // Set current combatant
109
+ const combatant = this.currentCombat.combatants[this.currentCombat.turn];
110
+ if (combatant) {
111
+ this.currentCombat.currentCombatant = combatant;
112
+ }
113
+ this.currentCombat.turnStartTime = new Date();
114
+ if (!this.currentCombat.started) {
115
+ this.currentCombat.started = true;
116
+ }
117
+ this.emitCombatEvent('turn_start', this.currentCombat);
118
+ return this.currentCombat.currentCombatant || null;
119
+ }
120
+ async applyDamage(combatantId, damage, damageType) {
121
+ if (!this.currentCombat) {
122
+ throw new Error('No active combat');
123
+ }
124
+ const combatant = this.currentCombat.combatants.find((c) => c.id === combatantId);
125
+ if (!combatant) {
126
+ throw new Error(`Combatant ${combatantId} not found`);
127
+ }
128
+ // Apply damage to temp HP first, then regular HP
129
+ let remainingDamage = damage;
130
+ if (combatant.hp.temp && combatant.hp.temp > 0) {
131
+ const tempDamage = Math.min(remainingDamage, combatant.hp.temp);
132
+ combatant.hp.temp -= tempDamage;
133
+ remainingDamage -= tempDamage;
134
+ }
135
+ combatant.hp.current = Math.max(0, combatant.hp.current - remainingDamage);
136
+ // Check if combatant is defeated
137
+ if (combatant.hp.current === 0) {
138
+ combatant.defeated = true;
139
+ }
140
+ this.emitCombatEvent('damage_dealt', this.currentCombat, {
141
+ combatantId,
142
+ damage,
143
+ damageType,
144
+ newHP: combatant.hp.current,
145
+ defeated: combatant.defeated,
146
+ });
147
+ logger.info(`${combatant.name} took ${damage} ${damageType || 'damage'}, HP: ${combatant.hp.current}/${combatant.hp.max}`);
148
+ return combatant;
149
+ }
150
+ async healCombatant(combatantId, healing) {
151
+ if (!this.currentCombat) {
152
+ throw new Error('No active combat');
153
+ }
154
+ const combatant = this.currentCombat.combatants.find((c) => c.id === combatantId);
155
+ if (!combatant) {
156
+ throw new Error(`Combatant ${combatantId} not found`);
157
+ }
158
+ combatant.hp.current = Math.min(combatant.hp.max, combatant.hp.current + healing);
159
+ if (combatant.hp.current > 0) {
160
+ combatant.defeated = false;
161
+ }
162
+ logger.info(`${combatant.name} healed for ${healing}, HP: ${combatant.hp.current}/${combatant.hp.max}`);
163
+ return combatant;
164
+ }
165
+ async applyCondition(combatantId, condition, duration) {
166
+ if (!this.currentCombat) {
167
+ throw new Error('No active combat');
168
+ }
169
+ const combatant = this.currentCombat.combatants.find((c) => c.id === combatantId);
170
+ if (!combatant) {
171
+ throw new Error(`Combatant ${combatantId} not found`);
172
+ }
173
+ if (!combatant.conditions.includes(condition)) {
174
+ combatant.conditions.push(condition);
175
+ this.emitCombatEvent('condition_applied', this.currentCombat, {
176
+ combatantId,
177
+ condition,
178
+ duration,
179
+ });
180
+ logger.info(`Applied ${condition} to ${combatant.name}`);
181
+ }
182
+ return combatant;
183
+ }
184
+ async removeCondition(combatantId, condition) {
185
+ if (!this.currentCombat) {
186
+ throw new Error('No active combat');
187
+ }
188
+ const combatant = this.currentCombat.combatants.find((c) => c.id === combatantId);
189
+ if (!combatant) {
190
+ throw new Error(`Combatant ${combatantId} not found`);
191
+ }
192
+ const index = combatant.conditions.indexOf(condition);
193
+ if (index > -1) {
194
+ combatant.conditions.splice(index, 1);
195
+ logger.info(`Removed ${condition} from ${combatant.name}`);
196
+ }
197
+ return combatant;
198
+ }
199
+ async endCombat() {
200
+ if (!this.currentCombat) {
201
+ throw new Error('No active combat');
202
+ }
203
+ this.currentCombat.active = false;
204
+ if (this.turnTimer) {
205
+ clearTimeout(this.turnTimer);
206
+ }
207
+ const endedCombat = { ...this.currentCombat };
208
+ this.emitCombatEvent('combat_end', endedCombat);
209
+ logger.info('Combat ended');
210
+ this.currentCombat = null;
211
+ return endedCombat;
212
+ }
213
+ // Event Handlers
214
+ handleCombatStart(event) {
215
+ logger.info(`Combat started with ${event.combat.combatants.length} combatants`);
216
+ }
217
+ handleTurnStart(event) {
218
+ const combatant = event.combat.currentCombatant;
219
+ if (combatant) {
220
+ logger.info(`Turn ${event.combat.turn + 1}, Round ${event.combat.round}: ${combatant.name}'s turn`);
221
+ // Set turn timer
222
+ this.turnTimer = setTimeout(() => {
223
+ this.emit('turn_warning', combatant);
224
+ }, this.TURN_WARNING_TIME);
225
+ }
226
+ }
227
+ handleTurnEnd(event) {
228
+ const combatant = event.combat.currentCombatant;
229
+ if (combatant) {
230
+ combatant.turnTaken = true;
231
+ logger.debug(`${combatant.name} ended their turn`);
232
+ }
233
+ }
234
+ handleRoundEnd(event) {
235
+ logger.info(`Round ${event.combat.round - 1} ended, starting Round ${event.combat.round}`);
236
+ }
237
+ // Helper Methods
238
+ async initializeCombatants(combatantData) {
239
+ const combatants = [];
240
+ for (const data of combatantData) {
241
+ const combatant = {
242
+ id: data.id || this.generateCombatantId(),
243
+ name: data.name || 'Unknown',
244
+ initiative: data.initiative || 0,
245
+ hp: data.hp || { current: 1, max: 1 },
246
+ ac: data.ac || 10,
247
+ conditions: data.conditions || [],
248
+ defeated: data.defeated || false,
249
+ hidden: data.hidden || false,
250
+ actorId: data.actorId || '',
251
+ tokenId: data.tokenId || '',
252
+ turnTaken: false,
253
+ actions: {
254
+ action: false,
255
+ bonus: false,
256
+ movement: 0,
257
+ reaction: false,
258
+ },
259
+ };
260
+ combatants.push(combatant);
261
+ }
262
+ return combatants;
263
+ }
264
+ getInitiativeModifier(_combatant) {
265
+ // Simplified initiative modifier calculation
266
+ // In a real implementation, this would pull from the actual character sheet
267
+ return Math.floor(Math.random() * 6) - 1; // -1 to +4
268
+ }
269
+ generateCombatId() {
270
+ return `combat_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
271
+ }
272
+ generateCombatantId() {
273
+ return `combatant_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
274
+ }
275
+ emitCombatEvent(type, combat, data) {
276
+ const event = {
277
+ type,
278
+ timestamp: new Date(),
279
+ combat: { ...combat }, // Deep copy to prevent mutations
280
+ data,
281
+ };
282
+ this.combatHistory.push(event);
283
+ // Keep history manageable
284
+ if (this.combatHistory.length > 1000) {
285
+ this.combatHistory = this.combatHistory.slice(-500);
286
+ }
287
+ this.emit(type, event);
288
+ this.emit('combat_event', event);
289
+ }
290
+ // Analysis Methods
291
+ getCombatStatistics() {
292
+ if (!this.currentCombat) {
293
+ return null;
294
+ }
295
+ const stats = {
296
+ totalRounds: this.currentCombat.round,
297
+ totalTurns: this.currentCombat.round * this.currentCombat.combatants.length + this.currentCombat.turn,
298
+ averageTurnTime: this.calculateAverageTurnTime(),
299
+ combatants: this.currentCombat.combatants.map((c) => ({
300
+ name: c.name,
301
+ initiative: c.initiative || 0,
302
+ hp: { current: c.hp.current, max: c.hp.max },
303
+ status: c.conditions,
304
+ })),
305
+ activeEffects: this.currentCombat.combatants.reduce((acc, c) => acc + c.conditions.length, 0),
306
+ };
307
+ return stats;
308
+ }
309
+ calculateAverageTurnTime() {
310
+ const turnEvents = this.combatHistory.filter((e) => e.type === 'turn_start');
311
+ if (turnEvents.length < 2) {
312
+ return 0;
313
+ }
314
+ let totalTime = 0;
315
+ for (let i = 1; i < turnEvents.length; i++) {
316
+ const currentEvent = turnEvents[i];
317
+ const previousEvent = turnEvents[i - 1];
318
+ if (currentEvent && previousEvent) {
319
+ totalTime += currentEvent.timestamp.getTime() - previousEvent.timestamp.getTime();
320
+ }
321
+ }
322
+ return Math.round(totalTime / (turnEvents.length - 1) / 1000); // seconds
323
+ }
324
+ suggestTacticalActions(combatantId) {
325
+ if (!this.currentCombat) {
326
+ return ['No active combat'];
327
+ }
328
+ const combatant = this.currentCombat.combatants.find((c) => c.id === combatantId);
329
+ if (!combatant) {
330
+ return ['Combatant not found'];
331
+ }
332
+ const suggestions = [];
333
+ // HP-based suggestions
334
+ const hpPercent = (combatant.hp.current / combatant.hp.max) * 100;
335
+ if (hpPercent < 25) {
336
+ suggestions.push('Consider healing or retreating - HP critically low');
337
+ suggestions.push('Use defensive actions like Dodge or Shield');
338
+ }
339
+ else if (hpPercent < 50) {
340
+ suggestions.push('Monitor HP carefully - consider healing');
341
+ }
342
+ // Condition-based suggestions
343
+ if (combatant.conditions.includes('poisoned')) {
344
+ suggestions.push('Remove poison condition if possible');
345
+ }
346
+ if (combatant.conditions.includes('prone')) {
347
+ suggestions.push('Use movement to stand up from prone');
348
+ }
349
+ if (combatant.conditions.includes('grappled')) {
350
+ suggestions.push('Attempt to escape grapple with Athletics or Acrobatics');
351
+ }
352
+ // Action economy suggestions
353
+ if (!combatant.actions.action) {
354
+ suggestions.push('Use your Action for Attack, Cast a Spell, or other actions');
355
+ }
356
+ if (!combatant.actions.bonus) {
357
+ suggestions.push('Check for available Bonus Actions');
358
+ }
359
+ // Enemy analysis
360
+ const enemies = this.currentCombat.combatants.filter((c) => c.id !== combatantId && !c.defeated);
361
+ const lowHpEnemies = enemies.filter((e) => e.hp.current / e.hp.max < 0.3);
362
+ if (lowHpEnemies.length > 0) {
363
+ suggestions.push(`Focus fire on low HP enemies: ${lowHpEnemies.map((e) => e.name).join(', ')}`);
364
+ }
365
+ if (suggestions.length === 0) {
366
+ suggestions.push('Assess battlefield and choose optimal action');
367
+ }
368
+ return suggestions;
369
+ }
370
+ }
371
+ //# sourceMappingURL=manager.js.map
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @fileoverview The two layers of configuration that come from the process
3
+ * itself: its environment (the MCP client's `env` block, or the system), and
4
+ * a `.env` file in the working directory (handy for development).
5
+ *
6
+ * `.env` is parsed, never loaded into `process.env`: a relay hands its own
7
+ * environment to the shared process it starts, and that process must tell
8
+ * the client's settings apart from the configuration file (see
9
+ * `config/sources.ts`). Kept free of config/logger imports so `paths.ts`,
10
+ * `status` and `stop` can use it without a valid configuration.
11
+ */
12
+ import { readFileSync } from 'node:fs';
13
+ import path from 'node:path';
14
+ import dotenv from 'dotenv';
15
+ /**
16
+ * Claude desktop starts MCP servers in `C:\Windows\System32`; a `.env` there
17
+ * is never the user's, so none is looked up.
18
+ */
19
+ export function isWindowsSystemDir(cwd, platform = process.platform, env = process.env) {
20
+ if (platform !== 'win32') {
21
+ return false;
22
+ }
23
+ // Windows path rules whatever the host, so `platform` decides alone.
24
+ const root = env.SystemRoot ?? env.windir ?? 'C:\\Windows';
25
+ const resolved = path.win32.resolve(cwd).toLowerCase();
26
+ return ['System32', 'SysWOW64'].some((dir) => resolved === path.win32.join(root, dir).toLowerCase());
27
+ }
28
+ /** Settings of the `.env` file in `cwd`; empty when there is none (or `cwd` is System32). */
29
+ export function readDotenv(cwd = process.cwd(), platform = process.platform, env = process.env) {
30
+ if (isWindowsSystemDir(cwd, platform, env)) {
31
+ return { path: null, values: {} };
32
+ }
33
+ const file = path.join(cwd, '.env');
34
+ try {
35
+ return { path: file, values: dotenv.parse(readFileSync(file, 'utf8')) };
36
+ }
37
+ catch {
38
+ return { path: null, values: {} };
39
+ }
40
+ }
41
+ /**
42
+ * The environment with the `.env` layer under it (an environment variable
43
+ * wins, as `dotenv.config()` did). For settings that locate things before
44
+ * the configuration file is read: `FOUNDRY_MCP_STATE_DIR`, `FOUNDRY_MCP_CONFIG`.
45
+ */
46
+ export function processSettings(env = process.env, cwd = process.cwd(), platform = process.platform) {
47
+ return { ...readDotenv(cwd, platform, env).values, ...env };
48
+ }
49
+ //# sourceMappingURL=env-layers.js.map