@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.
- package/LICENSE +22 -0
- package/README.md +457 -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 +414 -0
- package/dist/cli/prompt.js +117 -0
- package/dist/cli/snippets.js +64 -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 +481 -0
- package/dist/diagnostics/client.js +291 -0
- package/dist/diagnostics/types.js +94 -0
- package/dist/foundry/auth.js +224 -0
- package/dist/foundry/browser-detect.js +170 -0
- package/dist/foundry/client.js +5874 -0
- package/dist/foundry/dice-formula.js +154 -0
- package/dist/foundry/event-log.js +298 -0
- package/dist/foundry/headless-gm-session.js +857 -0
- package/dist/foundry/journal-conflicts.js +141 -0
- package/dist/foundry/journal-history.js +90 -0
- package/dist/foundry/journal-integrity.js +322 -0
- package/dist/foundry/message-author.js +19 -0
- package/dist/foundry/module-bridge.js +441 -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 +65 -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 +291 -0
- package/dist/shared/daemon-link.js +135 -0
- package/dist/shared/daemon.js +311 -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 +38 -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 +450 -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 +48 -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/tool-dependencies.js +194 -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/mcp-errors.js +47 -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,291 @@
|
|
|
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
|
+
* Logs, log search, error diagnosis and system health come from the REST API
|
|
28
|
+
* module only. Without `FOUNDRY_API_KEY` (or with a module that lacks the
|
|
29
|
+
* endpoint) asking for them is not a failure: an expected refusal, logged as
|
|
30
|
+
* one warning line at most — and no request is sent.
|
|
31
|
+
*/
|
|
32
|
+
export class RestApiRequiredError extends RefusedError {
|
|
33
|
+
name = 'RestApiRequiredError';
|
|
34
|
+
}
|
|
35
|
+
/** The REST API module did not answer a diagnostics request; see {@link restFailure}. */
|
|
36
|
+
export class RestApiUnavailableError extends RestApiRequiredError {
|
|
37
|
+
name = 'RestApiUnavailableError';
|
|
38
|
+
}
|
|
39
|
+
/** Longest reason kept from a failed request (a schema error lists every issue). */
|
|
40
|
+
const MAX_FAILURE_REASON_LENGTH = 200;
|
|
41
|
+
/**
|
|
42
|
+
* A diagnostics request to the REST API module failed: one short warning
|
|
43
|
+
* line, the full error at debug level, and a refusal for the caller, so the
|
|
44
|
+
* tool call that asked logs a warning rather than two errors with stacks.
|
|
45
|
+
*/
|
|
46
|
+
function restFailure(what, error) {
|
|
47
|
+
const status = httpStatus(error);
|
|
48
|
+
const reason = (status !== undefined ? `HTTP ${status}` : error instanceof Error ? error.message : String(error)).slice(0, MAX_FAILURE_REASON_LENGTH);
|
|
49
|
+
logger.warn(`DiagnosticsClient | ${what} unavailable from the REST API module: ${reason}`);
|
|
50
|
+
logger.debug(`DiagnosticsClient | ${what} request failed`, error instanceof Error ? { message: error.message, stack: error.stack } : error);
|
|
51
|
+
return new RestApiUnavailableError(`${what} unavailable from the REST API module: ${reason}`);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Client for accessing FoundryVTT diagnostic and logging information
|
|
55
|
+
*
|
|
56
|
+
* Provides methods to retrieve logs, search for specific patterns,
|
|
57
|
+
* monitor system health, and analyze errors through the REST API.
|
|
58
|
+
*
|
|
59
|
+
* @class DiagnosticsClient
|
|
60
|
+
* @example
|
|
61
|
+
* ```typescript
|
|
62
|
+
* const diagnostics = new DiagnosticsClient(foundryClient);
|
|
63
|
+
*
|
|
64
|
+
* // Get recent errors
|
|
65
|
+
* const errors = await diagnostics.getRecentLogs({ level: 'error', lines: 20 });
|
|
66
|
+
*
|
|
67
|
+
* // Search for specific patterns
|
|
68
|
+
* const matches = await diagnostics.searchLogs({ pattern: 'TypeError', timeframe: '3600' });
|
|
69
|
+
*
|
|
70
|
+
* // Check system health
|
|
71
|
+
* const health = await diagnostics.getSystemHealth();
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
export class DiagnosticsClient {
|
|
75
|
+
foundryClient;
|
|
76
|
+
/**
|
|
77
|
+
* Create a new DiagnosticsClient instance
|
|
78
|
+
*
|
|
79
|
+
* @param foundryClient - The FoundryClient instance to use for API calls
|
|
80
|
+
*/
|
|
81
|
+
/** The health endpoint answered 404 once already: warned, not again. */
|
|
82
|
+
healthEndpointMissingWarned = false;
|
|
83
|
+
/** Refuses, without any request, when no `FOUNDRY_API_KEY` is set. */
|
|
84
|
+
requireRestApi(what) {
|
|
85
|
+
if (!this.foundryClient.hasRestApi()) {
|
|
86
|
+
throw new RestApiRequiredError(`${what} requires the REST API module (FOUNDRY_API_KEY is not set)`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
constructor(foundryClient) {
|
|
90
|
+
this.foundryClient = foundryClient;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Get recent log entries with optional filtering
|
|
94
|
+
*
|
|
95
|
+
* @param params - Search parameters for filtering logs
|
|
96
|
+
* @returns Promise resolving to log response with entries and metadata
|
|
97
|
+
*
|
|
98
|
+
* @example
|
|
99
|
+
* ```typescript
|
|
100
|
+
* // Get last 50 log entries
|
|
101
|
+
* const logs = await diagnostics.getRecentLogs();
|
|
102
|
+
*
|
|
103
|
+
* // Get only error logs from the last hour
|
|
104
|
+
* const errors = await diagnostics.getRecentLogs({
|
|
105
|
+
* level: 'error',
|
|
106
|
+
* since: new Date(Date.now() - 3600000).toISOString()
|
|
107
|
+
* });
|
|
108
|
+
*
|
|
109
|
+
* // Get logs with stack traces included
|
|
110
|
+
* const detailed = await diagnostics.getRecentLogs({
|
|
111
|
+
* lines: 100,
|
|
112
|
+
* includeStack: true
|
|
113
|
+
* });
|
|
114
|
+
* ```
|
|
115
|
+
*/
|
|
116
|
+
async getRecentLogs(params = {}) {
|
|
117
|
+
this.requireRestApi('Recent logs');
|
|
118
|
+
try {
|
|
119
|
+
logger.debug('DiagnosticsClient | Getting recent logs', params);
|
|
120
|
+
const searchParams = new URLSearchParams();
|
|
121
|
+
if (params.lines !== undefined) {
|
|
122
|
+
searchParams.set('lines', params.lines.toString());
|
|
123
|
+
}
|
|
124
|
+
if (params.level) {
|
|
125
|
+
searchParams.set('level', params.level);
|
|
126
|
+
}
|
|
127
|
+
if (params.since) {
|
|
128
|
+
searchParams.set('since', params.since);
|
|
129
|
+
}
|
|
130
|
+
if (params.source) {
|
|
131
|
+
searchParams.set('source', params.source);
|
|
132
|
+
}
|
|
133
|
+
if (params.includeStack !== undefined) {
|
|
134
|
+
searchParams.set('includeStack', params.includeStack.toString());
|
|
135
|
+
}
|
|
136
|
+
const queryString = searchParams.toString();
|
|
137
|
+
const url = `/api/diagnostics/logs${queryString ? `?${queryString}` : ''}`;
|
|
138
|
+
const response = await this.foundryClient.get(url);
|
|
139
|
+
const parsed = LogResponseSchema.parse(response.data);
|
|
140
|
+
logger.debug('DiagnosticsClient | Retrieved logs', {
|
|
141
|
+
count: parsed.total,
|
|
142
|
+
bufferSize: parsed.bufferSize,
|
|
143
|
+
});
|
|
144
|
+
return parsed;
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
throw restFailure('Recent logs', error);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Search log entries for specific patterns using regular expressions
|
|
152
|
+
*
|
|
153
|
+
* @param params - Search parameters including pattern and filters
|
|
154
|
+
* @returns Promise resolving to matching log entries
|
|
155
|
+
*
|
|
156
|
+
* @example
|
|
157
|
+
* ```typescript
|
|
158
|
+
* // Search for any TypeError occurrences
|
|
159
|
+
* const typeErrors = await diagnostics.searchLogs({
|
|
160
|
+
* pattern: 'TypeError'
|
|
161
|
+
* });
|
|
162
|
+
*
|
|
163
|
+
* // Search for network errors in the last hour
|
|
164
|
+
* const networkErrors = await diagnostics.searchLogs({
|
|
165
|
+
* pattern: 'Failed to fetch|Network Error',
|
|
166
|
+
* timeframe: '3600',
|
|
167
|
+
* level: 'error'
|
|
168
|
+
* });
|
|
169
|
+
*
|
|
170
|
+
* // Case-sensitive search for specific module errors
|
|
171
|
+
* const moduleErrors = await diagnostics.searchLogs({
|
|
172
|
+
* pattern: 'Module.*failed',
|
|
173
|
+
* caseSensitive: true
|
|
174
|
+
* });
|
|
175
|
+
* ```
|
|
176
|
+
*/
|
|
177
|
+
async searchLogs(params) {
|
|
178
|
+
this.requireRestApi('Log search');
|
|
179
|
+
try {
|
|
180
|
+
logger.debug('DiagnosticsClient | Searching logs', params);
|
|
181
|
+
const searchParams = new URLSearchParams();
|
|
182
|
+
searchParams.set('pattern', params.pattern);
|
|
183
|
+
if (params.timeframe) {
|
|
184
|
+
searchParams.set('timeframe', params.timeframe);
|
|
185
|
+
}
|
|
186
|
+
if (params.level) {
|
|
187
|
+
searchParams.set('level', params.level);
|
|
188
|
+
}
|
|
189
|
+
if (params.caseSensitive !== undefined) {
|
|
190
|
+
searchParams.set('caseSensitive', params.caseSensitive.toString());
|
|
191
|
+
}
|
|
192
|
+
const url = `/api/diagnostics/search?${searchParams.toString()}`;
|
|
193
|
+
const response = await this.foundryClient.get(url);
|
|
194
|
+
const parsed = LogSearchResponseSchema.parse(response.data);
|
|
195
|
+
logger.debug('DiagnosticsClient | Search completed', {
|
|
196
|
+
pattern: params.pattern,
|
|
197
|
+
matches: parsed.matches,
|
|
198
|
+
});
|
|
199
|
+
return parsed;
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
throw restFailure('Log search', error);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Get comprehensive system health and performance metrics
|
|
207
|
+
*
|
|
208
|
+
* @returns Promise resolving to complete system health information
|
|
209
|
+
*
|
|
210
|
+
* @example
|
|
211
|
+
* ```typescript
|
|
212
|
+
* const health = await diagnostics.getSystemHealth();
|
|
213
|
+
*
|
|
214
|
+
* console.log(`Server status: ${health.status}`);
|
|
215
|
+
* console.log(`Active users: ${health.users.active}/${health.users.total}`);
|
|
216
|
+
* console.log(`Recent errors: ${health.logs.recentErrors}`);
|
|
217
|
+
*
|
|
218
|
+
* if (health.status === 'critical') {
|
|
219
|
+
* console.warn('Server requires immediate attention!');
|
|
220
|
+
* }
|
|
221
|
+
* ```
|
|
222
|
+
*/
|
|
223
|
+
async getSystemHealth() {
|
|
224
|
+
this.requireRestApi('System health');
|
|
225
|
+
try {
|
|
226
|
+
logger.debug('DiagnosticsClient | Getting system health');
|
|
227
|
+
const response = await this.foundryClient.get('/api/diagnostics/health');
|
|
228
|
+
const parsed = SystemHealthSchema.parse(response.data);
|
|
229
|
+
logger.debug('DiagnosticsClient | System health retrieved', {
|
|
230
|
+
status: parsed.status,
|
|
231
|
+
activeUsers: parsed.users?.active,
|
|
232
|
+
recentErrors: parsed.logs?.recentErrors,
|
|
233
|
+
});
|
|
234
|
+
return parsed;
|
|
235
|
+
}
|
|
236
|
+
catch (error) {
|
|
237
|
+
if (httpStatus(error) === 404) {
|
|
238
|
+
if (!this.healthEndpointMissingWarned) {
|
|
239
|
+
this.healthEndpointMissingWarned = true;
|
|
240
|
+
logger.warn('DiagnosticsClient | The REST API module does not provide /api/diagnostics/health (HTTP 404); system health is unavailable');
|
|
241
|
+
}
|
|
242
|
+
throw new RestApiRequiredError('System health is unavailable: the REST API module does not provide /api/diagnostics/health (HTTP 404)');
|
|
243
|
+
}
|
|
244
|
+
throw restFailure('System health', error);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Analyze recent errors and get diagnostic suggestions
|
|
249
|
+
*
|
|
250
|
+
* @param timeframe - Time window in seconds to analyze (default: 3600)
|
|
251
|
+
* @returns Promise resolving to error diagnosis with suggestions
|
|
252
|
+
*
|
|
253
|
+
* @example
|
|
254
|
+
* ```typescript
|
|
255
|
+
* // Analyze errors from the last hour
|
|
256
|
+
* const diagnosis = await diagnostics.diagnoseErrors();
|
|
257
|
+
*
|
|
258
|
+
* // Analyze errors from the last 30 minutes
|
|
259
|
+
* const recentDiagnosis = await diagnostics.diagnoseErrors(1800);
|
|
260
|
+
*
|
|
261
|
+
* console.log(`Health score: ${diagnosis.healthScore}/100`);
|
|
262
|
+
* console.log(`Total errors: ${diagnosis.summary.totalErrors}`);
|
|
263
|
+
*
|
|
264
|
+
* // Display suggestions
|
|
265
|
+
* diagnosis.suggestions.forEach(suggestion => {
|
|
266
|
+
* console.log(`${suggestion.priority.toUpperCase()}: ${suggestion.suggestion}`);
|
|
267
|
+
* });
|
|
268
|
+
* ```
|
|
269
|
+
*/
|
|
270
|
+
async diagnoseErrors(timeframe = 3600) {
|
|
271
|
+
this.requireRestApi('Error diagnosis');
|
|
272
|
+
try {
|
|
273
|
+
logger.debug('DiagnosticsClient | Diagnosing errors', { timeframe });
|
|
274
|
+
const searchParams = new URLSearchParams();
|
|
275
|
+
searchParams.set('timeframe', timeframe.toString());
|
|
276
|
+
const url = `/api/diagnostics/errors?${searchParams.toString()}`;
|
|
277
|
+
const response = await this.foundryClient.get(url);
|
|
278
|
+
const parsed = ErrorDiagnosisSchema.parse(response.data);
|
|
279
|
+
logger.debug('DiagnosticsClient | Error diagnosis completed', {
|
|
280
|
+
totalErrors: parsed.summary?.totalErrors,
|
|
281
|
+
healthScore: parsed.healthScore,
|
|
282
|
+
suggestionCount: parsed.suggestions?.length,
|
|
283
|
+
});
|
|
284
|
+
return parsed;
|
|
285
|
+
}
|
|
286
|
+
catch (error) {
|
|
287
|
+
throw restFailure('Error diagnosis', error);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
//# 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,224 @@
|
|
|
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
|
+
// Some FoundryVTT v14 setups reject the join POST (HTTP 400) unless it
|
|
199
|
+
// carries Sec-Fetch-Site: same-origin, as a browser's same-origin fetch
|
|
200
|
+
// does (reported on 14.369). Origin alone is enough on others, so send both.
|
|
201
|
+
'Sec-Fetch-Site': 'same-origin',
|
|
202
|
+
},
|
|
203
|
+
// Accept 200 (success JSON), 302 (redirect to /game on success) and 401
|
|
204
|
+
// (bad password). 401 carries FoundryVTT's own explanation in the body;
|
|
205
|
+
// letting axios throw on it would surface a bare
|
|
206
|
+
// "Request failed with status code 401" instead (laurigates/foundryvtt-mcp#206).
|
|
207
|
+
validateStatus: (status) => status === 200 || status === 302 || status === 401,
|
|
208
|
+
});
|
|
209
|
+
if (isNoWorldPage(joinRes.data)) {
|
|
210
|
+
await confirmNoActiveWorld(baseUrl, session);
|
|
211
|
+
}
|
|
212
|
+
if (joinRes.data?.status !== 'success' && joinRes.data?.redirect !== '/game') {
|
|
213
|
+
// FoundryVTT v13+ answers a rejected /join with a plain-text i18n key
|
|
214
|
+
// (e.g. "JOIN.ErrorInvalidPassword") rather than a JSON error object.
|
|
215
|
+
const msg = (typeof joinRes.data === 'string' && joinRes.data.trim()) ||
|
|
216
|
+
joinRes.data?.message ||
|
|
217
|
+
joinRes.data?.error ||
|
|
218
|
+
'Unknown error';
|
|
219
|
+
throw new Error(`FoundryVTT authentication failed (HTTP ${joinRes.status}): ${msg}`);
|
|
220
|
+
}
|
|
221
|
+
logger.info('FoundryVTT authentication successful', { userId });
|
|
222
|
+
return { session, userId };
|
|
223
|
+
}
|
|
224
|
+
//# sourceMappingURL=auth.js.map
|