@g33ks/foundryvtt-mcp 2.2.1 β†’ 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,461 +2,118 @@
2
2
 
3
3
  [![Test](https://github.com/G33ks/foundryvtt-mcp/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/G33ks/foundryvtt-mcp/actions/workflows/test.yml)
4
4
  [![Security](https://github.com/G33ks/foundryvtt-mcp/actions/workflows/security.yml/badge.svg?branch=main)](https://github.com/G33ks/foundryvtt-mcp/actions/workflows/security.yml)
5
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
6
- [![Node.js](https://img.shields.io/badge/Node.js-22%2B-green.svg)](https://nodejs.org/)
7
- [![TypeScript](https://img.shields.io/badge/TypeScript-6-blue.svg)](https://www.typescriptlang.org/)
8
- [![Tools](https://img.shields.io/badge/MCP%20Tools-115-purple.svg)](https://modelcontextprotocol.io/)
5
+ [![npm](https://img.shields.io/npm/v/@g33ks/foundryvtt-mcp.svg)](https://www.npmjs.com/package/@g33ks/foundryvtt-mcp)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/G33ks/foundryvtt-mcp/blob/main/LICENSE)
9
7
 
10
- A comprehensive, production-grade [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) server for **Foundry Virtual Tabletop (FoundryVTT)**.
8
+ A [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) server that lets an AI assistant such as Claude read and run a **Foundry Virtual Tabletop** world with you: look things up, keep notes, place tokens and scenery, run combat, roll dice. It is not tied to a game system: it works through FoundryVTT's own documents and each system's data as it is (see [Compatibility](https://github.com/G33ks/foundryvtt-mcp/blob/main/docs/compatibility.md)).
11
9
 
12
- This server empowers AI assistants (Claude Desktop, Claude Code, Oh My Pi, VS Code, Cursor, etc.) to act as fully capable, autonomous **Co-GMs and GM assistants** inside FoundryVTT. It provides complete read and write access across game mechanics, actors, items, tokens, combat encounters, canvas placeables (walls, lights, sounds, templates, drawings, notes, tiles), playlists, macros, roll tables, compendiums, world settings, and live canvas rendering.
10
+ ## How it works
13
11
 
14
- **To install it, follow the [Quick Start](#-quick-start)** β€” seven steps, from Foundry to a working connector in Claude.
12
+ ![Each AI client starts a small relay; the relays share one background process, which keeps the connection to FoundryVTT and runs an invisible browser where the companion module serves what only a FoundryVTT page can do.](https://raw.githubusercontent.com/G33ks/foundryvtt-mcp/main/docs/assets/how-it-works.png)
15
13
 
16
- ---
14
+ Your AI client starts a small relay program. Every relay hands its requests to one background process, which logs in to FoundryVTT with an account of its own, the way a player's browser does, and keeps the world in memory. For what only a real FoundryVTT page can do (capturing the canvas, native dice rolls, compendium documents, uploads), that process runs an invisible browser where the companion module **FoundryVTT MCP Bridge** connects to it. Details: [Architecture](https://github.com/G33ks/foundryvtt-mcp/blob/main/docs/architecture.md).
17
15
 
18
- ## 🧭 How it works
16
+ ## What it does
19
17
 
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)
18
+ More than a hundred tools, in these groups ([full list](https://github.com/G33ks/foundryvtt-mcp/blob/main/docs/tools.md)):
21
19
 
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>
20
+ - **Actors and items**: search, details, inventory, attribute changes, owned items, active effects, on a world actor or on one token.
21
+ - **Tokens**: place, move (with pathfinding around walls), remove, vision, status conditions.
22
+ - **Scenes**: create, activate, lighting, weather, fog of war.
23
+ - **Canvas**: walls and doors, lights, sounds, map notes, drawings, templates, regions, tiles, free grid cells, the images and sounds available.
24
+ - **Combat**: start, initiative, turns, end, current state.
25
+ - **Journals**: search, read, create, and edit pages safely (version check, local copies, overwrite detection).
26
+ - **Chat and dice**: read and send messages; roll dice, with FoundryVTT's own engine when the REST API module's key is set and locally otherwise.
27
+ - **World**: summary and search, folders, macros, playlists, roll tables, users and roles, ownership, settings.
28
+ - **Compendiums, rules and generators**: compendium search, rule lookup in journals and compendiums, quick NPC and loot generators.
29
+ - **Companion module**: canvas capture, rolls posted to chat by FoundryVTT, document schemas, compendium content and imports, an actor's prepared data, targets, pings, pause, file uploads.
30
+ - **Events and diagnostics**: a live activity log to follow the game, the connector's health, server logs.
23
31
 
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.
32
+ Writes are off until you allow them; while they are off, every tool that changes the world is refused. See [Security](https://github.com/G33ks/foundryvtt-mcp/blob/main/docs/security.md).
25
33
 
26
- **Technical details:**
34
+ ## Requirements
27
35
 
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
- - **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
- - **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`, 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
- - **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
- - **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.
36
+ - **Node.js 22 or newer**, with npm.
37
+ - **FoundryVTT v13 or v14** with a world you can open as its Gamemaster, on this computer or on a server. Tried with v14 builds 369 and 370; v13 is accepted by the companion module and handled by the code, but not tried (see [Compatibility](https://github.com/G33ks/foundryvtt-mcp/blob/main/docs/compatibility.md)).
38
+ - **A Chromium-based browser** on this computer: Google Chrome, Microsoft Edge, Brave, Vivaldi or Chromium. You never see it open.
39
+ - **An MCP client**: Claude desktop or Claude Code (others that start servers over stdio should work).
34
40
 
35
- ---
41
+ ## Quick start
36
42
 
37
- ## 🌟 Key Highlights & Capabilities (115 Tools)
43
+ ### 1. Install the companion module, create the connector's account
38
44
 
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
- - 🎲 **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`).
41
- - πŸ—ΊοΈ **Full Canvas & Spatial Control**: Create, inspect, update, and remove all canvas placeable types:
42
- - **Scene Regions (v12+)**: `create_region`, `delete_region`, `list_regions` with geometric shapes (`rectangle`, `circle`, `ellipse`, `polygon`) and automated trigger behaviors.
43
- - **Walls & Doors**: standard, doors (open/close/lock), secret doors, windows, ethereal walls, and custom coordinates (`create_wall`, `list_walls`, `set_door_state`).
44
- - **Ambient Lights**: coordinate or grid-cell placement, dim/bright radii, animation effects, color thresholds (`create_light`, `update_light`, `delete_light`, `list_lights`).
45
- - **Ambient Sounds**: audio tracks, radii, volume, repeat modes (`create_sound`, `delete_sound`, `list_sounds`).
46
- - **Measured Templates**: cone, circle, ray, and rect spell area-of-effect markers with directional rotation and colors (`create_template`, `delete_template`, `list_templates`).
47
- - **Drawings**: freehand and geometrical shapes, stroke/fill styling, and text annotations (`create_drawing`, `delete_drawing`, `list_drawings`).
48
- - **Map Notes & Pins**: landmark markers linked to journal entries or standalone labels (`create_note`, `delete_note`, `list_notes`).
49
- - **Tiles & Props**: place decorative tiles and backgrounds (`create_tile`, `delete_tile`, `list_tiles`).
50
- - **Canvas Viewport Capture**: screenshot the GM canvas viewport with a burned-in coordinate grid overlay (`[col,row]`) via `capture_scene`.
51
- - **Targeting & Animated Pings**: focus player attention with animated camera pings (`ping_canvas`) and view/set token targeting reticles (`set_target`, `get_targets`).
52
- - πŸ§™ **Token & Actor Control**:
53
- - **A\* Pathfinding Movement**: tokens navigate around walls and automatically open closed doors along their path (`move_token_pathfind`).
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 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
- - **Status Conditions**: apply/remove system-agnostic status conditions (`apply_status_effect`).
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
- - **System Attribute Mutations**: patch actor system data (HP, temporary HP, currency, resources, spell slots) using JSON merge patches (`update_actor_attributes`).
59
- - βš”οΈ **Combat Encounter Management**: Create encounters, seed combatants from tokens, manage initiative orders, advance turns/rounds, track active combatants, pause/unpause the game clock (`set_pause`), and end encounters.
60
- - πŸ“œ **World Documents & Organization**:
61
- - **Folders**: manage hierarchical folder structures for actors, items, journals, and scenes (`create_folder`, `list_folders`).
62
- - **Macros**: inspect, create, and delete script/chat macros (`create_macro`, `list_macros`, `delete_macro`).
63
- - **Playlists & Audio**: create multi-track playlists, control playback (play, pause, stop), and adjust track states (`create_playlist`, `set_playlist_state`, `list_playlists`).
64
- - **Roll Tables**: create tables with automatic sequential range distribution (`1dN`), and draw live results (`create_roll_table`, `roll_table`, `list_roll_tables`).
65
- - **Document Ownership & User Roles**: configure granular document permissions (`set_document_ownership`) and user roles with self-demotion lockout guards (`set_user_role`).
66
- - **World Settings**: safely inspect and update module and system settings with built-in protection against core engine corruption (`get_world_setting`, `set_world_setting`).
67
- - **Asset Uploads**: upload images, tokens, and audio directly into Foundry's `Data/` storage via native FilePicker or local filesystem (`upload_asset`).
68
- - 🌫️ **Scene, Weather & Exploration Management**: Switch active scenes, adjust darkness levels, toggle global illumination, set environmental weather effects (`set_scene_weather`), and reset Fog of War exploration (`reset_fog`).
69
- - πŸ” **Rules & Compendium Search**: Search world documents, compendium packs, and rule text with contextual snippets (`search_compendium_content`, `lookup_rule`).
70
- ---
71
-
72
- ## πŸš€ Quick Start
73
-
74
- Seven steps, in this order. [SETUP_GUIDE.md](SETUP_GUIDE.md) gives the details of each one; [TROUBLESHOOTING.md](TROUBLESHOOTING.md) helps when a step fails.
75
-
76
- ### 1. Check the prerequisites
77
-
78
- - **Node.js 22 or newer** (current LTS recommended), with npm β€” `node --version` shows yours. Download it from [nodejs.org](https://nodejs.org/).
79
- - **FoundryVTT v13 or v14**, with a world you can open as its Gamemaster. Foundry may run on this computer or on a server.
80
- - **A Chromium-based browser** on this computer: Google Chrome, Microsoft Edge, Brave, Vivaldi or Chromium. The server finds it by itself; you will never see it open.
81
- - **Claude desktop** or **Claude Code**.
82
-
83
- ### 2. Install the companion module
84
-
85
- On Foundry's **Setup** screen (the one listing your worlds; from a running world, **Game Settings** β†’ **Return to Setup**). Foundry may first ask for its administrator password, the one set when Foundry was installed, not a user's password:
86
-
87
- 1. Open **Add-on Modules** β†’ **Install Module**.
88
- 2. Paste this URL into the **Manifest URL** field at the bottom, then click **Install**:
45
+ 1. On FoundryVTT's **Setup** screen: **Add-on Modules** β†’ **Install Module**, paste this **Manifest URL**, then **Install**:
89
46
 
90
47
  ```
91
48
  https://raw.githubusercontent.com/G33ks/foundryvtt-mcp/main/foundry-module/module.json
92
49
  ```
93
50
 
94
- Updates and the manual copy: see [SETUP_GUIDE.md](SETUP_GUIDE.md#2-install-companion-module-foundryvtt-mcp-bridge).
95
-
96
- ### 3. In the world: create the user, then enable the module
97
-
98
- Launch your world and log in as its Gamemaster.
51
+ 2. Launch your world as its Gamemaster. **Game Settings** β†’ **User Management** β†’ **Create Additional User**: name it, for example, `mcp-api`, give it a long password used nowhere else and the **Assistant GM** role.
52
+ 3. **Game Settings** β†’ **Manage Modules**: check **FoundryVTT MCP Bridge**, then **Save Module Settings**.
99
53
 
100
- 1. **Create a dedicated user**: **Game Settings** β†’ **User Management** β†’ **Create Additional User**. Name it `mcp-api` (or any name), give it a **long password used nowhere else**, set its role to **Assistant GM**, then save.
101
- 2. **Enable the module**: **Game Settings** β†’ **Manage Modules**, check **FoundryVTT MCP Bridge**, then click **Save Module Settings**. The world reloads; log in again if Foundry asks.
102
-
103
- This one account is all the server needs. Prefer **Assistant GM** to **Gamemaster**: as a Gamemaster, the server's invisible session could take the *active GM* role from you β€” see [SETUP_GUIDE.md](SETUP_GUIDE.md#3-in-the-world-create-a-dedicated-user-and-enable-the-module).
104
-
105
- ### 4. Install the server
106
-
107
- In a terminal (PowerShell, Terminal on macOS, any shell on Linux):
54
+ ### 2. Install the connector
108
55
 
109
56
  ```bash
110
57
  npm install -g @g33ks/foundryvtt-mcp
111
58
  foundryvtt-mcp --version
112
59
  ```
113
60
 
114
- In Windows PowerShell, if `npm` is refused with *running scripts is disabled on this system*, type `npm.cmd` instead of `npm`. `npm` may print warnings (a blocked install script, funding messages); they do not stop the install. `foundryvtt-mcp --version` prints the installed version.
61
+ In Windows PowerShell, if `npm` or `foundryvtt-mcp` is refused (*running scripts is disabled*), type `npm.cmd` and `foundryvtt-mcp.cmd` instead. The package is `@g33ks/foundryvtt-mcp`, not the unscoped `foundryvtt-mcp`.
115
62
 
116
- - **The package is `@g33ks/foundryvtt-mcp`.** The unscoped `foundryvtt-mcp` package on npm is the original project's, no longer this one.
117
- - **Install it globally** rather than running it through `npx`: npx keeps packages in a cache that npm replaces or deletes, so `init` prints no client entry from there.
118
- - **To work on the code**, from a clone: see [CONTRIBUTING.md](CONTRIBUTING.md); in the commands of this guide, use `node dist/index.js` (from the clone) instead of `foundryvtt-mcp`.
119
-
120
- ### 5. Run `init`
63
+ ### 3. Run `init`
121
64
 
122
65
  ```bash
123
66
  foundryvtt-mcp init
124
67
  ```
125
68
 
126
- It asks for Foundry's address (the URL you open Foundry with in your browser, such as `http://localhost:30000` or `https://foundry.example.com`), the account from step 3 and whether the assistant may change the game (no by default), checking each answer against your Foundry: world running, account role, module enabled, browser. Then it writes the [configuration file](#configuration-file), the only place your settings live, and prints what to give your AI client. Details: [SETUP_GUIDE.md](SETUP_GUIDE.md#5-run-init).
127
-
128
- The client entries it prints name two absolute paths: the Node.js that ran `init` and the installed server. **After changing or updating Node.js** (nvm, a new installer), run `foundryvtt-mcp init` again and replace the entries.
129
-
130
- ### 6. Add the server to Claude
131
-
132
- Use what `init` printed at the end:
133
-
134
- - **Claude desktop**: **Settings** β†’ **Developer** β†’ **Edit Config** opens `claude_desktop_config.json`. Add the `foundryvtt` entry printed by `init` under `"mcpServers"` (keep any entries already there), save, then **quit Claude desktop completely** (also from the notification area or menu bar) and start it again.
135
- - **Claude Code**: run the `claude mcp add foundryvtt …` command printed by `init` in a terminal, then start a new Claude Code session.
136
-
137
- No `env` block is needed: the settings are in the configuration file.
69
+ It asks for FoundryVTT's address (the one you open in your browser), the account from step 1 and whether the AI may change the world (no by default). It checks each answer against your FoundryVTT, writes the configuration file, and prints what to give your MCP client. It needs an interactive terminal: on Windows, PowerShell or Command Prompt (in Git Bash, prefix it with `winpty`). You can allow writes later: see [Configuration](https://github.com/G33ks/foundryvtt-mcp/blob/main/docs/configuration.md).
138
70
 
139
- ### 7. Check that it works
71
+ ### 4. Add the connector to your MCP client
140
72
 
141
- 1. In the terminal: `foundryvtt-mcp init --check`. It should end with `All checks passed.`; a βœ– line says what to fix.
142
- 2. In Claude, ask: *"Show the FoundryVTT connector's health status."* Claude calls `get_health_status` (allow the tool when Claude asks), which should show the FoundryVTT connection βœ…, the module bridge βœ… connected with an authenticated module, the headless GM session logged in with its browser, and the configuration file the settings come from.
73
+ - **Claude desktop**: **Settings** β†’ **Developer** β†’ **Edit Config**, add the `foundryvtt` entry `init` printed under `"mcpServers"`, save, then quit Claude desktop completely (also from the notification area or menu bar) and start it again.
74
+ - **Claude Code**: run the `claude mcp add foundryvtt …` command `init` printed, then start a new session.
143
75
 
144
- The first call can take a few seconds while the server connects. If something is ❌, the message says why; see [TROUBLESHOOTING.md](TROUBLESHOOTING.md).
76
+ ### 5. First try
145
77
 
146
- > **Playing as a human while the AI GMs?** No extra setup needed. Log into your own Foundry client as a **Player** β€” or as your own **Gamemaster**: with `mcp-api` an Assistant GM, you stay the active GM. The server opens its own invisible background browser session with `mcp-api`'s session for GM-tier canvas access (screenshots, dice rolls, pausing, uploads); only `mcp-api` appears in the player list for it. The module bridge requires this session: a GM tab you open yourself never connects to it (see [Module Bridge Security](#module-bridge-security)).
147
-
148
- ### Updating
149
-
150
- 1. Close your AI clients (quit Claude desktop completely).
151
- 2. In a terminal:
152
-
153
- ```bash
154
- npm install -g @g33ks/foundryvtt-mcp@latest
155
- foundryvtt-mcp stop
156
- ```
157
-
158
- `stop` ends the shared process still running the previous version; `foundryvtt-mcp --version` shows the new one.
159
- 3. Start your clients again. Their entries stay valid: the installed server keeps its path. The companion module updates separately, from Foundry's Setup screen ([SETUP_GUIDE.md](SETUP_GUIDE.md#2-install-companion-module-foundryvtt-mcp-bridge)).
160
-
161
- ---
162
-
163
- ## βš™οΈ Configuration & Client Setup
164
-
165
- ### Configuration File
166
-
167
- Every MCP client on the machine shares **one configuration file**, so a client entry needs only the command and its arguments β€” no `env` block:
168
-
169
- | System | Location |
170
- | :--- | :--- |
171
- | Windows | `%LOCALAPPDATA%\foundryvtt-mcp\config.env` (next to the shared process's state) |
172
- | macOS, Linux | `$XDG_CONFIG_HOME/foundryvtt-mcp/config.env`, or `~/.config/foundryvtt-mcp/config.env` |
173
-
174
- `FOUNDRY_MCP_CONFIG` names another file and wins over everything; with `FOUNDRY_MCP_STATE_DIR` set, the file is `<that directory>/config.env` (a fully isolated setup, for tests).
175
-
176
- **The easy way** is `foundryvtt-mcp init` ([Quick Start](#5-run-init), step 5): it writes the file after checking each answer against your FoundryVTT. `foundryvtt-mcp init --check` re-runs the checks on the existing file, without asking or writing anything.
177
-
178
- By hand: one `KEY=value` per line, with exactly the names of the variables below; `#` starts a comment:
179
-
180
- ```env
181
- FOUNDRY_URL=https://foundry.example.com
182
- FOUNDRY_USERNAME=mcp-api
183
- FOUNDRY_PASSWORD='your password'
184
- FOUNDRY_WRITE_ENABLED=true
185
- FOUNDRY_MODULE_BRIDGE_ENABLED=true
186
- ```
187
-
188
- - **Quote values**: put each value between `'…'`; if it contains an apostrophe, between `` `…` ``. Unquoted, a `#` cuts the value (the rest is a comment) and surrounding spaces are dropped. Nothing is escaped inside quotes.
189
- - **Passwords** are stored in clear: the file is for your user only. On macOS and Linux the server warns when others may read it (`chmod 600` it). They never appear in logs or in `status` (shown as `<set>`).
190
- - **Priority, setting by setting**: an environment variable (the client's `env` block, or the system) wins, then a `.env` in the working directory (for development), then the file, then the default. `foundryvtt-mcp status` shows where each setting comes from.
191
- - **After editing the file**, run `foundryvtt-mcp stop`: the next call starts the shared process with the new settings. A client whose relay was waiting for a configuration needs nothing: its next call reads the file.
192
- - **The file is authoritative**: a client that still passes its own `env` block is served with the configuration the shared process runs, and its first tool result says which of its settings are ignored and where they come from (see [Shared Process Mode](#shared-process-mode)).
193
- - **No configuration at all**: the server still starts and lists its tools; each call says where the file is expected and what it needs (`FOUNDRY_URL`, `FOUNDRY_USERNAME`, `FOUNDRY_PASSWORD`) β€” see [SETUP_GUIDE.md](SETUP_GUIDE.md#the-configuration-file).
194
-
195
- ### Environment Variables
196
-
197
- The same names work in the configuration file, in an `env` block, in the system environment or in a development `.env`.
198
-
199
- | Variable | Required | Default | Description |
200
- | :--- | :--- | :--- | :--- |
201
- | `FOUNDRY_URL` | **Yes** | `http://localhost:30000` | FoundryVTT server URL |
202
- | `FOUNDRY_USERNAME` | **Yes** | β€” | FoundryVTT user account name |
203
- | `FOUNDRY_PASSWORD` | **Yes** | β€” | FoundryVTT user account password |
204
- | `FOUNDRY_WRITE_ENABLED` | No | `false` | Enables game-state mutations (walls, actors, tokens, etc.) |
205
- | `FOUNDRY_MODULE_BRIDGE_ENABLED` | No | `false` | Enables WebSocket bridge for canvas screenshots & chat rolls |
206
- | `FOUNDRY_MODULE_BRIDGE_PORT` | No | `31415` | WebSocket port for the companion module bridge |
207
- | `FOUNDRY_HEADLESS_GM_ENABLED` | No | `true` | Auto-launches an invisible GM-tier browser session to host the module bridge. Required for the bridge: with `false` the companion module never connects (manually opened GM tabs are not supported) and a warning is logged at startup |
208
- | `FOUNDRY_HEADLESS_GM_USERNAME` | No | β€” | Advanced two-account mode: another account the headless session logs in as through `/join`. Unset (or equal to `FOUNDRY_USERNAME`), the session shares the connector's own session |
209
- | `FOUNDRY_HEADLESS_GM_PASSWORD` | No | `FOUNDRY_PASSWORD` | Password of that other account (two-account mode only) |
210
- | `FOUNDRY_HEADLESS_GM_EXECUTABLE_PATH` | No | β€” | Path to any Chromium-based browser binary (Chrome, Edge, Brave, Vivaldi…), skipping auto-detection |
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 |
213
- | `FOUNDRY_API_KEY` | No | β€” | Optional REST API key for server diagnostics tools |
214
- | `FOUNDRY_EVENT_BUFFER_SIZE` | No | `500` | In-memory event log ring buffer capacity |
215
- | `FOUNDRY_EVENT_WAIT_MS` | No | `25000` | Default long-polling timeout for `watch_events` |
216
- | `LOG_LEVEL` | No | `info` | Logging verbosity (`debug`, `info`, `warn`, `error`) |
217
- | `FOUNDRY_MCP_SHARED` | No | `true` | Shared-process mode; `false` makes every instance own its own connection, bridge and browser (all-in-one) |
218
- | `FOUNDRY_MCP_IDLE_TIMEOUT_MINUTES` | No | `5` | Minutes the shared process stays up with **no relay connected** before exiting (it disconnects from FoundryVTT then); `0` = never |
219
- | `FOUNDRY_MCP_STATE_DIR` | No | see below | Directory for the shared process's token, state file and logs; a non-default directory also gets its own pipe (an isolated shared process) and its own `config.env`. Environment or `.env` only |
220
- | `FOUNDRY_MCP_CONFIG` | No | see [Configuration File](#configuration-file) | Path of the configuration file. Environment or `.env` only |
221
-
222
- #### Choosing the Headless GM Browser
223
-
224
- Without `FOUNDRY_HEADLESS_GM_EXECUTABLE_PATH`, the server looks at the usual install locations for Google Chrome, then Microsoft Edge, Brave, Vivaldi, a system Chromium, and last Playwright's own Chromium (only present after `npx playwright install chromium`), and uses the first one that starts. `status` and `get_health_status` show which (`detected`). To choose the browser β€” another Chromium-based one, or one installed elsewhere β€” point the variable at its executable in the configuration file; it is then used with no fallback (`configured`):
225
-
226
- ```env
227
- FOUNDRY_HEADLESS_GM_EXECUTABLE_PATH='C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe'
228
- ```
78
+ With your world launched in FoundryVTT:
229
79
 
230
- In a JSON `env` block instead, Windows backslashes must be doubled; forward slashes (`C:/Program Files/...`) work everywhere and need no escaping. The headless browser is launched with Chromium's local network access checks disabled so the module can reach `ws://localhost` from the Foundry page β€” see [TROUBLESHOOTING.md](TROUBLESHOOTING.md#module-bridge-never-connects--websocket--failed).
231
-
232
- ### Shared Process Mode
233
-
234
- By default `foundryvtt-mcp` is a **relay**: it answers `initialize` and `tools/list` immediately and forwards `tools/call` and `resources/read` to a **shared process** (`foundryvtt-mcp daemon`) that holds the FoundryVTT connection, the module bridge and the headless GM session.
235
-
236
- - **Automatic start**: the first relay that finds no shared process starts one in the background (detached, so it survives the client closing or restarting the relay) and waits for it β€” up to ~30 s. Relays started at the same time end up sharing a single process. Relays connect as soon as they start, so the FoundryVTT connection and the GM session are ready before the first tool call.
237
- - **Lifetime**: the shared process stays up while at least one relay is connected, however long it goes without calls. It exits `FOUNDRY_MCP_IDLE_TIMEOUT_MINUTES` (5 by default) after the last client closes, on `stop`, when a relay of a newer version connects (or, for the same version, of a later install or rebuild), or when a relay whose settings match a changed configuration file connects β€” it then lets running calls finish and the relay starts a fresh one. Closing and reopening a client within that delay keeps the same process and the same FoundryVTT connection. A call that was already running always completes, even if the client that asked for it went away.
238
- - **FoundryVTT not reachable yet**: the shared process stays up, returns the connection error to the call, and retries on the next call β€” start FoundryVTT before or after your AI client, in any order. With FoundryVTT up but no world launched, it retries by itself in the background (every 5 s at first, at most every 2 min) and connects as soon as the world is launched.
239
- - **Writes**: tools that change game state run one at a time, in arrival order; reads run in parallel.
240
- - **Commands**:
241
-
242
- ```bash
243
- foundryvtt-mcp status # pid, version, uptime, FoundryVTT / bridge / GM session state, relays, log path
244
- foundryvtt-mcp stop # finish running calls, then stop the shared process
245
- ```
246
-
247
- They only read the state directory, so they work from any terminal β€” no FoundryVTT configuration needed.
248
- - **State directory**: `%LOCALAPPDATA%\foundryvtt-mcp\` on Windows, `$XDG_STATE_HOME/foundryvtt-mcp/` (or `~/.local/state/foundryvtt-mcp/`) elsewhere. It holds the access token relays must present (`token`), the state file (`daemon.json`) and the logs (`daemon.log`, `relay.log`, rotated at 5 MB Γ— 3). Relays reach the shared process through the named pipe `\\.\pipe\foundryvtt-mcp-<user>` (Windows) or a Unix socket in the state directory.
249
- - **One configuration for every client**: put the settings in the [configuration file](#configuration-file) and leave the clients' `env` blocks out. The connection settings (URL, account, passwords, API key, socket path, writes, bridge, headless GM session, data path) decide which shared process serves a client:
250
- - a relay with the file's settings as it is now, while the running process was started differently (the file changed, or another client's `env` block started it), restarts the process once with the file's settings;
251
- - any other difference β€” a client still passing its own `env` block β€” is served with the running configuration, never restarted: the client's first tool result names its ignored settings, and `status` lists them;
252
- - other settings (`LOG_LEVEL`, timeouts, idle delay…) never matter: the shared process's own apply.
253
- - **Configuration source**: Claude Desktop starts MCP servers with `C:\Windows\System32` as working directory, where no `.env` file is looked up, and passes only a few Windows variables besides the `env` block; Claude Code passes its whole environment. The shared process inherits the environment and working directory of the relay that starts it, and reads the configuration file itself.
254
- - **Module bridge**: listens on loopback only (`127.0.0.1` and `::1`); the module reaches it at `ws://localhost:<port>` from the headless browser on the same machine, and authenticates β€” see [Module Bridge Security](#module-bridge-security).
255
-
256
- ### Module Bridge Security
257
-
258
- The bridge drives a GM session, and its loopback port is reachable by every local process and every page open in a local browser. So the server and the companion module (0.5.0 or later) authenticate each other, with nothing to configure:
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.
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.
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.
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.
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.
266
-
267
- ### Client entries
268
-
269
- A client entry starts Node.js on the installed server, both by their absolute path: MCP clients may start servers with a reduced `PATH` and an undefined working directory. `foundryvtt-mcp init` prints the entries with the right paths. By hand:
270
-
271
- - `<NODE>`: what `node -p process.execPath` prints, such as `C:\Program Files\nodejs\node.exe` or `/usr/local/bin/node`;
272
- - `<ENTRY>`: what `npm root -g` prints, followed by `/@g33ks/foundryvtt-mcp/dist/index.js` β€” such as `C:\Users\you\AppData\Roaming\npm\node_modules\@g33ks\foundryvtt-mcp\dist\index.js`. From a clone, `<clone>/dist/index.js`.
273
-
274
- In JSON, double each Windows backslash, or write forward slashes. After changing or updating Node.js, `<NODE>` changes: run `foundryvtt-mcp init` again.
275
-
276
- ### Claude Desktop Configuration
277
-
278
- With the settings in the [configuration file](#configuration-file), add to `claude_desktop_config.json`:
279
-
280
- ```json
281
- {
282
- "mcpServers": {
283
- "foundryvtt": {
284
- "command": "<NODE>",
285
- "args": ["<ENTRY>"]
286
- }
287
- }
288
- }
289
- ```
290
-
291
- ### Claude Code Configuration
292
-
293
- `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`):
294
-
295
- > **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.
296
-
297
- ```json
298
- {
299
- "mcpServers": {
300
- "foundryvtt": {
301
- "type": "stdio",
302
- "command": "<NODE>",
303
- "args": ["<ENTRY>"]
304
- }
305
- }
306
- }
307
- ```
308
-
309
- **Alternative, not recommended:** an `env` block in a client entry still works (its values win over the file for that client), but the shared process serves every client with one configuration, so a client whose `env` block disagrees is told its settings are ignored β€” see [Shared Process Mode](#shared-process-mode).
310
-
311
- ### Oh My Pi Configuration
312
-
313
- Add to `~/.omp/agent/mcp.json` (or `~/.omp/mcp.json`):
314
-
315
- ```json
316
- {
317
- "mcpServers": {
318
- "foundryvtt": {
319
- "type": "stdio",
320
- "command": "<NODE>",
321
- "args": ["<ENTRY>"],
322
- "timeout": 60000
323
- }
324
- }
325
- }
326
- ```
327
-
328
- ---
329
-
330
- ## πŸ› οΈ Tool Catalog (115 Tools)
331
-
332
- ### 1. Real-Time Event Awareness
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.
334
-
335
- ### 2. Canvas & Spatial Placeables
336
- - `create_region` / `delete_region` / `list_regions` β€” manage Scene Regions (v12+) with geometric shapes (`rectangle`, `circle`, `ellipse`, `polygon`) and automated behaviors.
337
- - `create_wall` / `delete_wall` / `list_walls` / `set_door_state` β€” complete wall and door geometry management.
338
- - `create_light` / `update_light` / `delete_light` / `list_lights` β€” ambient lighting control (radii, colors, animations).
339
- - `create_sound` / `delete_sound` / `list_sounds` β€” ambient audio placement on canvas scenes.
340
- - `create_template` / `delete_template` / `list_templates` β€” spell and effect area-of-effect templates.
341
- - `create_drawing` / `delete_drawing` / `list_drawings` β€” map shapes, zones, and text annotations.
342
- - `create_note` / `delete_note` / `list_notes` β€” map pins and landmark markers.
343
- - `create_tile` / `delete_tile` / `list_tiles` β€” decorative tiles and map props.
344
- - `capture_scene` β€” screenshot the active scene canvas with a grid coordinate overlay burned in.
345
- - `ping_canvas` β€” emit an animated canvas ping at specific pixel coordinates.
346
- - `find_open_cells` β€” scan scenes for unblocked grid cells suitable for token/prop placement.
347
- - `list_scene_assets` β€” discover map backgrounds, token art, and audio files with parsed tags and dimensions.
348
- - `upload_asset` β€” upload image/audio files into Foundry's `Data/` directory via FilePicker or local filesystem.
349
-
350
- ### 3. Tokens & Movement
351
- - `spawn_token` β€” place actor tokens on scenes with custom size, elevation, and coordinates.
352
- - `delete_token` β€” remove tokens from scenes without deleting the underlying actor.
353
- - `list_tokens` β€” list placed tokens on active or specific scenes.
354
- - `move_token` β€” teleport a token to exact pixel coordinates.
355
- - `move_token_pathfind` β€” move tokens using A* obstacle avoidance around walls with automatic door opening.
356
- - `move_tokens` β€” batch move multiple tokens simultaneously.
357
- - `set_target` / `get_targets` β€” set and inspect token targeting reticles across connected users.
358
- - `update_token_vision` β€” configure vision ranges, vision modes, dim/bright emitted lights, and angles.
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.
360
-
361
- ### 4. Actors & Inventory
362
- - `create_world_actor` / `create_full_actor` / `delete_world_actor` β€” create and delete actor documents.
363
- - `import_compendium_actor` β€” import entire NPCs/monsters from compendium packs with embedded items and automatic error recovery.
364
- - `search_actors` β€” query actors by name and type with cursor pagination support.
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).
369
- - `search_items` β€” search world item documents by name, optionally filtered by type (world items, not owned items).
370
- - `create_actor_item` β€” create inline items OR import directly from compendium packs (`source: { type: 'compendium', compendiumId, itemId }`).
371
- - `update_actor_item` β€” apply JSON merge patches to owned items.
372
- - `delete_actor_item` β€” delete specific items from actor inventories.
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).
375
-
376
- ### 5. Combat Encounters
377
- - `start_combat` β€” create encounters and seed combatants from scene tokens; the encounter begins at round 1.
378
- - `get_combat_state` β€” retrieve combatant turn order, HP, AC, and round number.
379
- - `set_initiative` β€” set combatant initiative values and re-order turns.
380
- - `next_turn` β€” advance the turn tracker (handles round increments and skips defeated combatants).
381
- - `set_pause` β€” pause or unpause the game clock.
382
- - `end_combat` β€” terminate active encounters.
383
-
384
- ### 6. World Documents & Organization
385
- - `list_folders` / `create_folder` β€” organize actors, items, journals, and scenes in nested folders.
386
- - `list_macros` / `create_macro` / `delete_macro` β€” manage script and chat macro documents.
387
- - `list_playlists` / `create_playlist` / `set_playlist_state` / `delete_playlist` β€” audio playlist and sound controls.
388
- - `create_roll_table` / `delete_roll_table` / `roll_table` / `list_roll_tables` β€” table creation and result rolling.
389
- - `get_world_setting` / `set_world_setting` β€” inspect and modify system/module settings with core protection.
390
- - `set_document_ownership` β€” configure granular document permissions (`none`, `limited`, `observer`, `owner`).
391
- - `get_world_summary` β€” world metadata (title, game system, core version) and per-collection document counts.
392
- - `search_world` β€” search actors, items, scenes, and journals by name at once, grouped by collection.
393
- - `get_users` / `set_user_role` β€” list connected users and change permission roles with self-demotion lockout guards.
394
- - `create_journal_entry` / `get_journal` / `search_journals` / `delete_journal_entry` β€” manage session notes and lore. `get_journal` lists each page's id; pass `raw: true` for the full, unmodified page HTML.
395
- - `update_journal_page` / `add_journal_page` / `update_journal_entry` β€” edit existing journals: replace or append to a page's content (or rename it), add a page after the last one, and rename, refile, or change the visibility of an entry. Page writes work on the page as stored on the server, never on the cache: an append is added to the current text, and a replace needs the `version` token printed by `get_journal` `raw: true` and is refused if the page changed since. Every write keeps a local copy of the previous text, returns the new version token, and the page is watched for a later overwrite (a stale save, or an open FoundryVTT editor's autosave) β€” see [TROUBLESHOOTING.md](TROUBLESHOOTING.md#a-journal-edit-was-overwritten).
396
-
397
- ### 7. Scene, Weather & Exploration
398
- - `create_scene` / `delete_scene` / `get_scene_info` / `switch_scene` β€” scene creation and player activation.
399
- - `set_scene_weather` β€” set or clear weather effects (`rain`, `snow`, `fog`, `""`).
400
- - `set_scene_lighting` β€” ambient darkness levels and global illumination settings.
401
- - `reset_fog` β€” reset Fog of War exploration on active scenes.
402
-
403
- ### 8. Game Mechanics & Bridge Tools
404
- - `roll_dice` β€” local mathematical dice formula evaluation.
405
- - `roll_and_post` β€” evaluates formulas via Foundry's native engine and posts interactive chat cards.
406
- - `lookup_rule` β€” search world journals and system compendium packs for rules with snippet previews.
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).
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).
409
- - `search_compendium_content` β€” deep search inside compendium pack documents and journal pages.
410
- - `send_chat_message` / `get_chat_messages` β€” post and read messages from the Foundry chat log.
411
- - `generate_npc` / `generate_loot` β€” instant procedural generators.
412
-
413
- ### 9. Diagnostics & Logging
414
- - `get_health_status` / `get_system_health` β€” connection and server health metrics.
415
- - `get_recent_logs` / `search_logs` β€” inspect server logs and error stack traces.
416
- - `diagnose_errors` β€” analyze recent errors into prioritized resolution suggestions.
417
- - `refresh_world_data` β€” force a re-fetch of the cached world state snapshot.
418
-
419
- ## πŸ§ͺ Development & Testing
420
-
421
- ```bash
422
- # Install dependencies (exactly the locked versions)
423
- npm ci
424
-
425
- # Compile TypeScript
426
- npm run build
427
-
428
- # Run the unit test suite
429
- npm test
430
-
431
- # Run linter and formatting checks
432
- npm run lint
433
-
434
- # Start server in development watch mode
435
- npm run dev
436
- ```
80
+ 1. `foundryvtt-mcp init --check` should end with `All checks passed.`
81
+ 2. Ask your AI client: *"Show the FoundryVTT connector's health status."* It should show the FoundryVTT connection, the module bridge and the GM session connected. The first call can take a few seconds.
437
82
 
438
- `npm run lint && npx tsc --noEmit && npm test` runs the lint, type check and unit tests in one go.
83
+ When something fails, the message says why; [TROUBLESHOOTING.md](https://github.com/G33ks/foundryvtt-mcp/blob/main/TROUBLESHOOTING.md) explains each one. Every step in detail, updates and uninstalling: [Installation](https://github.com/G33ks/foundryvtt-mcp/blob/main/docs/installation.md).
439
84
 
440
- ---
85
+ ## Known limitations
441
86
 
442
- ## 🀝 Contributing & Community
87
+ - **Close a journal page in FoundryVTT before the AI writes to it.** An open editor's autosave can overwrite the AI's change; the connector detects it and keeps a copy, but cannot prevent it.
88
+ - **Write stored fields only.** A value the game system computes is accepted and saved, but has no effect in play; `get_document_schema` tells them apart.
89
+ - **`search_compendium` needs the separate REST API module.** Without it, use `search_compendium_content`, which goes through the companion module.
90
+ - **`watch_events` does not see the connector's own changes**, only those of other users.
91
+ - **One connector per computer**: two would compete for the companion module's port.
92
+ - **Some changes stay yours**: the connector does not promote anyone to Gamemaster nor change the world's permission settings.
93
+ - **After FoundryVTT restarts, launch the world again.** The connector waits for it and reconnects by itself.
94
+ - **After an update, restart your MCP client**: a client started earlier keeps the previous list of tools.
443
95
 
444
- - **Questions and help**: [GitHub Discussions](https://github.com/G33ks/foundryvtt-mcp/discussions) (Q&A).
445
- - **Bugs and feature requests**: [issues](https://github.com/G33ks/foundryvtt-mcp/issues/new/choose).
446
- - **Contributing**: [CONTRIBUTING.md](CONTRIBUTING.md) β€” setup, checks, testing against a real world.
447
- - **Security**: report vulnerabilities privately, as described in [SECURITY.md](SECURITY.md).
448
- - **Code of Conduct**: [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
96
+ ## Documentation
449
97
 
450
- ---
98
+ - [Installation](https://github.com/G33ks/foundryvtt-mcp/blob/main/docs/installation.md): every step, other clients, updating, uninstalling.
99
+ - [Configuration](https://github.com/G33ks/foundryvtt-mcp/blob/main/docs/configuration.md): the configuration file and every setting.
100
+ - [Tools](https://github.com/G33ks/foundryvtt-mcp/blob/main/docs/tools.md): every tool, what it needs, whether it writes.
101
+ - [Architecture](https://github.com/G33ks/foundryvtt-mcp/blob/main/docs/architecture.md): relays, the shared process, the invisible session, the bridge.
102
+ - [Security](https://github.com/G33ks/foundryvtt-mcp/blob/main/docs/security.md): what the connector can do and keeps, and how to limit it.
103
+ - [Compatibility](https://github.com/G33ks/foundryvtt-mcp/blob/main/docs/compatibility.md): FoundryVTT versions, hosting, clients, game systems.
104
+ - [Troubleshooting](https://github.com/G33ks/foundryvtt-mcp/blob/main/TROUBLESHOOTING.md) and the [changelog](https://github.com/G33ks/foundryvtt-mcp/blob/main/CHANGELOG.md).
451
105
 
452
- ## 🌱 Origins
106
+ ## Contributing and support
453
107
 
454
- This project was started by Lauri Gates as [laurigates/foundryvtt-mcp](https://github.com/laurigates/foundryvtt-mcp). It was continued in [RN0000/foundryvtt-mcp](https://github.com/RN0000/foundryvtt-mcp), then forked as [duckpuppy/foundryvtt-mcp](https://github.com/duckpuppy/foundryvtt-mcp), from which this repository, [G33ks/foundryvtt-mcp](https://github.com/G33ks/foundryvtt-mcp), was forked. It now continues independently.
108
+ - Questions: [GitHub Discussions](https://github.com/G33ks/foundryvtt-mcp/discussions). Bugs and requests: [issues](https://github.com/G33ks/foundryvtt-mcp/issues/new/choose).
109
+ - Working on the code: [CONTRIBUTING.md](https://github.com/G33ks/foundryvtt-mcp/blob/main/CONTRIBUTING.md).
110
+ - Vulnerabilities: privately, as [SECURITY.md](https://github.com/G33ks/foundryvtt-mcp/blob/main/SECURITY.md) describes.
111
+ - [Code of Conduct](https://github.com/G33ks/foundryvtt-mcp/blob/main/CODE_OF_CONDUCT.md).
455
112
 
456
- Thanks to everyone who built the earlier versions. Their work is kept in this repository's history and in [CHANGELOG.md](CHANGELOG.md); issue numbers from before the fork refer to the laurigates tracker.
113
+ ## Origins
457
114
 
458
- ---
115
+ Started by Lauri Gates as [laurigates/foundryvtt-mcp](https://github.com/laurigates/foundryvtt-mcp), continued in [RN0000/foundryvtt-mcp](https://github.com/RN0000/foundryvtt-mcp), then forked as [duckpuppy/foundryvtt-mcp](https://github.com/duckpuppy/foundryvtt-mcp), from which this repository was forked; it now continues independently. Thanks to everyone who built the earlier versions; their work is kept in the history and in the changelog.
459
116
 
460
- ## πŸ“„ License
117
+ ## License
461
118
 
462
- This project is licensed under the [MIT License](LICENSE).
119
+ [MIT](https://github.com/G33ks/foundryvtt-mcp/blob/main/LICENSE).
@@ -9,6 +9,7 @@
9
9
  */
10
10
  import axios from 'axios';
11
11
  import { io } from 'socket.io-client';
12
+ import { isRecord } from '../utils/guards.js';
12
13
  import { logger } from '../utils/logger.js';
13
14
  import { RefusedError } from '../utils/refusal.js';
14
15
  /**
@@ -151,6 +152,44 @@ async function resolveUserId(baseUrl, user, session) {
151
152
  logger.debug('Resolved user document _id', { displayName: user, _id: found._id });
152
153
  return found._id;
153
154
  }
155
+ /** A redirect path as FoundryVTT gives it, without its query or fragment. */
156
+ function redirectPath(value) {
157
+ if (typeof value !== 'string' || !value) {
158
+ return undefined;
159
+ }
160
+ return value.split(/[?#]/, 1)[0] || undefined;
161
+ }
162
+ /**
163
+ * Logs the HTTP status of a POST /join answer and where it redirects to,
164
+ * for diagnosis after a FoundryVTT update. Never the headers (cookie), the
165
+ * body or the request.
166
+ */
167
+ function logJoinAnswer(response) {
168
+ if (typeof response.status !== 'number') {
169
+ return;
170
+ }
171
+ const data = response.data;
172
+ const redirect = redirectPath(isRecord(data) ? data.redirect : undefined) ??
173
+ redirectPath(isRecord(response.headers) ? response.headers.location : undefined);
174
+ logger.info('POST /join answered', {
175
+ status: response.status,
176
+ ...(redirect ? { redirect } : {}),
177
+ });
178
+ }
179
+ /** `axios.post` that logs the status of the answer, including one axios throws on. */
180
+ async function postJoin(...args) {
181
+ try {
182
+ const response = await axios.post(...args);
183
+ logJoinAnswer(response);
184
+ return response;
185
+ }
186
+ catch (error) {
187
+ if (isRecord(error) && isRecord(error.response)) {
188
+ logJoinAnswer(error.response);
189
+ }
190
+ throw error;
191
+ }
192
+ }
154
193
  /**
155
194
  * Authenticates with FoundryVTT using the proven 4-step flow.
156
195
  *
@@ -183,7 +222,7 @@ export async function authenticateFoundry(baseUrl, user, password) {
183
222
  // Step 2: Resolve user to document _id
184
223
  const userId = await resolveUserId(baseUrl, user, session);
185
224
  // Step 3: POST /join as JSON with document _id
186
- const joinRes = await axios.post(`${baseUrl}/join`, {
225
+ const joinRes = await postJoin(`${baseUrl}/join`, {
187
226
  action: 'join',
188
227
  userid: userId, // Foundry v13
189
228
  userId, // Foundry v14 reads camelCase
@@ -20,6 +20,7 @@ import { summarizeDocumentBroadcast, WorldEventLog } from './event-log.js';
20
20
  import { JournalConflictFile } from './journal-conflicts.js';
21
21
  import { JournalHistory } from './journal-history.js';
22
22
  import { conflictAuthor, JOURNAL_CONFLICT_SPEAKER, JournalWatch, journalConflictMessage, journalContribution, journalVersion, OVERWRITTEN_BY_CONNECTOR, RECENT_AUTOSAVE_MS, } from './journal-integrity.js';
23
+ import { readSceneLighting, sceneLightingUpdate, } from './scene-lighting.js';
23
24
  import { ACTIVE_EFFECT_MODES, OWNERSHIP_LEVELS, USER_ROLES, VISIBILITY_LEVELS } from './types.js';
24
25
  import { applyDocumentBroadcast, applyUserActivity, mergePatch, parseDocumentBatch, parseDocumentBroadcast, parseUserActivity, } from './world-cache.js';
25
26
  /** Who overwrote a page when an editor autosave did: FoundryVTT does not say. */
@@ -2835,7 +2836,7 @@ export class FoundryClient {
2835
2836
  title: w.title || 'Unknown World',
2836
2837
  description: w.description || '',
2837
2838
  system: s.id || 'unknown',
2838
- coreVersion: r.version || r.generation || 'unknown',
2839
+ coreVersion: coreVersionLabel(r),
2839
2840
  systemVersion: s.version || 'unknown',
2840
2841
  playtime: 0,
2841
2842
  created: new Date().toISOString(),
@@ -4092,9 +4093,9 @@ export class FoundryClient {
4092
4093
  // Scene lighting mutation methods (WRITE β€” Socket.IO modifyDocument)
4093
4094
  // ==========================================================================
4094
4095
  /**
4095
- * Sets a scene's ambient darkness level and/or global illumination fields.
4096
- * All three are plain top-level fields on the `Scene` document (mirrors
4097
- * {@link switchScene}) β€” no canvas access required.
4096
+ * Sets a scene's ambient darkness level and/or global illumination fields,
4097
+ * under the `Scene` document's `environment` (see scene-lighting.ts) β€” no
4098
+ * canvas access required.
4098
4099
  *
4099
4100
  * @param sceneId - 16-char alphanumeric Scene document id
4100
4101
  * @param options - at least one of darkness (0-1), globalLight, globalLightThreshold
@@ -4108,16 +4109,7 @@ export class FoundryClient {
4108
4109
  (!Number.isFinite(options.darkness) || options.darkness < 0 || options.darkness > 1)) {
4109
4110
  throw new Error(`Invalid darkness: ${options.darkness} (must be a number between 0 and 1)`);
4110
4111
  }
4111
- const update = { _id: sceneId };
4112
- if (options.darkness !== undefined) {
4113
- update.darkness = options.darkness;
4114
- }
4115
- if (options.globalLight !== undefined) {
4116
- update.globalLight = options.globalLight;
4117
- }
4118
- if (options.globalLightThreshold !== undefined) {
4119
- update.globalLightThreshold = options.globalLightThreshold;
4120
- }
4112
+ const update = { _id: sceneId, ...sceneLightingUpdate(options) };
4121
4113
  if (Object.keys(update).length === 1) {
4122
4114
  throw new Error('At least one of darkness, globalLight, globalLightThreshold is required');
4123
4115
  }
@@ -6017,6 +6009,21 @@ function worldActorToFoundry(a) {
6017
6009
  }
6018
6010
  return actor;
6019
6011
  }
6012
+ /**
6013
+ * The core version from the world's `release`. FoundryVTT sends its
6014
+ * ReleaseData without the `version` getter (`<generation>.<build>`), so it is
6015
+ * rebuilt from `generation` and `build`; a bare `version` is used as it is.
6016
+ */
6017
+ function coreVersionLabel(release) {
6018
+ const { generation, build, version } = release ?? {};
6019
+ if (typeof generation === 'number' && typeof build === 'number') {
6020
+ return `${generation}.${build} (generation ${generation}, build ${build})`;
6021
+ }
6022
+ if (typeof version === 'string' && version) {
6023
+ return version;
6024
+ }
6025
+ return typeof generation === 'number' ? String(generation) : 'unknown';
6026
+ }
6020
6027
  function worldSceneToFoundry(s) {
6021
6028
  const scene = {
6022
6029
  _id: s._id,
@@ -6028,8 +6035,7 @@ function worldSceneToFoundry(s) {
6028
6035
  padding: s.padding,
6029
6036
  shiftX: 0,
6030
6037
  shiftY: 0,
6031
- globalLight: s.globalLight,
6032
- darkness: s.darkness,
6038
+ ...readSceneLighting(s),
6033
6039
  };
6034
6040
  if (s.img) {
6035
6041
  scene.img = s.img;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * @fileoverview A scene's darkness and global light.
3
+ *
4
+ * Since v12, FoundryVTT keeps them under `environment`: `darknessLevel`,
5
+ * `globalLight.enabled` and `globalLight.darkness.max` (the darkness above
6
+ * which the global light goes out). It migrated the top-level `darkness`,
7
+ * `globalLight` and `globalLightThreshold` there when loading a document,
8
+ * and v14 (14.370) drops them from an update. They are read only as a
9
+ * fallback, for a payload that still carries them.
10
+ */
11
+ import { isRecord } from '../utils/guards.js';
12
+ /** The darkness and global light of a scene, from `environment` or the older fields. */
13
+ export function readSceneLighting(scene) {
14
+ const environment = isRecord(scene.environment) ? scene.environment : {};
15
+ const light = isRecord(environment.globalLight) ? environment.globalLight : {};
16
+ const darkness = typeof environment.darknessLevel === 'number' ? environment.darknessLevel : scene.darkness;
17
+ const globalLight = typeof light.enabled === 'boolean' ? light.enabled : scene.globalLight;
18
+ return {
19
+ ...(typeof darkness === 'number' && Number.isFinite(darkness) ? { darkness } : {}),
20
+ ...(typeof globalLight === 'boolean' ? { globalLight } : {}),
21
+ };
22
+ }
23
+ /** The Scene update fields for a lighting change, under `environment`. */
24
+ export function sceneLightingUpdate(change) {
25
+ const globalLight = {};
26
+ if (change.globalLight !== undefined) {
27
+ globalLight.enabled = change.globalLight;
28
+ }
29
+ if (change.globalLightThreshold !== undefined) {
30
+ globalLight.darkness = { max: change.globalLightThreshold };
31
+ }
32
+ const environment = {};
33
+ if (change.darkness !== undefined) {
34
+ environment.darknessLevel = change.darkness;
35
+ }
36
+ if (Object.keys(globalLight).length > 0) {
37
+ environment.globalLight = globalLight;
38
+ }
39
+ return Object.keys(environment).length > 0 ? { environment } : {};
40
+ }
41
+ //# sourceMappingURL=scene-lighting.js.map
@@ -14,7 +14,7 @@ import { packageVersion } from './shared/version.js';
14
14
  import { getAllTools } from './tools/definitions.js';
15
15
  import { getAllResources } from './tools/resources.js';
16
16
  import { logger } from './utils/logger.js';
17
- import { withBareErrors } from './utils/mcp-errors.js';
17
+ import { toolErrorResult, withBareErrors } from './utils/mcp-errors.js';
18
18
  export function createMcpServer(backend) {
19
19
  // Answers `initialize` even with no usable configuration yet: tool calls
20
20
  // then say what is missing (see the relay and the all-in-one server).
@@ -42,13 +42,20 @@ export function createMcpServer(backend) {
42
42
  resources: getAllResources(),
43
43
  };
44
44
  });
45
- // Handle tool calls. Errors leave with their bare message: the client adds
46
- // the "MCP error <code>: " prefix itself (see withBareErrors).
45
+ // Handle tool calls. A failure is an isError result carrying one
46
+ // "MCP error <code>: " prefix; an unknown tool stays a JSON-RPC error
47
+ // (see toolErrorResult).
47
48
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
48
49
  const { name, arguments: args } = request.params;
49
- return withBareErrors(() => backend.callTool(name, args || {}));
50
+ try {
51
+ return await backend.callTool(name, args || {});
52
+ }
53
+ catch (error) {
54
+ return toolErrorResult(error);
55
+ }
50
56
  });
51
- // Handle resource reads
57
+ // Handle resource reads. Errors leave with their bare message: the client
58
+ // adds the "MCP error <code>: " prefix itself (see withBareErrors).
52
59
  server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
53
60
  return withBareErrors(() => backend.readResource(request.params.uri));
54
61
  });
@@ -32,7 +32,7 @@ const CONFIRM_FIRST = 'DESTRUCTIVE and not undoable from this server: confirm th
32
32
  * registry class is what *executes* the tool while `getAllTools()` is what is
33
33
  * *listed*, so a divergence would be invisible.
34
34
  */
35
- export const ROLL_DICE_DESCRIPTION = 'Roll dice and return the total with a per-term breakdown. Dice terms and whole numbers joined by + or -, with whitespace allowed anywhere ("1d20+5", "1d20 + 5", "1d20+5+3", "2d6 + 1d4", "3d6"; a count-less "d20" means one die), always work and every term counts towards the total - that is the portable grammar, safe on either transport. Multiplication and Foundry modifier syntax such as "4d6kh3" or "1d20r1" are rejected on both transports, with an error naming the offending character and its position, never dropped from the total in silence. Parentheses are the one difference: with FOUNDRY_API_KEY set the formula goes to FoundryVTT\'s own Roll engine, which evaluates them, while the default Socket.IO transport rolls locally and rejects them by name - and a REST roll that cannot reach the server falls back to that same local roller, so a parenthesised formula can still fail there. Prefer the expanded form when it matters. Use when: the user asks for a check, save, attack, damage, or any random result.';
35
+ export const ROLL_DICE_DESCRIPTION = 'Roll dice and return the total with a per-term breakdown. Dice terms and whole numbers joined by + or -, with whitespace allowed anywhere ("1d20+5", "1d20 + 5", "1d20+5+3", "2d6 + 1d4", "3d6"; a count-less "d20" means one die), always work and every term counts towards the total - that is the portable grammar, safe on either transport. Multiplication and Foundry modifier syntax such as "4d6kh3" or "1d20r1" are rejected on both transports, with an error naming the offending character and its position, never dropped from the total in silence. Parentheses are the one difference: with FOUNDRY_API_KEY set the formula goes to FoundryVTT\'s own Roll engine, which evaluates them, while the default Socket.IO transport rolls locally and rejects them by name - and a REST roll that cannot reach the server falls back to that same local roller, so a parenthesised formula can still fail there. Prefer the expanded form when it matters. Use when: the user asks for a check, an attack, damage, or any random result.';
36
36
  /**
37
37
  * Dice rolling tool definitions
38
38
  */
@@ -62,7 +62,7 @@ export const diceTools = [
62
62
  export const actorTools = [
63
63
  {
64
64
  name: 'search_actors',
65
- description: "Search actors (player characters, NPCs) by name, optionally filtered by type. Returns a summary line per match: name, type, level and current/max HP. Use when: checking whether an actor exists, or getting a quick roster with HP. Do not use when: you already have the actorId and want that actor's ability scores - use get_actor_details; or you need the actorId itself, which this tool does not print - read the foundry://actors resource, whose JSON lists up to the first 100 actors with their _id (not exhaustive in larger worlds).",
65
+ description: "Search actors (player characters, NPCs) by name, optionally filtered by type. Returns a summary line per match: name, type, and the level and current/max hit points when the actor stores them at details.level and attributes.hp. Use when: checking whether an actor exists, or getting a quick roster. Do not use when: you already have the actorId and want more of that actor's values - use get_actor_details; or you need the actorId itself, which this tool does not print - read the foundry://actors resource, whose JSON lists up to the first 100 actors with their _id (not exhaustive in larger worlds).",
66
66
  inputSchema: {
67
67
  type: 'object',
68
68
  properties: {
@@ -88,7 +88,7 @@ export const actorTools = [
88
88
  },
89
89
  {
90
90
  name: 'get_actor_details',
91
- description: 'Get details for one actor by id: type, level, current/max HP, AC and ability scores; no biography or description text is returned (the description line always reads "No description available."). Use when: you have an actorId and need its current HP or ability scores - notably as the read-before-write step for update_actor_attributes. For one token on a map, give sceneId + tokenId instead of actorId: an unlinked token (a copy of a monster with its own HP) reports its own values, a linked token the values of its world actor. Do not use when: you only have a name - run search_actors first; or you need the ids of items the actor owns, which this tool does not return - get_actor_inventory lists them.',
91
+ description: 'Get details for one actor by id: type, and the level, current/max hit points, armour class and ability values the actor stores at details.level, attributes.hp, attributes.ac and abilities (a game system that stores them elsewhere shows fewer fields; get_actor_stats returns all of its data); no biography or description text is returned (the description line always reads "No description available."). Use when: you have an actorId and need its current values - notably as the read-before-write step for update_actor_attributes. For one token on a map, give sceneId + tokenId instead of actorId: an unlinked token (a copy of a creature with its own values) reports its own values, a linked token the values of its world actor. Do not use when: you only have a name - run search_actors first; or you need the ids of items the actor owns, which this tool does not return - get_actor_inventory lists them.',
92
92
  inputSchema: {
93
93
  type: 'object',
94
94
  properties: {
@@ -110,7 +110,7 @@ export const actorTools = [
110
110
  },
111
111
  {
112
112
  name: 'get_actor_inventory',
113
- description: "List an actor's owned items (equipment, spells, features) with full system data per item, unlike get_actor_details which only reports the actor's own top-level stats. Use when: checking what a character or NPC carries or knows before an attack, spell, or trade. For one token on a map, give sceneId + tokenId instead of actorId: an unlinked token lists its own items (those it inherits from its base actor and its own, without the ones removed from it), a linked token its world actor's. Do not use when: you only need the actor's HP/AC/abilities - use get_actor_details.",
113
+ description: "List an actor's owned items (equipment, features, abilities…) with full system data per item, unlike get_actor_details which only reports the actor's own top-level stats. Use when: checking what a character or NPC carries or knows before an action or a trade. For one token on a map, give sceneId + tokenId instead of actorId: an unlinked token lists its own items (those it inherits from its base actor and its own, without the ones removed from it), a linked token its world actor's. Do not use when: you only need the actor's own values - use get_actor_details.",
114
114
  inputSchema: {
115
115
  type: 'object',
116
116
  properties: {
@@ -140,7 +140,7 @@ export const actorTools = [
140
140
  export const actorMutationTools = [
141
141
  {
142
142
  name: 'update_actor_attributes',
143
- description: 'Update fields on an actor\'s system data. Patch keys are dot-paths into actor.system (e.g. "attributes.hp.value", "attributes.hp.temp", "currency.gp", "resources.primary.value", "spells.spell1.value", "attributes.exhaustion") and values are absolute target values, never relative deltas. Validates HP <= max + temp, spell slots <= max, and exhaustion within 0-10 (2024) or 0-6 (2014), and returns the post-update value for every patched path. Use when: applying damage or healing, spending a spell slot or resource, or adjusting currency on a known actorId. For one token on a map - an unlinked copy of a monster, which has its own HP - give sceneId + tokenId instead of actorId: only that token changes, not the base actor or its other copies. Write only stored fields: a field the game system computes from others is accepted and saved by the server, but has no effect in play. Do not use when: changing an item the actor owns (use update_actor_item) or only reading current values (use get_actor_details). ' +
143
+ description: 'Update fields on an actor\'s system data. Patch keys are dot-paths into actor.system (e.g. "attributes.health.value", "resources.primary.value", "details.notes") and values are absolute target values, never relative deltas. If the actor stores a value at one of these paths, it is range-checked: attributes.hp.value against max + temp, spells.<key>.value against the max of that entry, and attributes.exhaustion against 0-10 (0-6 when the data of the actor marks older rules). Returns the post-update value for every patched path. Use when: applying damage or healing, spending a resource, or adjusting a stored value on a known actorId. For one token on a map - an unlinked copy of a creature, which has its own values - give sceneId + tokenId instead of actorId: only that token changes, not the base actor or its other copies. Write only stored fields: a field the game system computes from others is accepted and saved by the server, but has no effect in play. Do not use when: changing an item the actor owns (use update_actor_item) or only reading current values (use get_actor_details). ' +
144
144
  WRITE_GATE,
145
145
  inputSchema: {
146
146
  type: 'object',
@@ -160,7 +160,7 @@ export const actorMutationTools = [
160
160
  patch: {
161
161
  type: 'object',
162
162
  description: 'Map of dot-path β†’ value, where each dot-path addresses a field under actor.system ' +
163
- '(e.g. {"attributes.hp.value": 30, "currency.gp": 12}). Values must be number, string, or boolean.',
163
+ '(e.g. {"attributes.health.value": 30, "resources.primary.value": 2}). Values must be number, string, or boolean.',
164
164
  additionalProperties: {
165
165
  type: ['number', 'string', 'boolean'],
166
166
  },
@@ -202,7 +202,7 @@ export const actorMutationTools = [
202
202
  },
203
203
  {
204
204
  name: 'create_full_actor',
205
- description: "Create a new top-level Actor document AND seed it with starting items (skills, gear, weapons, cyberware, …) in one call, instead of create_world_actor followed by one create_actor_item per item. Pairs with get_document_schema: call that once per Actor/Item type to learn the real field names for `system`, then build the whole character here in a single call. The actor is always created first - a failure there aborts the whole call. Item creation is best-effort per item, not atomic: a bad item (e.g. a typo'd type) is reported in the response's item-failures list rather than losing the actor or the items that did succeed. Use when: standing up a fully-statted PC or NPC (correct ability scores/attributes plus starting equipment/skills) in one round trip. Do not use when: the actor already exists - use create_actor_item to add items to it; or a bare/generic actor is enough - use create_world_actor. " +
205
+ description: "Create a new top-level Actor document AND seed it with starting items (gear, weapons, features, …) in one call, instead of create_world_actor followed by one create_actor_item per item. Pairs with get_document_schema: call that once per Actor/Item type to learn the real field names for `system`, then build the whole character here in a single call. The actor is always created first - a failure there aborts the whole call. Item creation is best-effort per item, not atomic: a bad item (e.g. a typo'd type) is reported in the response's item-failures list rather than losing the actor or the items that did succeed. Use when: standing up a fully-statted PC or NPC (correct attributes plus starting equipment and features) in one round trip. Do not use when: the actor already exists - use create_actor_item to add items to it; or a bare/generic actor is enough - use create_world_actor. " +
206
206
  WRITE_GATE,
207
207
  inputSchema: {
208
208
  type: 'object',
@@ -225,7 +225,7 @@ export const actorMutationTools = [
225
225
  },
226
226
  items: {
227
227
  type: 'array',
228
- description: 'Optional starting items (skills, weapons, gear, cyberware, …) to create on the actor immediately after it exists',
228
+ description: 'Optional starting items (weapons, gear, features, …) to create on the actor immediately after it exists',
229
229
  items: {
230
230
  type: 'object',
231
231
  properties: {
@@ -235,7 +235,7 @@ export const actorMutationTools = [
235
235
  },
236
236
  type: {
237
237
  type: 'string',
238
- description: 'Game-system item type (e.g. "weapon", "skill") - use get_document_schema("Item", type) to learn the real field names first',
238
+ description: 'Game-system item type (e.g. "weapon", "feature") - use get_document_schema("Item", type) to learn the real field names first',
239
239
  },
240
240
  system: {
241
241
  type: 'object',
@@ -308,7 +308,7 @@ export const itemTools = [
308
308
  export const compendiumTools = [
309
309
  {
310
310
  name: 'search_compendium',
311
- description: 'Search FoundryVTT compendium packs by name and metadata; searches all enabled packs unless compendiumId scopes it to one pack. Use when: looking up spells, monsters, or equipment that are not yet present in the world. Do not use when: the document already exists in the world - use search_items or search_world. Requires the REST API module (FOUNDRY_API_KEY); without it the search returns no results instead of failing.',
311
+ description: 'Search FoundryVTT compendium packs by name and metadata; searches all enabled packs unless compendiumId scopes it to one pack. Use when: looking up creatures, items or rules that are not yet present in the world. Do not use when: the document already exists in the world - use search_items or search_world. Requires the REST API module (FOUNDRY_API_KEY); without it the search returns no results instead of failing.',
312
312
  inputSchema: {
313
313
  type: 'object',
314
314
  properties: {
@@ -330,7 +330,7 @@ export const compendiumTools = [
330
330
  },
331
331
  itemType: {
332
332
  type: 'string',
333
- description: 'Item type filter (spell, weapon, feat, etc.)',
333
+ description: 'Item type filter (e.g. weapon, equipment, feature)',
334
334
  },
335
335
  spellLevel: {
336
336
  type: 'number',
@@ -366,7 +366,7 @@ export const compendiumTools = [
366
366
  export const itemMutationTools = [
367
367
  {
368
368
  name: 'create_actor_item',
369
- description: 'Create an item on an actor from an inline item document (type, name, system) or by referencing a compendium pack entry (compendium sources require the companion Foundry module). Use when: adding a new weapon, spell, feature, or piece of equipment to a known actorId. For one token on a map, give sceneId + tokenId (an actorId given as well must be the actor of the token): an unlinked token gets the item on that token only, a linked token on its world actor. Do not use when: editing an item the actor already owns - use update_actor_item. Replacing an item is not atomic: create the replacement first and delete the old one second. Canonical target: D&D 5e v4+ activity schema. ' +
369
+ description: 'Create an item on an actor from an inline item document (type, name, system) or by referencing a compendium pack entry (compendium sources require the companion Foundry module). Use when: adding a new weapon, feature, or piece of equipment to a known actorId. For one token on a map, give sceneId + tokenId (an actorId given as well must be the actor of the token): an unlinked token gets the item on that token only, a linked token on its world actor. Do not use when: editing an item the actor already owns - use update_actor_item. Replacing an item is not atomic: create the replacement first and delete the old one second. Canonical target: D&D 5e v4+ activity schema. ' +
370
370
  WRITE_GATE,
371
371
  inputSchema: {
372
372
  type: 'object',
@@ -510,7 +510,7 @@ export const sceneMutationTools = [
510
510
  },
511
511
  backgroundSrc: {
512
512
  type: 'string',
513
- description: 'Data-relative path to the background image (e.g. "assets/cyberpunk/maps/v1/x.jpg"), as returned by list_scene_assets',
513
+ description: 'Data-relative path to the background image (e.g. "assets/maps/v1/x.jpg"), as returned by list_scene_assets',
514
514
  },
515
515
  width: {
516
516
  type: 'number',
@@ -586,7 +586,7 @@ export const sceneMutationTools = [
586
586
  },
587
587
  {
588
588
  name: 'set_scene_lighting',
589
- description: "Set a scene's ambient darkness level (0-1) and/or global illumination fields (globalLight, globalLightThreshold). Plain Scene document fields - no canvas access required. Use when: transitioning to night, dimming a room, or lighting a torch-lit area. Do not use when: you only need to read current lighting - use get_scene_info. " +
589
+ description: "Set a scene's ambient darkness level (0-1) and/or global illumination (globalLight, globalLightThreshold). Written to the Scene document's environment fields (environment.darknessLevel, environment.globalLight) - no canvas access required. Use when: transitioning to night, dimming a room, or lighting a torch-lit area. Do not use when: you only need to read current lighting - use get_scene_info. " +
590
590
  WRITE_GATE,
591
591
  inputSchema: {
592
592
  type: 'object',
@@ -846,7 +846,7 @@ export const tileTools = [
846
846
  export const tileMutationTools = [
847
847
  {
848
848
  name: 'create_tile',
849
- description: "Place a decorative Tile on a scene from an image already present under FoundryVTT's Data directory (see list_scene_assets). Width/height default to the image's real pixel dimensions when not given. Position is either explicit pixel x/y (top-left corner) or a gridCol/gridRow cell (the tile is centred in that cell - see find_open_cells for candidates). By default refuses to place a tile whose bounding box crosses a scene wall; pass allowWallOverlap: true to place anyway (e.g. a wall-mounted prop). Use when: decorating a scene with scenery (crates, dumpsters, vehicles, graffiti) that is not a creature or NPC. Do not use when: the object is a creature/NPC that should have HP and act in combat - use create_world_actor + spawn_token instead. " +
849
+ description: "Place a decorative Tile on a scene from an image already present under FoundryVTT's Data directory (see list_scene_assets). Width/height default to the image's real pixel dimensions when not given. Position is either explicit pixel x/y (top-left corner) or a gridCol/gridRow cell (the tile is centred in that cell - see find_open_cells for candidates). By default refuses to place a tile whose bounding box crosses a scene wall; pass allowWallOverlap: true to place anyway (e.g. a wall-mounted prop). Use when: decorating a scene with scenery (crates, dumpsters, vehicles, graffiti) that is not a creature or NPC. Do not use when: the object is a creature/NPC that should have its own statistics and act in combat - use create_world_actor + spawn_token instead. " +
850
850
  WRITE_GATE,
851
851
  inputSchema: {
852
852
  type: 'object',
@@ -982,7 +982,7 @@ export const placeableTools = [
982
982
  },
983
983
  {
984
984
  name: 'list_templates',
985
- description: 'List the Measured Templates (AOE spell/effect shapes) placed on a scene (id, template type, position, distance, direction, angle, width, colors, hidden), defaulting to the active scene when sceneId is omitted. Read from cached worldData - no canvas access needed. Use when: inspecting active spell areas or finding a templateId for delete_template.',
985
+ description: 'List the Measured Templates (area-of-effect shapes) placed on a scene (id, template type, position, distance, direction, angle, width, colors, hidden), defaulting to the active scene when sceneId is omitted. Read from cached worldData - no canvas access needed. Use when: inspecting active areas of effect or finding a templateId for delete_template.',
986
986
  inputSchema: {
987
987
  type: 'object',
988
988
  properties: {
@@ -1308,7 +1308,7 @@ export const placeableMutationTools = [
1308
1308
  },
1309
1309
  {
1310
1310
  name: 'create_template',
1311
- description: 'Place a Measured Template (spell/area-of-effect shape: "circle", "cone", "rect", "ray") on a scene at pixel x/y or a gridCol/gridRow cell. Distance is specified in scene grid units (e.g. metres or feet). ' +
1311
+ description: 'Place a Measured Template (area-of-effect shape: "circle", "cone", "rect", "ray") on a scene at pixel x/y or a gridCol/gridRow cell. Distance is specified in scene grid units (e.g. metres or feet). ' +
1312
1312
  WRITE_GATE,
1313
1313
  inputSchema: {
1314
1314
  type: 'object',
@@ -1376,7 +1376,7 @@ export const placeableMutationTools = [
1376
1376
  export const generationTools = [
1377
1377
  {
1378
1378
  name: 'generate_npc',
1379
- description: 'Generate a random NPC (name, race, class, HP, ability scores, background) as text. Use when: the user needs a throwaway NPC on the spot. Do not use when: the NPC must exist in FoundryVTT - this creates no documents, and the result still has to be entered into the world by hand.',
1379
+ description: 'Generate a random fantasy-style NPC as text, from built-in lists that do not depend on the game system of the world (name, people, profession, hit points, ability values, background). Use when: the user needs a throwaway NPC on the spot. Do not use when: the NPC must exist in FoundryVTT - this creates no documents, and the result still has to be entered into the world by hand.',
1380
1380
  inputSchema: {
1381
1381
  type: 'object',
1382
1382
  properties: {
@@ -1400,13 +1400,13 @@ export const generationTools = [
1400
1400
  },
1401
1401
  {
1402
1402
  name: 'generate_loot',
1403
- description: "Generate random treasure for an encounter as text. Only the currency amounts vary: they scale with the challenge rating, while the item list is fixed (a Healing Potion and a Silver Ring) and the treasureType argument is accepted but not used. Use when: the user wants a quick coin total for an encounter. Do not use when: the loot should end up in an actor's inventory - this creates no documents; use create_actor_item for that.",
1403
+ description: "Generate random fantasy-style treasure for an encounter as text, from built-in tables that do not depend on the game system of the world. Only the coin amounts vary: they scale with challengeRating, while the item list is fixed (a healing potion and a silver ring) and the treasureType argument is accepted but not used. Use when: the user wants a quick coin total for an encounter. Do not use when: the loot should end up in an actor's inventory - this creates no documents; use create_actor_item for that.",
1404
1404
  inputSchema: {
1405
1405
  type: 'object',
1406
1406
  properties: {
1407
1407
  challengeRating: {
1408
1408
  type: 'number',
1409
- description: 'Challenge rating for loot generation',
1409
+ description: 'Difficulty of the encounter; the coin amounts scale with it',
1410
1410
  minimum: 0,
1411
1411
  maximum: 30,
1412
1412
  },
@@ -1526,7 +1526,7 @@ export const diagnosticsTools = [
1526
1526
  export const combatTools = [
1527
1527
  {
1528
1528
  name: 'get_combat_state',
1529
- description: "Get the active combat encounter: initiative order with each combatant's name, initiative, HP and AC, plus the current round and which combatant is up. Use when: reporting whose turn it is, or checking whether a combat is already running before start_combat. Do not use when: you need a combatantId for set_initiative - this prints names and ordinals, not ids; read the foundry://combat resource, whose JSON includes each combatant's _id and lists combatants in this same initiative order, so the Nth entry printed here is that resource's combatants[N-1] and combat.turn indexes it directly.",
1529
+ description: "Get the active combat encounter: initiative order with each combatant's name and initiative, its hit points and armour class when its actor stores them at attributes.hp and attributes.ac, plus the current round and which combatant is up. Use when: reporting whose turn it is, or checking whether a combat is already running before start_combat. Do not use when: you need a combatantId for set_initiative - this prints names and ordinals, not ids; read the foundry://combat resource, whose JSON includes each combatant's _id and lists combatants in this same initiative order, so the Nth entry printed here is that resource's combatants[N-1] and combat.turn indexes it directly.",
1530
1530
  inputSchema: {
1531
1531
  type: 'object',
1532
1532
  properties: {},
@@ -1665,7 +1665,7 @@ export const tokenMutationTools = [
1665
1665
  },
1666
1666
  {
1667
1667
  name: 'apply_status_effect',
1668
- description: 'Apply or remove a status condition (e.g. "prone", "stunned") on a token\'s actor. Set active=false to remove. Matches by status id, so re-applying or clearing-when-absent is a no-op. With the module bridge enabled, it first waits up to 10 s for the companion module if it is still connecting. With module 0.6.0 or later, the status goes through the game system\'s own status effects, so the system recognises the effect as its condition; effects carrying the status that were written earlier over the socket are reported when applying and removed with active=false. Some game systems ask for a value when a status is created; pass it in createOptions, under the option name the system documents. Without it, the call fails at once and nothing is created. createOptions need that path: they are refused when it is not available (no module 0.6.0, or writes disabled), and ignored when the status is already active. Otherwise, or if the module does not come, an effect carrying the status is written over the socket (its 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. On an unlinked token only that token changes: a status it inherits from its base actor is found and can be removed from that token alone. Use when: a condition is gained or lost. Do not use when: changing numeric state such as HP - use update_actor_attributes. ' +
1668
+ description: 'Apply or remove a status condition (e.g. "prone", "stunned") on a token\'s actor. Set active=false to remove. Matches by status id, so re-applying or clearing-when-absent is a no-op. With the module bridge enabled, it first waits up to 10 s for the companion module if it is still connecting. With module 0.6.0 or later, the status goes through the game system\'s own status effects, so the system recognises the effect as its condition; effects carrying the status that were written earlier over the socket are reported when applying and removed with active=false. Some game systems ask for a value when a status is created; pass it in createOptions, under the option name the system documents. Without it, the call fails at once and nothing is created. createOptions need that path: they are refused when it is not available (no module 0.6.0, or writes disabled), and ignored when the status is already active. Otherwise, or if the module does not come, an effect carrying the status is written over the socket (its 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. On an unlinked token only that token changes: a status it inherits from its base actor is found and can be removed from that token alone. Use when: a condition is gained or lost. Do not use when: changing numeric state such as hit points - use update_actor_attributes. ' +
1669
1669
  WRITE_GATE +
1670
1670
  ' Exception: the no-op cases (applying an already-present status, or clearing an absent one) report success without attempting a write, so they also return normally while writes are disabled.',
1671
1671
  inputSchema: {
@@ -1698,7 +1698,7 @@ export const tokenMutationTools = [
1698
1698
  },
1699
1699
  {
1700
1700
  name: 'spawn_token',
1701
- description: "Place a new token for an existing actor onto a scene at given x/y pixel coordinates, defaulting to the active scene when sceneId is omitted. Base display fields (texture, size, vision) are seeded from the actor's prototypeToken. Use when: a monster, NPC, or reinforcement needs to appear on the map. Do not use when: repositioning a token that is already on the scene - use move_token. " +
1701
+ description: "Place a new token for an existing actor onto a scene at given x/y pixel coordinates, defaulting to the active scene when sceneId is omitted. Base display fields (texture, size, vision) are seeded from the actor's prototypeToken. Use when: a creature, NPC, or reinforcement needs to appear on the map. Do not use when: repositioning a token that is already on the scene - use move_token. " +
1702
1702
  WRITE_GATE,
1703
1703
  inputSchema: {
1704
1704
  type: 'object',
@@ -1733,7 +1733,7 @@ export const tokenMutationTools = [
1733
1733
  },
1734
1734
  {
1735
1735
  name: 'delete_token',
1736
- description: "Remove a token from a scene without deleting the underlying actor. Use when: a monster is defeated and removed from the battle, or a token was placed by mistake. Do not use when: the actor document itself should be deleted - use delete_world_actor; this only removes the token's placement on the map. " +
1736
+ description: "Remove a token from a scene without deleting the underlying actor. Use when: a creature is defeated and removed from the battle, or a token was placed by mistake. Do not use when: the actor document itself should be deleted - use delete_world_actor; this only removes the token's placement on the map. " +
1737
1737
  WRITE_GATE,
1738
1738
  inputSchema: {
1739
1739
  type: 'object',
@@ -2531,7 +2531,7 @@ export const rollTableTools = [
2531
2531
  export const settingsTools = [
2532
2532
  {
2533
2533
  name: 'get_world_setting',
2534
- description: 'Read a world setting by its namespaced key (e.g. "cyberpunk-red-core.customSetting" or "simple-calendar.year"). If the setting has never been modified from its system/module default, exists will be false. Use when: inspecting world configuration.',
2534
+ description: 'Read a world setting by its namespaced key (e.g. "my-module.customSetting" or "simple-calendar.year"). If the setting has never been modified from its system/module default, exists will be false. Use when: inspecting world configuration.',
2535
2535
  inputSchema: {
2536
2536
  type: 'object',
2537
2537
  properties: {
@@ -2545,7 +2545,7 @@ export const settingsTools = [
2545
2545
  },
2546
2546
  {
2547
2547
  name: 'set_world_setting',
2548
- description: 'Update or create a world setting value for a system or module namespace (e.g. "cyberpunk-red-core.settingName"). Refuses writes to the "core.*" namespace (core settings control the Foundry client itself and can break the world; change those in the UI). ' +
2548
+ description: 'Update or create a world setting value for a system or module namespace (e.g. "my-module.settingName"). Refuses writes to the "core.*" namespace (core settings control the Foundry client itself and can break the world; change those in the UI). ' +
2549
2549
  CONFIRM_FIRST +
2550
2550
  ' ' +
2551
2551
  WRITE_GATE,
@@ -2594,7 +2594,7 @@ export const moduleBridgeTools = [
2594
2594
  },
2595
2595
  type: {
2596
2596
  type: 'string',
2597
- description: 'The Actor or Item type to introspect (e.g. "character", "npc", "weapon", "spell") - system-specific; list valid types by trying an obviously-wrong one, or check get_world_summary/the system documentation',
2597
+ description: 'The Actor or Item type to introspect (e.g. "character", "npc", "weapon") - system-specific; list valid types by trying an obviously-wrong one, or check get_world_summary/the system documentation',
2598
2598
  },
2599
2599
  },
2600
2600
  required: ['documentType', 'type'],
@@ -2659,14 +2659,14 @@ export const moduleBridgeTools = [
2659
2659
  },
2660
2660
  {
2661
2661
  name: 'import_compendium_actor',
2662
- description: 'Import a compendium Actor (with its embedded items and effects) as a new top-level world Actor - the gap spawn_token cannot close alone, since it requires an actor that already exists in the world. Best-effort on embedded items: if the game system rejects embedded documents on create, the actor is recreated without them and each item is seeded individually, reporting per-item failures rather than losing the whole import. Requires the companion Foundry module. Use when: adding a monster or NPC from a compendium to the world before spawning its token. Do not use when: the actor already exists in the world - use spawn_token directly.' +
2662
+ description: 'Import a compendium Actor (with its embedded items and effects) as a new top-level world Actor - the gap spawn_token cannot close alone, since it requires an actor that already exists in the world. Best-effort on embedded items: if the game system rejects embedded documents on create, the actor is recreated without them and each item is seeded individually, reporting per-item failures rather than losing the whole import. Requires the companion Foundry module. Use when: adding a creature or NPC from a compendium to the world before spawning its token. Do not use when: the actor already exists in the world - use spawn_token directly.' +
2663
2663
  WRITE_GATE,
2664
2664
  inputSchema: {
2665
2665
  type: 'object',
2666
2666
  properties: {
2667
2667
  compendiumId: {
2668
2668
  type: 'string',
2669
- description: 'Compendium pack id the actor lives in (e.g. "dnd5e.monsters")',
2669
+ description: 'Compendium pack id the actor lives in (e.g. "world.creatures")',
2670
2670
  },
2671
2671
  actorId: {
2672
2672
  type: 'string',
@@ -2686,7 +2686,7 @@ export const moduleBridgeTools = [
2686
2686
  },
2687
2687
  {
2688
2688
  name: 'set_target',
2689
- description: "Set or clear this GM user's target selection on the active canvas (renders the targeting reticle in connected player browsers). tokenIds are token document IDs on the currently viewed scene. Requires the companion Foundry module. Use when: directing player attention, declaring spell targets, or marking focus fire. " +
2689
+ description: "Set or clear this GM user's target selection on the active canvas (renders the targeting reticle in connected player browsers). tokenIds are token document IDs on the currently viewed scene. Requires the companion Foundry module. Use when: directing player attention, declaring targets, or marking a shared target. " +
2690
2690
  MODULE_WRITE_GATE,
2691
2691
  inputSchema: {
2692
2692
  type: 'object',
@@ -2822,7 +2822,7 @@ export const moduleBridgeTools = [
2822
2822
  export const effectTools = [
2823
2823
  {
2824
2824
  name: 'create_actor_effect',
2825
- description: 'Create a general-purpose ActiveEffect on an actor with mechanical changes (attribute modifiers) and/or a duration - not just a status toggle (use apply_status_effect for that). Give actorId alone for a world actor, or actorId plus the sceneId+tokenId pair for one token: a linked token writes its world actor, an unlinked token only that token (its own copy of the actor), never the base actor or its other tokens. The token must carry actorId. changes[].mode is a named FoundryVTT ACTIVE_EFFECT_MODES combine rule (add/multiply/override/upgrade/downgrade/custom), not a raw number. Use when: applying a spell buff, a debuff, or an equipment bonus with a real mechanical effect. Do not use when: toggling a simple named condition (prone, stunned) - use apply_status_effect. ' +
2825
+ description: 'Create a general-purpose ActiveEffect on an actor with mechanical changes (attribute modifiers) and/or a duration - not just a status toggle (use apply_status_effect for that). Give actorId alone for a world actor, or actorId plus the sceneId+tokenId pair for one token: a linked token writes its world actor, an unlinked token only that token (its own copy of the actor), never the base actor or its other tokens. The token must carry actorId. changes[].mode is a named FoundryVTT ACTIVE_EFFECT_MODES combine rule (add/multiply/override/upgrade/downgrade/custom), not a raw number. Use when: applying a buff, a debuff, or an equipment bonus with a real mechanical effect. Do not use when: toggling a simple named condition (prone, stunned) - use apply_status_effect. ' +
2826
2826
  WRITE_GATE,
2827
2827
  inputSchema: {
2828
2828
  type: 'object',
@@ -2867,7 +2867,7 @@ export const effectTools = [
2867
2867
  properties: {
2868
2868
  key: {
2869
2869
  type: 'string',
2870
- description: 'Dot-path into the actor being modified (e.g. "system.attributes.hp.max")',
2870
+ description: 'Dot-path into the actor being modified (e.g. "system.attributes.health.max")',
2871
2871
  },
2872
2872
  mode: {
2873
2873
  type: 'string',
@@ -4,6 +4,7 @@
4
4
  * Handles scene information retrieval and management.
5
5
  */
6
6
  import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
7
+ import { readSceneLighting } from '../../foundry/scene-lighting.js';
7
8
  import { withToolError } from './utils.js';
8
9
  /**
9
10
  * Handles scene information requests
@@ -12,6 +13,10 @@ export async function handleGetSceneInfo(args, foundryClient) {
12
13
  const { sceneId } = args;
13
14
  return withToolError('get scene info', async () => {
14
15
  const scene = await foundryClient.getCurrentScene(sceneId);
16
+ // The REST API module answers with the raw document, which keeps them under `environment`.
17
+ const { darkness, globalLight } = readSceneLighting(scene);
18
+ const lightLabel = globalLight === undefined ? 'Unknown' : globalLight ? 'Enabled' : 'Disabled';
19
+ const darknessLabel = darkness === undefined ? 'Unknown' : `${Math.round(darkness * 100)}%`;
15
20
  return {
16
21
  content: [
17
22
  {
@@ -24,8 +29,8 @@ export async function handleGetSceneInfo(args, foundryClient) {
24
29
  **Dimensions:** ${scene.width} x ${scene.height} pixels
25
30
  **Padding:** ${scene.padding * 100}%
26
31
  **Grid:** ${scene.grid ? `${scene.grid.size}px, distance ${scene.grid.distance}${scene.grid.units ? ` ${scene.grid.units}` : ''}` : 'Unknown'}
27
- **Global Light:** ${scene.globalLight ? 'Enabled' : 'Disabled'}
28
- **Darkness Level:** ${scene.darkness * 100}%
32
+ **Global Light:** ${lightLabel}
33
+ **Darkness Level:** ${darknessLabel}
29
34
 
30
35
  **Description:** ${scene.description || 'No description available.'}`,
31
36
  },
@@ -6,8 +6,14 @@
6
6
  * client's SDK then builds its own `McpError`, which adds the prefix a second
7
7
  * time (G33ks/foundryvtt-mcp#15). The message
8
8
  * on the wire must therefore be the bare text.
9
+ *
10
+ * A failed tool call is not a JSON-RPC error but a result with
11
+ * `isError: true`, so the model reads why it failed (MCP specification,
12
+ * "Error Handling" of tools). No client adds a prefix to a result: the text
13
+ * carries the one prefix itself. An unknown tool and a failed resource read
14
+ * (`resources/read` has no `isError`) stay JSON-RPC errors.
9
15
  */
10
- import { McpError } from '@modelcontextprotocol/sdk/types.js';
16
+ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
11
17
  /** McpError prefixes its message with "MCP error <code>: "; this is the text without it. */
12
18
  export function bareMessage(error) {
13
19
  return error.message.replace(/^MCP error -?\d+: /, '');
@@ -28,6 +34,24 @@ export class WireError extends Error {
28
34
  this.data = data;
29
35
  }
30
36
  }
37
+ /**
38
+ * A failed tool call as the client gets it: an `isError` result whose text
39
+ * is "MCP error <code>: <message>", with the McpError's code, or
40
+ * InternalError for any other error. An unknown tool is thrown again as a
41
+ * {@link WireError}, to stay a JSON-RPC error.
42
+ */
43
+ export function toolErrorResult(error) {
44
+ if (error instanceof McpError && error.code === ErrorCode.MethodNotFound) {
45
+ throw new WireError(error.code, bareMessage(error), error.data);
46
+ }
47
+ const code = error instanceof McpError ? error.code : ErrorCode.InternalError;
48
+ const message = error instanceof McpError
49
+ ? bareMessage(error)
50
+ : error instanceof Error
51
+ ? error.message
52
+ : String(error);
53
+ return { isError: true, content: [{ type: 'text', text: `MCP error ${code}: ${message}` }] };
54
+ }
31
55
  /**
32
56
  * Runs a request handler; an `McpError` it throws leaves with its bare
33
57
  * message, its code and its data, so the client shows one prefix. Any other
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@g33ks/foundryvtt-mcp",
3
- "version": "2.2.1",
3
+ "version": "3.0.0",
4
4
  "description": "Model Context Protocol server for FoundryVTT integration",
5
5
  "bin": {
6
6
  "foundryvtt-mcp": "dist/index.js"
@@ -13,6 +13,7 @@
13
13
  "smoke": "node scripts/smoke-test.js",
14
14
  "smoke:dotenv": "node scripts/smoke-dotenv.js",
15
15
  "smoke:pack": "node scripts/smoke-pack.js",
16
+ "docs:tools": "node scripts/generate-tools-doc.js",
16
17
  "stress:shared": "node scripts/stress-shared.js",
17
18
  "check:bridge-security": "node scripts/check-bridge-security.js",
18
19
  "bridge:package": "node scripts/package-bridge.js",