@g33ks/foundryvtt-mcp 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1454,7 +1454,7 @@ export const diagnosticsTools = [
1454
1454
  },
1455
1455
  {
1456
1456
  name: 'get_health_status',
1457
- description: "Get a combined health report: MCP-to-FoundryVTT connection state, world title/system/core version, and the server's health status with its active/total user counts, uptime, heap memory and recent error/warning counts. The world section is prefixed with a stale marker when the cached snapshot stopped following live document changes - typically a dropped connection, whose missed updates are never replayed - and refresh_world_data resyncs it. The connection line is a live read of the socket on the default Socket.IO transport, so it follows a link that drops or comes back in both directions; with FOUNDRY_API_KEY set there is no socket and it reports the outcome of the last REST request instead, not a live probe, so a server that went away between requests still reads as connected until the next request fails. Uptime and memory are omitted when the server does not report them; CPU, disk and playtime are not reported at all. Also lists the journal page overwrites detected in the last 24 hours (a connector write lost to a stale save or an open editor's autosave), with the path of each local copy. Degrades gracefully - sections that need the REST API module (FOUNDRY_API_KEY) report as unavailable rather than failing. Use when: first checking which world is loaded and whether the server reports itself healthy.",
1457
+ description: "Get a combined health report: MCP-to-FoundryVTT connection state, world title/system/core version, and the server's health status with its active/total user counts, uptime, heap memory and recent error/warning counts. The world section is prefixed with a stale marker when the cached snapshot stopped following live document changes - typically a dropped connection, until the world is reloaded once it comes back (on its own, or with refresh_world_data). The connection line is a live read of the socket on the default Socket.IO transport, so it follows a link that drops or comes back in both directions; with FOUNDRY_API_KEY set there is no socket and it reports the outcome of the last REST request instead, not a live probe, so a server that went away between requests still reads as connected until the next request fails. Uptime and memory are omitted when the server does not report them; CPU, disk and playtime are not reported at all. Also lists the journal page overwrites detected in the last 24 hours (a connector write lost to a stale save or an open editor's autosave), with the path of each local copy. Degrades gracefully - sections that need the REST API module (FOUNDRY_API_KEY) report as unavailable rather than failing. Use when: first checking which world is loaded and whether the server reports itself healthy.",
1458
1458
  inputSchema: {
1459
1459
  type: 'object',
1460
1460
  properties: {},
@@ -1887,7 +1887,7 @@ export const chatMutationTools = [
1887
1887
  export const userTools = [
1888
1888
  {
1889
1889
  name: 'get_users',
1890
- description: "List the world's users with their roles and online status. Online status is live while the Socket.IO connection is up: FoundryVTT's userActivity broadcasts are applied to the cached presence list as users connect and disconnect. It stops tracking if that connection drops and the missed changes are not replayed - get_health_status shows the snapshot as stale, and refresh_world_data resyncs it. Use when: you need to know which user holds the GM role, or who is connected right now.",
1890
+ description: "List the world's users with their roles and online status. Online status is live while the Socket.IO connection is up: FoundryVTT's userActivity broadcasts are applied to the cached presence list as users connect and disconnect. It stops tracking while that connection is down - get_health_status shows the snapshot as stale until the world is reloaded, on its own once the connection comes back, or with refresh_world_data. Use when: you need to know which user holds the GM role, or who is connected right now.",
1891
1891
  inputSchema: {
1892
1892
  type: 'object',
1893
1893
  properties: {},
@@ -2142,7 +2142,7 @@ export const worldTools = [
2142
2142
  },
2143
2143
  {
2144
2144
  name: 'refresh_world_data',
2145
- description: 'Force a re-fetch of the cached world data from the FoundryVTT server. Reads are normally served from a cache that follows live document changes for as long as the connection holds, so this is rarely needed. Use when: the connection dropped and came back - the cache stopped following changes while it was down and nothing replays them, so it stays a point-in-time copy until this runs, and get_health_status flags it as stale until then; or a read still looks stale after an out-of-band change - notably edits to unlinked (synthetic) token actors, which the live update feed does not cover. Refreshes the cache only; it does not modify the world.',
2145
+ description: 'Force a re-fetch of the cached world data from the FoundryVTT server. Reads are normally served from a cache that follows live document changes for as long as the connection holds, so this is rarely needed. When the connection drops and comes back with the same session, the world is reloaded on its own in the background. Use when: get_health_status still flags the cache as stale (that reload failed, or changes arrived too fast to replay); or a read still looks stale after an out-of-band change - notably edits to unlinked (synthetic) token actors, which the live update feed does not cover. Refreshes the cache only; it does not modify the world.',
2146
2146
  inputSchema: {
2147
2147
  type: 'object',
2148
2148
  properties: {},
@@ -3042,7 +3042,7 @@ export const eventTools = [
3042
3042
  },
3043
3043
  excludeSelf: {
3044
3044
  type: 'boolean',
3045
- description: "Drop events this server's own writes caused, when FoundryVTT echoes them back (default true)",
3045
+ description: "Drop events caused by this server's own account (default true). FoundryVTT does not send a client the broadcast of its own writes, so on v14 the connector's writes never reach the event log and false adds nothing for them; it still lets through changes saved by the same account elsewhere (the headless GM page, an editor open as that user).",
3046
3046
  default: true,
3047
3047
  },
3048
3048
  },
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * Chat message tool handler
3
3
  */
4
+ import { messageAuthorId } from '../../foundry/message-author.js';
4
5
  import { stripHtml } from '../../utils/sanitize.js';
5
6
  import { withToolError } from './utils.js';
6
7
  export async function handleGetChatMessages(args, foundryClient) {
@@ -17,7 +18,8 @@ export async function handleGetChatMessages(args, foundryClient) {
17
18
  const userMap = new Map(users.map((u) => [u._id, u.name]));
18
19
  const formatted = messages
19
20
  .map((m) => {
20
- const speaker = m.speaker?.alias || userMap.get(m.user) || 'Unknown';
21
+ const authorId = messageAuthorId(m);
22
+ const speaker = m.speaker?.alias || (authorId ? userMap.get(authorId) : undefined) || 'Unknown';
21
23
  const time = new Date(m.timestamp).toLocaleTimeString();
22
24
  const content = stripHtml(m.content).trim().slice(0, 200);
23
25
  return `[${time}] **${speaker}**: ${content}`;
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * Handles system diagnostics, logging, and health monitoring.
5
5
  */
6
+ import { existsSync } from 'node:fs';
6
7
  import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
7
8
  import { RestApiRequiredError } from '../../diagnostics/client.js';
8
9
  import { LogEntrySchema } from '../../diagnostics/types.js';
@@ -289,6 +290,17 @@ ${errorLines}`,
289
290
  };
290
291
  });
291
292
  }
293
+ /**
294
+ * Where the local copy of an overwritten page is: its path, "(copy missing)"
295
+ * after it when the file is gone (the list outlives restarts, the folder may
296
+ * have been cleaned), or "none" when no copy could be written.
297
+ */
298
+ function describeCopy(historyPath) {
299
+ if (historyPath === null) {
300
+ return 'none';
301
+ }
302
+ return existsSync(historyPath) ? historyPath : `${historyPath} (copy missing)`;
303
+ }
292
304
  /**
293
305
  * Handles comprehensive health status requests
294
306
  *
@@ -404,7 +416,7 @@ export async function handleGetHealthStatus(_args, foundryClient, diagnosticsCli
404
416
  : [
405
417
  `⚠️ ${conflicts.length} overwrite(s) detected in the last 24 hours:`,
406
418
  ...conflicts.map((c) => `- ${new Date(c.at).toISOString()} — "${c.pageName}" of "${c.journalName}" ` +
407
- `(${c.journalId}/${c.pageId}), ${c.reason}; copy: ${c.historyPath ?? 'none'}`),
419
+ `(${c.journalId}/${c.pageId}), ${c.reason}; copy: ${describeCopy(c.historyPath)}`),
408
420
  ].join('\n');
409
421
  return {
410
422
  content: [
@@ -36,9 +36,10 @@ export async function withToolError(toolName, fn) {
36
36
  if (error instanceof McpError) {
37
37
  throw error;
38
38
  }
39
- // Expected refusals are logged once, as a warning, by FoundryCore.
39
+ // Expected refusals are logged once, as a warning, by FoundryCore. Their
40
+ // message already says what was refused and why: no "Failed to …" prefix.
40
41
  if (error instanceof RefusedError) {
41
- throw refusalError(ErrorCode.InvalidRequest, `Failed to ${toolName}: ${error.message}`);
42
+ throw refusalError(ErrorCode.InvalidRequest, error.message);
42
43
  }
43
44
  logger.error(`Failed to ${toolName}:`, error);
44
45
  throw new McpError(ErrorCode.InternalError, `Failed to ${toolName}: ${error instanceof Error ? error.message : 'Unknown error'}`);
@@ -0,0 +1,194 @@
1
+ /**
2
+ * @fileoverview What each tool and resource needs from FoundryVTT.
3
+ *
4
+ * Decides which calls wait for a connection being restored (see
5
+ * {@link FoundryCore}): only those that read the Socket.IO cache or go
6
+ * through the socket wait for it — a cache nobody keeps live must not answer
7
+ * during an outage. The others never touch the socket and must not wait for it.
8
+ *
9
+ * - `socket`: the cached world or a Socket.IO request (every document write).
10
+ * - `socket+bridge`: the socket and the companion module (see {@link needsBridge}).
11
+ * - `bridge`: the companion module only.
12
+ * - `rest`: the REST API module (`FOUNDRY_API_KEY`) only.
13
+ * - `rest-or-local`: the REST API module when a key is set, a local computation otherwise.
14
+ * - `local`: no FoundryVTT at all (a computation, or files under `FOUNDRY_DATA_PATH`).
15
+ * - `health`: reports the connections themselves, so waits for none.
16
+ *
17
+ * A unit test checks that every tool and resource is classified.
18
+ */
19
+ import { isRecord } from '../utils/guards.js';
20
+ const SOCKET_TOOLS = [
21
+ // Reads from the cached world (search_actors, get_actor_details,
22
+ // search_items, get_scene_info and get_world_summary ask the REST API
23
+ // module first when a key is set, then fall back to the cache).
24
+ 'search_actors',
25
+ 'get_actor_details',
26
+ 'get_actor_inventory',
27
+ 'search_items',
28
+ 'get_scene_info',
29
+ 'list_tiles',
30
+ 'list_walls',
31
+ 'list_tokens',
32
+ 'list_lights',
33
+ 'list_sounds',
34
+ 'list_notes',
35
+ 'list_drawings',
36
+ 'list_templates',
37
+ 'list_regions',
38
+ 'find_open_cells',
39
+ 'list_actor_effects',
40
+ 'get_combat_state',
41
+ 'get_chat_messages',
42
+ 'get_users',
43
+ 'search_journals',
44
+ 'search_world',
45
+ 'get_world_summary',
46
+ 'list_roll_tables',
47
+ 'roll_table',
48
+ 'list_folders',
49
+ 'list_macros',
50
+ 'list_playlists',
51
+ 'get_world_setting',
52
+ // The event log is fed by socket broadcasts: during an outage it would
53
+ // answer "nothing new", which is not true.
54
+ 'watch_events',
55
+ // The cache, plus compendium packs through the module when it is there.
56
+ 'lookup_rule',
57
+ // Requests to the server over the socket.
58
+ 'get_journal',
59
+ 'refresh_world_data',
60
+ // Writes (Socket.IO modifyDocument).
61
+ 'update_actor_attributes',
62
+ 'create_world_actor',
63
+ 'create_full_actor',
64
+ 'delete_world_actor',
65
+ 'update_actor_item',
66
+ 'delete_actor_item',
67
+ 'create_scene',
68
+ 'switch_scene',
69
+ 'delete_scene',
70
+ 'set_scene_lighting',
71
+ 'reset_fog',
72
+ 'set_scene_weather',
73
+ 'create_wall',
74
+ 'delete_wall',
75
+ 'set_door_state',
76
+ 'create_tile',
77
+ 'delete_tile',
78
+ 'create_light',
79
+ 'update_light',
80
+ 'delete_light',
81
+ 'create_sound',
82
+ 'delete_sound',
83
+ 'create_note',
84
+ 'delete_note',
85
+ 'create_drawing',
86
+ 'delete_drawing',
87
+ 'create_template',
88
+ 'delete_template',
89
+ 'create_region',
90
+ 'delete_region',
91
+ 'next_turn',
92
+ 'end_combat',
93
+ 'set_initiative',
94
+ 'start_combat',
95
+ 'move_token',
96
+ 'apply_status_effect',
97
+ 'spawn_token',
98
+ 'delete_token',
99
+ 'move_token_pathfind',
100
+ 'move_tokens',
101
+ 'update_token_vision',
102
+ 'send_chat_message',
103
+ 'create_journal_entry',
104
+ 'update_journal_page',
105
+ 'add_journal_page',
106
+ 'update_journal_entry',
107
+ 'delete_journal_entry',
108
+ 'create_folder',
109
+ 'create_macro',
110
+ 'delete_macro',
111
+ 'create_playlist',
112
+ 'set_playlist_state',
113
+ 'delete_playlist',
114
+ 'set_document_ownership',
115
+ 'create_actor_effect',
116
+ 'update_actor_effect',
117
+ 'delete_actor_effect',
118
+ 'create_roll_table',
119
+ 'delete_roll_table',
120
+ 'set_world_setting',
121
+ 'set_user_role',
122
+ ];
123
+ const TOOL_DEPENDENCIES = new Map([
124
+ ...SOCKET_TOOLS.map((name) => [name, 'socket']),
125
+ // Reads a compendium document through the module, then writes over the socket.
126
+ ['import_compendium_actor', 'socket+bridge'],
127
+ // The module only for a compendium source; see needsBridge.
128
+ ['create_actor_item', 'socket+bridge'],
129
+ ['capture_scene', 'bridge'],
130
+ ['get_document_schema', 'bridge'],
131
+ ['search_compendium_content', 'bridge'],
132
+ ['get_targets', 'bridge'],
133
+ ['roll_and_post', 'bridge'],
134
+ ['set_target', 'bridge'],
135
+ ['ping_canvas', 'bridge'],
136
+ ['set_pause', 'bridge'],
137
+ ['upload_asset', 'bridge'],
138
+ ['search_compendium', 'rest'],
139
+ ['get_recent_logs', 'rest'],
140
+ ['search_logs', 'rest'],
141
+ ['get_system_health', 'rest'],
142
+ ['diagnose_errors', 'rest'],
143
+ ['roll_dice', 'rest-or-local'],
144
+ ['generate_npc', 'local'],
145
+ ['generate_loot', 'local'],
146
+ ['list_scene_assets', 'local'],
147
+ ['get_health_status', 'health'],
148
+ ]);
149
+ /** Every `foundry://` resource reads the cache, except the REST diagnostics. */
150
+ const RESOURCE_DEPENDENCIES = new Map([
151
+ ['foundry://actors', 'socket'],
152
+ ['foundry://items', 'socket'],
153
+ ['foundry://scenes', 'socket'],
154
+ ['foundry://scenes/current', 'socket'],
155
+ ['foundry://journals', 'socket'],
156
+ ['foundry://users', 'socket'],
157
+ ['foundry://combat', 'socket'],
158
+ ['foundry://world/settings', 'socket'],
159
+ ['foundry://system/diagnostics', 'rest'],
160
+ ]);
161
+ /** The tool's dependency; `undefined` for a name nobody classified. */
162
+ export function toolDependency(name) {
163
+ return TOOL_DEPENDENCIES.get(name);
164
+ }
165
+ /** The resource's dependency; `undefined` for a URI nobody classified. */
166
+ export function resourceDependency(uri) {
167
+ return RESOURCE_DEPENDENCIES.get(uri);
168
+ }
169
+ /**
170
+ * True when the dependency involves the socket. An unclassified name counts
171
+ * as one: waiting is the safe default for something that may read the cache.
172
+ */
173
+ export function waitsForSocket(dependency) {
174
+ return dependency === undefined || dependency === 'socket' || dependency === 'socket+bridge';
175
+ }
176
+ /**
177
+ * True when this call goes through the companion module: every `bridge`
178
+ * tool, `import_compendium_actor`, and `create_actor_item` from a
179
+ * compendium source (an inline item needs only the socket).
180
+ */
181
+ export function needsBridge(name, args) {
182
+ const dependency = toolDependency(name);
183
+ if (dependency === 'bridge') {
184
+ return true;
185
+ }
186
+ if (dependency !== 'socket+bridge') {
187
+ return false;
188
+ }
189
+ if (name === 'create_actor_item') {
190
+ return isRecord(args.source) && args.source.type === 'compendium';
191
+ }
192
+ return true;
193
+ }
194
+ //# sourceMappingURL=tool-dependencies.js.map
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @fileoverview MCP errors on their way to a client.
3
+ *
4
+ * `McpError` puts "MCP error <code>: " in front of its message, and the
5
+ * SDK's `Protocol` sends `error.message` as it is in the JSON-RPC error; the
6
+ * client's SDK then builds its own `McpError`, which adds the prefix a second
7
+ * time (G33ks/foundryvtt-mcp#15). The message
8
+ * on the wire must therefore be the bare text.
9
+ */
10
+ import { McpError } from '@modelcontextprotocol/sdk/types.js';
11
+ /** McpError prefixes its message with "MCP error <code>: "; this is the text without it. */
12
+ export function bareMessage(error) {
13
+ return error.message.replace(/^MCP error -?\d+: /, '');
14
+ }
15
+ /**
16
+ * An error as the SDK sends it: `Protocol` reads `code` (a safe integer),
17
+ * `message` and `data` from whatever a handler throws (SDK 1.32.2,
18
+ * dist/esm/shared/protocol.js:426-428), so a plain `Error` with those
19
+ * fields reaches the client unchanged.
20
+ */
21
+ export class WireError extends Error {
22
+ code;
23
+ data;
24
+ name = 'WireError';
25
+ constructor(code, message, data) {
26
+ super(message);
27
+ this.code = code;
28
+ this.data = data;
29
+ }
30
+ }
31
+ /**
32
+ * Runs a request handler; an `McpError` it throws leaves with its bare
33
+ * message, its code and its data, so the client shows one prefix. Any other
34
+ * error is left to the SDK.
35
+ */
36
+ export async function withBareErrors(handler) {
37
+ try {
38
+ return await handler();
39
+ }
40
+ catch (error) {
41
+ if (error instanceof McpError) {
42
+ throw new WireError(error.code, bareMessage(error), error.data);
43
+ }
44
+ throw error;
45
+ }
46
+ }
47
+ //# sourceMappingURL=mcp-errors.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@g33ks/foundryvtt-mcp",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "Model Context Protocol server for FoundryVTT integration",
5
5
  "bin": {
6
6
  "foundryvtt-mcp": "dist/index.js"
@@ -76,7 +76,7 @@
76
76
  "@modelcontextprotocol/sdk": "^1.32.2",
77
77
  "ajv": "^8.20.0",
78
78
  "axios": "^1.21.0",
79
- "dotenv": "^17.4.2",
79
+ "dotenv": "^18.0.9",
80
80
  "playwright-core": "^1.63.0",
81
81
  "socket.io-client": "^4.8.3",
82
82
  "ws": "^8.21.0",
@@ -85,7 +85,7 @@
85
85
  "devDependencies": {
86
86
  "@biomejs/biome": "^2.5.0",
87
87
  "@playwright/test": "^1.61.0",
88
- "@types/node": "^25.9.4",
88
+ "@types/node": "^22.20.5",
89
89
  "@types/ws": "^8.18.1",
90
90
  "husky": "^9.1.7",
91
91
  "lint-staged": "^17.0.7",
@@ -112,7 +112,7 @@
112
112
  "picomatch": "^4.0.4",
113
113
  "brace-expansion": "^5.0.12",
114
114
  "form-data": "^4.0.6",
115
- "ws": "^8.21.0",
115
+ "ws": "$ws",
116
116
  "qs": "^6.17.1"
117
117
  },
118
118
  "lint-staged": {