@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.
- package/LICENSE +22 -0
- package/README.md +468 -2
- package/dist/character/manager.js +208 -0
- package/dist/cli/checks.js +307 -0
- package/dist/cli/config-file.js +120 -0
- package/dist/cli/init.js +410 -0
- package/dist/cli/prompt.js +117 -0
- package/dist/cli/snippets.js +49 -0
- package/dist/combat/manager.js +371 -0
- package/dist/config/env-layers.js +49 -0
- package/dist/config/index.js +298 -0
- package/dist/config/sources.js +201 -0
- package/dist/core.js +415 -0
- package/dist/diagnostics/client.js +353 -0
- package/dist/diagnostics/types.js +94 -0
- package/dist/foundry/auth.js +220 -0
- package/dist/foundry/browser-detect.js +170 -0
- package/dist/foundry/client.js +5555 -0
- package/dist/foundry/dice-formula.js +154 -0
- package/dist/foundry/event-log.js +299 -0
- package/dist/foundry/headless-gm-session.js +740 -0
- package/dist/foundry/journal-history.js +90 -0
- package/dist/foundry/journal-integrity.js +306 -0
- package/dist/foundry/module-bridge.js +413 -0
- package/dist/foundry/types.js +52 -0
- package/dist/foundry/world-cache.js +386 -0
- package/dist/index.js +107 -0
- package/dist/mcp-server.js +63 -0
- package/dist/server.js +159 -0
- package/dist/shared/build-order.js +134 -0
- package/dist/shared/config-hash.js +62 -0
- package/dist/shared/config-notice.js +55 -0
- package/dist/shared/control.js +255 -0
- package/dist/shared/daemon-link.js +135 -0
- package/dist/shared/daemon.js +313 -0
- package/dist/shared/ipc-client.js +200 -0
- package/dist/shared/ipc-server.js +316 -0
- package/dist/shared/paths.js +79 -0
- package/dist/shared/protocol.js +230 -0
- package/dist/shared/relay-config.js +65 -0
- package/dist/shared/relay.js +120 -0
- package/dist/shared/rotating-log.js +57 -0
- package/dist/shared/spawn.js +39 -0
- package/dist/shared/state-file.js +33 -0
- package/dist/shared/token.js +62 -0
- package/dist/shared/version.js +57 -0
- package/dist/tools/base.js +74 -0
- package/dist/tools/definitions.js +3109 -0
- package/dist/tools/handlers/actor-mutations.js +128 -0
- package/dist/tools/handlers/actors.js +114 -0
- package/dist/tools/handlers/chat-mutations.js +49 -0
- package/dist/tools/handlers/chat.js +36 -0
- package/dist/tools/handlers/combat-mutations.js +215 -0
- package/dist/tools/handlers/combat-order.js +94 -0
- package/dist/tools/handlers/combat.js +51 -0
- package/dist/tools/handlers/compendium.js +83 -0
- package/dist/tools/handlers/diagnostics.js +438 -0
- package/dist/tools/handlers/dice.js +54 -0
- package/dist/tools/handlers/effects.js +103 -0
- package/dist/tools/handlers/events.js +50 -0
- package/dist/tools/handlers/generation.js +258 -0
- package/dist/tools/handlers/item-mutations.js +132 -0
- package/dist/tools/handlers/items.js +53 -0
- package/dist/tools/handlers/journal-mutations.js +230 -0
- package/dist/tools/handlers/journals.js +80 -0
- package/dist/tools/handlers/module-bridge.js +421 -0
- package/dist/tools/handlers/placeable-mutations.js +272 -0
- package/dist/tools/handlers/resources.js +203 -0
- package/dist/tools/handlers/roll-tables.js +97 -0
- package/dist/tools/handlers/scene-mutations.js +159 -0
- package/dist/tools/handlers/scenes.js +355 -0
- package/dist/tools/handlers/settings.js +53 -0
- package/dist/tools/handlers/tile-mutations.js +56 -0
- package/dist/tools/handlers/token-mutations.js +356 -0
- package/dist/tools/handlers/users.js +59 -0
- package/dist/tools/handlers/utils.js +47 -0
- package/dist/tools/handlers/wall-mutations.js +98 -0
- package/dist/tools/handlers/world-documents.js +222 -0
- package/dist/tools/handlers/world.js +92 -0
- package/dist/tools/index.js +25 -0
- package/dist/tools/new-router.js +97 -0
- package/dist/tools/registry.js +79 -0
- package/dist/tools/resources.js +63 -0
- package/dist/tools/router.js +688 -0
- package/dist/tools/write-tools.js +97 -0
- package/dist/utils/cache-instance.js +30 -0
- package/dist/utils/cache.js +205 -0
- package/dist/utils/diagnostics.js +332 -0
- package/dist/utils/guards.js +17 -0
- package/dist/utils/image-size.js +160 -0
- package/dist/utils/log-args.js +47 -0
- package/dist/utils/logger.js +203 -0
- package/dist/utils/refusal.js +30 -0
- package/dist/utils/sanitize.js +22 -0
- package/dist/utils/serial-queue.js +22 -0
- package/package.json +124 -4
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview DiagnosticsClient for accessing FoundryVTT logs and system health
|
|
3
|
+
*
|
|
4
|
+
* This module provides a client interface for accessing diagnostic information
|
|
5
|
+
* from FoundryVTT through the REST API module's diagnostic endpoints.
|
|
6
|
+
*
|
|
7
|
+
* @version 0.1.0
|
|
8
|
+
* @author FoundryVTT MCP Team
|
|
9
|
+
*/
|
|
10
|
+
import { logger } from '../utils/logger.js';
|
|
11
|
+
import { RefusedError } from '../utils/refusal.js';
|
|
12
|
+
import { ErrorDiagnosisSchema, LogResponseSchema, LogSearchResponseSchema, SystemHealthSchema, } from './types.js';
|
|
13
|
+
/** HTTP status of an axios error, if it carries a response. */
|
|
14
|
+
function httpStatus(error) {
|
|
15
|
+
if (typeof error !== 'object' || error === null || !('response' in error)) {
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
const { response } = error;
|
|
19
|
+
return typeof response === 'object' &&
|
|
20
|
+
response !== null &&
|
|
21
|
+
'status' in response &&
|
|
22
|
+
typeof response.status === 'number'
|
|
23
|
+
? response.status
|
|
24
|
+
: undefined;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* System health comes from the REST API module only. Without `FOUNDRY_API_KEY`
|
|
28
|
+
* (or with a module that lacks the endpoint) asking for it is not a failure:
|
|
29
|
+
* an expected refusal, logged as one warning line at most.
|
|
30
|
+
*/
|
|
31
|
+
export class RestApiRequiredError extends RefusedError {
|
|
32
|
+
name = 'RestApiRequiredError';
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Client for accessing FoundryVTT diagnostic and logging information
|
|
36
|
+
*
|
|
37
|
+
* Provides methods to retrieve logs, search for specific patterns,
|
|
38
|
+
* monitor system health, and analyze errors through the REST API.
|
|
39
|
+
*
|
|
40
|
+
* @class DiagnosticsClient
|
|
41
|
+
* @example
|
|
42
|
+
* ```typescript
|
|
43
|
+
* const diagnostics = new DiagnosticsClient(foundryClient);
|
|
44
|
+
*
|
|
45
|
+
* // Get recent errors
|
|
46
|
+
* const errors = await diagnostics.getRecentLogs({ level: 'error', lines: 20 });
|
|
47
|
+
*
|
|
48
|
+
* // Search for specific patterns
|
|
49
|
+
* const matches = await diagnostics.searchLogs({ pattern: 'TypeError', timeframe: '3600' });
|
|
50
|
+
*
|
|
51
|
+
* // Check system health
|
|
52
|
+
* const health = await diagnostics.getSystemHealth();
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
export class DiagnosticsClient {
|
|
56
|
+
foundryClient;
|
|
57
|
+
/**
|
|
58
|
+
* Create a new DiagnosticsClient instance
|
|
59
|
+
*
|
|
60
|
+
* @param foundryClient - The FoundryClient instance to use for API calls
|
|
61
|
+
*/
|
|
62
|
+
/** The health endpoint answered 404 once already: warned, not again. */
|
|
63
|
+
healthEndpointMissingWarned = false;
|
|
64
|
+
constructor(foundryClient) {
|
|
65
|
+
this.foundryClient = foundryClient;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Get recent log entries with optional filtering
|
|
69
|
+
*
|
|
70
|
+
* @param params - Search parameters for filtering logs
|
|
71
|
+
* @returns Promise resolving to log response with entries and metadata
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```typescript
|
|
75
|
+
* // Get last 50 log entries
|
|
76
|
+
* const logs = await diagnostics.getRecentLogs();
|
|
77
|
+
*
|
|
78
|
+
* // Get only error logs from the last hour
|
|
79
|
+
* const errors = await diagnostics.getRecentLogs({
|
|
80
|
+
* level: 'error',
|
|
81
|
+
* since: new Date(Date.now() - 3600000).toISOString()
|
|
82
|
+
* });
|
|
83
|
+
*
|
|
84
|
+
* // Get logs with stack traces included
|
|
85
|
+
* const detailed = await diagnostics.getRecentLogs({
|
|
86
|
+
* lines: 100,
|
|
87
|
+
* includeStack: true
|
|
88
|
+
* });
|
|
89
|
+
* ```
|
|
90
|
+
*/
|
|
91
|
+
async getRecentLogs(params = {}) {
|
|
92
|
+
try {
|
|
93
|
+
logger.debug('DiagnosticsClient | Getting recent logs', params);
|
|
94
|
+
const searchParams = new URLSearchParams();
|
|
95
|
+
if (params.lines !== undefined) {
|
|
96
|
+
searchParams.set('lines', params.lines.toString());
|
|
97
|
+
}
|
|
98
|
+
if (params.level) {
|
|
99
|
+
searchParams.set('level', params.level);
|
|
100
|
+
}
|
|
101
|
+
if (params.since) {
|
|
102
|
+
searchParams.set('since', params.since);
|
|
103
|
+
}
|
|
104
|
+
if (params.source) {
|
|
105
|
+
searchParams.set('source', params.source);
|
|
106
|
+
}
|
|
107
|
+
if (params.includeStack !== undefined) {
|
|
108
|
+
searchParams.set('includeStack', params.includeStack.toString());
|
|
109
|
+
}
|
|
110
|
+
const queryString = searchParams.toString();
|
|
111
|
+
const url = `/api/diagnostics/logs${queryString ? `?${queryString}` : ''}`;
|
|
112
|
+
const response = await this.foundryClient.get(url);
|
|
113
|
+
const parsed = LogResponseSchema.parse(response.data);
|
|
114
|
+
logger.debug('DiagnosticsClient | Retrieved logs', {
|
|
115
|
+
count: parsed.total,
|
|
116
|
+
bufferSize: parsed.bufferSize,
|
|
117
|
+
});
|
|
118
|
+
return parsed;
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
logger.error('DiagnosticsClient | Failed to get recent logs:', error);
|
|
122
|
+
throw new Error(`Failed to retrieve recent logs: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Search log entries for specific patterns using regular expressions
|
|
127
|
+
*
|
|
128
|
+
* @param params - Search parameters including pattern and filters
|
|
129
|
+
* @returns Promise resolving to matching log entries
|
|
130
|
+
*
|
|
131
|
+
* @example
|
|
132
|
+
* ```typescript
|
|
133
|
+
* // Search for any TypeError occurrences
|
|
134
|
+
* const typeErrors = await diagnostics.searchLogs({
|
|
135
|
+
* pattern: 'TypeError'
|
|
136
|
+
* });
|
|
137
|
+
*
|
|
138
|
+
* // Search for network errors in the last hour
|
|
139
|
+
* const networkErrors = await diagnostics.searchLogs({
|
|
140
|
+
* pattern: 'Failed to fetch|Network Error',
|
|
141
|
+
* timeframe: '3600',
|
|
142
|
+
* level: 'error'
|
|
143
|
+
* });
|
|
144
|
+
*
|
|
145
|
+
* // Case-sensitive search for specific module errors
|
|
146
|
+
* const moduleErrors = await diagnostics.searchLogs({
|
|
147
|
+
* pattern: 'Module.*failed',
|
|
148
|
+
* caseSensitive: true
|
|
149
|
+
* });
|
|
150
|
+
* ```
|
|
151
|
+
*/
|
|
152
|
+
async searchLogs(params) {
|
|
153
|
+
try {
|
|
154
|
+
logger.debug('DiagnosticsClient | Searching logs', params);
|
|
155
|
+
const searchParams = new URLSearchParams();
|
|
156
|
+
searchParams.set('pattern', params.pattern);
|
|
157
|
+
if (params.timeframe) {
|
|
158
|
+
searchParams.set('timeframe', params.timeframe);
|
|
159
|
+
}
|
|
160
|
+
if (params.level) {
|
|
161
|
+
searchParams.set('level', params.level);
|
|
162
|
+
}
|
|
163
|
+
if (params.caseSensitive !== undefined) {
|
|
164
|
+
searchParams.set('caseSensitive', params.caseSensitive.toString());
|
|
165
|
+
}
|
|
166
|
+
const url = `/api/diagnostics/search?${searchParams.toString()}`;
|
|
167
|
+
const response = await this.foundryClient.get(url);
|
|
168
|
+
const parsed = LogSearchResponseSchema.parse(response.data);
|
|
169
|
+
logger.debug('DiagnosticsClient | Search completed', {
|
|
170
|
+
pattern: params.pattern,
|
|
171
|
+
matches: parsed.matches,
|
|
172
|
+
});
|
|
173
|
+
return parsed;
|
|
174
|
+
}
|
|
175
|
+
catch (error) {
|
|
176
|
+
logger.error('DiagnosticsClient | Failed to search logs:', error);
|
|
177
|
+
throw new Error(`Failed to search logs: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Get comprehensive system health and performance metrics
|
|
182
|
+
*
|
|
183
|
+
* @returns Promise resolving to complete system health information
|
|
184
|
+
*
|
|
185
|
+
* @example
|
|
186
|
+
* ```typescript
|
|
187
|
+
* const health = await diagnostics.getSystemHealth();
|
|
188
|
+
*
|
|
189
|
+
* console.log(`Server status: ${health.status}`);
|
|
190
|
+
* console.log(`Active users: ${health.users.active}/${health.users.total}`);
|
|
191
|
+
* console.log(`Recent errors: ${health.logs.recentErrors}`);
|
|
192
|
+
*
|
|
193
|
+
* if (health.status === 'critical') {
|
|
194
|
+
* console.warn('Server requires immediate attention!');
|
|
195
|
+
* }
|
|
196
|
+
* ```
|
|
197
|
+
*/
|
|
198
|
+
async getSystemHealth() {
|
|
199
|
+
if (!this.foundryClient.hasRestApi()) {
|
|
200
|
+
throw new RestApiRequiredError('System health requires the REST API module (FOUNDRY_API_KEY is not set)');
|
|
201
|
+
}
|
|
202
|
+
try {
|
|
203
|
+
logger.debug('DiagnosticsClient | Getting system health');
|
|
204
|
+
const response = await this.foundryClient.get('/api/diagnostics/health');
|
|
205
|
+
const parsed = SystemHealthSchema.parse(response.data);
|
|
206
|
+
logger.debug('DiagnosticsClient | System health retrieved', {
|
|
207
|
+
status: parsed.status,
|
|
208
|
+
activeUsers: parsed.users?.active,
|
|
209
|
+
recentErrors: parsed.logs?.recentErrors,
|
|
210
|
+
});
|
|
211
|
+
return parsed;
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
if (httpStatus(error) === 404) {
|
|
215
|
+
if (!this.healthEndpointMissingWarned) {
|
|
216
|
+
this.healthEndpointMissingWarned = true;
|
|
217
|
+
logger.warn('DiagnosticsClient | The REST API module does not provide /api/diagnostics/health (HTTP 404); system health is unavailable');
|
|
218
|
+
}
|
|
219
|
+
throw new RestApiRequiredError('System health is unavailable: the REST API module does not provide /api/diagnostics/health (HTTP 404)');
|
|
220
|
+
}
|
|
221
|
+
logger.error('DiagnosticsClient | Failed to get system health:', error);
|
|
222
|
+
throw new Error(`Failed to retrieve system health: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Analyze recent errors and get diagnostic suggestions
|
|
227
|
+
*
|
|
228
|
+
* @param timeframe - Time window in seconds to analyze (default: 3600)
|
|
229
|
+
* @returns Promise resolving to error diagnosis with suggestions
|
|
230
|
+
*
|
|
231
|
+
* @example
|
|
232
|
+
* ```typescript
|
|
233
|
+
* // Analyze errors from the last hour
|
|
234
|
+
* const diagnosis = await diagnostics.diagnoseErrors();
|
|
235
|
+
*
|
|
236
|
+
* // Analyze errors from the last 30 minutes
|
|
237
|
+
* const recentDiagnosis = await diagnostics.diagnoseErrors(1800);
|
|
238
|
+
*
|
|
239
|
+
* console.log(`Health score: ${diagnosis.healthScore}/100`);
|
|
240
|
+
* console.log(`Total errors: ${diagnosis.summary.totalErrors}`);
|
|
241
|
+
*
|
|
242
|
+
* // Display suggestions
|
|
243
|
+
* diagnosis.suggestions.forEach(suggestion => {
|
|
244
|
+
* console.log(`${suggestion.priority.toUpperCase()}: ${suggestion.suggestion}`);
|
|
245
|
+
* });
|
|
246
|
+
* ```
|
|
247
|
+
*/
|
|
248
|
+
async diagnoseErrors(timeframe = 3600) {
|
|
249
|
+
try {
|
|
250
|
+
logger.debug('DiagnosticsClient | Diagnosing errors', { timeframe });
|
|
251
|
+
const searchParams = new URLSearchParams();
|
|
252
|
+
searchParams.set('timeframe', timeframe.toString());
|
|
253
|
+
const url = `/api/diagnostics/errors?${searchParams.toString()}`;
|
|
254
|
+
const response = await this.foundryClient.get(url);
|
|
255
|
+
const parsed = ErrorDiagnosisSchema.parse(response.data);
|
|
256
|
+
logger.debug('DiagnosticsClient | Error diagnosis completed', {
|
|
257
|
+
totalErrors: parsed.summary?.totalErrors,
|
|
258
|
+
healthScore: parsed.healthScore,
|
|
259
|
+
suggestionCount: parsed.suggestions?.length,
|
|
260
|
+
});
|
|
261
|
+
return parsed;
|
|
262
|
+
}
|
|
263
|
+
catch (error) {
|
|
264
|
+
logger.error('DiagnosticsClient | Failed to diagnose errors:', error);
|
|
265
|
+
throw new Error(`Failed to diagnose errors: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Get errors filtered by severity and time window
|
|
270
|
+
*
|
|
271
|
+
* @param timeframe - Time window in seconds (default: 3600)
|
|
272
|
+
* @param level - Log level to filter by (default: 'error')
|
|
273
|
+
* @returns Promise resolving to filtered log entries
|
|
274
|
+
*
|
|
275
|
+
* @example
|
|
276
|
+
* ```typescript
|
|
277
|
+
* // Get all errors from the last 2 hours
|
|
278
|
+
* const errors = await diagnostics.getErrorsOnly(7200);
|
|
279
|
+
*
|
|
280
|
+
* // Get warnings from the last 30 minutes
|
|
281
|
+
* const warnings = await diagnostics.getErrorsOnly(1800, 'warn');
|
|
282
|
+
* ```
|
|
283
|
+
*/
|
|
284
|
+
async getErrorsOnly(timeframe = 3600, level = 'error') {
|
|
285
|
+
try {
|
|
286
|
+
const since = new Date(Date.now() - timeframe * 1000).toISOString();
|
|
287
|
+
const response = await this.getRecentLogs({
|
|
288
|
+
level,
|
|
289
|
+
since,
|
|
290
|
+
lines: 1000, // Get a large number to ensure we capture all errors
|
|
291
|
+
includeStack: true,
|
|
292
|
+
});
|
|
293
|
+
return response.logs;
|
|
294
|
+
}
|
|
295
|
+
catch (error) {
|
|
296
|
+
logger.error('DiagnosticsClient | Failed to get errors only:', error);
|
|
297
|
+
throw new Error(`Failed to retrieve ${level} logs: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Monitor system health and return status summary
|
|
302
|
+
*
|
|
303
|
+
* Only the overall status: there is no numeric score behind it. The
|
|
304
|
+
* signature used to declare an optional `score` and the example used to show
|
|
305
|
+
* one, but nothing ever set it and {@link SystemHealth} has no such field —
|
|
306
|
+
* so a caller that read it got `undefined` from a documented field.
|
|
307
|
+
*
|
|
308
|
+
* @returns Promise resolving to the overall status, `'critical'` if health
|
|
309
|
+
* could not be retrieved at all
|
|
310
|
+
*
|
|
311
|
+
* @example
|
|
312
|
+
* ```typescript
|
|
313
|
+
* const status = await diagnostics.getHealthStatus();
|
|
314
|
+
* // Returns: { status: 'healthy' | 'warning' | 'critical' }
|
|
315
|
+
* ```
|
|
316
|
+
*/
|
|
317
|
+
async getHealthStatus() {
|
|
318
|
+
try {
|
|
319
|
+
const health = await this.getSystemHealth();
|
|
320
|
+
return {
|
|
321
|
+
status: health.status,
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
catch (error) {
|
|
325
|
+
logger.error('DiagnosticsClient | Failed to get health status:', error);
|
|
326
|
+
return { status: 'critical' };
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Check if diagnostics API is available
|
|
331
|
+
*
|
|
332
|
+
* @returns Promise resolving to boolean indicating availability
|
|
333
|
+
*
|
|
334
|
+
* @example
|
|
335
|
+
* ```typescript
|
|
336
|
+
* const available = await diagnostics.isAvailable();
|
|
337
|
+
* if (!available) {
|
|
338
|
+
* console.log('Diagnostics API not available - check module installation');
|
|
339
|
+
* }
|
|
340
|
+
* ```
|
|
341
|
+
*/
|
|
342
|
+
async isAvailable() {
|
|
343
|
+
try {
|
|
344
|
+
await this.foundryClient.get('/api/diagnostics/health');
|
|
345
|
+
return true;
|
|
346
|
+
}
|
|
347
|
+
catch (error) {
|
|
348
|
+
logger.debug('DiagnosticsClient | Diagnostics API not available:', error);
|
|
349
|
+
return false;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Type definitions for FoundryVTT diagnostics and logging
|
|
3
|
+
*
|
|
4
|
+
* This module provides TypeScript interfaces for log entries, system health metrics,
|
|
5
|
+
* and diagnostic data structures used by the MCP server for FoundryVTT monitoring.
|
|
6
|
+
*
|
|
7
|
+
* @version 0.1.0
|
|
8
|
+
* @author FoundryVTT MCP Team
|
|
9
|
+
*/
|
|
10
|
+
import { z } from 'zod';
|
|
11
|
+
export const LogEntrySchema = z.object({
|
|
12
|
+
timestamp: z.string(),
|
|
13
|
+
level: z.enum(['log', 'warn', 'error', 'info', 'notification']),
|
|
14
|
+
message: z.string(),
|
|
15
|
+
stack: z.string().optional(),
|
|
16
|
+
source: z.enum(['foundry', 'module', 'system', 'api', 'unknown']),
|
|
17
|
+
});
|
|
18
|
+
export const LogResponseSchema = z.object({
|
|
19
|
+
logs: z.array(LogEntrySchema),
|
|
20
|
+
total: z.number(),
|
|
21
|
+
bufferSize: z.number().optional(),
|
|
22
|
+
maxBufferSize: z.number().optional(),
|
|
23
|
+
});
|
|
24
|
+
export const LogSearchResponseSchema = z.object({
|
|
25
|
+
logs: z.array(LogEntrySchema),
|
|
26
|
+
matches: z.number(),
|
|
27
|
+
pattern: z.string(),
|
|
28
|
+
searchTimeframe: z.string(),
|
|
29
|
+
});
|
|
30
|
+
const ServerInfoSchema = z.object({
|
|
31
|
+
foundryVersion: z.string(),
|
|
32
|
+
systemVersion: z.string(),
|
|
33
|
+
worldId: z.string(),
|
|
34
|
+
uptime: z.number().optional(),
|
|
35
|
+
});
|
|
36
|
+
const UserInfoSchema = z.object({
|
|
37
|
+
total: z.number(),
|
|
38
|
+
active: z.number(),
|
|
39
|
+
gm: z.number(),
|
|
40
|
+
});
|
|
41
|
+
const ModuleInfoSchema = z.object({
|
|
42
|
+
total: z.number(),
|
|
43
|
+
active: z.number(),
|
|
44
|
+
});
|
|
45
|
+
const PerformanceInfoSchema = z.object({
|
|
46
|
+
memory: z
|
|
47
|
+
.object({
|
|
48
|
+
rss: z.number(),
|
|
49
|
+
heapTotal: z.number(),
|
|
50
|
+
heapUsed: z.number(),
|
|
51
|
+
external: z.number(),
|
|
52
|
+
arrayBuffers: z.number(),
|
|
53
|
+
})
|
|
54
|
+
.optional(),
|
|
55
|
+
connectedClients: z.number(),
|
|
56
|
+
});
|
|
57
|
+
const LogInfoSchema = z.object({
|
|
58
|
+
bufferSize: z.number(),
|
|
59
|
+
recentErrors: z.number(),
|
|
60
|
+
recentWarnings: z.number(),
|
|
61
|
+
errorRate: z.number(),
|
|
62
|
+
});
|
|
63
|
+
export const SystemHealthSchema = z.object({
|
|
64
|
+
timestamp: z.string(),
|
|
65
|
+
server: ServerInfoSchema,
|
|
66
|
+
users: UserInfoSchema,
|
|
67
|
+
modules: ModuleInfoSchema,
|
|
68
|
+
performance: PerformanceInfoSchema,
|
|
69
|
+
logs: LogInfoSchema,
|
|
70
|
+
status: z.enum(['healthy', 'warning', 'critical']),
|
|
71
|
+
});
|
|
72
|
+
const ErrorCategoriesSchema = z.record(z.string(), z.number());
|
|
73
|
+
const DiagnosticSuggestionSchema = z.object({
|
|
74
|
+
category: z.string(),
|
|
75
|
+
suggestion: z.string(),
|
|
76
|
+
priority: z.enum(['low', 'medium', 'high', 'critical']),
|
|
77
|
+
});
|
|
78
|
+
const ErrorSummarySchema = z.object({
|
|
79
|
+
totalErrors: z.number(),
|
|
80
|
+
uniqueErrors: z.number(),
|
|
81
|
+
categories: ErrorCategoriesSchema,
|
|
82
|
+
});
|
|
83
|
+
export const ErrorDiagnosisSchema = z.object({
|
|
84
|
+
timestamp: z.string(),
|
|
85
|
+
timeframe: z.string(),
|
|
86
|
+
summary: ErrorSummarySchema,
|
|
87
|
+
recentErrors: z.array(LogEntrySchema),
|
|
88
|
+
suggestions: z.array(DiagnosticSuggestionSchema),
|
|
89
|
+
healthScore: z.number(),
|
|
90
|
+
});
|
|
91
|
+
export const ApiStatusResponseSchema = z.object({
|
|
92
|
+
status: z.string(),
|
|
93
|
+
});
|
|
94
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FoundryVTT authentication module
|
|
3
|
+
*
|
|
4
|
+
* Implements the proven 4-step authentication flow for direct WebSocket access:
|
|
5
|
+
* 1. GET /join → session cookie
|
|
6
|
+
* 2. Socket.IO connect + getJoinData → resolve user document _id
|
|
7
|
+
* 3. POST /join as JSON with document _id → authenticated session
|
|
8
|
+
* 4. Socket.IO reconnect with session → full game state access
|
|
9
|
+
*/
|
|
10
|
+
import axios from 'axios';
|
|
11
|
+
import { io } from 'socket.io-client';
|
|
12
|
+
import { logger } from '../utils/logger.js';
|
|
13
|
+
import { RefusedError } from '../utils/refusal.js';
|
|
14
|
+
/**
|
|
15
|
+
* Socket.IO connection options carrying a FoundryVTT session.
|
|
16
|
+
*
|
|
17
|
+
* FoundryVTT resolves the session from the `session` **cookie** on the
|
|
18
|
+
* handshake request; the `session` query parameter alone leaves the socket
|
|
19
|
+
* anonymous. An anonymous socket still connects at the transport level — it
|
|
20
|
+
* simply never answers `getJoinData` and emits `session` as `null` — so the
|
|
21
|
+
* only symptom is a bare timeout with no `connect_error` (laurigates/foundryvtt-mcp#206).
|
|
22
|
+
*
|
|
23
|
+
* `extraHeaders` is honoured by socket.io-client in Node.js for both the
|
|
24
|
+
* WebSocket and polling handshakes; the query parameter is kept for servers
|
|
25
|
+
* that read it.
|
|
26
|
+
*/
|
|
27
|
+
export function sessionSocketOptions(session) {
|
|
28
|
+
return {
|
|
29
|
+
transports: ['websocket'],
|
|
30
|
+
query: { session },
|
|
31
|
+
extraHeaders: { Cookie: `session=${session}` },
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* No world is launched: FoundryVTT sits on its Setup screen. Expected while
|
|
36
|
+
* the GM has not launched one (e.g. after a server restart), so a refusal —
|
|
37
|
+
* one warning line, no stack — and the next tool call retries.
|
|
38
|
+
*/
|
|
39
|
+
export class NoActiveWorldError extends RefusedError {
|
|
40
|
+
name = 'NoActiveWorldError';
|
|
41
|
+
constructor() {
|
|
42
|
+
super('No active world on FoundryVTT: launch it from the Setup screen.');
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* FoundryVTT v14's answer to GET and POST /join with no active world: its
|
|
47
|
+
* "No Active Game" error page, HTTP 200 (dist/server/views/view.mjs `_noWorld`).
|
|
48
|
+
* A hint only — English text that may change: the decision is
|
|
49
|
+
* {@link fetchJoinUsers} returning no user list.
|
|
50
|
+
*/
|
|
51
|
+
export function isNoWorldPage(data) {
|
|
52
|
+
return (typeof data === 'string' &&
|
|
53
|
+
/There is currently no active game session|<title>[^<]*No Active Game/i.test(data));
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Extracts the session cookie value from a GET /join response, and whether
|
|
57
|
+
* the response looked like the "No Active Game" page.
|
|
58
|
+
*/
|
|
59
|
+
async function getSessionCookie(baseUrl) {
|
|
60
|
+
const res = await axios.get(`${baseUrl}/join`, {
|
|
61
|
+
// Accept 200 (join page) and 302 (redirect after cookie set)
|
|
62
|
+
validateStatus: (status) => status === 200 || status === 302,
|
|
63
|
+
maxRedirects: 0,
|
|
64
|
+
});
|
|
65
|
+
const cookies = res.headers['set-cookie'];
|
|
66
|
+
if (!cookies) {
|
|
67
|
+
throw new Error('No session cookie returned from /join');
|
|
68
|
+
}
|
|
69
|
+
const cookieString = Array.isArray(cookies) ? cookies.join(' ') : cookies;
|
|
70
|
+
const match = cookieString.match(/session=([^;]+)/);
|
|
71
|
+
if (!match?.[1]) {
|
|
72
|
+
throw new Error('Could not extract session cookie from response');
|
|
73
|
+
}
|
|
74
|
+
logger.debug('Session cookie obtained');
|
|
75
|
+
return { session: match[1], noWorldPage: isNoWorldPage(res.data) };
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Asks FoundryVTT for its join data over Socket.IO (`getJoinData`).
|
|
79
|
+
*
|
|
80
|
+
* @returns the world's users, or `null` when the answer carries no user
|
|
81
|
+
* list — FoundryVTT answers `{}` when no world is active (join.mjs
|
|
82
|
+
* `handleSocket`), which is what decides {@link NoActiveWorldError}
|
|
83
|
+
*/
|
|
84
|
+
function fetchJoinUsers(baseUrl, session) {
|
|
85
|
+
return new Promise((resolve, reject) => {
|
|
86
|
+
const socket = io(baseUrl, sessionSocketOptions(session));
|
|
87
|
+
const cleanup = () => {
|
|
88
|
+
socket.off('session', onSession);
|
|
89
|
+
socket.off('connect_error', onConnectError);
|
|
90
|
+
};
|
|
91
|
+
const timeout = setTimeout(() => {
|
|
92
|
+
cleanup();
|
|
93
|
+
socket.disconnect();
|
|
94
|
+
reject(new Error('Timeout resolving user ID via getJoinData'));
|
|
95
|
+
}, 10000);
|
|
96
|
+
const onSession = () => {
|
|
97
|
+
socket.emit('getJoinData', (data) => {
|
|
98
|
+
clearTimeout(timeout);
|
|
99
|
+
cleanup();
|
|
100
|
+
socket.disconnect();
|
|
101
|
+
resolve(Array.isArray(data?.users) ? data.users : null);
|
|
102
|
+
});
|
|
103
|
+
};
|
|
104
|
+
const onConnectError = (err) => {
|
|
105
|
+
clearTimeout(timeout);
|
|
106
|
+
cleanup();
|
|
107
|
+
socket.disconnect();
|
|
108
|
+
reject(new Error(`Socket.IO connection failed during user resolution: ${err.message}`));
|
|
109
|
+
};
|
|
110
|
+
socket.on('session', onSession);
|
|
111
|
+
socket.on('connect_error', onConnectError);
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* A /join response looked like the "No Active Game" page: confirm with
|
|
116
|
+
* `getJoinData` before saying so.
|
|
117
|
+
*
|
|
118
|
+
* @throws {NoActiveWorldError} getJoinData returned no user list
|
|
119
|
+
*/
|
|
120
|
+
async function confirmNoActiveWorld(baseUrl, session) {
|
|
121
|
+
if ((await fetchJoinUsers(baseUrl, session)) === null) {
|
|
122
|
+
throw new NoActiveWorldError();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Resolves a user identifier to a FoundryVTT document _id.
|
|
127
|
+
*
|
|
128
|
+
* If the input is already a 16-character alphanumeric string (document _id format),
|
|
129
|
+
* returns it directly. Otherwise, connects via Socket.IO and emits getJoinData
|
|
130
|
+
* to look up the _id by display name.
|
|
131
|
+
*
|
|
132
|
+
* @throws {NoActiveWorldError} getJoinData returned no user list
|
|
133
|
+
*/
|
|
134
|
+
async function resolveUserId(baseUrl, user, session) {
|
|
135
|
+
// FoundryVTT document IDs are 16-character alphanumeric strings
|
|
136
|
+
if (/^[a-zA-Z0-9]{16}$/.test(user)) {
|
|
137
|
+
logger.debug('User identifier is already a document _id', { userId: user });
|
|
138
|
+
return user;
|
|
139
|
+
}
|
|
140
|
+
logger.debug('Resolving display name to document _id', { displayName: user });
|
|
141
|
+
const users = await fetchJoinUsers(baseUrl, session);
|
|
142
|
+
if (users === null) {
|
|
143
|
+
throw new NoActiveWorldError();
|
|
144
|
+
}
|
|
145
|
+
const found = users.find((u) => u.name.toLowerCase() === user.toLowerCase());
|
|
146
|
+
if (!found) {
|
|
147
|
+
const available = users.map((u) => u.name).join(', ');
|
|
148
|
+
logger.debug('User not found in FoundryVTT user list', { available });
|
|
149
|
+
throw new Error(`User "${user}" not found`);
|
|
150
|
+
}
|
|
151
|
+
logger.debug('Resolved user document _id', { displayName: user, _id: found._id });
|
|
152
|
+
return found._id;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Authenticates with FoundryVTT using the proven 4-step flow.
|
|
156
|
+
*
|
|
157
|
+
* @returns Session cookie and resolved user document _id
|
|
158
|
+
*/
|
|
159
|
+
export async function authenticateFoundry(baseUrl, user, password) {
|
|
160
|
+
// Warn when credentials are sent over plaintext HTTP to a non-localhost host
|
|
161
|
+
try {
|
|
162
|
+
const parsed = new URL(baseUrl);
|
|
163
|
+
// new URL('http://[::1]').hostname returns the bracketed form '[::1]';
|
|
164
|
+
// strip IPv6 brackets so loopback comparison is uniform.
|
|
165
|
+
const host = parsed.hostname.replace(/^\[|\]$/g, '');
|
|
166
|
+
const isLocalhost = host === 'localhost' || host === '127.0.0.1' || host === '::1';
|
|
167
|
+
if (parsed.protocol === 'http:' && !isLocalhost) {
|
|
168
|
+
logger.warn('WARNING: Connecting to a non-localhost host over plain HTTP. ' +
|
|
169
|
+
'Your password will be transmitted in plaintext. ' +
|
|
170
|
+
'Use HTTPS for non-local FoundryVTT instances.', { host: parsed.hostname });
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
// URL already validated by config; ignore parse errors here
|
|
175
|
+
}
|
|
176
|
+
// Step 1: Get session cookie
|
|
177
|
+
const { session, noWorldPage } = await getSessionCookie(baseUrl);
|
|
178
|
+
// The getJoinData lookup below decides on its own; a FOUNDRY_USER_ID skips
|
|
179
|
+
// it, so confirm a "No Active Game" page with it here.
|
|
180
|
+
if (noWorldPage && /^[a-zA-Z0-9]{16}$/.test(user)) {
|
|
181
|
+
await confirmNoActiveWorld(baseUrl, session);
|
|
182
|
+
}
|
|
183
|
+
// Step 2: Resolve user to document _id
|
|
184
|
+
const userId = await resolveUserId(baseUrl, user, session);
|
|
185
|
+
// Step 3: POST /join as JSON with document _id
|
|
186
|
+
const joinRes = await axios.post(`${baseUrl}/join`, {
|
|
187
|
+
action: 'join',
|
|
188
|
+
userid: userId, // Foundry v13
|
|
189
|
+
userId, // Foundry v14 reads camelCase
|
|
190
|
+
password,
|
|
191
|
+
}, {
|
|
192
|
+
headers: {
|
|
193
|
+
'Content-Type': 'application/json',
|
|
194
|
+
Cookie: `session=${session}`,
|
|
195
|
+
// FoundryVTT v14 rejects POST /join without an Origin header (HTTP 400),
|
|
196
|
+
// so send the server's own origin as a browser would.
|
|
197
|
+
Origin: new URL(baseUrl).origin,
|
|
198
|
+
},
|
|
199
|
+
// Accept 200 (success JSON), 302 (redirect to /game on success) and 401
|
|
200
|
+
// (bad password). 401 carries FoundryVTT's own explanation in the body;
|
|
201
|
+
// letting axios throw on it would surface a bare
|
|
202
|
+
// "Request failed with status code 401" instead (laurigates/foundryvtt-mcp#206).
|
|
203
|
+
validateStatus: (status) => status === 200 || status === 302 || status === 401,
|
|
204
|
+
});
|
|
205
|
+
if (isNoWorldPage(joinRes.data)) {
|
|
206
|
+
await confirmNoActiveWorld(baseUrl, session);
|
|
207
|
+
}
|
|
208
|
+
if (joinRes.data?.status !== 'success' && joinRes.data?.redirect !== '/game') {
|
|
209
|
+
// FoundryVTT v13+ answers a rejected /join with a plain-text i18n key
|
|
210
|
+
// (e.g. "JOIN.ErrorInvalidPassword") rather than a JSON error object.
|
|
211
|
+
const msg = (typeof joinRes.data === 'string' && joinRes.data.trim()) ||
|
|
212
|
+
joinRes.data?.message ||
|
|
213
|
+
joinRes.data?.error ||
|
|
214
|
+
'Unknown error';
|
|
215
|
+
throw new Error(`FoundryVTT authentication failed (HTTP ${joinRes.status}): ${msg}`);
|
|
216
|
+
}
|
|
217
|
+
logger.info('FoundryVTT authentication successful', { userId });
|
|
218
|
+
return { session, userId };
|
|
219
|
+
}
|
|
220
|
+
//# sourceMappingURL=auth.js.map
|