@g33ks/foundryvtt-mcp 2.1.0 → 2.2.1

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 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
 
@@ -28,13 +28,13 @@ Your AI assistant starts a small relay program for this server. Every relay, fro
28
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.
29
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.
30
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.
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`. 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).
32
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.
33
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.
34
34
 
35
35
  ---
36
36
 
37
- ## 🌟 Key Highlights & Capabilities (114 Tools)
37
+ ## 🌟 Key Highlights & Capabilities (115 Tools)
38
38
 
39
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.
40
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`).
@@ -52,7 +52,7 @@ Your AI assistant starts a small relay program for this server. Every relay, fro
52
52
  - 🧙 **Token & Actor Control**:
53
53
  - **A\* Pathfinding Movement**: tokens navigate around walls and automatically open closed doors along their path (`move_token_pathfind`).
54
54
  - **Token Vision & Lighting**: configure sight ranges, vision modes, dim/bright emitted light, and vision detection angles (`update_token_vision`).
55
- - **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`).
56
56
  - **Status Conditions**: apply/remove system-agnostic status conditions (`apply_status_effect`).
57
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`).
58
58
  - **System Attribute Mutations**: patch actor system data (HP, temporary HP, currency, resources, spell slots) using JSON merge patches (`update_actor_attributes`).
@@ -209,6 +209,7 @@ The same names work in the configuration file, in an `env` block, in the system
209
209
  | `FOUNDRY_HEADLESS_GM_PASSWORD` | No | `FOUNDRY_PASSWORD` | Password of that other account (two-account mode only) |
210
210
  | `FOUNDRY_HEADLESS_GM_EXECUTABLE_PATH` | No | — | Path to any Chromium-based browser binary (Chrome, Edge, Brave, Vivaldi…), skipping auto-detection |
211
211
  | `FOUNDRY_DATA_PATH` | No | — | Local path to Foundry `Data/` for asset dimension discovery |
212
+ | `FOUNDRY_UPLOAD_SOURCE_DIR` | No | — | The one folder `upload_asset` may read a local file from (`sourcePath`); unset, it takes `contentBase64` only |
212
213
  | `FOUNDRY_API_KEY` | No | — | Optional REST API key for server diagnostics tools |
213
214
  | `FOUNDRY_EVENT_BUFFER_SIZE` | No | `500` | In-memory event log ring buffer capacity |
214
215
  | `FOUNDRY_EVENT_WAIT_MS` | No | `25000` | Default long-polling timeout for `watch_events` |
@@ -258,7 +259,8 @@ The bridge drives a GM session, and its loopback port is reachable by every loca
258
259
 
259
260
  - **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.
260
261
  - **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.
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.
262
+ - **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)`.
263
+ - **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.
262
264
  - **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.
263
265
  - **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.
264
266
 
@@ -325,7 +327,7 @@ Add to `~/.omp/agent/mcp.json` (or `~/.omp/mcp.json`):
325
327
 
326
328
  ---
327
329
 
328
- ## 🛠️ Tool Catalog (114 Tools)
330
+ ## 🛠️ Tool Catalog (115 Tools)
329
331
 
330
332
  ### 1. Real-Time Event Awareness
331
333
  - `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.
@@ -354,23 +356,25 @@ Add to `~/.omp/agent/mcp.json` (or `~/.omp/mcp.json`):
354
356
  - `move_tokens` — batch move multiple tokens simultaneously.
355
357
  - `set_target` / `get_targets` — set and inspect token targeting reticles across connected users.
356
358
  - `update_token_vision` — configure vision ranges, vision modes, dim/bright emitted lights, and angles.
