@g33ks/foundryvtt-mcp 2.0.0 → 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/README.md +5 -16
- package/dist/cli/init.js +5 -1
- package/dist/cli/snippets.js +16 -1
- package/dist/core.js +80 -14
- package/dist/diagnostics/client.js +36 -98
- package/dist/foundry/auth.js +4 -0
- package/dist/foundry/client.js +457 -138
- package/dist/foundry/event-log.js +2 -3
- package/dist/foundry/headless-gm-session.js +119 -2
- package/dist/foundry/journal-conflicts.js +141 -0
- package/dist/foundry/journal-integrity.js +20 -4
- package/dist/foundry/message-author.js +19 -0
- package/dist/foundry/module-bridge.js +28 -0
- package/dist/mcp-server.js +5 -3
- package/dist/shared/control.js +41 -5
- package/dist/shared/daemon.js +2 -4
- package/dist/shared/protocol.js +10 -10
- package/dist/tools/definitions.js +4 -4
- package/dist/tools/handlers/chat.js +3 -1
- package/dist/tools/handlers/diagnostics.js +13 -1
- package/dist/tools/handlers/utils.js +3 -2
- package/dist/tools/tool-dependencies.js +194 -0
- package/dist/utils/mcp-errors.js +47 -0
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -17,22 +17,9 @@ This server empowers AI assistants (Claude Desktop, Claude Code, Oh My Pi, VS Co
|
|
|
17
17
|
|
|
18
18
|
## 🧭 How it works
|
|
19
19
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
C1["AI client<br/>(Claude Desktop, Claude Code…)"] -->|"MCP (stdio)"| R1["Relay"]
|
|
24
|
-
C2["Another AI client"] -->|"MCP (stdio)"| R2["Relay"]
|
|
25
|
-
R1 & R2 -->|"named pipe /<br/>Unix socket"| D["Shared process"]
|
|
26
|
-
D -->|"launches"| B["Invisible GM browser<br/>+ companion module"]
|
|
27
|
-
D <-->|"bridge WebSocket<br/>(loopback, authenticated)"| B
|
|
28
|
-
end
|
|
29
|
-
subgraph S["Foundry server (local or remote)"]
|
|
30
|
-
F["FoundryVTT world"]
|
|
31
|
-
end
|
|
32
|
-
D -->|"Socket.IO:<br/>read & write documents"| F
|
|
33
|
-
B -->|"loads the game page<br/>as a GM user"| F
|
|
34
|
-
D -.->|"HTTP (optional):<br/>REST API module"| F
|
|
35
|
-
```
|
|
20
|
+

|
|
21
|
+
|
|
22
|
+
<sub>Diagram source: [docs/assets/how-it-works.mmd](https://github.com/G33ks/foundryvtt-mcp/blob/main/docs/assets/how-it-works.mmd) (Mermaid).</sub>
|
|
36
23
|
|
|
37
24
|
Your AI assistant starts a small relay program for this server. Every relay, from one assistant or several, hands its requests to the same background process, which keeps a single connection to Foundry open. That process reads and changes the world through Foundry's normal connection, the one any player's browser uses. Some things only a real Foundry page can do: capturing the canvas, rolling dice with Foundry's own engine, reading compendium documents, uploading files, pausing the game. For those, the background process runs an invisible browser, sharing its own Foundry session, where the companion module runs. The module talks only to that process, and only after each has proven its identity to the other.
|
|
38
25
|
|
|
@@ -303,6 +290,8 @@ With the settings in the [configuration file](#configuration-file), add to `clau
|
|
|
303
290
|
|
|
304
291
|
`claude mcp add foundryvtt --scope user -- "<NODE>" "<ENTRY>"` (all your projects; `--scope local` for the current project only), or in `~/.claude.json` (or a project's `.mcp.json`):
|
|
305
292
|
|
|
293
|
+
> **Windows PowerShell:** the command works as printed when `claude` is the installer's `claude.exe` (or a `.cmd`). If `Get-Command claude` shows a `claude.ps1` (installed with npm), PowerShell swallows the `--`: write `'--'` instead.
|
|
294
|
+
|
|
306
295
|
```json
|
|
307
296
|
{
|
|
308
297
|
"mcpServers": {
|
package/dist/cli/init.js
CHANGED
|
@@ -15,7 +15,7 @@ import { packageName } from '../shared/version.js';
|
|
|
15
15
|
import { checkBrowser, describeLoginError, evaluateModule, evaluateRole, loginAndReadWorld, normalizeUrl, probeJoin, } from './checks.js';
|
|
16
16
|
import { quoteValue, UnwritableValueError, writeConfig } from './config-file.js';
|
|
17
17
|
import { PromptCancelled, terminalProblem, terminalPrompter } from './prompt.js';
|
|
18
|
-
import { claudeCodeCommand, claudeDesktopSnippet, connectorCommand, installKind, } from './snippets.js';
|
|
18
|
+
import { claudeCodeCommand, claudeCodePowerShellNote, claudeDesktopSnippet, connectorCommand, installKind, } from './snippets.js';
|
|
19
19
|
const MANAGED_KEYS = [
|
|
20
20
|
'FOUNDRY_URL',
|
|
21
21
|
'FOUNDRY_USERNAME',
|
|
@@ -330,6 +330,10 @@ async function runInteractive(deps) {
|
|
|
330
330
|
print(` ${claudeCodeCommand(deps.node, deps.entry)}`);
|
|
331
331
|
print('or for the current project only, on this machine:');
|
|
332
332
|
print(` ${claudeCodeCommand(deps.node, deps.entry, 'local')}`);
|
|
333
|
+
const powerShellNote = claudeCodePowerShellNote(deps.node);
|
|
334
|
+
if (powerShellNote) {
|
|
335
|
+
print(powerShellNote);
|
|
336
|
+
}
|
|
333
337
|
print('');
|
|
334
338
|
print(`Both name this Node.js: ${deps.node}. After changing or updating Node.js (nvm, installer), run \`${deps.command} init\` again for new ones.`);
|
|
335
339
|
}
|
package/dist/cli/snippets.js
CHANGED
|
@@ -41,9 +41,24 @@ export function claudeDesktopSnippet(node, entry) {
|
|
|
41
41
|
/**
|
|
42
42
|
* `claude mcp add` command registering the connector in Claude Code. The
|
|
43
43
|
* paths go between double quotes, which PowerShell, cmd and POSIX shells
|
|
44
|
-
* all read the same way for a path (no `"` in a path on Windows).
|
|
44
|
+
* all read the same way for a path (no `"` in a path on Windows). The `--`
|
|
45
|
+
* reaches `claude` from every shell when it is an executable or a `.cmd`
|
|
46
|
+
* shim; see {@link claudeCodePowerShellNote} for the one exception.
|
|
45
47
|
*/
|
|
46
48
|
export function claudeCodeCommand(node, entry, scope = 'user') {
|
|
47
49
|
return `claude mcp add ${SERVER_NAME} --scope ${scope} -- "${node}" "${entry}"`;
|
|
48
50
|
}
|
|
51
|
+
/**
|
|
52
|
+
* The one case where {@link claudeCodeCommand} breaks: in PowerShell, when
|
|
53
|
+
* `claude` is the `claude.ps1` shim of an npm global install, PowerShell
|
|
54
|
+
* itself takes `--` as its end-of-parameters marker and never passes it on
|
|
55
|
+
* (a native `claude.exe` or a `.cmd` receives it). Written `'--'`, it
|
|
56
|
+
* arrives in all three cases. Only for Windows paths; `null` otherwise.
|
|
57
|
+
*/
|
|
58
|
+
export function claudeCodePowerShellNote(node) {
|
|
59
|
+
if (!/^[A-Za-z]:\\/.test(node)) {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
return "In PowerShell, if `Get-Command claude` shows a claude.ps1 (npm install), write '--' instead of --.";
|
|
63
|
+
}
|
|
49
64
|
//# sourceMappingURL=snippets.js.map
|
package/dist/core.js
CHANGED
|
@@ -17,10 +17,12 @@ import { HeadlessGmSession } from './foundry/headless-gm-session.js';
|
|
|
17
17
|
import { BRIDGE_PROTOCOL_VERSION, ModuleBridge } from './foundry/module-bridge.js';
|
|
18
18
|
import { defaultStateDir } from './shared/paths.js';
|
|
19
19
|
import { routeResourceRequest, routeToolRequest } from './tools/index.js';
|
|
20
|
+
import { needsBridge, resourceDependency, toolDependency, waitsForSocket, } from './tools/tool-dependencies.js';
|
|
20
21
|
import { isWriteTool } from './tools/write-tools.js';
|
|
21
22
|
import { DiagnosticSystem } from './utils/diagnostics.js';
|
|
22
23
|
import { redactToolArgs } from './utils/log-args.js';
|
|
23
24
|
import { logger } from './utils/logger.js';
|
|
25
|
+
import { bareMessage } from './utils/mcp-errors.js';
|
|
24
26
|
import { isRefusal, refusalError } from './utils/refusal.js';
|
|
25
27
|
import { SerialQueue } from './utils/serial-queue.js';
|
|
26
28
|
/**
|
|
@@ -29,8 +31,17 @@ import { SerialQueue } from './utils/serial-queue.js';
|
|
|
29
31
|
* socket.io transport reconnection a few.
|
|
30
32
|
*/
|
|
31
33
|
export const TOOL_RECONNECT_WAIT_MS = 15_000;
|
|
32
|
-
/**
|
|
33
|
-
|
|
34
|
+
/**
|
|
35
|
+
* How long a call that needs the companion module waits for it while the
|
|
36
|
+
* headless page is starting or reconnecting. The module authenticates about
|
|
37
|
+
* 0.6 s after `game.ready`, about 4 s after the browser launch.
|
|
38
|
+
*/
|
|
39
|
+
export const BRIDGE_CONNECT_WAIT_MS = 10_000;
|
|
40
|
+
/**
|
|
41
|
+
* A page logged in for longer than this without a module is not about to
|
|
42
|
+
* get one: the watchdog reloads it, and a call is refused at once meanwhile.
|
|
43
|
+
*/
|
|
44
|
+
export const BRIDGE_LOGGED_IN_GRACE_MS = 15_000;
|
|
34
45
|
/**
|
|
35
46
|
* True when the headless GM page shares the connector's account (and
|
|
36
47
|
* session): no FOUNDRY_HEADLESS_GM_USERNAME, or the same name as
|
|
@@ -39,6 +50,13 @@ const NO_RECONNECT_WAIT_TOOLS = new Set(['get_health_status']);
|
|
|
39
50
|
export function isSharedAccount(headlessUsername, foundryUsername) {
|
|
40
51
|
return !headlessUsername || headlessUsername === foundryUsername;
|
|
41
52
|
}
|
|
53
|
+
/** The reason of a refusal for the log: an McpError's text without its "MCP error <code>: " prefix. */
|
|
54
|
+
function refusalReason(error) {
|
|
55
|
+
if (error instanceof McpError) {
|
|
56
|
+
return bareMessage(error);
|
|
57
|
+
}
|
|
58
|
+
return error instanceof Error ? error.message : String(error);
|
|
59
|
+
}
|
|
42
60
|
/** One line for get_health_status: the configuration file and where settings come from. */
|
|
43
61
|
function configurationSummary() {
|
|
44
62
|
let settings;
|
|
@@ -98,6 +116,7 @@ export class FoundryCore {
|
|
|
98
116
|
}
|
|
99
117
|
// Same state directory as the shared process's daemon.json, in both modes.
|
|
100
118
|
clientConfig.journalHistoryDir = path.join(defaultStateDir(), 'journal-history');
|
|
119
|
+
clientConfig.journalConflictsFile = path.join(defaultStateDir(), 'journal-conflicts.json');
|
|
101
120
|
// Shared account: the page reuses the connector's own session, so the
|
|
102
121
|
// connector's user id already covers it. Separate account: its changes
|
|
103
122
|
// are the connector's own too.
|
|
@@ -284,17 +303,17 @@ export class FoundryCore {
|
|
|
284
303
|
async executeTool(name, args) {
|
|
285
304
|
logger.info('Executing tool', { name, args: redactToolArgs(args) });
|
|
286
305
|
try {
|
|
287
|
-
await this.waitForReconnection(name);
|
|
306
|
+
await this.waitForReconnection(toolDependency(name));
|
|
307
|
+
if (needsBridge(name, args)) {
|
|
308
|
+
await this.waitForModule();
|
|
309
|
+
}
|
|
288
310
|
return (await routeToolRequest(name, args, this.foundryClient, this.diagnosticsClient, this.diagnosticSystem, this.moduleBridge, this.headlessGmSession, this.healthRuntime()));
|
|
289
311
|
}
|
|
290
312
|
catch (error) {
|
|
291
313
|
if (isRefusal(error)) {
|
|
292
314
|
// Turned down by design (e.g. an outdated journal page version): the
|
|
293
315
|
// caller is told why; the log needs one line, not a stack.
|
|
294
|
-
logger.warn('Tool call refused', {
|
|
295
|
-
name,
|
|
296
|
-
reason: error instanceof Error ? error.message : String(error),
|
|
297
|
-
});
|
|
316
|
+
logger.warn('Tool call refused', { name, reason: refusalReason(error) });
|
|
298
317
|
}
|
|
299
318
|
else {
|
|
300
319
|
logger.error('Tool execution failed:', error);
|
|
@@ -306,13 +325,15 @@ export class FoundryCore {
|
|
|
306
325
|
}
|
|
307
326
|
}
|
|
308
327
|
/**
|
|
309
|
-
* A call made while the connection is being
|
|
310
|
-
* keeps its place in the write queue
|
|
311
|
-
* reason if it is still down: reads
|
|
312
|
-
* live, and nothing may be sent on
|
|
328
|
+
* A call that needs the socket, made while the connection is being
|
|
329
|
+
* restored, waits for it (a write keeps its place in the write queue
|
|
330
|
+
* meanwhile), then is refused with the reason if it is still down: reads
|
|
331
|
+
* would answer from a cache nobody keeps live, and nothing may be sent on
|
|
332
|
+
* an anonymous socket. Calls that never touch the socket (module, REST,
|
|
333
|
+
* local, health) go ahead at once; see {@link toolDependency}.
|
|
313
334
|
*/
|
|
314
|
-
async waitForReconnection(
|
|
315
|
-
if (
|
|
335
|
+
async waitForReconnection(dependency) {
|
|
336
|
+
if (!waitsForSocket(dependency) || !this.foundryClient.isReconnecting()) {
|
|
316
337
|
return;
|
|
317
338
|
}
|
|
318
339
|
if (await this.foundryClient.waitUntilConnected(TOOL_RECONNECT_WAIT_MS)) {
|
|
@@ -322,6 +343,44 @@ export class FoundryCore {
|
|
|
322
343
|
throw refusalError(ErrorCode.InvalidRequest, `Reconnecting to FoundryVTT… (${state}${error ? `: ${error}` : ''}). ` +
|
|
323
344
|
'The connector retries on its own; try again in a moment.');
|
|
324
345
|
}
|
|
346
|
+
/**
|
|
347
|
+
* A call that needs the companion module waits for it while the headless
|
|
348
|
+
* page is on its way (browser starting, /game loading, page reconnecting,
|
|
349
|
+
* just logged in), up to {@link BRIDGE_CONNECT_WAIT_MS}. It is refused at
|
|
350
|
+
* once when the module cannot come: the bridge is disabled or failed to
|
|
351
|
+
* start, the browser could not be launched, no headless session is
|
|
352
|
+
* configured, the session is failing, or the page has been logged in for
|
|
353
|
+
* more than {@link BRIDGE_LOGGED_IN_GRACE_MS} without a module.
|
|
354
|
+
*/
|
|
355
|
+
async waitForModule() {
|
|
356
|
+
const bridge = this.moduleBridge;
|
|
357
|
+
if (bridge?.isConnected()) {
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
const refuse = (reason) => refusalError(ErrorCode.InvalidRequest, `The companion module is not connected: ${reason}`);
|
|
361
|
+
if (!bridge) {
|
|
362
|
+
throw refuse(this.bridgeError !== null
|
|
363
|
+
? `the module bridge failed to start (${this.bridgeError}). Fix the cause (often the port is taken), then restart the shared process (foundryvtt-mcp stop).`
|
|
364
|
+
: 'the module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');
|
|
365
|
+
}
|
|
366
|
+
const session = this.headlessGmSession;
|
|
367
|
+
if (!session) {
|
|
368
|
+
throw refuse(this.headlessLaunchError !== null
|
|
369
|
+
? `the headless GM browser could not be launched (${this.headlessLaunchError}).`
|
|
370
|
+
: 'no headless GM session is configured (FOUNDRY_HEADLESS_GM_ENABLED and credentials), and the module only connects from it.');
|
|
371
|
+
}
|
|
372
|
+
if (session.isRetrying()) {
|
|
373
|
+
throw refuse(`the headless GM session is failing and retries on its own — ${session.statusText()}`);
|
|
374
|
+
}
|
|
375
|
+
const loggedInSince = session.loggedInSince();
|
|
376
|
+
if (loggedInSince !== null && Date.now() - loggedInSince > BRIDGE_LOGGED_IN_GRACE_MS) {
|
|
377
|
+
throw refuse('the headless GM page is logged in but the module has not connected; the watchdog reloads the page. Check that the companion module is enabled in the world.');
|
|
378
|
+
}
|
|
379
|
+
if (await bridge.waitUntilConnected(BRIDGE_CONNECT_WAIT_MS)) {
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
throw refuse(`still waiting for it after ${BRIDGE_CONNECT_WAIT_MS / 1000} s — ${session.statusText()}. Try again in a moment.`);
|
|
383
|
+
}
|
|
325
384
|
/** Logs {@link gamemasterAccountWarning} after each authentication. */
|
|
326
385
|
warnIfGamemaster() {
|
|
327
386
|
const warning = gamemasterAccountWarning(this.sharedAccount, this.foundryClient.accountInfo());
|
|
@@ -344,10 +403,16 @@ export class FoundryCore {
|
|
|
344
403
|
async readResource(uri) {
|
|
345
404
|
logger.info('Reading resource', { uri });
|
|
346
405
|
try {
|
|
406
|
+
await this.waitForReconnection(resourceDependency(uri));
|
|
347
407
|
return (await routeResourceRequest(uri, this.foundryClient, this.diagnosticsClient));
|
|
348
408
|
}
|
|
349
409
|
catch (error) {
|
|
350
|
-
|
|
410
|
+
if (isRefusal(error)) {
|
|
411
|
+
logger.warn('Resource read refused', { uri, reason: refusalReason(error) });
|
|
412
|
+
}
|
|
413
|
+
else {
|
|
414
|
+
logger.error('Resource read failed:', error);
|
|
415
|
+
}
|
|
351
416
|
if (error instanceof McpError) {
|
|
352
417
|
throw error;
|
|
353
418
|
}
|
|
@@ -379,6 +444,7 @@ export class FoundryCore {
|
|
|
379
444
|
return {
|
|
380
445
|
foundryConnected: this.foundryClient.isConnected(),
|
|
381
446
|
foundryConnection: this.foundryClient.connectionStatus(),
|
|
447
|
+
staleCache: this.foundryClient.worldDataStaleness(),
|
|
382
448
|
account: account
|
|
383
449
|
? {
|
|
384
450
|
name: account.name,
|
|
@@ -24,13 +24,32 @@ function httpStatus(error) {
|
|
|
24
24
|
: undefined;
|
|
25
25
|
}
|
|
26
26
|
/**
|
|
27
|
-
*
|
|
28
|
-
* (or with a module that lacks the
|
|
29
|
-
* an expected refusal, logged as
|
|
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.
|
|
30
31
|
*/
|
|
31
32
|
export class RestApiRequiredError extends RefusedError {
|
|
32
33
|
name = 'RestApiRequiredError';
|
|
33
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
|
+
}
|
|
34
53
|
/**
|
|
35
54
|
* Client for accessing FoundryVTT diagnostic and logging information
|
|
36
55
|
*
|
|
@@ -61,6 +80,12 @@ export class DiagnosticsClient {
|
|
|
61
80
|
*/
|
|
62
81
|
/** The health endpoint answered 404 once already: warned, not again. */
|
|
63
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
|
+
}
|
|
64
89
|
constructor(foundryClient) {
|
|
65
90
|
this.foundryClient = foundryClient;
|
|
66
91
|
}
|
|
@@ -89,6 +114,7 @@ export class DiagnosticsClient {
|
|
|
89
114
|
* ```
|
|
90
115
|
*/
|
|
91
116
|
async getRecentLogs(params = {}) {
|
|
117
|
+
this.requireRestApi('Recent logs');
|
|
92
118
|
try {
|
|
93
119
|
logger.debug('DiagnosticsClient | Getting recent logs', params);
|
|
94
120
|
const searchParams = new URLSearchParams();
|
|
@@ -118,8 +144,7 @@ export class DiagnosticsClient {
|
|
|
118
144
|
return parsed;
|
|
119
145
|
}
|
|
120
146
|
catch (error) {
|
|
121
|
-
|
|
122
|
-
throw new Error(`Failed to retrieve recent logs: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
147
|
+
throw restFailure('Recent logs', error);
|
|
123
148
|
}
|
|
124
149
|
}
|
|
125
150
|
/**
|
|
@@ -150,6 +175,7 @@ export class DiagnosticsClient {
|
|
|
150
175
|
* ```
|
|
151
176
|
*/
|
|
152
177
|
async searchLogs(params) {
|
|
178
|
+
this.requireRestApi('Log search');
|
|
153
179
|
try {
|
|
154
180
|
logger.debug('DiagnosticsClient | Searching logs', params);
|
|
155
181
|
const searchParams = new URLSearchParams();
|
|
@@ -173,8 +199,7 @@ export class DiagnosticsClient {
|
|
|
173
199
|
return parsed;
|
|
174
200
|
}
|
|
175
201
|
catch (error) {
|
|
176
|
-
|
|
177
|
-
throw new Error(`Failed to search logs: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
202
|
+
throw restFailure('Log search', error);
|
|
178
203
|
}
|
|
179
204
|
}
|
|
180
205
|
/**
|
|
@@ -196,9 +221,7 @@ export class DiagnosticsClient {
|
|
|
196
221
|
* ```
|
|
197
222
|
*/
|
|
198
223
|
async getSystemHealth() {
|
|
199
|
-
|
|
200
|
-
throw new RestApiRequiredError('System health requires the REST API module (FOUNDRY_API_KEY is not set)');
|
|
201
|
-
}
|
|
224
|
+
this.requireRestApi('System health');
|
|
202
225
|
try {
|
|
203
226
|
logger.debug('DiagnosticsClient | Getting system health');
|
|
204
227
|
const response = await this.foundryClient.get('/api/diagnostics/health');
|
|
@@ -218,8 +241,7 @@ export class DiagnosticsClient {
|
|
|
218
241
|
}
|
|
219
242
|
throw new RestApiRequiredError('System health is unavailable: the REST API module does not provide /api/diagnostics/health (HTTP 404)');
|
|
220
243
|
}
|
|
221
|
-
|
|
222
|
-
throw new Error(`Failed to retrieve system health: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
244
|
+
throw restFailure('System health', error);
|
|
223
245
|
}
|
|
224
246
|
}
|
|
225
247
|
/**
|
|
@@ -246,6 +268,7 @@ export class DiagnosticsClient {
|
|
|
246
268
|
* ```
|
|
247
269
|
*/
|
|
248
270
|
async diagnoseErrors(timeframe = 3600) {
|
|
271
|
+
this.requireRestApi('Error diagnosis');
|
|
249
272
|
try {
|
|
250
273
|
logger.debug('DiagnosticsClient | Diagnosing errors', { timeframe });
|
|
251
274
|
const searchParams = new URLSearchParams();
|
|
@@ -261,92 +284,7 @@ export class DiagnosticsClient {
|
|
|
261
284
|
return parsed;
|
|
262
285
|
}
|
|
263
286
|
catch (error) {
|
|
264
|
-
|
|
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;
|
|
287
|
+
throw restFailure('Error diagnosis', error);
|
|
350
288
|
}
|
|
351
289
|
}
|
|
352
290
|
}
|
package/dist/foundry/auth.js
CHANGED
|
@@ -195,6 +195,10 @@ export async function authenticateFoundry(baseUrl, user, password) {
|
|
|
195
195
|
// FoundryVTT v14 rejects POST /join without an Origin header (HTTP 400),
|
|
196
196
|
// so send the server's own origin as a browser would.
|
|
197
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',
|
|
198
202
|
},
|
|
199
203
|
// Accept 200 (success JSON), 302 (redirect to /game on success) and 401
|
|
200
204
|
// (bad password). 401 carries FoundryVTT's own explanation in the body;
|