@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,51 @@
1
+ /**
2
+ * Combat state tool handler
3
+ */
4
+ import { getTurnOrder } from './combat-order.js';
5
+ import { withToolError } from './utils.js';
6
+ export async function handleGetCombatState(_args, foundryClient) {
7
+ return withToolError('get combat state', async () => {
8
+ const combat = foundryClient.getCombatState();
9
+ if (!combat) {
10
+ return {
11
+ content: [{ type: 'text', text: 'No active combat encounter.' }],
12
+ };
13
+ }
14
+ // `combat` is a live reference into the world-data cache: sort a COPY via
15
+ // the shared helper so a read never reorders cached state (laurigates/foundryvtt-mcp#214). The same
16
+ // helper backs `next_turn`, so both tools agree on what `combat.turn` means.
17
+ const combatants = getTurnOrder(combat)
18
+ .map((c, i) => {
19
+ const current = combat.turn === i ? ' <-- CURRENT' : '';
20
+ const status = c.defeated ? ' [DEFEATED]' : c.hidden ? ' [HIDDEN]' : '';
21
+ 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}`;
39
+ })
40
+ .join('\n');
41
+ return {
42
+ content: [
43
+ {
44
+ type: 'text',
45
+ text: `**Active Combat** — Round ${combat.round}\n\n${combatants}`,
46
+ },
47
+ ],
48
+ };
49
+ });
50
+ }
51
+ //# sourceMappingURL=combat.js.map
@@ -0,0 +1,83 @@
1
+ /**
2
+ * @fileoverview Compendium search tool handlers
3
+ *
4
+ * Read-only search across FoundryVTT compendium packs by name and metadata.
5
+ * Compendium data is not part of the cached worldData snapshot, so this tool
6
+ * requires the REST API module (FOUNDRY_API_KEY). Without it the search
7
+ * returns gracefully empty and the handler explains why.
8
+ */
9
+ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
10
+ import { withToolError } from './utils.js';
11
+ /**
12
+ * Handles compendium search requests.
13
+ *
14
+ * Searches across all enabled compendiums by default; the `compendiumId`
15
+ * filter scopes the search to a single pack. Returns enough metadata
16
+ * (compendiumId, itemId, type, system.source.rules) to disambiguate
17
+ * near-identical entries across rule revisions.
18
+ */
19
+ export async function handleSearchCompendium(args, foundryClient) {
20
+ const { query, filters, limit = 20, cursor } = args;
21
+ if (!query || typeof query !== 'string') {
22
+ throw new McpError(ErrorCode.InvalidParams, 'query is required and must be a string');
23
+ }
24
+ return withToolError('search compendium', async () => {
25
+ const params = { query, limit };
26
+ if (cursor) {
27
+ params.cursor = cursor;
28
+ }
29
+ if (filters?.compendiumId) {
30
+ params.compendiumId = filters.compendiumId;
31
+ }
32
+ if (filters?.packType) {
33
+ params.packType = filters.packType;
34
+ }
35
+ if (filters?.itemType) {
36
+ params.itemType = filters.itemType;
37
+ }
38
+ if (filters?.spellLevel !== undefined) {
39
+ params.spellLevel = filters.spellLevel;
40
+ }
41
+ if (filters?.source) {
42
+ params.source = filters.source;
43
+ }
44
+ const result = await foundryClient.searchCompendium(params);
45
+ const entryList = result.results
46
+ .map((entry) => {
47
+ const meta = [`pack: ${entry.compendiumId}`, `id: ${entry.itemId}`];
48
+ if (entry.system?.level !== undefined) {
49
+ meta.push(`level ${entry.system.level}`);
50
+ }
51
+ if (entry.system?.school) {
52
+ meta.push(entry.system.school);
53
+ }
54
+ if (entry.system?.source?.rules) {
55
+ meta.push(`rules: ${entry.system.source.rules}`);
56
+ }
57
+ return `- **${entry.name}** (${entry.type}) — ${meta.join(', ')}`;
58
+ })
59
+ .join('\n');
60
+ const restNote = result.restAvailable === false
61
+ ? '\n\n_Note: compendium search requires FOUNDRY_API_KEY (REST API module); returning no results._'
62
+ : '';
63
+ const cursorNote = result.nextCursor
64
+ ? `\n**Next page:** pass cursor \`${result.nextCursor}\` to retrieve more results.`
65
+ : '';
66
+ return {
67
+ content: [
68
+ {
69
+ type: 'text',
70
+ text: `📚 **Compendium Search Results**
71
+ **Query:** ${query}
72
+ **Pack Filter:** ${filters?.compendiumId || 'All enabled compendiums'}
73
+ **Results:** ${result.results.length}/${result.total} total
74
+
75
+ ${entryList || 'No compendium entries found matching the criteria.'}
76
+
77
+ **Page:** ${result.page} | **Limit:** ${result.limit}${cursorNote}${restNote}`,
78
+ },
79
+ ],
80
+ };
81
+ });
82
+ }
83
+ //# sourceMappingURL=compendium.js.map
@@ -0,0 +1,450 @@
1
+ /**
2
+ * @fileoverview Diagnostics and logging tool handlers
3
+ *
4
+ * Handles system diagnostics, logging, and health monitoring.
5
+ */
6
+ import { existsSync } from 'node:fs';
7
+ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
8
+ import { RestApiRequiredError } from '../../diagnostics/client.js';
9
+ import { LogEntrySchema } from '../../diagnostics/types.js';
10
+ import { describeBrowser } from '../../foundry/browser-detect.js';
11
+ import { gamemasterAccountWarning, roleLabel } from '../../foundry/client.js';
12
+ import { BRIDGE_PROTOCOL_VERSION } from '../../foundry/module-bridge.js';
13
+ import { withToolError } from './utils.js';
14
+ /** Valid log levels recognized by the tool schema */
15
+ const VALID_LOG_LEVELS = new Set(['debug', 'info', 'warn', 'error', 'log', 'notification']);
16
+ /** Hard upper bound on entries returned, regardless of caller-supplied limit */
17
+ const MAX_LOG_LIMIT = 1000;
18
+ /** Default number of search hits rendered when the caller supplies no limit */
19
+ const DEFAULT_SEARCH_LIMIT = 50;
20
+ /**
21
+ * Shown whenever `FoundryClient.isWorldDataStale()` is set (laurigates/foundryvtt-mcp#217): the cached
22
+ * world snapshot is still being served, but it stopped following live document
23
+ * changes when the socket dropped and nothing replays the gap.
24
+ */
25
+ const STALE_WORLD_DATA_NOTICE = '⚠️ **Stale:** this snapshot stopped following live changes when the connection dropped, ' +
26
+ 'and document changes made since are missing. Run `refresh_world_data` to resync.';
27
+ function sharedProcessSection(relays) {
28
+ const lines = [`- **Relays:** ${relays.connected} connected`];
29
+ if (relays.outdated.length > 0) {
30
+ lines.push(`⚠️ ${relays.outdated.length} on an older connector build ` +
31
+ `(${relays.outdated.map((v) => `v${v}`).join(', ')}): those clients keep working, ` +
32
+ 'but restart them to load the current tool list.');
33
+ }
34
+ return lines.join('\n');
35
+ }
36
+ /**
37
+ * Handles recent log retrieval requests
38
+ *
39
+ * Filtering is applied after fetching all logs from the underlying source:
40
+ * - `limit`: clamps result count (default 20, hard cap 1000)
41
+ * - `level`: case-insensitive match against log entry level; unrecognized values are silently ignored
42
+ * - `since`: ISO 8601 timestamp; entries older than this are excluded; unparseable values are silently ignored
43
+ */
44
+ export async function handleGetRecentLogs(args, diagnosticsClient) {
45
+ const { limit = 20, level, since } = args;
46
+ // Clamp limit to [1, MAX_LOG_LIMIT]
47
+ const effectiveLimit = Math.min(Math.max(1, limit ?? 20), MAX_LOG_LIMIT);
48
+ // Normalize level filter: resolve to a Set of valid lowercase level strings, or null if none recognized
49
+ let levelFilter = null;
50
+ if (level !== undefined && level !== null) {
51
+ const requested = (Array.isArray(level) ? level : [level])
52
+ .map((l) => l.toLowerCase())
53
+ .filter((l) => VALID_LOG_LEVELS.has(l));
54
+ if (requested.length > 0) {
55
+ levelFilter = new Set(requested);
56
+ }
57
+ // If no recognized levels, levelFilter stays null → all entries pass through
58
+ }
59
+ // Parse since timestamp; ignore if unparseable
60
+ let sinceMs = null;
61
+ if (since !== undefined && since !== null && since !== '') {
62
+ const parsed = Date.parse(since);
63
+ if (!Number.isNaN(parsed)) {
64
+ sinceMs = parsed;
65
+ }
66
+ }
67
+ return withToolError('get recent logs', async () => {
68
+ const response = await diagnosticsClient.getRecentLogs();
69
+ let entries = response.logs;
70
+ // Apply level filter
71
+ if (levelFilter !== null) {
72
+ entries = entries.filter((entry) => levelFilter?.has(entry.level.toLowerCase()));
73
+ }
74
+ // Apply since filter
75
+ if (sinceMs !== null) {
76
+ const sinceThreshold = sinceMs;
77
+ entries = entries.filter((entry) => {
78
+ const entryMs = Date.parse(entry.timestamp);
79
+ return !Number.isNaN(entryMs) && entryMs >= sinceThreshold;
80
+ });
81
+ }
82
+ // Apply limit
83
+ entries = entries.slice(0, effectiveLimit);
84
+ const logEntries = entries
85
+ .map((entry) => `[${entry.timestamp}] **${entry.level.toUpperCase()}** ${entry.message}`)
86
+ .join('\n');
87
+ const levelLabel = level ? (Array.isArray(level) ? level.join(', ') : level) : 'All levels';
88
+ return {
89
+ content: [
90
+ {
91
+ type: 'text',
92
+ text: `📋 **Recent Log Entries**
93
+ **Filter:** ${levelLabel}
94
+ **Limit:** ${effectiveLimit}
95
+ **Since:** ${since || 'Beginning'}
96
+
97
+ ${logEntries || 'No log entries found.'}`,
98
+ },
99
+ ],
100
+ };
101
+ });
102
+ }
103
+ /**
104
+ * Resolves a caller-supplied level string to a level the search endpoint accepts.
105
+ *
106
+ * The tool schema advertises `debug`, which has no counterpart in the log
107
+ * entry level enum; such values are dropped rather than sent upstream.
108
+ *
109
+ * @returns the normalized level, or `undefined` when unsupported/absent
110
+ */
111
+ function resolveSearchLevel(level) {
112
+ if (typeof level !== 'string' || level === '') {
113
+ return undefined;
114
+ }
115
+ const parsed = LogEntrySchema.shape.level.safeParse(level.toLowerCase());
116
+ return parsed.success ? parsed.data : undefined;
117
+ }
118
+ /**
119
+ * Handles log search requests
120
+ *
121
+ * `searchLogs()` resolves to a `LogSearchResponse` object; matched entries live
122
+ * under `response.logs` and the upstream match count under `response.matches`.
123
+ *
124
+ * - `level`: forwarded to the search request when it names a real log level
125
+ * - `limit`: applied to the rendered entries (default 50, hard cap 1000); it
126
+ * does not shrink the reported `matches` total
127
+ */
128
+ export async function handleSearchLogs(args, diagnosticsClient) {
129
+ const { query, level, limit } = args;
130
+ if (!query || typeof query !== 'string') {
131
+ throw new McpError(ErrorCode.InvalidParams, 'Query is required and must be a string');
132
+ }
133
+ const searchLevel = resolveSearchLevel(level);
134
+ const effectiveLimit = Math.min(Math.max(1, limit ?? DEFAULT_SEARCH_LIMIT), MAX_LOG_LIMIT);
135
+ let levelLabel = 'All levels';
136
+ if (searchLevel !== undefined) {
137
+ levelLabel = searchLevel;
138
+ }
139
+ else if (level) {
140
+ levelLabel = `${level} (unsupported — not applied)`;
141
+ }
142
+ return withToolError('search logs', async () => {
143
+ const response = await diagnosticsClient.searchLogs({
144
+ pattern: query,
145
+ ...(searchLevel !== undefined ? { level: searchLevel } : {}),
146
+ });
147
+ const shown = response.logs.slice(0, effectiveLimit);
148
+ const logEntries = shown
149
+ .map((entry) => `[${entry.timestamp}] **${entry.level.toUpperCase()}** ${entry.message}`)
150
+ .join('\n');
151
+ return {
152
+ content: [
153
+ {
154
+ type: 'text',
155
+ text: `🔍 **Log Search Results**
156
+ **Query:** "${query}"
157
+ **Level Filter:** ${levelLabel}
158
+ **Limit:** ${effectiveLimit}
159
+ **Timeframe:** ${response.searchTimeframe}
160
+ **Matches:** ${response.matches}
161
+ **Showing:** ${shown.length}
162
+
163
+ ${logEntries || 'No matching log entries found.'}`,
164
+ },
165
+ ],
166
+ };
167
+ });
168
+ }
169
+ /**
170
+ * Formats an uptime in seconds as a compact human-readable duration
171
+ */
172
+ function formatUptime(seconds) {
173
+ const total = Math.max(0, Math.floor(seconds));
174
+ const hours = Math.floor(total / 3600);
175
+ const minutes = Math.floor((total % 3600) / 60);
176
+ if (hours > 0) {
177
+ return `${hours}h ${minutes}m`;
178
+ }
179
+ if (minutes > 0) {
180
+ return `${minutes}m ${total % 60}s`;
181
+ }
182
+ return `${total}s`;
183
+ }
184
+ /**
185
+ * Formats a byte count (as reported by `process.memoryUsage()`) in binary
186
+ * megabytes (MiB, the unit Node.js tooling conventionally labels "MB")
187
+ */
188
+ function formatMegabytes(bytes) {
189
+ return `${Math.round(bytes / (1024 * 1024))} MB`;
190
+ }
191
+ /**
192
+ * Handles system health requests
193
+ *
194
+ * Every value rendered here is a field `SystemHealthSchema` actually declares.
195
+ * The schema strips unknown keys, so metrics it does not model (CPU, disk,
196
+ * response time, throughput) cannot be reported and are deliberately absent
197
+ * rather than rendered as a permanent `N/A`. Optional fields (`server.uptime`,
198
+ * `performance.memory`) are omitted when the server does not supply them.
199
+ */
200
+ export async function handleGetSystemHealth(_args, diagnosticsClient) {
201
+ return withToolError('get system health', async () => {
202
+ const health = await diagnosticsClient.getSystemHealth();
203
+ const { server, users, modules, performance, logs } = health;
204
+ const serverLines = [
205
+ `- **FoundryVTT Version:** ${server.foundryVersion}`,
206
+ `- **Game System:** ${server.systemVersion}`,
207
+ `- **World:** ${server.worldId}`,
208
+ ];
209
+ if (server.uptime !== undefined) {
210
+ serverLines.push(`- **Uptime:** ${formatUptime(server.uptime)}`);
211
+ }
212
+ const performanceLines = [`- **Connected Clients:** ${performance.connectedClients}`];
213
+ if (performance.memory) {
214
+ performanceLines.push(`- **Memory (heap):** ${formatMegabytes(performance.memory.heapUsed)} used / ${formatMegabytes(performance.memory.heapTotal)} total`, `- **Memory (RSS):** ${formatMegabytes(performance.memory.rss)}`);
215
+ }
216
+ return {
217
+ content: [
218
+ {
219
+ type: 'text',
220
+ text: `🏥 **System Health Status**
221
+ **Overall Status:** ${health.status}
222
+ **Reported At:** ${health.timestamp}
223
+
224
+ **Server:**
225
+ ${serverLines.join('\n')}
226
+
227
+ **Sessions:**
228
+ - **Users:** ${users.active} active / ${users.total} total (${users.gm} GM)
229
+ - **Modules:** ${modules.active} active / ${modules.total} installed
230
+
231
+ **Performance:**
232
+ ${performanceLines.join('\n')}
233
+
234
+ **Logs:**
235
+ - **Buffer:** ${logs.bufferSize} entries
236
+ - **Recent Errors:** ${logs.recentErrors}
237
+ - **Recent Warnings:** ${logs.recentWarnings}
238
+ - **Error Rate:** ${logs.errorRate}%`,
239
+ },
240
+ ],
241
+ };
242
+ });
243
+ }
244
+ /**
245
+ * Handles error diagnosis requests via the REST API module.
246
+ */
247
+ export async function handleDiagnoseErrors(args, diagnosticsClient) {
248
+ const { category, timeframe = 3600 } = args;
249
+ return withToolError('diagnose errors', async () => {
250
+ const diagnosis = await diagnosticsClient.diagnoseErrors(timeframe);
251
+ const categoriesEntries = Object.entries(diagnosis.summary?.categories ?? {});
252
+ const filteredCategories = category
253
+ ? categoriesEntries.filter(([cat]) => cat.toLowerCase() === category.toLowerCase())
254
+ : categoriesEntries;
255
+ const categoryLines = filteredCategories.length > 0
256
+ ? filteredCategories.map(([cat, count]) => `- **${cat}:** ${count} error(s)`).join('\n')
257
+ : 'No categorized errors recorded.';
258
+ const priorityOrder = { critical: 4, high: 3, medium: 2, low: 1 };
259
+ const sortedSuggestions = [...(diagnosis.suggestions ?? [])].sort((a, b) => (priorityOrder[b.priority] ?? 0) - (priorityOrder[a.priority] ?? 0));
260
+ const suggestionLines = sortedSuggestions.length > 0
261
+ ? sortedSuggestions
262
+ .map((s) => `- [${s.priority.toUpperCase()}] **${s.category}:** ${s.suggestion}`)
263
+ .join('\n')
264
+ : 'No specific recommendations.';
265
+ const recentErrors = (diagnosis.recentErrors ?? []).slice(-10);
266
+ const errorLines = recentErrors.length > 0
267
+ ? recentErrors
268
+ .map((e) => `- \`[${e.timestamp}]\` [${e.level.toUpperCase()}] ${e.message}`)
269
+ .join('\n')
270
+ : 'No recent error logs.';
271
+ return {
272
+ content: [
273
+ {
274
+ type: 'text',
275
+ text: `🔧 **Error Diagnosis**
276
+ **Timeframe:** Last ${timeframe}s
277
+ **Health Score:** ${diagnosis.healthScore}/100
278
+ **Total Errors:** ${diagnosis.summary?.totalErrors ?? 0}, **Unique:** ${diagnosis.summary?.uniqueErrors ?? 0}
279
+
280
+ **Errors by Category:**
281
+ ${categoryLines}
282
+
283
+ **Recommendations:**
284
+ ${suggestionLines}
285
+
286
+ **Recent Errors:**
287
+ ${errorLines}`,
288
+ },
289
+ ],
290
+ };
291
+ });
292
+ }
293
+ /**
294
+ * Where the local copy of an overwritten page is: its path, "(copy missing)"
295
+ * after it when the file is gone (the list outlives restarts, the folder may
296
+ * have been cleaned), or "none" when no copy could be written.
297
+ */
298
+ function describeCopy(historyPath) {
299
+ if (historyPath === null) {
300
+ return 'none';
301
+ }
302
+ return existsSync(historyPath) ? historyPath : `${historyPath} (copy missing)`;
303
+ }
304
+ /**
305
+ * Handles comprehensive health status requests
306
+ *
307
+ * The system-health section reads the nested fields `SystemHealthSchema`
308
+ * declares. Playtime is not reported: `getWorldInfo()` has no genuine source
309
+ * for it and hard-codes 0.
310
+ *
311
+ * The world section carries {@link STALE_WORLD_DATA_NOTICE} whenever the cache
312
+ * has stopped following live document changes (laurigates/foundryvtt-mcp#217). Reads keep being served
313
+ * from that snapshot, which is the right call — a flagged answer beats no
314
+ * answer — but rendering it bare presents a point-in-time copy as though it
315
+ * were live. It matters most right after an automatic reconnect, where the
316
+ * connection line legitimately reads "✅ Connected" while the cache is still
317
+ * missing every broadcast the outage swallowed.
318
+ */
319
+ export async function handleGetHealthStatus(_args, foundryClient, diagnosticsClient, moduleBridge = null, headlessGmSession = null, runtime = {}) {
320
+ return withToolError('get health status', async () => {
321
+ let systemHealthUnavailable = 'ℹ️ Not available';
322
+ const [worldInfo, systemHealth] = await Promise.all([
323
+ foundryClient.getWorldInfo().catch(() => null),
324
+ diagnosticsClient.getSystemHealth().catch((error) => {
325
+ if (error instanceof RestApiRequiredError) {
326
+ systemHealthUnavailable = `ℹ️ ${error.message}`;
327
+ }
328
+ return null;
329
+ }),
330
+ ]);
331
+ const worldLines = worldInfo
332
+ ? [
333
+ `- **Title:** ${worldInfo.title}`,
334
+ `- **System:** ${worldInfo.system}`,
335
+ `- **Core Version:** ${worldInfo.coreVersion}`,
336
+ ]
337
+ : ['ℹ️ Not available'];
338
+ if (foundryClient.isWorldDataStale()) {
339
+ worldLines.unshift(STALE_WORLD_DATA_NOTICE);
340
+ }
341
+ let healthSection = systemHealthUnavailable;
342
+ if (systemHealth) {
343
+ const healthLines = [
344
+ `- **Status:** ${systemHealth.status}`,
345
+ `- **Users:** ${systemHealth.users.active} active / ${systemHealth.users.total} total`,
346
+ ];
347
+ if (systemHealth.server.uptime !== undefined) {
348
+ healthLines.push(`- **Uptime:** ${formatUptime(systemHealth.server.uptime)}`);
349
+ }
350
+ if (systemHealth.performance.memory) {
351
+ healthLines.push(`- **Memory (heap used):** ${formatMegabytes(systemHealth.performance.memory.heapUsed)}`);
352
+ }
353
+ healthLines.push(`- **Recent Errors:** ${systemHealth.logs.recentErrors} (warnings: ${systemHealth.logs.recentWarnings})`);
354
+ healthSection = `\n${healthLines.join('\n')}`;
355
+ }
356
+ // Only rendered when the bridge is configured at all — most setups run
357
+ // without it, and a permanent "not connected" line for a feature nobody
358
+ // opted into would just be noise.
359
+ let moduleBridgeSection = null;
360
+ if (runtime.bridgeState === 'failed') {
361
+ moduleBridgeSection = `❌ Failed to start — ${runtime.bridgeError ?? 'see the log'}`;
362
+ }
363
+ else if (runtime.bridgeState === 'not-started') {
364
+ moduleBridgeSection = foundryClient.isConnected()
365
+ ? '⏳ Not started yet'
366
+ : '⏸️ Not started — it starts once the FoundryVTT connection is up';
367
+ }
368
+ else if (moduleBridge) {
369
+ if (moduleBridge.isConnected()) {
370
+ moduleBridgeSection = `✅ Connected — authenticated module (protocol v${BRIDGE_PROTOCOL_VERSION})`;
371
+ }
372
+ else if (headlessGmSession) {
373
+ moduleBridgeSection = `❌ Not connected — no authenticated module (protocol v${BRIDGE_PROTOCOL_VERSION}); see the headless GM session below`;
374
+ }
375
+ else if (runtime.headlessLaunchError) {
376
+ moduleBridgeSection =
377
+ '❌ Not connected — the companion module only connects from the headless GM session, ' +
378
+ `whose browser could not be launched:\n- **Headless GM session:** ❌ ${runtime.headlessLaunchError}`;
379
+ }
380
+ else {
381
+ moduleBridgeSection =
382
+ '❌ Not connected — the companion module only connects from the headless GM session, ' +
383
+ 'which is not running. Set FOUNDRY_HEADLESS_GM_ENABLED=true with ' +
384
+ 'FOUNDRY_USERNAME/FOUNDRY_PASSWORD (a manually opened GM tab is no longer supported).';
385
+ }
386
+ }
387
+ const browser = headlessGmSession?.browserInfo();
388
+ const headlessSection = headlessGmSession
389
+ ? `\n\n**Headless GM Session:**\n${headlessGmSession.statusText()}${browser ? `\n- **Browser:** ${describeBrowser(browser)}` : ''}`
390
+ : '';
391
+ const account = foundryClient.accountInfo();
392
+ let accountSection = '';
393
+ if (account) {
394
+ const activeGm = foundryClient.activeGameMaster();
395
+ const accountLines = [
396
+ `- **Name:** ${account.name}${account.role === null ? '' : ` (${roleLabel(account.role)})`}`,
397
+ `- **Active GM (as FoundryVTT's clients elect it):** ${activeGm ? `${activeGm.name} (${roleLabel(activeGm.role)})` : 'none connected'}`,
398
+ ];
399
+ const warning = gamemasterAccountWarning(runtime.sharedAccount === true, account);
400
+ if (warning) {
401
+ accountLines.push(`⚠️ ${warning}`);
402
+ }
403
+ accountSection = `\n\n**Connector Account:**\n${accountLines.join('\n')}`;
404
+ }
405
+ let connectionLine = '✅ Connected';
406
+ if (!foundryClient.isConnected()) {
407
+ const { state, error } = foundryClient.connectionStatus();
408
+ connectionLine =
409
+ foundryClient.isReconnecting() && state !== 'disconnected'
410
+ ? `❌ Disconnected — ${state}${error ? `: ${error}` : ''} (retrying on its own)`
411
+ : `❌ Disconnected${error ? ` — ${error}` : ''}`;
412
+ }
413
+ const conflicts = foundryClient.getRecentJournalConflicts();
414
+ const journalSection = conflicts.length === 0
415
+ ? '✅ No overwrite detected in the last 24 hours'
416
+ : [
417
+ `⚠️ ${conflicts.length} overwrite(s) detected in the last 24 hours:`,
418
+ ...conflicts.map((c) => `- ${new Date(c.at).toISOString()} — "${c.pageName}" of "${c.journalName}" ` +
419
+ `(${c.journalId}/${c.pageId}), ${c.reason}; copy: ${describeCopy(c.historyPath)}`),
420
+ ].join('\n');
421
+ return {
422
+ content: [
423
+ {
424
+ type: 'text',
425
+ text: `\u{1FA7A} **Comprehensive Health Status**
426
+
427
+ **FoundryVTT Connection:**
428
+ ${connectionLine}${accountSection}
429
+
430
+ **World Information:**
431
+ ${worldLines.join('\n')}
432
+
433
+ **System Health:**
434
+ ${healthSection}${moduleBridgeSection ? `\n\n**Module Bridge:**\n${moduleBridgeSection}` : ''}${headlessSection}${runtime.relays ? `\n\n**Shared Process:**\n${sharedProcessSection(runtime.relays)}` : ''}
435
+
436
+ **Configuration:**
437
+ ${runtime.configuration
438
+ ? `- **File:** ${runtime.configuration.file}
439
+ - **Settings:** ${runtime.configuration.sources}`
440
+ : 'ℹ️ Not available'}
441
+
442
+ **Journal Integrity:**
443
+ ${journalSection}
444
+ - **Local copies:** ${foundryClient.getJournalHistoryDir()}`,
445
+ },
446
+ ],
447
+ };
448
+ });
449
+ }
450
+ //# sourceMappingURL=diagnostics.js.map
@@ -0,0 +1,54 @@
1
+ /**
2
+ * @fileoverview Dice rolling tool handlers
3
+ *
4
+ * Handles dice rolling operations using FoundryVTT's dice system
5
+ * or fallback mechanisms when the API is unavailable.
6
+ */
7
+ import { logger } from '../../utils/logger.js';
8
+ // import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
9
+ import { BaseTool } from '../base.js';
10
+ import { ROLL_DICE_DESCRIPTION } from '../definitions.js';
11
+ /**
12
+ * Dice rolling tool implementation
13
+ */
14
+ export class RollDiceTool extends BaseTool {
15
+ name = 'roll_dice';
16
+ description = ROLL_DICE_DESCRIPTION;
17
+ inputSchema = {
18
+ type: 'object',
19
+ properties: {
20
+ formula: {
21
+ type: 'string',
22
+ description: 'Dice formula (e.g., "1d20+5", "3d6")',
23
+ },
24
+ reason: {
25
+ type: 'string',
26
+ description: 'Optional reason for the roll',
27
+ },
28
+ },
29
+ required: ['formula'],
30
+ };
31
+ async executeValidated(args, context) {
32
+ const { formula, reason } = args;
33
+ logger.info(`Rolling dice: ${formula}${reason ? ` (${reason})` : ''}`);
34
+ const result = await context.foundryClient.rollDice(formula, reason);
35
+ return this.createTextResponse(`🎲 **Dice Roll Result**
36
+ **Formula:** ${result.formula}
37
+ **Total:** ${result.total}
38
+ **Breakdown:** ${result.breakdown}
39
+ ${result.reason ? `**Reason:** ${result.reason}` : ''}
40
+ **Timestamp:** ${result.timestamp}`);
41
+ }
42
+ }
43
+ /**
44
+ * Legacy function for backward compatibility
45
+ * @deprecated Use RollDiceTool class instead
46
+ */
47
+ export async function handleRollDice(args, foundryClient) {
48
+ const tool = new RollDiceTool();
49
+ const context = {
50
+ foundryClient,
51
+ };
52
+ return tool.execute(args, context);
53
+ }
54
+ //# sourceMappingURL=dice.js.map