@g33ks/foundryvtt-mcp 2.0.0 β†’ 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +21 -29
  2. package/dist/cli/init.js +5 -1
  3. package/dist/cli/snippets.js +16 -1
  4. package/dist/core.js +104 -14
  5. package/dist/diagnostics/client.js +36 -98
  6. package/dist/foundry/auth.js +4 -0
  7. package/dist/foundry/client.js +750 -157
  8. package/dist/foundry/event-log.js +2 -3
  9. package/dist/foundry/headless-gm-session.js +119 -2
  10. package/dist/foundry/journal-conflicts.js +141 -0
  11. package/dist/foundry/journal-integrity.js +20 -4
  12. package/dist/foundry/message-author.js +19 -0
  13. package/dist/foundry/module-bridge.js +153 -6
  14. package/dist/foundry/world-cache.js +206 -8
  15. package/dist/mcp-server.js +5 -3
  16. package/dist/shared/control.js +47 -6
  17. package/dist/shared/daemon.js +2 -4
  18. package/dist/shared/protocol.js +14 -10
  19. package/dist/tools/definitions.js +128 -31
  20. package/dist/tools/handlers/actor-mutations.js +13 -7
  21. package/dist/tools/handlers/actor-target.js +80 -0
  22. package/dist/tools/handlers/actors.js +25 -12
  23. package/dist/tools/handlers/chat.js +3 -1
  24. package/dist/tools/handlers/combat-mutations.js +3 -2
  25. package/dist/tools/handlers/combat.js +48 -17
  26. package/dist/tools/handlers/diagnostics.js +14 -2
  27. package/dist/tools/handlers/effects.js +23 -24
  28. package/dist/tools/handlers/item-mutations.js +23 -21
  29. package/dist/tools/handlers/module-bridge.js +131 -2
  30. package/dist/tools/handlers/token-mutations.js +151 -16
  31. package/dist/tools/handlers/utils.js +3 -2
  32. package/dist/tools/router.js +6 -23
  33. package/dist/tools/tool-dependencies.js +207 -0
  34. package/dist/utils/mcp-errors.js +47 -0
  35. package/package.json +5 -5
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
6
6
  [![Node.js](https://img.shields.io/badge/Node.js-22%2B-green.svg)](https://nodejs.org/)
7
7
  [![TypeScript](https://img.shields.io/badge/TypeScript-6-blue.svg)](https://www.typescriptlang.org/)
8
- [![Tools](https://img.shields.io/badge/MCP%20Tools-114-purple.svg)](https://modelcontextprotocol.io/)
8
+ [![Tools](https://img.shields.io/badge/MCP%20Tools-115-purple.svg)](https://modelcontextprotocol.io/)
9
9
 
10
10
  A comprehensive, production-grade [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) server for **Foundry Virtual Tabletop (FoundryVTT)**.
11
11
 
@@ -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
- ```mermaid
21
- flowchart LR
22
- subgraph PC["Your computer"]
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
+ ![How it works: on your computer, each AI client (Claude Desktop, Claude Code…) starts a relay over MCP stdio; the relays hand their requests through a named pipe or Unix socket to one shared process. That process reads and writes the FoundryVTT world over Socket.IO, optionally queries the REST API module over HTTP, and launches an invisible GM browser that loads the game page as a GM user; the companion module in that page talks to the shared process over an authenticated loopback WebSocket bridge.](https://raw.githubusercontent.com/G33ks/foundryvtt-mcp/main/docs/assets/how-it-works.png)
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
 
@@ -41,13 +28,13 @@ Your AI assistant starts a small relay program for this server. Every relay, fro
41
28
  - **Live world cache**: on connect, the server loads the world over Socket.IO and keeps it in memory; every `modifyDocument` broadcast β€” from the AI's own writes or from any user in Foundry β€” updates it, so reads are instant and stay current. `refresh_world_data` forces a full reload.
42
29
  - **Socket.IO connection**: authenticates as `FOUNDRY_USERNAME` (Assistant GM role recommended) and performs every write over Foundry's core `modifyDocument` protocol β€” only when `FOUNDRY_WRITE_ENABLED=true`. It is the only side that logs in: when Foundry forgets its session (server restart, world shut down) it logs in again by itself, retrying every 5 s at first and at most every 2 min, and tool calls made meanwhile wait up to 15 s before being refused with the reason.
43
30
  - **Invisible GM session**: started when `FOUNDRY_MODULE_BRIDGE_ENABLED=true`. The shared process drives a background browser through `playwright-core`: the first one found among Chrome, Edge, Brave, Vivaldi, a system Chromium and Playwright's own Chromium (`npx playwright install chromium`), or the Chromium-based browser set in `FOUNDRY_HEADLESS_GM_EXECUTABLE_PATH`. The page shares the Socket.IO connection's session β€” one account, one login β€” and never fills the `/join` form: Foundry keeps several connections per session, so neither ejects the other. The page stays on `/game` (a navigation elsewhere, such as **Log Out**, is blocked and the page reloads `/game`, because leaving would log the shared session out). A watchdog reloads the page if the module stays disconnected for about a minute. Advanced: `FOUNDRY_HEADLESS_GM_USERNAME` / `FOUNDRY_HEADLESS_GM_PASSWORD` naming another account give the page its own login instead. A human can meanwhile play as a normal **Player** in their own browser.
44
- - **Companion module** (`foundryvtt-mcp-bridge`, 0.5.0 or later): runs only in that GM session and serves the bridge tools β€” `capture_scene` (canvas screenshot with a grid overlay), `roll_and_post` (native `Roll` chat cards), `get_document_schema`, `search_compendium_content` and compendium imports, `upload_asset` (FilePicker), `set_pause`, `ping_canvas`, `set_target` / `get_targets`. Without it these tools report unavailable; everything else keeps working. The bridge listens on loopback only and authenticates the module β€” see [Module Bridge Security](#module-bridge-security).
31
+ - **Companion module** (`foundryvtt-mcp-bridge`, 0.5.0 or later): runs only in that GM session and serves the bridge tools β€” `capture_scene` (canvas screenshot with a grid overlay), `roll_and_post` (native `Roll` chat cards), `get_document_schema`, `search_compendium_content` and compendium imports, `upload_asset` (FilePicker), `set_pause`, `ping_canvas`, `set_target` / `get_targets`, and since 0.6.0 `get_actor_stats` (an actor's prepared data) and the game system's own path for `apply_status_effect`. Without it these tools report unavailable (`apply_status_effect` keeps its socket path); everything else keeps working. From 0.6.0 the module announces its version and commands when it connects, and the server sends it no command it does not announce; an older module is sent only the commands every 0.5 module serves. The bridge listens on loopback only and authenticates the module β€” see [Module Bridge Security](#module-bridge-security).
45
32
  - **Optional REST API module**: with `FOUNDRY_API_KEY` set, the server also connects to the Foundry Local REST API module over HTTP. It backs the diagnostics tools (`get_health_status`, `get_system_health`, `get_recent_logs`, `search_logs`, `diagnose_errors`) and `search_compendium`, and some reads use it instead of the cache (actor and item search, actor details, scene and world info, `roll_dice`). Socket.IO stays the main connection and carries every write.
46
33
  - **Shared process** (default): MCP clients may start several server instances β€” Claude Desktop starts several at launch β€” so each instance is only a lightweight relay, and the FoundryVTT connection, the bridge and the GM session live once, in a background process every relay shares. See [Shared Process Mode](#shared-process-mode); `FOUNDRY_MCP_SHARED=false` runs everything in one process instead.
47
34
 
48
35
  ---
49
36
 
50
- ## 🌟 Key Highlights & Capabilities (114 Tools)
37
+ ## 🌟 Key Highlights & Capabilities (115 Tools)
51
38
 
52
39
  - πŸ‘οΈ **Real-Time Event Stream & Activity Log (`watch_events`)**: Zero-polling event awareness via Socket.IO `modifyDocument` and companion bridge pushes. An AI DM agent can long-poll on a cursor-addressed stream (`cursor`, `waitMs`, `excludeSelf`, `types`, `sceneId`) to react instantly when players chat, move tokens, advance combat, toggle doors, or select targets.
53
40
  - 🎲 **Game Mechanics & Interactive Chat**: Roll dice with standard or complex drop/keep notation (`4d6kh3`, `1d20r1`). Roll and post interactive, clickable chat cards directly to the Foundry chat log via the companion bridge (`roll_and_post`).
@@ -65,7 +52,7 @@ Your AI assistant starts a small relay program for this server. Every relay, fro
65
52
  - πŸ§™ **Token & Actor Control**:
66
53
  - **A\* Pathfinding Movement**: tokens navigate around walls and automatically open closed doors along their path (`move_token_pathfind`).
67
54
  - **Token Vision & Lighting**: configure sight ranges, vision modes, dim/bright emitted light, and vision detection angles (`update_token_vision`).
68
- - **Generalized ActiveEffects**: create, update, delete, and inspect mechanical buffs/debuffs with attribute changes (`key`, `mode`, `value`, `priority`) and durations (`rounds`, `seconds`, `turns`) on top-level or synthetic unlinked token actors (`create_actor_effect`, `update_actor_effect`, `delete_actor_effect`, `list_actor_effects`).
55
+ - **Generalized ActiveEffects**: create, update, delete, and inspect mechanical buffs/debuffs with attribute changes (`key`, `mode`, `value`, `priority`) and durations (`rounds`, `seconds`, `turns`) on world actors or on one token (an unlinked token changes alone, not its base actor) (`create_actor_effect`, `update_actor_effect`, `delete_actor_effect`, `list_actor_effects`).
69
56
  - **Status Conditions**: apply/remove system-agnostic status conditions (`apply_status_effect`).
70
57
  - **Compendium Actor & Item Import**: import entire NPC/monster documents from compendium packs with automatic per-item error recovery (`import_compendium_actor`), or import specific items into actor inventories (`create_actor_item`).
71
58
  - **System Attribute Mutations**: patch actor system data (HP, temporary HP, currency, resources, spell slots) using JSON merge patches (`update_actor_attributes`).
@@ -271,7 +258,8 @@ The bridge drives a GM session, and its loopback port is reachable by every loca
271
258
 
272
259
  - **Origin**: the WebSocket upgrade is refused (HTTP 403) unless its `Origin` header is the origin of `FOUNDRY_URL` β€” a page from another site cannot open the socket.
273
260
  - **Mutual handshake (protocol v1)**: the server sends a random challenge; the module answers with an HMAC-SHA256 proof, and the server answers with its own proof, which the module checks before obeying. Both are keyed by a random secret the shared process generates at startup and keeps in memory only β€” never written to disk, logged or returned by a tool. The headless GM session exposes a `window.foundryMcpBridge` function to its page (a Playwright binding) that computes the proofs, so the secret never enters the page or the WebSocket. It disappears with the shared process.
274
- - **Until authenticated**, a connection receives no command, nothing it sends is processed, and it cannot displace the connected module. It is closed with `4401` (wrong proof, unknown protocol, any other message), `4408` (no answer within 5 s β€” typically a module older than 0.5.0, logged as such) or `1009` (a message over 4 KiB). Refusals are logged as warnings (rate-limited); `status` and `get_health_status` show whether an authenticated module is connected.
261
+ - **Until authenticated**, a connection receives no command, nothing it sends is processed, and it cannot displace the connected module. It is closed with `4401` (wrong proof, unknown protocol, any other message), `4408` (no answer within 5 s β€” typically a module older than 0.5.0, logged as such) or `1009` (a message over 4 KiB). Refusals are logged as warnings (rate-limited); `status` and `get_health_status` show whether an authenticated module is connected, and its version: the one it announced (0.6.0 or later), otherwise the version installed in the world followed by `(not announced)`.
262
+ - **Module announcement (0.6.0 or later)**: the module's answer to the challenge also lists its version and the commands it serves. The proofs do not cover this list: it only decides which commands the server tries to send, and an absent or malformed one never fails the authentication.
275
263
  - **No manual GM tab**: a GM tab opened by hand has no `window.foundryMcpBridge`, so the module logs `no foundryvtt-mcp credentials in this browser, bridge disabled` to the browser console and stays silent. `FOUNDRY_HEADLESS_GM_ENABLED=false` therefore disables the bridge in practice.
276
264
  - **Check it**: with the connector running and the module connected, `npm run check:bridge-security`, from a clone, tries four forged connections and confirms each is refused while the module stays connected.
277
265
 
@@ -303,6 +291,8 @@ With the settings in the [configuration file](#configuration-file), add to `clau
303
291
 
304
292
  `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
293
 
294
+ > **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.
295
+
306
296
  ```json
307
297
  {
308
298
  "mcpServers": {
@@ -336,7 +326,7 @@ Add to `~/.omp/agent/mcp.json` (or `~/.omp/mcp.json`):
336
326
 
337
327
  ---
338
328
 
339
- ## πŸ› οΈ Tool Catalog (114 Tools)
329
+ ## πŸ› οΈ Tool Catalog (115 Tools)
340
330
 
341
331
  ### 1. Real-Time Event Awareness
342
332
  - `watch_events` β€” long-poll a cursor-addressed activity log (`cursor`, `waitMs`, `limit`, `kinds`, `types`, `actions`, `sceneId`, `excludeSelf`) capturing document broadcasts and canvas activity without polling.
@@ -365,23 +355,25 @@ Add to `~/.omp/agent/mcp.json` (or `~/.omp/mcp.json`):
365
355
  - `move_tokens` β€” batch move multiple tokens simultaneously.
366
356
  - `set_target` / `get_targets` β€” set and inspect token targeting reticles across connected users.
367
357
  - `update_token_vision` β€” configure vision ranges, vision modes, dim/bright emitted lights, and angles.
368
- - `apply_status_effect` β€” toggle simple status conditions (`prone`, `stunned`, `blinded`, `invisible`, etc.).
358
+ - `apply_status_effect` β€” toggle status conditions (`prone`, `stunned`, `blinded`, `invisible`, etc.). With the companion module 0.6.0 or later connected (it waits up to 10 s for one still connecting), it goes through the game system's own status effects, so the system recognises the condition, and effects an earlier version wrote for the status are reported, then removed with `active=false`. A game system that asks for a value when a status is created gets it from `createOptions`, under the option name the system documents; without it the call fails at once and nothing is created. `createOptions` are refused when that path is not available. Otherwise it writes an effect carrying the status over the socket (token icon always shown), which a game system that defines its own statuses with fixed effect ids may not recognise. The answer names the path used.
369
359
 
370
360
  ### 4. Actors & Inventory
371
361
  - `create_world_actor` / `create_full_actor` / `delete_world_actor` β€” create and delete actor documents.
372
362
  - `import_compendium_actor` β€” import entire NPCs/monsters from compendium packs with embedded items and automatic error recovery.
373
363
  - `search_actors` β€” query actors by name and type with cursor pagination support.
374
- - `get_actor_details` β€” retrieve actor system data, statistics, attributes, and health.
375
- - `update_actor_attributes` β€” patch nested system data using dot paths (`attributes.hp.value`, `currency.gp`).
376
- - `get_actor_inventory` β€” list owned items with full system properties.
364
+ - `get_actor_details` β€” retrieve actor system data, statistics, attributes, and health; with `sceneId` + `tokenId`, those of one token (an unlinked token has its own).
365
+ - `update_actor_attributes` β€” patch nested system data using dot paths (`attributes.hp.value`, `currency.gp`), on a world actor or one token. Write stored fields only: a field the game system computes is saved but has no effect in play.
366
+ - `get_actor_inventory` β€” list owned items with full system properties, of a world actor or one token.
367
+ - `get_actor_stats` β€” an actor's prepared system data as JSON, including the values the game system computes and does not store, of a world actor or one token; `paths` narrows it, `maxBytes` bounds it (companion module 0.6.0 or later).
377
368
  - `search_items` β€” search world item documents by name, optionally filtered by type (world items, not owned items).
378
369
  - `create_actor_item` β€” create inline items OR import directly from compendium packs (`source: { type: 'compendium', compendiumId, itemId }`).
379
370
  - `update_actor_item` β€” apply JSON merge patches to owned items.
380
371
  - `delete_actor_item` β€” delete specific items from actor inventories.
381
- - `create_actor_effect` / `update_actor_effect` / `delete_actor_effect` / `list_actor_effects` β€” general-purpose ActiveEffects with mechanical changes (`key`, `mode`, `value`, `priority`) and durations on top-level or synthetic unlinked token actors.
372
+ - The three item tools also take `sceneId` + `tokenId`: on an unlinked token, only that token changes.
373
+ - `create_actor_effect` / `update_actor_effect` / `delete_actor_effect` / `list_actor_effects` β€” general-purpose ActiveEffects with mechanical changes (`key`, `mode`, `value`, `priority`) and durations, on a world actor or one token (on an unlinked token, only that token changes).
382
374
 
383
375
  ### 5. Combat Encounters
384
- - `start_combat` β€” create encounters and seed combatants from scene tokens.
376
+ - `start_combat` β€” create encounters and seed combatants from scene tokens; the encounter begins at round 1.
385
377
  - `get_combat_state` β€” retrieve combatant turn order, HP, AC, and round number.
386
378
  - `set_initiative` β€” set combatant initiative values and re-order turns.
387
379
  - `next_turn` β€” advance the turn tracker (handles round increments and skips defeated combatants).
@@ -411,7 +403,7 @@ Add to `~/.omp/agent/mcp.json` (or `~/.omp/mcp.json`):
411
403
  - `roll_dice` β€” local mathematical dice formula evaluation.
412
404
  - `roll_and_post` β€” evaluates formulas via Foundry's native engine and posts interactive chat cards.
413
405
  - `lookup_rule` β€” search world journals and system compendium packs for rules with snippet previews.
414
- - `get_document_schema` β€” introspect game system DataModel schemas for actor and item types.
406
+ - `get_document_schema` β€” introspect game system DataModel schemas for actor and item types, with computed (`persisted: false`) fields and number bounds; for a type declared only by template.json, its default values with inferred types (module 0.6.0 or later).
415
407
  - `search_compendium` β€” search compendium packs by name and metadata, across all enabled packs or one pack (requires the REST API module; returns no results without it).
416
408
  - `search_compendium_content` β€” deep search inside compendium pack documents and journal pages.
417
409
  - `send_chat_message` / `get_chat_messages` β€” post and read messages from the Foundry chat log.
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
  }
@@ -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
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import path from 'node:path';
10
10
  import { ErrorCode, McpError, } from '@modelcontextprotocol/sdk/types.js';
11
+ import { BRIDGE_MODULE_ID } from './cli/checks.js';
11
12
  import { config, configSettings } from './config/index.js';
12
13
  import { summarizeSources } from './config/sources.js';
13
14
  import { DiagnosticsClient } from './diagnostics/client.js';
@@ -17,10 +18,12 @@ import { HeadlessGmSession } from './foundry/headless-gm-session.js';
17
18
  import { BRIDGE_PROTOCOL_VERSION, ModuleBridge } from './foundry/module-bridge.js';
18
19
  import { defaultStateDir } from './shared/paths.js';
19
20
  import { routeResourceRequest, routeToolRequest } from './tools/index.js';
21
+ import { needsBridge, prefersBridge, resourceDependency, toolDependency, waitsForSocket, } from './tools/tool-dependencies.js';
20
22
  import { isWriteTool } from './tools/write-tools.js';
21
23
  import { DiagnosticSystem } from './utils/diagnostics.js';
22
24
  import { redactToolArgs } from './utils/log-args.js';
23
25
  import { logger } from './utils/logger.js';
26
+ import { bareMessage } from './utils/mcp-errors.js';
24
27
  import { isRefusal, refusalError } from './utils/refusal.js';
25
28
  import { SerialQueue } from './utils/serial-queue.js';
26
29
  /**
@@ -29,8 +32,17 @@ import { SerialQueue } from './utils/serial-queue.js';
29
32
  * socket.io transport reconnection a few.
30
33
  */
31
34
  export const TOOL_RECONNECT_WAIT_MS = 15_000;
32
- /** Tools that report the connection itself, and so must not wait for it. */
33
- const NO_RECONNECT_WAIT_TOOLS = new Set(['get_health_status']);
35
+ /**
36
+ * How long a call that needs the companion module waits for it while the
37
+ * headless page is starting or reconnecting. The module authenticates about
38
+ * 0.6 s after `game.ready`, about 4 s after the browser launch.
39
+ */
40
+ export const BRIDGE_CONNECT_WAIT_MS = 10_000;
41
+ /**
42
+ * A page logged in for longer than this without a module is not about to
43
+ * get one: the watchdog reloads it, and a call is refused at once meanwhile.
44
+ */
45
+ export const BRIDGE_LOGGED_IN_GRACE_MS = 15_000;
34
46
  /**
35
47
  * True when the headless GM page shares the connector's account (and
36
48
  * session): no FOUNDRY_HEADLESS_GM_USERNAME, or the same name as
@@ -39,6 +51,13 @@ const NO_RECONNECT_WAIT_TOOLS = new Set(['get_health_status']);
39
51
  export function isSharedAccount(headlessUsername, foundryUsername) {
40
52
  return !headlessUsername || headlessUsername === foundryUsername;
41
53
  }
54
+ /** The reason of a refusal for the log: an McpError's text without its "MCP error <code>: " prefix. */
55
+ function refusalReason(error) {
56
+ if (error instanceof McpError) {
57
+ return bareMessage(error);
58
+ }
59
+ return error instanceof Error ? error.message : String(error);
60
+ }
42
61
  /** One line for get_health_status: the configuration file and where settings come from. */
43
62
  function configurationSummary() {
44
63
  let settings;
@@ -98,6 +117,7 @@ export class FoundryCore {
98
117
  }
99
118
  // Same state directory as the shared process's daemon.json, in both modes.
100
119
  clientConfig.journalHistoryDir = path.join(defaultStateDir(), 'journal-history');
120
+ clientConfig.journalConflictsFile = path.join(defaultStateDir(), 'journal-conflicts.json');
101
121
  // Shared account: the page reuses the connector's own session, so the
102
122
  // connector's user id already covers it. Separate account: its changes
103
123
  // are the connector's own too.
@@ -127,6 +147,7 @@ export class FoundryCore {
127
147
  this.moduleBridge = config.moduleBridge.enabled
128
148
  ? new ModuleBridge(config.moduleBridge.port, {
129
149
  expectedOrigin: new URL(config.foundry.url).origin,
150
+ installedModuleVersion: () => this.foundryClient.installedModuleVersion(BRIDGE_MODULE_ID),
130
151
  })
131
152
  : null;
132
153
  if (this.moduleBridge) {
@@ -284,17 +305,20 @@ export class FoundryCore {
284
305
  async executeTool(name, args) {
285
306
  logger.info('Executing tool', { name, args: redactToolArgs(args) });
286
307
  try {
287
- await this.waitForReconnection(name);
308
+ await this.waitForReconnection(toolDependency(name));
309
+ if (needsBridge(name, args)) {
310
+ await this.waitForModule();
311
+ }
312
+ else if (prefersBridge(name) && this.foundryClient.isWriteEnabled()) {
313
+ await this.waitForModuleIfComing();
314
+ }
288
315
  return (await routeToolRequest(name, args, this.foundryClient, this.diagnosticsClient, this.diagnosticSystem, this.moduleBridge, this.headlessGmSession, this.healthRuntime()));
289
316
  }
290
317
  catch (error) {
291
318
  if (isRefusal(error)) {
292
319
  // Turned down by design (e.g. an outdated journal page version): the
293
320
  // 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
- });
321
+ logger.warn('Tool call refused', { name, reason: refusalReason(error) });
298
322
  }
299
323
  else {
300
324
  logger.error('Tool execution failed:', error);
@@ -306,13 +330,15 @@ export class FoundryCore {
306
330
  }
307
331
  }
308
332
  /**
309
- * A call made while the connection is being restored waits for it (a write
310
- * keeps its place in the write queue meanwhile), then is refused with the
311
- * reason if it is still down: reads would answer from a cache nobody keeps
312
- * live, and nothing may be sent on an anonymous socket.
333
+ * A call that needs the socket, made while the connection is being
334
+ * restored, waits for it (a write keeps its place in the write queue
335
+ * meanwhile), then is refused with the reason if it is still down: reads
336
+ * would answer from a cache nobody keeps live, and nothing may be sent on
337
+ * an anonymous socket. Calls that never touch the socket (module, REST,
338
+ * local, health) go ahead at once; see {@link toolDependency}.
313
339
  */
314
- async waitForReconnection(name) {
315
- if (NO_RECONNECT_WAIT_TOOLS.has(name) || !this.foundryClient.isReconnecting()) {
340
+ async waitForReconnection(dependency) {
341
+ if (!waitsForSocket(dependency) || !this.foundryClient.isReconnecting()) {
316
342
  return;
317
343
  }
318
344
  if (await this.foundryClient.waitUntilConnected(TOOL_RECONNECT_WAIT_MS)) {
@@ -322,6 +348,60 @@ export class FoundryCore {
322
348
  throw refusalError(ErrorCode.InvalidRequest, `Reconnecting to FoundryVTT… (${state}${error ? `: ${error}` : ''}). ` +
323
349
  'The connector retries on its own; try again in a moment.');
324
350
  }
351
+ /**
352
+ * A call that needs the companion module waits for it while the headless
353
+ * page is on its way (browser starting, /game loading, page reconnecting,
354
+ * just logged in), up to {@link BRIDGE_CONNECT_WAIT_MS}. It is refused at
355
+ * once when the module cannot come: the bridge is disabled or failed to
356
+ * start, the browser could not be launched, no headless session is
357
+ * configured, the session is failing, or the page has been logged in for
358
+ * more than {@link BRIDGE_LOGGED_IN_GRACE_MS} without a module.
359
+ */
360
+ async waitForModule() {
361
+ const bridge = this.moduleBridge;
362
+ if (bridge?.isConnected()) {
363
+ return;
364
+ }
365
+ const refuse = (reason) => refusalError(ErrorCode.InvalidRequest, `The companion module is not connected: ${reason}`);
366
+ if (!bridge) {
367
+ throw refuse(this.bridgeError !== null
368
+ ? `the module bridge failed to start (${this.bridgeError}). Fix the cause (often the port is taken), then restart the shared process (foundryvtt-mcp stop).`
369
+ : 'the module bridge is disabled. Set FOUNDRY_MODULE_BRIDGE_ENABLED=true and install the companion Foundry module.');
370
+ }
371
+ const session = this.headlessGmSession;
372
+ if (!session) {
373
+ throw refuse(this.headlessLaunchError !== null
374
+ ? `the headless GM browser could not be launched (${this.headlessLaunchError}).`
375
+ : 'no headless GM session is configured (FOUNDRY_HEADLESS_GM_ENABLED and credentials), and the module only connects from it.');
376
+ }
377
+ if (session.isRetrying()) {
378
+ throw refuse(`the headless GM session is failing and retries on its own β€” ${session.statusText()}`);
379
+ }
380
+ const loggedInSince = session.loggedInSince();
381
+ if (loggedInSince !== null && Date.now() - loggedInSince > BRIDGE_LOGGED_IN_GRACE_MS) {
382
+ 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.');
383
+ }
384
+ if (await bridge.waitUntilConnected(BRIDGE_CONNECT_WAIT_MS)) {
385
+ return;
386
+ }
387
+ throw refuse(`still waiting for it after ${BRIDGE_CONNECT_WAIT_MS / 1000} s β€” ${session.statusText()}. Try again in a moment.`);
388
+ }
389
+ /**
390
+ * For a tool that only prefers the module ({@link prefersBridge}): the same
391
+ * wait as {@link waitForModule}, but a module that cannot come, or does not
392
+ * come in time, leaves the call to go ahead on its socket path.
393
+ */
394
+ async waitForModuleIfComing() {
395
+ try {
396
+ await this.waitForModule();
397
+ }
398
+ catch (error) {
399
+ if (!isRefusal(error)) {
400
+ throw error;
401
+ }
402
+ logger.debug('Going ahead without the companion module', { reason: refusalReason(error) });
403
+ }
404
+ }
325
405
  /** Logs {@link gamemasterAccountWarning} after each authentication. */
326
406
  warnIfGamemaster() {
327
407
  const warning = gamemasterAccountWarning(this.sharedAccount, this.foundryClient.accountInfo());
@@ -344,10 +424,16 @@ export class FoundryCore {
344
424
  async readResource(uri) {
345
425
  logger.info('Reading resource', { uri });
346
426
  try {
427
+ await this.waitForReconnection(resourceDependency(uri));
347
428
  return (await routeResourceRequest(uri, this.foundryClient, this.diagnosticsClient));
348
429
  }
349
430
  catch (error) {
350
- logger.error('Resource read failed:', error);
431
+ if (isRefusal(error)) {
432
+ logger.warn('Resource read refused', { uri, reason: refusalReason(error) });
433
+ }
434
+ else {
435
+ logger.error('Resource read failed:', error);
436
+ }
351
437
  if (error instanceof McpError) {
352
438
  throw error;
353
439
  }
@@ -379,6 +465,7 @@ export class FoundryCore {
379
465
  return {
380
466
  foundryConnected: this.foundryClient.isConnected(),
381
467
  foundryConnection: this.foundryClient.connectionStatus(),
468
+ staleCache: this.foundryClient.worldDataStaleness(),
382
469
  account: account
383
470
  ? {
384
471
  name: account.name,
@@ -396,6 +483,9 @@ export class FoundryCore {
396
483
  protocol: BRIDGE_PROTOCOL_VERSION,
397
484
  origin: new URL(config.foundry.url).origin,
398
485
  moduleConnectedSince: this.moduleBridge?.moduleConnectedSince()?.toISOString() ?? null,
486
+ moduleVersion: this.moduleBridge?.moduleAnnouncement().version ?? null,
487
+ moduleInstalledVersion: this.foundryClient.installedModuleVersion(BRIDGE_MODULE_ID),
488
+ moduleCommands: this.moduleBridge?.moduleAnnouncement().commands ?? null,
399
489
  },
400
490
  headlessGm: {
401
491
  enabled: headlessGmState !== 'disabled',
@@ -24,13 +24,32 @@ function httpStatus(error) {
24
24
  : undefined;
25
25
  }
26
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.
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
- 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'}`);
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
- logger.error('DiagnosticsClient | Failed to search logs:', error);
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
- if (!this.foundryClient.hasRestApi()) {
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
- 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'}`);
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
- 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;
287
+ throw restFailure('Error diagnosis', error);
350
288
  }
351
289
  }
352
290
  }
@@ -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;