@g33ks/foundryvtt-mcp 2.0.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -29
- package/dist/cli/init.js +5 -1
- package/dist/cli/snippets.js +16 -1
- package/dist/core.js +104 -14
- package/dist/diagnostics/client.js +36 -98
- package/dist/foundry/auth.js +4 -0
- package/dist/foundry/client.js +750 -157
- package/dist/foundry/event-log.js +2 -3
- package/dist/foundry/headless-gm-session.js +119 -2
- package/dist/foundry/journal-conflicts.js +141 -0
- package/dist/foundry/journal-integrity.js +20 -4
- package/dist/foundry/message-author.js +19 -0
- package/dist/foundry/module-bridge.js +153 -6
- package/dist/foundry/world-cache.js +206 -8
- package/dist/mcp-server.js +5 -3
- package/dist/shared/control.js +47 -6
- package/dist/shared/daemon.js +2 -4
- package/dist/shared/protocol.js +14 -10
- package/dist/tools/definitions.js +128 -31
- package/dist/tools/handlers/actor-mutations.js +13 -7
- package/dist/tools/handlers/actor-target.js +80 -0
- package/dist/tools/handlers/actors.js +25 -12
- package/dist/tools/handlers/chat.js +3 -1
- package/dist/tools/handlers/combat-mutations.js +3 -2
- package/dist/tools/handlers/combat.js +48 -17
- package/dist/tools/handlers/diagnostics.js +14 -2
- package/dist/tools/handlers/effects.js +23 -24
- package/dist/tools/handlers/item-mutations.js +23 -21
- package/dist/tools/handlers/module-bridge.js +131 -2
- package/dist/tools/handlers/token-mutations.js +151 -16
- package/dist/tools/handlers/utils.js +3 -2
- package/dist/tools/router.js +6 -23
- package/dist/tools/tool-dependencies.js +207 -0
- package/dist/utils/mcp-errors.js +47 -0
- package/package.json +5 -5
|
@@ -34,11 +34,18 @@
|
|
|
34
34
|
* headless session exposes to its page through a Playwright binding. Until
|
|
35
35
|
* step 3 checks out, a connection cannot replace the current module, receives
|
|
36
36
|
* no command, and nothing it sends is processed.
|
|
37
|
+
*
|
|
38
|
+
* Since module 0.6.0, `auth_response` also carries `module: {version,
|
|
39
|
+
* commands}`: the module's version and the commands it serves. The proofs do
|
|
40
|
+
* not cover it; it only decides which commands the server tries to send (see
|
|
41
|
+
* {@link ModuleBridge.send}). An older module omits it, and is then sent only
|
|
42
|
+
* {@link LEGACY_COMMANDS}.
|
|
37
43
|
*/
|
|
38
44
|
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
39
45
|
import { WebSocket, WebSocketServer } from 'ws';
|
|
40
46
|
import { isRecord } from '../utils/guards.js';
|
|
41
47
|
import { logger } from '../utils/logger.js';
|
|
48
|
+
import { RefusedError } from '../utils/refusal.js';
|
|
42
49
|
/** Version of the authentication handshake spoken by this server. */
|
|
43
50
|
export const BRIDGE_PROTOCOL_VERSION = 1;
|
|
44
51
|
/** Close codes sent to a connection that fails authentication. */
|
|
@@ -56,9 +63,77 @@ const NONCE_BASE64_LENGTH = 44;
|
|
|
56
63
|
const AUTH_TIMEOUT_MS = 5000;
|
|
57
64
|
const MAX_PREAUTH_MESSAGE_BYTES = 4096;
|
|
58
65
|
const PROOF_LABEL = 'foundryvtt-mcp-bridge/v1';
|
|
66
|
+
/** The commands every module before 0.6.0 serves: all a module that announces none is sent. */
|
|
67
|
+
export const LEGACY_COMMANDS = [
|
|
68
|
+
'capture_scene',
|
|
69
|
+
'get_document_schema',
|
|
70
|
+
'search_compendium_content',
|
|
71
|
+
'get_compendium_document',
|
|
72
|
+
'roll_and_post',
|
|
73
|
+
'set_target',
|
|
74
|
+
'get_targets',
|
|
75
|
+
'ping_canvas',
|
|
76
|
+
'set_pause',
|
|
77
|
+
'upload_asset',
|
|
78
|
+
];
|
|
79
|
+
/** The module version that first serves each command newer than {@link LEGACY_COMMANDS}. */
|
|
80
|
+
export const COMMAND_SINCE = {
|
|
81
|
+
get_actor_stats: '0.6.0',
|
|
82
|
+
toggle_status_effect: '0.6.0',
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* Bounds of the `module` announcement in `auth_response`: at worst (100
|
|
86
|
+
* names of 32 characters, a 64-character version) the message stays under
|
|
87
|
+
* {@link MAX_PREAUTH_MESSAGE_BYTES}, so a full announcement cannot fail the handshake.
|
|
88
|
+
*/
|
|
89
|
+
const MAX_ANNOUNCED_VERSION_LENGTH = 64;
|
|
90
|
+
const MAX_ANNOUNCED_COMMANDS = 100;
|
|
91
|
+
const MAX_COMMAND_NAME_LENGTH = 32;
|
|
92
|
+
const COMMAND_NAME_PATTERN = /^[a-z_]+$/;
|
|
59
93
|
/** Refusal warnings logged per window; the rest are counted and summarised. */
|
|
60
94
|
const REFUSAL_LOG_LIMIT = 10;
|
|
61
95
|
const REFUSAL_LOG_WINDOW_MS = 60_000;
|
|
96
|
+
const NO_ANNOUNCEMENT = { version: null, commands: null };
|
|
97
|
+
/**
|
|
98
|
+
* Reads the optional `module` field of an authenticated `auth_response`.
|
|
99
|
+
* A part that is absent or malformed is left `null`; a malformed one is
|
|
100
|
+
* logged, and never fails the authentication.
|
|
101
|
+
*/
|
|
102
|
+
export function parseModuleAnnouncement(value) {
|
|
103
|
+
if (value === undefined) {
|
|
104
|
+
return NO_ANNOUNCEMENT;
|
|
105
|
+
}
|
|
106
|
+
if (!isRecord(value)) {
|
|
107
|
+
logger.warn('Module bridge: ignoring a malformed module announcement');
|
|
108
|
+
return NO_ANNOUNCEMENT;
|
|
109
|
+
}
|
|
110
|
+
let version = null;
|
|
111
|
+
if (value.version !== undefined) {
|
|
112
|
+
if (typeof value.version === 'string' &&
|
|
113
|
+
value.version.length > 0 &&
|
|
114
|
+
value.version.length <= MAX_ANNOUNCED_VERSION_LENGTH) {
|
|
115
|
+
version = value.version;
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
logger.warn('Module bridge: ignoring a malformed module version');
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
let commands = null;
|
|
122
|
+
if (value.commands !== undefined) {
|
|
123
|
+
const list = value.commands;
|
|
124
|
+
if (Array.isArray(list) &&
|
|
125
|
+
list.length <= MAX_ANNOUNCED_COMMANDS &&
|
|
126
|
+
list.every((name) => typeof name === 'string' &&
|
|
127
|
+
name.length <= MAX_COMMAND_NAME_LENGTH &&
|
|
128
|
+
COMMAND_NAME_PATTERN.test(name))) {
|
|
129
|
+
commands = list.map(String);
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
logger.warn('Module bridge: ignoring a malformed module command list');
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return { version, commands };
|
|
136
|
+
}
|
|
62
137
|
function isBridgeMessage(value) {
|
|
63
138
|
return typeof value === 'object' && value !== null;
|
|
64
139
|
}
|
|
@@ -116,12 +191,17 @@ export class ModuleBridge {
|
|
|
116
191
|
/** The authenticated module connection; unauthenticated ones are never stored here. */
|
|
117
192
|
socket = null;
|
|
118
193
|
connectedSince = null;
|
|
194
|
+
/** What the current module announced; reset when it disconnects. */
|
|
195
|
+
announcement = NO_ANNOUNCEMENT;
|
|
119
196
|
pending = new Map();
|
|
197
|
+
/** Callers of {@link waitUntilConnected}, woken by the next authentication. */
|
|
198
|
+
connectionWaiters = new Set();
|
|
120
199
|
nextId = 1;
|
|
121
200
|
port;
|
|
122
201
|
expectedOrigin;
|
|
123
202
|
requestTimeoutMs;
|
|
124
203
|
authTimeoutMs;
|
|
204
|
+
installedModuleVersion;
|
|
125
205
|
/** HMAC key of the handshake. In memory only: never logged, persisted or returned. */
|
|
126
206
|
secret = randomBytes(32);
|
|
127
207
|
refusals = new RefusalLog();
|
|
@@ -136,6 +216,7 @@ export class ModuleBridge {
|
|
|
136
216
|
this.expectedOrigin = options.expectedOrigin;
|
|
137
217
|
this.requestTimeoutMs = options.requestTimeoutMs ?? 15000;
|
|
138
218
|
this.authTimeoutMs = options.authTimeoutMs ?? AUTH_TIMEOUT_MS;
|
|
219
|
+
this.installedModuleVersion = options.installedModuleVersion ?? (() => null);
|
|
139
220
|
}
|
|
140
221
|
/**
|
|
141
222
|
* Starts the relay server and waits for it to be listening.
|
|
@@ -229,7 +310,7 @@ export class ModuleBridge {
|
|
|
229
310
|
authenticated = true;
|
|
230
311
|
clearTimeout(authTimer);
|
|
231
312
|
ws.send(JSON.stringify({ type: 'auth_ok', proof: verdict.serverProof }));
|
|
232
|
-
this.adopt(ws, remoteAddress);
|
|
313
|
+
this.adopt(ws, remoteAddress, parseModuleAnnouncement(verdict.module));
|
|
233
314
|
});
|
|
234
315
|
ws.on('close', () => {
|
|
235
316
|
clearTimeout(authTimer);
|
|
@@ -237,6 +318,7 @@ export class ModuleBridge {
|
|
|
237
318
|
logger.warn('Foundry module disconnected from bridge');
|
|
238
319
|
this.socket = null;
|
|
239
320
|
this.connectedSince = null;
|
|
321
|
+
this.announcement = NO_ANNOUNCEMENT;
|
|
240
322
|
}
|
|
241
323
|
});
|
|
242
324
|
ws.on('error', (err) => {
|
|
@@ -249,10 +331,11 @@ export class ModuleBridge {
|
|
|
249
331
|
}));
|
|
250
332
|
}
|
|
251
333
|
/** Makes an authenticated connection the module connection. */
|
|
252
|
-
adopt(ws, remoteAddress) {
|
|
334
|
+
adopt(ws, remoteAddress, announcement) {
|
|
253
335
|
const previous = this.socket;
|
|
254
336
|
this.socket = ws;
|
|
255
337
|
this.connectedSince = new Date();
|
|
338
|
+
this.announcement = announcement;
|
|
256
339
|
if (previous) {
|
|
257
340
|
// e.g. the headless page reloaded before its old socket closed.
|
|
258
341
|
previous.terminate();
|
|
@@ -261,9 +344,34 @@ export class ModuleBridge {
|
|
|
261
344
|
});
|
|
262
345
|
}
|
|
263
346
|
else {
|
|
264
|
-
logger.info(`Foundry module connected and authenticated (protocol v${BRIDGE_PROTOCOL_VERSION})`, { remoteAddress });
|
|
347
|
+
logger.info(`Foundry module connected and authenticated (protocol v${BRIDGE_PROTOCOL_VERSION})`, { remoteAddress, moduleVersion: announcement.version ?? '(not announced)' });
|
|
348
|
+
}
|
|
349
|
+
this.wakeConnectionWaiters(true);
|
|
350
|
+
}
|
|
351
|
+
wakeConnectionWaiters(connected) {
|
|
352
|
+
for (const wake of [...this.connectionWaiters]) {
|
|
353
|
+
wake(connected);
|
|
265
354
|
}
|
|
266
355
|
}
|
|
356
|
+
/**
|
|
357
|
+
* Waits until an authenticated module is connected.
|
|
358
|
+
*
|
|
359
|
+
* @returns true once connected, false when `timeoutMs` ran out first or the bridge stopped
|
|
360
|
+
*/
|
|
361
|
+
waitUntilConnected(timeoutMs) {
|
|
362
|
+
if (this.isConnected()) {
|
|
363
|
+
return Promise.resolve(true);
|
|
364
|
+
}
|
|
365
|
+
return new Promise((resolve) => {
|
|
366
|
+
const wake = (connected) => {
|
|
367
|
+
clearTimeout(timer);
|
|
368
|
+
this.connectionWaiters.delete(wake);
|
|
369
|
+
resolve(connected);
|
|
370
|
+
};
|
|
371
|
+
const timer = setTimeout(() => wake(false), timeoutMs);
|
|
372
|
+
this.connectionWaiters.add(wake);
|
|
373
|
+
});
|
|
374
|
+
}
|
|
267
375
|
checkAuthResponse(raw, serverNonce) {
|
|
268
376
|
let parsed;
|
|
269
377
|
try {
|
|
@@ -292,6 +400,7 @@ export class ModuleBridge {
|
|
|
292
400
|
return {
|
|
293
401
|
ok: true,
|
|
294
402
|
serverProof: this.hmac('server', serverNonce, parsed.nonce).toString('base64'),
|
|
403
|
+
module: parsed.module,
|
|
295
404
|
};
|
|
296
405
|
}
|
|
297
406
|
hmac(role, serverNonce, clientNonce) {
|
|
@@ -327,9 +436,11 @@ export class ModuleBridge {
|
|
|
327
436
|
pending.reject(new Error('Module bridge shutting down'));
|
|
328
437
|
}
|
|
329
438
|
this.pending.clear();
|
|
439
|
+
this.wakeConnectionWaiters(false);
|
|
330
440
|
this.socket?.close();
|
|
331
441
|
this.socket = null;
|
|
332
442
|
this.connectedSince = null;
|
|
443
|
+
this.announcement = NO_ANNOUNCEMENT;
|
|
333
444
|
const servers = this.servers;
|
|
334
445
|
this.servers = [];
|
|
335
446
|
await Promise.all(servers.map((wss) => new Promise((resolve, reject) => {
|
|
@@ -352,17 +463,53 @@ export class ModuleBridge {
|
|
|
352
463
|
moduleConnectedSince() {
|
|
353
464
|
return this.isConnected() ? this.connectedSince : null;
|
|
354
465
|
}
|
|
466
|
+
/** What the connected module announced; all `null` while none is connected. */
|
|
467
|
+
moduleAnnouncement() {
|
|
468
|
+
return this.isConnected() ? this.announcement : NO_ANNOUNCEMENT;
|
|
469
|
+
}
|
|
470
|
+
/** The module version installed in the world, as the connector's cache has it. */
|
|
471
|
+
moduleInstalledVersion() {
|
|
472
|
+
return this.installedModuleVersion();
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* The connected module's version for display: the announced one, otherwise
|
|
476
|
+
* `<installed or unknown> (not announced)`.
|
|
477
|
+
*/
|
|
478
|
+
describeModuleVersion() {
|
|
479
|
+
return (this.moduleAnnouncement().version ??
|
|
480
|
+
`${this.installedModuleVersion() ?? 'unknown'} (not announced)`);
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Whether the connected module serves `type`: one of the commands it
|
|
484
|
+
* announced, or of {@link LEGACY_COMMANDS} when it announced none.
|
|
485
|
+
*/
|
|
486
|
+
supports(type) {
|
|
487
|
+
return (this.moduleAnnouncement().commands ?? LEGACY_COMMANDS).includes(type);
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Why the connected module cannot be sent `type`: the refusal of
|
|
491
|
+
* {@link send}, also quoted by a tool that needs a command it lacks.
|
|
492
|
+
*/
|
|
493
|
+
missingCommandMessage(type) {
|
|
494
|
+
const since = COMMAND_SINCE[type];
|
|
495
|
+
return (`the connected companion module ${this.describeModuleVersion()} does not provide '${type}'` +
|
|
496
|
+
(since ? `, which needs ${since} or later` : ''));
|
|
497
|
+
}
|
|
355
498
|
/**
|
|
356
499
|
* Sends a command to the connected module and awaits its response.
|
|
357
500
|
*
|
|
358
|
-
* @throws if no module is connected
|
|
359
|
-
*
|
|
360
|
-
*
|
|
501
|
+
* @throws if no module is connected or the module does not serve `type`
|
|
502
|
+
* (see {@link supports}; a {@link RefusedError}) — both before anything
|
|
503
|
+
* is sent — or if the module reports an error, or the request times out
|
|
504
|
+
* (the module hung).
|
|
361
505
|
*/
|
|
362
506
|
send(type, params = {}) {
|
|
363
507
|
if (!this.isConnected() || !this.socket) {
|
|
364
508
|
throw new Error('No authenticated Foundry module connected to the bridge. Install and enable the companion module (0.5.0 or later), confirm FOUNDRY_MODULE_BRIDGE_ENABLED=true, and check that the headless GM session is logged in.');
|
|
365
509
|
}
|
|
510
|
+
if (!this.supports(type)) {
|
|
511
|
+
throw new RefusedError(this.missingCommandMessage(type));
|
|
512
|
+
}
|
|
366
513
|
const id = String(this.nextId++);
|
|
367
514
|
const socket = this.socket;
|
|
368
515
|
return new Promise((resolve, reject) => {
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
*/
|
|
18
18
|
import { z } from 'zod';
|
|
19
19
|
import { isRecord } from '../utils/guards.js';
|
|
20
|
+
import { logger } from '../utils/logger.js';
|
|
20
21
|
/**
|
|
21
22
|
* Document name → the `WorldData` collection holding it.
|
|
22
23
|
*
|
|
@@ -186,7 +187,7 @@ function setDotPath(target, path, value) {
|
|
|
186
187
|
* Prototype-polluting keys are dropped rather than merged (see
|
|
187
188
|
* {@link FORBIDDEN_KEYS}).
|
|
188
189
|
*/
|
|
189
|
-
function mergePatch(target, patch) {
|
|
190
|
+
export function mergePatch(target, patch) {
|
|
190
191
|
for (const [key, value] of Object.entries(patch)) {
|
|
191
192
|
if (key === '__proto__' ||
|
|
192
193
|
key === 'constructor' ||
|
|
@@ -257,11 +258,10 @@ function applyToCollection(collection, action, result) {
|
|
|
257
258
|
/**
|
|
258
259
|
* Resolves the parent document a broadcast targets.
|
|
259
260
|
*
|
|
260
|
-
* Handles the simple `<Type>.<id>` form.
|
|
261
|
-
*
|
|
262
|
-
*
|
|
263
|
-
*
|
|
264
|
-
* stale until `refresh_world_data`.
|
|
261
|
+
* Handles the simple `<Type>.<id>` form only. An unlinked token's writes,
|
|
262
|
+
* parented to the token or to its ActorDelta, are applied before this by
|
|
263
|
+
* {@link applyTokenDeltaBroadcast}; the `Scene.<sid>.Token.<tid>.Actor.<aid>`
|
|
264
|
+
* form is not a parent FoundryVTT v14 accepts, so it resolves to nothing.
|
|
265
265
|
*/
|
|
266
266
|
function resolveParent(worldData, parentUuid) {
|
|
267
267
|
const segments = parentUuid.split('.');
|
|
@@ -287,12 +287,206 @@ function resolveParent(worldData, parentUuid) {
|
|
|
287
287
|
}
|
|
288
288
|
return { parentType, parent: parent };
|
|
289
289
|
}
|
|
290
|
+
/**
|
|
291
|
+
* `Scene.<sid>.Token.<tid>`, `….ActorDelta.<did>`, or `….ActorDelta.<did>.Item.<iid>`
|
|
292
|
+
* (an effect on one of the token's items).
|
|
293
|
+
*/
|
|
294
|
+
const TOKEN_DELTA_PARENT_PATTERN = /^Scene\.([a-zA-Z0-9]{16})\.Token\.([a-zA-Z0-9]{16})(?:\.ActorDelta\.([a-zA-Z0-9]{16})(?:\.Item\.([a-zA-Z0-9]{16}))?)?$/;
|
|
295
|
+
/** The document with this `_id` in `collection`, when it is an array holding one. */
|
|
296
|
+
function findById(collection, id) {
|
|
297
|
+
if (!Array.isArray(collection)) {
|
|
298
|
+
return undefined;
|
|
299
|
+
}
|
|
300
|
+
return collection.find((doc) => isRecord(doc) && doc._id === id);
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Applies an update to a token delta's items or effects.
|
|
304
|
+
*
|
|
305
|
+
* An entry the delta lacks but the base actor has is adopted first - copied
|
|
306
|
+
* from the base, then changed - as FoundryVTT's server does. An entry already
|
|
307
|
+
* in the delta is never copied again, so re-applying the update is a no-op.
|
|
308
|
+
*
|
|
309
|
+
* @returns true if the collection changed
|
|
310
|
+
*/
|
|
311
|
+
function updateDeltaCollection(collection, inherited, result) {
|
|
312
|
+
let changed = false;
|
|
313
|
+
for (const doc of result) {
|
|
314
|
+
if (!isRecord(doc) || typeof doc._id !== 'string') {
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
let target = findById(collection, doc._id);
|
|
318
|
+
if (!target) {
|
|
319
|
+
const source = findById(inherited, doc._id);
|
|
320
|
+
if (!source) {
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
target = structuredClone(source);
|
|
324
|
+
collection.push(target);
|
|
325
|
+
}
|
|
326
|
+
mergePatch(target, doc);
|
|
327
|
+
changed = true;
|
|
328
|
+
}
|
|
329
|
+
return changed;
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Applies a delete to a token delta's items or effects: an entry the base
|
|
333
|
+
* actor has becomes a tombstone (`{_id, _tombstone: true}`, FoundryVTT's mark
|
|
334
|
+
* that the token no longer inherits it), one of the token's own is removed.
|
|
335
|
+
*
|
|
336
|
+
* @returns true if the collection changed
|
|
337
|
+
*/
|
|
338
|
+
function deleteFromDeltaCollection(collection, inherited, result) {
|
|
339
|
+
let changed = false;
|
|
340
|
+
for (const id of result) {
|
|
341
|
+
if (typeof id !== 'string') {
|
|
342
|
+
continue;
|
|
343
|
+
}
|
|
344
|
+
const index = collection.findIndex((doc) => doc._id === id);
|
|
345
|
+
if (findById(inherited, id)) {
|
|
346
|
+
const tombstone = { _id: id, _tombstone: true };
|
|
347
|
+
if (index === -1) {
|
|
348
|
+
collection.push(tombstone);
|
|
349
|
+
}
|
|
350
|
+
else {
|
|
351
|
+
collection[index] = tombstone;
|
|
352
|
+
}
|
|
353
|
+
changed = true;
|
|
354
|
+
}
|
|
355
|
+
else if (index !== -1) {
|
|
356
|
+
collection.splice(index, 1);
|
|
357
|
+
changed = true;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return changed;
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Applies a create to a token delta's items or effects. A created document
|
|
364
|
+
* whose id the delta holds as a tombstone takes the tombstone's place, as
|
|
365
|
+
* FoundryVTT's `EmbeddedCollectionDelta#_set` replaces a managed entry's
|
|
366
|
+
* source; any other create is the usual upsert.
|
|
367
|
+
*
|
|
368
|
+
* @returns true if the collection changed
|
|
369
|
+
*/
|
|
370
|
+
function createInDeltaCollection(collection, result) {
|
|
371
|
+
for (const doc of result) {
|
|
372
|
+
if (!isRecord(doc) || typeof doc._id !== 'string') {
|
|
373
|
+
continue;
|
|
374
|
+
}
|
|
375
|
+
const index = collection.findIndex((entry) => entry._id === doc._id && entry._tombstone === true);
|
|
376
|
+
if (index !== -1) {
|
|
377
|
+
collection[index] = sanitize(doc);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return applyToCollection(collection, 'create', result);
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Applies a write to an unlinked token's synthetic actor.
|
|
384
|
+
*
|
|
385
|
+
* FoundryVTT stores an unlinked token's own HP, items and effects in the
|
|
386
|
+
* token's `delta` (an ActorDelta), and its client sends those writes as
|
|
387
|
+
* `ActorDelta` updates parented to the token, as embedded Item/ActiveEffect
|
|
388
|
+
* operations parented to `<token>.ActorDelta.<id>`, or as ActiveEffect
|
|
389
|
+
* operations on one of its items (`….ActorDelta.<id>.Item.<iid>`). All land in
|
|
390
|
+
* `token.delta`, which only holds what differs from the base actor: an
|
|
391
|
+
* inherited entry is adopted on its first change, tombstoned on delete, and a
|
|
392
|
+
* tombstone gives way to a document created again with its id (see
|
|
393
|
+
* {@link updateDeltaCollection}, {@link deleteFromDeltaCollection},
|
|
394
|
+
* {@link createInDeltaCollection}).
|
|
395
|
+
* The delta itself is created only once something is applied to it.
|
|
396
|
+
*
|
|
397
|
+
* @returns true/false when the broadcast targets a token delta (changed or
|
|
398
|
+
* not), or null when it doesn't, so the caller falls through to the
|
|
399
|
+
* ordinary parent resolution.
|
|
400
|
+
*/
|
|
401
|
+
function applyTokenDeltaBroadcast(worldData, broadcast) {
|
|
402
|
+
const { type, action, result, parentUuid } = broadcast;
|
|
403
|
+
const match = parentUuid ? TOKEN_DELTA_PARENT_PATTERN.exec(parentUuid) : null;
|
|
404
|
+
if (!match) {
|
|
405
|
+
return null;
|
|
406
|
+
}
|
|
407
|
+
const [, sceneId, tokenId, deltaId, itemId] = match;
|
|
408
|
+
const scene = worldData.scenes?.find((sc) => sc._id === sceneId);
|
|
409
|
+
const token = scene?.tokens?.find((t) => t._id === tokenId);
|
|
410
|
+
if (!token) {
|
|
411
|
+
return false;
|
|
412
|
+
}
|
|
413
|
+
const baseActorId = typeof token.actorId === 'string' ? token.actorId : undefined;
|
|
414
|
+
const base = baseActorId
|
|
415
|
+
? worldData.actors?.find((actor) => actor._id === baseActorId)
|
|
416
|
+
: undefined;
|
|
417
|
+
const existingDelta = isRecord(token.delta) ? token.delta : undefined;
|
|
418
|
+
const ensureDelta = () => {
|
|
419
|
+
if (!isRecord(token.delta)) {
|
|
420
|
+
token.delta = { _id: deltaId ?? tokenId };
|
|
421
|
+
}
|
|
422
|
+
return token.delta;
|
|
423
|
+
};
|
|
424
|
+
if (!deltaId) {
|
|
425
|
+
if (type !== 'ActorDelta' || action !== 'update') {
|
|
426
|
+
return false;
|
|
427
|
+
}
|
|
428
|
+
const docs = result.filter(isRecord);
|
|
429
|
+
if (docs.length === 0) {
|
|
430
|
+
return false;
|
|
431
|
+
}
|
|
432
|
+
const delta = ensureDelta();
|
|
433
|
+
for (const doc of docs) {
|
|
434
|
+
mergePatch(delta, doc);
|
|
435
|
+
}
|
|
436
|
+
return true;
|
|
437
|
+
}
|
|
438
|
+
if (itemId) {
|
|
439
|
+
if (type !== 'ActiveEffect') {
|
|
440
|
+
return false;
|
|
441
|
+
}
|
|
442
|
+
const own = findById(existingDelta?.items, itemId);
|
|
443
|
+
const baseItem = findById(base?.items, itemId);
|
|
444
|
+
const item = own ?? (baseItem ? structuredClone(baseItem) : undefined);
|
|
445
|
+
if (!item || item._tombstone === true) {
|
|
446
|
+
logger.debug(`Ignored ${action} ActiveEffect broadcast: item ${itemId} is not on token ${tokenId} or its base actor`);
|
|
447
|
+
return false;
|
|
448
|
+
}
|
|
449
|
+
if (!Array.isArray(item.effects)) {
|
|
450
|
+
if (action !== 'create') {
|
|
451
|
+
return false;
|
|
452
|
+
}
|
|
453
|
+
item.effects = [];
|
|
454
|
+
}
|
|
455
|
+
const changed = applyToCollection(item.effects, action, result);
|
|
456
|
+
if (changed && !own) {
|
|
457
|
+
const delta = ensureDelta();
|
|
458
|
+
if (!Array.isArray(delta.items)) {
|
|
459
|
+
delta.items = [];
|
|
460
|
+
}
|
|
461
|
+
delta.items.push(item);
|
|
462
|
+
}
|
|
463
|
+
return changed;
|
|
464
|
+
}
|
|
465
|
+
const field = EMBEDDED_COLLECTIONS.Actor?.[type];
|
|
466
|
+
if (!field) {
|
|
467
|
+
return false;
|
|
468
|
+
}
|
|
469
|
+
const existing = Array.isArray(existingDelta?.[field])
|
|
470
|
+
? existingDelta[field]
|
|
471
|
+
: undefined;
|
|
472
|
+
const collection = existing ?? [];
|
|
473
|
+
const inherited = base?.[field];
|
|
474
|
+
const changed = action === 'create'
|
|
475
|
+
? createInDeltaCollection(collection, result)
|
|
476
|
+
: action === 'update'
|
|
477
|
+
? updateDeltaCollection(collection, inherited, result)
|
|
478
|
+
: deleteFromDeltaCollection(collection, inherited, result);
|
|
479
|
+
if (changed && !existing) {
|
|
480
|
+
ensureDelta()[field] = collection;
|
|
481
|
+
}
|
|
482
|
+
return changed;
|
|
483
|
+
}
|
|
290
484
|
/**
|
|
291
485
|
* Applies a validated broadcast to the cached world state, in place.
|
|
292
486
|
*
|
|
293
487
|
* @returns true if the cache changed; false when the broadcast targets something
|
|
294
|
-
* not cached (an unmodelled document type, an unknown parent, a
|
|
295
|
-
*
|
|
488
|
+
* not cached (an unmodelled document type, an unknown parent, a token that is
|
|
489
|
+
* not in the cache), in which case the cache is left untouched.
|
|
296
490
|
*/
|
|
297
491
|
export function applyDocumentBroadcast(worldData, broadcast) {
|
|
298
492
|
const { type, action, result, parentUuid } = broadcast;
|
|
@@ -300,6 +494,10 @@ export function applyDocumentBroadcast(worldData, broadcast) {
|
|
|
300
494
|
return false;
|
|
301
495
|
}
|
|
302
496
|
if (parentUuid) {
|
|
497
|
+
const deltaApplied = applyTokenDeltaBroadcast(worldData, broadcast);
|
|
498
|
+
if (deltaApplied !== null) {
|
|
499
|
+
return deltaApplied;
|
|
500
|
+
}
|
|
303
501
|
const resolved = resolveParent(worldData, parentUuid);
|
|
304
502
|
if (!resolved) {
|
|
305
503
|
return false;
|
package/dist/mcp-server.js
CHANGED
|
@@ -14,6 +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
18
|
export function createMcpServer(backend) {
|
|
18
19
|
// Answers `initialize` even with no usable configuration yet: tool calls
|
|
19
20
|
// then say what is missing (see the relay and the all-in-one server).
|
|
@@ -41,14 +42,15 @@ export function createMcpServer(backend) {
|
|
|
41
42
|
resources: getAllResources(),
|
|
42
43
|
};
|
|
43
44
|
});
|
|
44
|
-
// Handle tool calls
|
|
45
|
+
// Handle tool calls. Errors leave with their bare message: the client adds
|
|
46
|
+
// the "MCP error <code>: " prefix itself (see withBareErrors).
|
|
45
47
|
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
46
48
|
const { name, arguments: args } = request.params;
|
|
47
|
-
return backend.callTool(name, args || {});
|
|
49
|
+
return withBareErrors(() => backend.callTool(name, args || {}));
|
|
48
50
|
});
|
|
49
51
|
// Handle resource reads
|
|
50
52
|
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
51
|
-
return backend.readResource(request.params.uri);
|
|
53
|
+
return withBareErrors(() => backend.readResource(request.params.uri));
|
|
52
54
|
});
|
|
53
55
|
return server;
|
|
54
56
|
}
|
package/dist/shared/control.js
CHANGED
|
@@ -71,6 +71,9 @@ export function formatStatus(status) {
|
|
|
71
71
|
lines.push(` Write queue: ${status.writeQueue} pending`);
|
|
72
72
|
}
|
|
73
73
|
lines.push(` FoundryVTT: ${formatFoundryConnection(status)}`);
|
|
74
|
+
if (status.staleCache) {
|
|
75
|
+
lines.push(` World cache: ${formatStaleCache(status.staleCache)}`);
|
|
76
|
+
}
|
|
74
77
|
if (status.account) {
|
|
75
78
|
const role = status.account.role ? ` (${status.account.role})` : '';
|
|
76
79
|
lines.push(` Account: ${status.account.name}${role}`);
|
|
@@ -81,10 +84,14 @@ export function formatStatus(status) {
|
|
|
81
84
|
if (status.startupError) {
|
|
82
85
|
lines.push(` Startup error: ${status.startupError}`);
|
|
83
86
|
}
|
|
84
|
-
const
|
|
87
|
+
const connecting = isConnecting(status);
|
|
88
|
+
// Before the core is built, nothing reports the bridge: it is not started yet.
|
|
89
|
+
const bridgeState = bridge?.state ?? (connecting ? 'not-started' : 'disabled');
|
|
85
90
|
const notStarted = status.foundryConnected
|
|
86
91
|
? 'not started yet'
|
|
87
|
-
:
|
|
92
|
+
: connecting
|
|
93
|
+
? 'not started yet (connecting to FoundryVTT)'
|
|
94
|
+
: 'not started (FoundryVTT connection failed)';
|
|
88
95
|
lines.push(` Module bridge: ${formatBridge(bridge, bridgeState, notStarted)}`);
|
|
89
96
|
if (bridgeState === 'listening' && bridge?.origin) {
|
|
90
97
|
lines.push(` Bridge origin: ${bridge.origin}`);
|
|
@@ -157,10 +164,35 @@ export function formatTerminalConfig(settings = resolveSettings()) {
|
|
|
157
164
|
}))),
|
|
158
165
|
];
|
|
159
166
|
}
|
|
167
|
+
/** e.g. "stale since 2026-11-06T13:02:11.000Z — the socket dropped". */
|
|
168
|
+
function formatStaleCache(stale) {
|
|
169
|
+
const since = stale.since ? ` since ${stale.since}` : '';
|
|
170
|
+
const reason = stale.reason ? ` — ${stale.reason}` : '';
|
|
171
|
+
return `stale${since}${reason}`;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* True while the shared process makes its first connection to FoundryVTT:
|
|
175
|
+
* not connected, no startup error, and either the core is not built yet (no
|
|
176
|
+
* connection nor bridge reported) or the link is still in its initial state
|
|
177
|
+
* (`disconnected` with no reason: every later disconnection carries one).
|
|
178
|
+
*/
|
|
179
|
+
function isConnecting(status) {
|
|
180
|
+
if (status.foundryConnected || status.startupError) {
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
const connection = status.foundryConnection;
|
|
184
|
+
if (connection === undefined) {
|
|
185
|
+
return status.bridge === undefined && status.headlessGm === undefined;
|
|
186
|
+
}
|
|
187
|
+
return connection.state === 'disconnected' && connection.error === null;
|
|
188
|
+
}
|
|
160
189
|
function formatFoundryConnection(status) {
|
|
161
190
|
if (status.foundryConnected) {
|
|
162
191
|
return 'connected';
|
|
163
192
|
}
|
|
193
|
+
if (isConnecting(status)) {
|
|
194
|
+
return 'connecting…';
|
|
195
|
+
}
|
|
164
196
|
const connection = status.foundryConnection;
|
|
165
197
|
if (!connection || connection.state === 'disconnected') {
|
|
166
198
|
return connection?.error ? `not connected — ${connection.error}` : 'not connected';
|
|
@@ -168,23 +200,32 @@ function formatFoundryConnection(status) {
|
|
|
168
200
|
return `not connected (${connection.state}${connection.error ? ` — ${connection.error}` : ''})`;
|
|
169
201
|
}
|
|
170
202
|
function formatBridge(bridge, state, notStarted) {
|
|
203
|
+
if (state === 'not-started') {
|
|
204
|
+
return notStarted;
|
|
205
|
+
}
|
|
171
206
|
if (!bridge || state === 'disabled') {
|
|
172
207
|
return 'disabled';
|
|
173
208
|
}
|
|
174
209
|
if (state === 'failed') {
|
|
175
210
|
return `failed to start — ${bridge.error ?? 'see the log'}`;
|
|
176
211
|
}
|
|
177
|
-
if (state === 'not-started') {
|
|
178
|
-
return notStarted;
|
|
179
|
-
}
|
|
180
212
|
return (`listening on port ${bridge.port}, protocol v${bridge.protocol}, authenticated module connected: ` +
|
|
181
213
|
yesNo(bridge.moduleConnected) +
|
|
182
|
-
(bridge.moduleConnectedSince ? ` (since ${bridge.moduleConnectedSince})` : '')
|
|
214
|
+
(bridge.moduleConnectedSince ? ` (since ${bridge.moduleConnectedSince})` : '') +
|
|
215
|
+
(bridge.moduleConnected ? `, module ${formatModuleVersion(bridge)}` : ''));
|
|
216
|
+
}
|
|
217
|
+
/** The announced module version, otherwise `<installed or unknown> (not announced)`. */
|
|
218
|
+
function formatModuleVersion(bridge) {
|
|
219
|
+
return bridge.moduleVersion ?? `${bridge.moduleInstalledVersion ?? 'unknown'} (not announced)`;
|
|
183
220
|
}
|
|
184
221
|
function formatHeadlessGm(headlessGm, bridgeState, notStarted) {
|
|
185
222
|
if (headlessGm?.launchError) {
|
|
186
223
|
return `browser launch failed — ${headlessGm.launchError}`;
|
|
187
224
|
}
|
|
225
|
+
if (!headlessGm && bridgeState === 'not-started') {
|
|
226
|
+
// The core is not built yet (see isConnecting).
|
|
227
|
+
return notStarted;
|
|
228
|
+
}
|
|
188
229
|
const state = headlessGm?.state ?? 'disabled';
|
|
189
230
|
if (!headlessGm || state === 'disabled') {
|
|
190
231
|
return 'disabled';
|
package/dist/shared/daemon.js
CHANGED
|
@@ -14,6 +14,7 @@ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
|
|
|
14
14
|
import { configFromSettings, getConfig } from '../config/index.js';
|
|
15
15
|
import { displayValue, KNOWN_SETTINGS, resolveSettings } from '../config/sources.js';
|
|
16
16
|
import { logger } from '../utils/logger.js';
|
|
17
|
+
import { bareMessage } from '../utils/mcp-errors.js';
|
|
17
18
|
import { isRefusal } from '../utils/refusal.js';
|
|
18
19
|
import { compareBuilds } from './build-order.js';
|
|
19
20
|
import { configDigests, configFingerprint } from './config-hash.js';
|
|
@@ -23,10 +24,7 @@ import { RotatingLog } from './rotating-log.js';
|
|
|
23
24
|
import { removeStateFile, writeStateFile } from './state-file.js';
|
|
24
25
|
import { loadOrCreateToken } from './token.js';
|
|
25
26
|
import { buildVersion } from './version.js';
|
|
26
|
-
/**
|
|
27
|
-
function bareMessage(error) {
|
|
28
|
-
return error.message.replace(/^MCP error -?\d+: /, '');
|
|
29
|
-
}
|
|
27
|
+
/** Sends the bare text of an McpError: the relay rebuilds the McpError. */
|
|
30
28
|
export function toIpcError(error) {
|
|
31
29
|
if (error instanceof McpError) {
|
|
32
30
|
return {
|