357
- - `apply_status_effect` — toggle simple status conditions (`prone`, `stunned`, `blinded`, `invisible`, etc.).
359
+ - `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.
358
360
 
359
361
  ### 4. Actors & Inventory
360
362
  - `create_world_actor` / `create_full_actor` / `delete_world_actor` — create and delete actor documents.
361
363
  - `import_compendium_actor` — import entire NPCs/monsters from compendium packs with embedded items and automatic error recovery.
362
364
  - `search_actors` — query actors by name and type with cursor pagination support.
363
- - `get_actor_details` — retrieve actor system data, statistics, attributes, and health.
364
- - `update_actor_attributes` — patch nested system data using dot paths (`attributes.hp.value`, `currency.gp`).
365
- - `get_actor_inventory` — list owned items with full system properties.
365
+ - `get_actor_details` — retrieve actor system data, statistics, attributes, and health; with `sceneId` + `tokenId`, those of one token (an unlinked token has its own).
366
+ - `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.
367
+ - `get_actor_inventory` — list owned items with full system properties, of a world actor or one token.
368
+ - `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).
366
369
  - `search_items` — search world item documents by name, optionally filtered by type (world items, not owned items).
367
370
  - `create_actor_item` — create inline items OR import directly from compendium packs (`source: { type: 'compendium', compendiumId, itemId }`).
368
371
  - `update_actor_item` — apply JSON merge patches to owned items.
369
372
  - `delete_actor_item` — delete specific items from actor inventories.
370
- - `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.
373
+ - The three item tools also take `sceneId` + `tokenId`: on an unlinked token, only that token changes.
374
+ - `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).
371
375
 
372
376
  ### 5. Combat Encounters
373
- - `start_combat` — create encounters and seed combatants from scene tokens.
377
+ - `start_combat` — create encounters and seed combatants from scene tokens; the encounter begins at round 1.
374
378
  - `get_combat_state` — retrieve combatant turn order, HP, AC, and round number.
375
379
  - `set_initiative` — set combatant initiative values and re-order turns.
376
380
  - `next_turn` — advance the turn tracker (handles round increments and skips defeated combatants).
@@ -400,7 +404,7 @@ Add to `~/.omp/agent/mcp.json` (or `~/.omp/mcp.json`):
400
404
  - `roll_dice` — local mathematical dice formula evaluation.
401
405
  - `roll_and_post` — evaluates formulas via Foundry's native engine and posts interactive chat cards.
402
406
  - `lookup_rule` — search world journals and system compendium packs for rules with snippet previews.
403
- - `get_document_schema` — introspect game system DataModel schemas for actor and item types.
407
+ - `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).
404
408
  - `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).
405
409
  - `search_compendium_content` — deep search inside compendium pack documents and journal pages.
406
410
  - `send_chat_message` / `get_chat_messages` — post and read messages from the Foundry chat log.
@@ -100,6 +100,11 @@ const ConfigSchema = z.object({
100
100
  */
101
101
  assets: z.object({
102
102
  dataPath: z.string().optional(),
103
+ /**
104
+ * The one folder `upload_asset` may read a `sourcePath` from. Unset, the
105
+ * tool takes `contentBase64` only: the server reads no local file for it.
106
+ */
107
+ uploadSourceDir: z.string().optional(),
103
108
  }),
104
109
  /**
105
110
  * In-memory world-event ring backing `watch_events` — the cursor-addressed
@@ -172,6 +177,7 @@ function rawConfig(v) {
172
177
  },
173
178
  assets: {
174
179
  dataPath: v.FOUNDRY_DATA_PATH,
180
+ uploadSourceDir: v.FOUNDRY_UPLOAD_SOURCE_DIR,
175
181
  },
176
182
  events: {
177
183
  bufferSize: int(v.FOUNDRY_EVENT_BUFFER_SIZE),
@@ -41,6 +41,7 @@ export const KNOWN_SETTINGS = [
41
41
  'FOUNDRY_HEADLESS_GM_PASSWORD',
42
42
  'FOUNDRY_HEADLESS_GM_EXECUTABLE_PATH',
43
43
  'FOUNDRY_DATA_PATH',
44
+ 'FOUNDRY_UPLOAD_SOURCE_DIR',
44
45
  'FOUNDRY_EVENT_BUFFER_SIZE',
45
46
  'FOUNDRY_EVENT_WAIT_MS',
46
47
  'FOUNDRY_MCP_SHARED',
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,7 +18,7 @@ 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';
20
- import { needsBridge, resourceDependency, toolDependency, waitsForSocket, } from './tools/tool-dependencies.js';
21
+ import { needsBridge, prefersBridge, resourceDependency, toolDependency, waitsForSocket, } from './tools/tool-dependencies.js';
21
22
  import { isWriteTool } from './tools/write-tools.js';
22
23
  import { DiagnosticSystem } from './utils/diagnostics.js';
23
24
  import { redactToolArgs } from './utils/log-args.js';
@@ -114,6 +115,9 @@ export class FoundryCore {
114
115
  if (config.assets.dataPath) {
115
116
  clientConfig.dataPath = config.assets.dataPath;
116
117
  }
118
+ if (config.assets.uploadSourceDir) {
119
+ clientConfig.uploadSourceDir = config.assets.uploadSourceDir;
120
+ }
117
121
  // Same state directory as the shared process's daemon.json, in both modes.
118
122
  clientConfig.journalHistoryDir = path.join(defaultStateDir(), 'journal-history');
119
123
  clientConfig.journalConflictsFile = path.join(defaultStateDir(), 'journal-conflicts.json');
@@ -146,6 +150,7 @@ export class FoundryCore {
146
150
  this.moduleBridge = config.moduleBridge.enabled
147
151
  ? new ModuleBridge(config.moduleBridge.port, {
148
152
  expectedOrigin: new URL(config.foundry.url).origin,
153
+ installedModuleVersion: () => this.foundryClient.installedModuleVersion(BRIDGE_MODULE_ID),
149
154
  })
150
155
  : null;
151
156
  if (this.moduleBridge) {
@@ -307,6 +312,9 @@ export class FoundryCore {
307
312
  if (needsBridge(name, args)) {
308
313
  await this.waitForModule();
309
314
  }
315
+ else if (prefersBridge(name) && this.foundryClient.isWriteEnabled()) {
316
+ await this.waitForModuleIfComing();
317
+ }
310
318
  return (await routeToolRequest(name, args, this.foundryClient, this.diagnosticsClient, this.diagnosticSystem, this.moduleBridge, this.headlessGmSession, this.healthRuntime()));
311
319
  }
312
320
  catch (error) {
@@ -381,6 +389,22 @@ export class FoundryCore {
381
389
  }
382
390
  throw refuse(`still waiting for it after ${BRIDGE_CONNECT_WAIT_MS / 1000} s — ${session.statusText()}. Try again in a moment.`);
383
391
  }
392
+ /**
393
+ * For a tool that only prefers the module ({@link prefersBridge}): the same
394
+ * wait as {@link waitForModule}, but a module that cannot come, or does not
395
+ * come in time, leaves the call to go ahead on its socket path.
396
+ */
397
+ async waitForModuleIfComing() {
398
+ try {
399
+ await this.waitForModule();
400
+ }
401
+ catch (error) {
402
+ if (!isRefusal(error)) {
403
+ throw error;
404
+ }
405
+ logger.debug('Going ahead without the companion module', { reason: refusalReason(error) });
406
+ }
407
+ }
384
408
  /** Logs {@link gamemasterAccountWarning} after each authentication. */
385
409
  warnIfGamemaster() {
386
410
  const warning = gamemasterAccountWarning(this.sharedAccount, this.foundryClient.accountInfo());
@@ -462,6 +486,9 @@ export class FoundryCore {
462
486
  protocol: BRIDGE_PROTOCOL_VERSION,
463
487
  origin: new URL(config.foundry.url).origin,
464
488
  moduleConnectedSince: this.moduleBridge?.moduleConnectedSince()?.toISOString() ?? null,
489
+ moduleVersion: this.moduleBridge?.moduleAnnouncement().version ?? null,
490
+ moduleInstalledVersion: this.foundryClient.installedModuleVersion(BRIDGE_MODULE_ID),
491
+ moduleCommands: this.moduleBridge?.moduleAnnouncement().commands ?? null,
465
492
  },
466
493
  headlessGm: {
467
494
  enabled: headlessGmState !== 'disabled',