@g33ks/foundryvtt-mcp 2.2.0 → 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.
@@ -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. */
@@ -81,6 +82,11 @@ const FOLDER_DOCUMENT_TYPES = [
81
82
  * preset touches the exact "blocking" (NORMAL) value, which is left to the
82
83
  * server's own schema default rather than guessed.
83
84
  */
85
+ /**
86
+ * The id FoundryVTT v14 gives the Level it creates with a new scene
87
+ * (`BaseScene.metadata.defaultLevelId`).
88
+ */
89
+ const DEFAULT_LEVEL_ID = 'defaultLevel0000';
84
90
  const WALL_TYPE_PRESETS = {
85
91
  wall: {},
86
92
  door: { door: 1, ds: 0 },
@@ -1334,6 +1340,10 @@ export class FoundryClient {
1334
1340
  isWriteEnabled() {
1335
1341
  return this.config.writeEnabled === true;
1336
1342
  }
1343
+ /** The folder `upload_asset` may read a `sourcePath` from; `undefined` when none is set. */
1344
+ uploadSourceDir() {
1345
+ return this.config.uploadSourceDir;
1346
+ }
1337
1347
  /**
1338
1348
  * Returns true if worldData is available (Socket.IO mode connected).
1339
1349
  */
@@ -2826,7 +2836,7 @@ export class FoundryClient {
2826
2836
  title: w.title || 'Unknown World',
2827
2837
  description: w.description || '',
2828
2838
  system: s.id || 'unknown',
2829
- coreVersion: r.version || r.generation || 'unknown',
2839
+ coreVersion: coreVersionLabel(r),
2830
2840
  systemVersion: s.version || 'unknown',
2831
2841
  playtime: 0,
2832
2842
  created: new Date().toISOString(),
@@ -4083,9 +4093,9 @@ export class FoundryClient {
4083
4093
  // Scene lighting mutation methods (WRITE — Socket.IO modifyDocument)
4084
4094
  // ==========================================================================
4085
4095
  /**
4086
- * Sets a scene's ambient darkness level and/or global illumination fields.
4087
- * All three are plain top-level fields on the `Scene` document (mirrors
4088
- * {@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.
4089
4099
  *
4090
4100
  * @param sceneId - 16-char alphanumeric Scene document id
4091
4101
  * @param options - at least one of darkness (0-1), globalLight, globalLightThreshold
@@ -4099,16 +4109,7 @@ export class FoundryClient {
4099
4109
  (!Number.isFinite(options.darkness) || options.darkness < 0 || options.darkness > 1)) {
4100
4110
  throw new Error(`Invalid darkness: ${options.darkness} (must be a number between 0 and 1)`);
4101
4111
  }
4102
- const update = { _id: sceneId };
4103
- if (options.darkness !== undefined) {
4104
- update.darkness = options.darkness;
4105
- }
4106
- if (options.globalLight !== undefined) {
4107
- update.globalLight = options.globalLight;
4108
- }
4109
- if (options.globalLightThreshold !== undefined) {
4110
- update.globalLightThreshold = options.globalLightThreshold;
4111
- }
4112
+ const update = { _id: sceneId, ...sceneLightingUpdate(options) };
4112
4113
  if (Object.keys(update).length === 1) {
4113
4114
  throw new Error('At least one of darkness, globalLight, globalLightThreshold is required');
4114
4115
  }
@@ -4306,6 +4307,19 @@ export class FoundryClient {
4306
4307
  }
4307
4308
  return size;
4308
4309
  }
4310
+ /**
4311
+ * The connected FoundryVTT generation (13, 14, ...), from the world's
4312
+ * `release`: v14 sends `generation` (and no `version`), earlier releases
4313
+ * a `version` such as "13.351". 0 when neither is known.
4314
+ */
4315
+ getCoreGeneration() {
4316
+ const release = this.worldData?.release ?? {};
4317
+ if (typeof release.generation === 'number') {
4318
+ return release.generation;
4319
+ }
4320
+ const major = Number.parseInt(String(release.version ?? ''), 10);
4321
+ return Number.isFinite(major) ? major : 0;
4322
+ }
4309
4323
  /**
4310
4324
  * Creates a new Scene document from a background image already present
4311
4325
  * under FoundryVTT's `Data` directory. Width/height default to the
@@ -4331,13 +4345,29 @@ export class FoundryClient {
4331
4345
  : this.requireImageSize(backgroundSrc);
4332
4346
  const width = options.width ?? size.width;
4333
4347
  const height = options.height ?? size.height;
4348
+ const backgroundColor = options.backgroundColor ?? '#999999';
4349
+ // v14 moved the background onto the scene's Levels: a scene created
4350
+ // without one has nothing to draw. The Foundry client adds a default
4351
+ // Level in Scene#_preCreate (client/documents/scene.mjs, 14.370:
4352
+ // 1009-1031), which a socket create never runs, so it is built here.
4353
+ const backgroundData = this.getCoreGeneration() >= 14
4354
+ ? {
4355
+ levels: [
4356
+ {
4357
+ _id: DEFAULT_LEVEL_ID,
4358
+ name: 'Level',
4359
+ background: { src: backgroundSrc, color: backgroundColor },
4360
+ },
4361
+ ],
4362
+ initialLevel: DEFAULT_LEVEL_ID,
4363
+ }
4364
+ : { background: { src: backgroundSrc }, backgroundColor };
4334
4365
  const data = {
4335
4366
  name,
4336
- background: { src: backgroundSrc },
4367
+ ...backgroundData,
4337
4368
  width,
4338
4369
  height,
4339
4370
  padding: options.padding ?? 0.25,
4340
- backgroundColor: options.backgroundColor ?? '#999999',
4341
4371
  grid: {
4342
4372
  type: options.gridType ?? 1,
4343
4373
  size: options.gridSize ?? 100,
@@ -5979,6 +6009,21 @@ function worldActorToFoundry(a) {
5979
6009
  }
5980
6010
  return actor;
5981
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
+ }
5982
6027
  function worldSceneToFoundry(s) {
5983
6028
  const scene = {
5984
6029
  _id: s._id,
@@ -5990,8 +6035,7 @@ function worldSceneToFoundry(s) {
5990
6035
  padding: s.padding,
5991
6036
  shiftX: 0,
5992
6037
  shiftY: 0,
5993
- globalLight: s.globalLight,
5994
- darkness: s.darkness,
6038
+ ...readSceneLighting(s),
5995
6039
  };
5996
6040
  if (s.img) {
5997
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
  });
@@ -30,6 +30,7 @@ export const IDENTITY_SETTINGS = {
30
30
  FOUNDRY_HEADLESS_GM_PASSWORD: (c) => c.headlessGm.password,
31
31
  FOUNDRY_HEADLESS_GM_EXECUTABLE_PATH: (c) => c.headlessGm.executablePath,
32
32
  FOUNDRY_DATA_PATH: (c) => c.assets.dataPath,
33
+ FOUNDRY_UPLOAD_SOURCE_DIR: (c) => c.assets.uploadSourceDir,
33
34
  };
34
35
  function identityValues(config) {
35
36
  return Object.keys(IDENTITY_SETTINGS)