@g33ks/foundryvtt-mcp 0.0.0-stage → 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.
- package/LICENSE +22 -0
- package/README.md +457 -2
- package/dist/character/manager.js +208 -0
- package/dist/cli/checks.js +307 -0
- package/dist/cli/config-file.js +120 -0
- package/dist/cli/init.js +414 -0
- package/dist/cli/prompt.js +117 -0
- package/dist/cli/snippets.js +64 -0
- package/dist/combat/manager.js +371 -0
- package/dist/config/env-layers.js +49 -0
- package/dist/config/index.js +298 -0
- package/dist/config/sources.js +201 -0
- package/dist/core.js +481 -0
- package/dist/diagnostics/client.js +291 -0
- package/dist/diagnostics/types.js +94 -0
- package/dist/foundry/auth.js +224 -0
- package/dist/foundry/browser-detect.js +170 -0
- package/dist/foundry/client.js +5874 -0
- package/dist/foundry/dice-formula.js +154 -0
- package/dist/foundry/event-log.js +298 -0
- package/dist/foundry/headless-gm-session.js +857 -0
- package/dist/foundry/journal-conflicts.js +141 -0
- package/dist/foundry/journal-history.js +90 -0
- package/dist/foundry/journal-integrity.js +322 -0
- package/dist/foundry/message-author.js +19 -0
- package/dist/foundry/module-bridge.js +441 -0
- package/dist/foundry/types.js +52 -0
- package/dist/foundry/world-cache.js +386 -0
- package/dist/index.js +107 -0
- package/dist/mcp-server.js +65 -0
- package/dist/server.js +159 -0
- package/dist/shared/build-order.js +134 -0
- package/dist/shared/config-hash.js +62 -0
- package/dist/shared/config-notice.js +55 -0
- package/dist/shared/control.js +291 -0
- package/dist/shared/daemon-link.js +135 -0
- package/dist/shared/daemon.js +311 -0
- package/dist/shared/ipc-client.js +200 -0
- package/dist/shared/ipc-server.js +316 -0
- package/dist/shared/paths.js +79 -0
- package/dist/shared/protocol.js +230 -0
- package/dist/shared/relay-config.js +65 -0
- package/dist/shared/relay.js +120 -0
- package/dist/shared/rotating-log.js +57 -0
- package/dist/shared/spawn.js +39 -0
- package/dist/shared/state-file.js +33 -0
- package/dist/shared/token.js +62 -0
- package/dist/shared/version.js +57 -0
- package/dist/tools/base.js +74 -0
- package/dist/tools/definitions.js +3109 -0
- package/dist/tools/handlers/actor-mutations.js +128 -0
- package/dist/tools/handlers/actors.js +114 -0
- package/dist/tools/handlers/chat-mutations.js +49 -0
- package/dist/tools/handlers/chat.js +38 -0
- package/dist/tools/handlers/combat-mutations.js +215 -0
- package/dist/tools/handlers/combat-order.js +94 -0
- package/dist/tools/handlers/combat.js +51 -0
- package/dist/tools/handlers/compendium.js +83 -0
- package/dist/tools/handlers/diagnostics.js +450 -0
- package/dist/tools/handlers/dice.js +54 -0
- package/dist/tools/handlers/effects.js +103 -0
- package/dist/tools/handlers/events.js +50 -0
- package/dist/tools/handlers/generation.js +258 -0
- package/dist/tools/handlers/item-mutations.js +132 -0
- package/dist/tools/handlers/items.js +53 -0
- package/dist/tools/handlers/journal-mutations.js +230 -0
- package/dist/tools/handlers/journals.js +80 -0
- package/dist/tools/handlers/module-bridge.js +421 -0
- package/dist/tools/handlers/placeable-mutations.js +272 -0
- package/dist/tools/handlers/resources.js +203 -0
- package/dist/tools/handlers/roll-tables.js +97 -0
- package/dist/tools/handlers/scene-mutations.js +159 -0
- package/dist/tools/handlers/scenes.js +355 -0
- package/dist/tools/handlers/settings.js +53 -0
- package/dist/tools/handlers/tile-mutations.js +56 -0
- package/dist/tools/handlers/token-mutations.js +356 -0
- package/dist/tools/handlers/users.js +59 -0
- package/dist/tools/handlers/utils.js +48 -0
- package/dist/tools/handlers/wall-mutations.js +98 -0
- package/dist/tools/handlers/world-documents.js +222 -0
- package/dist/tools/handlers/world.js +92 -0
- package/dist/tools/index.js +25 -0
- package/dist/tools/new-router.js +97 -0
- package/dist/tools/registry.js +79 -0
- package/dist/tools/resources.js +63 -0
- package/dist/tools/router.js +688 -0
- package/dist/tools/tool-dependencies.js +194 -0
- package/dist/tools/write-tools.js +97 -0
- package/dist/utils/cache-instance.js +30 -0
- package/dist/utils/cache.js +205 -0
- package/dist/utils/diagnostics.js +332 -0
- package/dist/utils/guards.js +17 -0
- package/dist/utils/image-size.js +160 -0
- package/dist/utils/log-args.js +47 -0
- package/dist/utils/logger.js +203 -0
- package/dist/utils/mcp-errors.js +47 -0
- package/dist/utils/refusal.js +30 -0
- package/dist/utils/sanitize.js +22 -0
- package/dist/utils/serial-queue.js +22 -0
- package/package.json +124 -4
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Applies FoundryVTT `modifyDocument` broadcasts to the cached world state.
|
|
3
|
+
*
|
|
4
|
+
* `worldData` is loaded once at connect time (ADR-004) and was, until laurigates/foundryvtt-mcp#205, never
|
|
5
|
+
* updated afterwards — so a write followed by a read returned pre-write data, and
|
|
6
|
+
* changes made by other users (a player moving a token, the GM editing in the
|
|
7
|
+
* Foundry UI) were invisible for the life of the connection.
|
|
8
|
+
*
|
|
9
|
+
* FoundryVTT broadcasts every accepted document mutation to connected clients on
|
|
10
|
+
* the `modifyDocument` event. This module turns one such broadcast into an
|
|
11
|
+
* in-place edit of the cached snapshot.
|
|
12
|
+
*
|
|
13
|
+
* **Idempotent by construction.** `create` upserts by `_id` rather than pushing,
|
|
14
|
+
* and `delete` tolerates an id that is already gone. So it does not matter
|
|
15
|
+
* whether FoundryVTT echoes a client's own writes back to it — applying the same
|
|
16
|
+
* broadcast twice lands on the same state as applying it once.
|
|
17
|
+
*/
|
|
18
|
+
import { z } from 'zod';
|
|
19
|
+
import { isRecord } from '../utils/guards.js';
|
|
20
|
+
/**
|
|
21
|
+
* Document name → the `WorldData` collection holding it.
|
|
22
|
+
*
|
|
23
|
+
* Types absent here (Setting, Adventure, …) are not cached, so broadcasts about
|
|
24
|
+
* them are ignored rather than mishandled.
|
|
25
|
+
*/
|
|
26
|
+
const TOP_LEVEL_COLLECTIONS = {
|
|
27
|
+
Actor: 'actors',
|
|
28
|
+
Item: 'items',
|
|
29
|
+
Scene: 'scenes',
|
|
30
|
+
JournalEntry: 'journal',
|
|
31
|
+
Combat: 'combats',
|
|
32
|
+
ChatMessage: 'messages',
|
|
33
|
+
User: 'users',
|
|
34
|
+
Folder: 'folders',
|
|
35
|
+
Macro: 'macros',
|
|
36
|
+
Playlist: 'playlists',
|
|
37
|
+
RollTable: 'tables',
|
|
38
|
+
Cards: 'cards',
|
|
39
|
+
Setting: 'settings',
|
|
40
|
+
};
|
|
41
|
+
/** Parent document name → embedded document name → the parent's array field. */
|
|
42
|
+
const EMBEDDED_COLLECTIONS = {
|
|
43
|
+
Actor: { Item: 'items', ActiveEffect: 'effects' },
|
|
44
|
+
Scene: {
|
|
45
|
+
Token: 'tokens',
|
|
46
|
+
AmbientLight: 'lights',
|
|
47
|
+
AmbientSound: 'sounds',
|
|
48
|
+
Wall: 'walls',
|
|
49
|
+
Drawing: 'drawings',
|
|
50
|
+
Note: 'notes',
|
|
51
|
+
Tile: 'tiles',
|
|
52
|
+
MeasuredTemplate: 'templates',
|
|
53
|
+
Region: 'regions',
|
|
54
|
+
},
|
|
55
|
+
Combat: { Combatant: 'combatants' },
|
|
56
|
+
Item: { ActiveEffect: 'effects' },
|
|
57
|
+
JournalEntry: { JournalEntryPage: 'pages' },
|
|
58
|
+
Playlist: { PlaylistSound: 'sounds' },
|
|
59
|
+
RollTable: { TableResult: 'results' },
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* Validates a raw socket payload as a `modifyDocument` broadcast.
|
|
63
|
+
*
|
|
64
|
+
* Returns `null` for anything unrecognized — a payload shape we do not model is
|
|
65
|
+
* dropped rather than guessed at, leaving the cache untouched (and stale) rather
|
|
66
|
+
* than corrupted.
|
|
67
|
+
*/
|
|
68
|
+
export function parseDocumentBroadcast(payload) {
|
|
69
|
+
if (!isRecord(payload)) {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
const { type, action, result, operation } = payload;
|
|
73
|
+
if (typeof type !== 'string' || !type) {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
if (action !== 'create' && action !== 'update' && action !== 'delete') {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
if (!Array.isArray(result)) {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
// A rejected operation is broadcast to nobody, but be explicit about it.
|
|
83
|
+
if (payload.error) {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
const broadcast = { type, action, result };
|
|
87
|
+
const parentUuid = isRecord(operation) ? operation.parentUuid : undefined;
|
|
88
|
+
if (typeof parentUuid === 'string' && parentUuid) {
|
|
89
|
+
broadcast.parentUuid = parentUuid;
|
|
90
|
+
}
|
|
91
|
+
if (typeof payload.userId === 'string' && payload.userId) {
|
|
92
|
+
broadcast.userId = payload.userId;
|
|
93
|
+
}
|
|
94
|
+
return broadcast;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Validates a `modifyDocumentBatch` payload and splits it into broadcasts.
|
|
98
|
+
*
|
|
99
|
+
* FoundryVTT v14 sends `{results: DocumentSocketResponse[]}` on this event
|
|
100
|
+
* instead of `modifyDocument` for a `foundry.documents.modifyBatch()` call,
|
|
101
|
+
* and for any single operation with server-side side effects (activating a
|
|
102
|
+
* scene deactivates the others, deleting a folder deletes its contents, …):
|
|
103
|
+
* side effects first, the operation itself last. Each element has the shape
|
|
104
|
+
* of a `modifyDocument` broadcast; invalid ones are dropped, the rest kept.
|
|
105
|
+
*
|
|
106
|
+
* @returns the broadcasts in order, or `null` when the payload is not a batch
|
|
107
|
+
*/
|
|
108
|
+
export function parseDocumentBatch(payload) {
|
|
109
|
+
if (!isRecord(payload) || !Array.isArray(payload.results)) {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
return payload.results.flatMap((element) => parseDocumentBroadcast(element) ?? []);
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Keys that must never be copied out of a broadcast payload.
|
|
116
|
+
*
|
|
117
|
+
* Broadcast data arrives off the network from whatever FoundryVTT relays, so it
|
|
118
|
+
* is untrusted input; writing these would reach `Object.prototype` and poison
|
|
119
|
+
* every object in the process. ADR-010 already mandates hard-failing these in
|
|
120
|
+
* mutation patches — the same rule applies on the way back in.
|
|
121
|
+
*/
|
|
122
|
+
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
123
|
+
/**
|
|
124
|
+
* Copies own, safe keys out of an untrusted object.
|
|
125
|
+
*
|
|
126
|
+
* Applied to created documents before they enter the cache, so a hostile
|
|
127
|
+
* payload cannot smuggle a `__proto__` key in through the create path either.
|
|
128
|
+
*/
|
|
129
|
+
function sanitize(doc) {
|
|
130
|
+
const clean = {};
|
|
131
|
+
for (const [key, value] of Object.entries(doc)) {
|
|
132
|
+
if (key === '__proto__' ||
|
|
133
|
+
key === 'constructor' ||
|
|
134
|
+
key === 'prototype' ||
|
|
135
|
+
FORBIDDEN_KEYS.has(key)) {
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
clean[key] = value;
|
|
139
|
+
}
|
|
140
|
+
return clean;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Sets or merges a value at a dot-separated path in `target`, creating nested
|
|
144
|
+
* objects as needed.
|
|
145
|
+
*/
|
|
146
|
+
function setDotPath(target, path, value) {
|
|
147
|
+
const parts = path.split('.');
|
|
148
|
+
let curr = target;
|
|
149
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
150
|
+
const part = parts[i];
|
|
151
|
+
if (!part ||
|
|
152
|
+
part === '__proto__' ||
|
|
153
|
+
part === 'constructor' ||
|
|
154
|
+
part === 'prototype' ||
|
|
155
|
+
FORBIDDEN_KEYS.has(part)) {
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (!isRecord(curr[part])) {
|
|
159
|
+
curr[part] = {};
|
|
160
|
+
}
|
|
161
|
+
curr = curr[part];
|
|
162
|
+
}
|
|
163
|
+
const last = parts[parts.length - 1];
|
|
164
|
+
if (!last ||
|
|
165
|
+
last === '__proto__' ||
|
|
166
|
+
last === 'constructor' ||
|
|
167
|
+
last === 'prototype' ||
|
|
168
|
+
FORBIDDEN_KEYS.has(last)) {
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (value === null) {
|
|
172
|
+
delete curr[last];
|
|
173
|
+
}
|
|
174
|
+
else if (isRecord(value) && isRecord(curr[last])) {
|
|
175
|
+
mergePatch(curr[last], value);
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
curr[last] = value;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Recursively merges `patch` into `target`, matching FoundryVTT's own update
|
|
183
|
+
* semantics: keys merge, `null` deletes, arrays replace wholesale, and
|
|
184
|
+
* dot-notation keys (e.g. `'config.dim'`) expand into nested structures.
|
|
185
|
+
*
|
|
186
|
+
* Prototype-polluting keys are dropped rather than merged (see
|
|
187
|
+
* {@link FORBIDDEN_KEYS}).
|
|
188
|
+
*/
|
|
189
|
+
function mergePatch(target, patch) {
|
|
190
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
191
|
+
if (key === '__proto__' ||
|
|
192
|
+
key === 'constructor' ||
|
|
193
|
+
key === 'prototype' ||
|
|
194
|
+
FORBIDDEN_KEYS.has(key)) {
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
if (key.includes('.')) {
|
|
198
|
+
setDotPath(target, key, value);
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
if (value === null) {
|
|
202
|
+
delete target[key];
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
if (isRecord(value) && isRecord(target[key])) {
|
|
206
|
+
mergePatch(target[key], value);
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
target[key] = value;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Applies one broadcast to a document array in place.
|
|
214
|
+
*
|
|
215
|
+
* @returns true if the collection changed
|
|
216
|
+
*/
|
|
217
|
+
function applyToCollection(collection, action, result) {
|
|
218
|
+
let changed = false;
|
|
219
|
+
if (action === 'delete') {
|
|
220
|
+
// `result` is an array of deleted document ids.
|
|
221
|
+
for (const id of result) {
|
|
222
|
+
if (typeof id !== 'string') {
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
const index = collection.findIndex((doc) => doc._id === id);
|
|
226
|
+
if (index !== -1) {
|
|
227
|
+
collection.splice(index, 1);
|
|
228
|
+
changed = true;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return changed;
|
|
232
|
+
}
|
|
233
|
+
for (const doc of result) {
|
|
234
|
+
if (!isRecord(doc) || typeof doc._id !== 'string') {
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
const existing = collection.find((d) => d._id === doc._id);
|
|
238
|
+
if (action === 'create') {
|
|
239
|
+
// Upsert, not push — re-applying a create must not duplicate the document.
|
|
240
|
+
if (existing) {
|
|
241
|
+
mergePatch(existing, doc);
|
|
242
|
+
}
|
|
243
|
+
else {
|
|
244
|
+
collection.push(sanitize(doc));
|
|
245
|
+
}
|
|
246
|
+
changed = true;
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
// update: FoundryVTT broadcasts the diff, so merge rather than replace.
|
|
250
|
+
if (existing) {
|
|
251
|
+
mergePatch(existing, doc);
|
|
252
|
+
changed = true;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return changed;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Resolves the parent document a broadcast targets.
|
|
259
|
+
*
|
|
260
|
+
* Handles the simple `<Type>.<id>` form. The synthetic-token-actor form
|
|
261
|
+
* (`Scene.<sid>.Token.<tid>.Actor.<aid>`, used for unlinked tokens) is **not**
|
|
262
|
+
* resolved: that actor is a per-token delta rather than a document in any cached
|
|
263
|
+
* collection, so those broadcasts are dropped and the affected token actor stays
|
|
264
|
+
* stale until `refresh_world_data`.
|
|
265
|
+
*/
|
|
266
|
+
function resolveParent(worldData, parentUuid) {
|
|
267
|
+
const segments = parentUuid.split('.');
|
|
268
|
+
if (segments.length !== 2) {
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
const parentType = segments[0];
|
|
272
|
+
const parentId = segments[1];
|
|
273
|
+
if (!parentType || !parentId) {
|
|
274
|
+
return null;
|
|
275
|
+
}
|
|
276
|
+
const collectionKey = TOP_LEVEL_COLLECTIONS[parentType];
|
|
277
|
+
if (!collectionKey) {
|
|
278
|
+
return null;
|
|
279
|
+
}
|
|
280
|
+
const collection = worldData[collectionKey];
|
|
281
|
+
if (!Array.isArray(collection)) {
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
const parent = collection.find((doc) => doc._id === parentId);
|
|
285
|
+
if (!parent) {
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
288
|
+
return { parentType, parent: parent };
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Applies a validated broadcast to the cached world state, in place.
|
|
292
|
+
*
|
|
293
|
+
* @returns true if the cache changed; false when the broadcast targets something
|
|
294
|
+
* not cached (an unmodelled document type, an unknown parent, a synthetic
|
|
295
|
+
* token actor), in which case the cache is left untouched.
|
|
296
|
+
*/
|
|
297
|
+
export function applyDocumentBroadcast(worldData, broadcast) {
|
|
298
|
+
const { type, action, result, parentUuid } = broadcast;
|
|
299
|
+
if (result.length === 0) {
|
|
300
|
+
return false;
|
|
301
|
+
}
|
|
302
|
+
if (parentUuid) {
|
|
303
|
+
const resolved = resolveParent(worldData, parentUuid);
|
|
304
|
+
if (!resolved) {
|
|
305
|
+
return false;
|
|
306
|
+
}
|
|
307
|
+
const field = EMBEDDED_COLLECTIONS[resolved.parentType]?.[type];
|
|
308
|
+
if (!field) {
|
|
309
|
+
return false;
|
|
310
|
+
}
|
|
311
|
+
// The field is optional on several world types (an actor with no effects
|
|
312
|
+
// omits `effects` entirely), so materialize it before a create.
|
|
313
|
+
if (!Array.isArray(resolved.parent[field])) {
|
|
314
|
+
if (action !== 'create') {
|
|
315
|
+
return false;
|
|
316
|
+
}
|
|
317
|
+
resolved.parent[field] = [];
|
|
318
|
+
}
|
|
319
|
+
return applyToCollection(resolved.parent[field], action, result);
|
|
320
|
+
}
|
|
321
|
+
const collectionKey = TOP_LEVEL_COLLECTIONS[type];
|
|
322
|
+
if (!collectionKey) {
|
|
323
|
+
return false;
|
|
324
|
+
}
|
|
325
|
+
const collection = worldData[collectionKey];
|
|
326
|
+
if (!Array.isArray(collection)) {
|
|
327
|
+
return false;
|
|
328
|
+
}
|
|
329
|
+
return applyToCollection(collection, action, result);
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* FoundryVTT's `userActivity` payload, as far as presence is concerned.
|
|
333
|
+
*
|
|
334
|
+
* The event carries a grab-bag of ephemeral state (cursor position, ruler,
|
|
335
|
+
* targets, active scene). Only `active` matters here; everything else is
|
|
336
|
+
* accepted and ignored. The flag is absent on ordinary activity pings — Foundry
|
|
337
|
+
* itself treats "no flag" as "present", so the parser defaults to `true`.
|
|
338
|
+
*/
|
|
339
|
+
const UserActivityDataSchema = z.object({ active: z.boolean().optional() });
|
|
340
|
+
/**
|
|
341
|
+
* Validates a raw `userActivity` socket payload (laurigates/foundryvtt-mcp#218).
|
|
342
|
+
*
|
|
343
|
+
* This is untrusted network data, so it is schema-checked rather than cast.
|
|
344
|
+
* Returns `null` for anything unrecognized, leaving presence as it was.
|
|
345
|
+
*/
|
|
346
|
+
export function parseUserActivity(userId, activityData) {
|
|
347
|
+
if (typeof userId !== 'string' || !userId) {
|
|
348
|
+
return null;
|
|
349
|
+
}
|
|
350
|
+
if (activityData === undefined || activityData === null) {
|
|
351
|
+
return { userId, active: true };
|
|
352
|
+
}
|
|
353
|
+
const parsed = UserActivityDataSchema.safeParse(activityData);
|
|
354
|
+
if (!parsed.success) {
|
|
355
|
+
return null;
|
|
356
|
+
}
|
|
357
|
+
return { userId, active: parsed.data.active ?? true };
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Applies a presence change to `worldData.activeUsers`, in place.
|
|
361
|
+
*
|
|
362
|
+
* `activeUsers` is a top-level `WorldData` field rather than a document
|
|
363
|
+
* collection, which is exactly why `modifyDocument` broadcasts never reached it
|
|
364
|
+
* and presence stayed frozen at the connect-time snapshot (laurigates/foundryvtt-mcp#218).
|
|
365
|
+
*
|
|
366
|
+
* @returns true if the active-user list changed
|
|
367
|
+
*/
|
|
368
|
+
export function applyUserActivity(worldData, activity) {
|
|
369
|
+
if (!Array.isArray(worldData.activeUsers)) {
|
|
370
|
+
worldData.activeUsers = [];
|
|
371
|
+
}
|
|
372
|
+
const index = worldData.activeUsers.indexOf(activity.userId);
|
|
373
|
+
if (activity.active) {
|
|
374
|
+
if (index !== -1) {
|
|
375
|
+
return false;
|
|
376
|
+
}
|
|
377
|
+
worldData.activeUsers.push(activity.userId);
|
|
378
|
+
return true;
|
|
379
|
+
}
|
|
380
|
+
if (index === -1) {
|
|
381
|
+
return false;
|
|
382
|
+
}
|
|
383
|
+
worldData.activeUsers.splice(index, 1);
|
|
384
|
+
return true;
|
|
385
|
+
}
|
|
386
|
+
//# sourceMappingURL=world-cache.js.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* FoundryVTT Model Context Protocol Server
|
|
4
|
+
*
|
|
5
|
+
* This server provides integration between FoundryVTT and AI models through the Model Context Protocol (MCP).
|
|
6
|
+
* It enables AI assistants to interact with FoundryVTT instances for RPG campaign management,
|
|
7
|
+
* character handling, and game automation.
|
|
8
|
+
*
|
|
9
|
+
* One binary, several roles (first argument):
|
|
10
|
+
* - (none) MCP stdio server. By default a lightweight relay to the shared
|
|
11
|
+
* process; with `FOUNDRY_MCP_SHARED=false`, the all-in-one server.
|
|
12
|
+
* - `daemon` the shared process owning the FoundryVTT connection.
|
|
13
|
+
* - `status` print the shared process's state.
|
|
14
|
+
* - `stop` stop the shared process.
|
|
15
|
+
* - `init` write the configuration file interactively; `init --check`
|
|
16
|
+
* checks the existing configuration without writing anything.
|
|
17
|
+
* - `--version` print the package version (also `-v` and `version`); reads
|
|
18
|
+
* no configuration and connects to nothing.
|
|
19
|
+
* - `daemon-launch` internal: starts `daemon` detached and exits (see shared/spawn.ts).
|
|
20
|
+
*
|
|
21
|
+
* Each role is imported on demand so the relay and the control commands do
|
|
22
|
+
* not load Socket.IO or Playwright.
|
|
23
|
+
*
|
|
24
|
+
* @fileoverview Main entry point for the FoundryVTT MCP Server
|
|
25
|
+
* @see {@link https://github.com/anthropics/mcp} Model Context Protocol
|
|
26
|
+
* @see {@link https://foundryvtt.com/} FoundryVTT Virtual Tabletop
|
|
27
|
+
*/
|
|
28
|
+
import { realpathSync } from 'node:fs';
|
|
29
|
+
import { fileURLToPath } from 'node:url';
|
|
30
|
+
/** This script, re-run by the relay to start the shared process. */
|
|
31
|
+
const ENTRY = fileURLToPath(import.meta.url);
|
|
32
|
+
async function main(role) {
|
|
33
|
+
switch (role) {
|
|
34
|
+
case '--version':
|
|
35
|
+
case '-v':
|
|
36
|
+
case 'version': {
|
|
37
|
+
const { packageVersion } = await import('./shared/version.js');
|
|
38
|
+
process.stdout.write(`${packageVersion()}\n`);
|
|
39
|
+
break;
|
|
40
|
+
}
|
|
41
|
+
case 'status': {
|
|
42
|
+
const { runStatus } = await import('./shared/control.js');
|
|
43
|
+
process.exit(await runStatus());
|
|
44
|
+
break;
|
|
45
|
+
}
|
|
46
|
+
case 'stop': {
|
|
47
|
+
const { runStop } = await import('./shared/control.js');
|
|
48
|
+
process.exit(await runStop());
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
case 'init': {
|
|
52
|
+
const { runInit } = await import('./cli/init.js');
|
|
53
|
+
process.exit(await runInit(process.argv.slice(3), ENTRY));
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
case 'daemon-launch': {
|
|
57
|
+
const { runDaemonLauncher } = await import('./shared/spawn.js');
|
|
58
|
+
runDaemonLauncher(ENTRY);
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
case 'daemon': {
|
|
62
|
+
const { runDaemon } = await import('./shared/daemon.js');
|
|
63
|
+
await runDaemon();
|
|
64
|
+
break;
|
|
65
|
+
}
|
|
66
|
+
case undefined: {
|
|
67
|
+
// Read without validating: with no usable configuration yet the relay
|
|
68
|
+
// (or the all-in-one server) still starts and explains it on each call.
|
|
69
|
+
const { resolveSettings } = await import('./config/sources.js');
|
|
70
|
+
if (resolveSettings().values.FOUNDRY_MCP_SHARED !== 'false') {
|
|
71
|
+
const { runRelay } = await import('./shared/relay.js');
|
|
72
|
+
await runRelay(ENTRY);
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
const { runAllInOne } = await import('./server.js');
|
|
76
|
+
await runAllInOne();
|
|
77
|
+
}
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
default:
|
|
81
|
+
process.stderr.write(`Unknown command: ${role}\nUsage: foundryvtt-mcp [init [--check] | daemon | status | stop | --version]\n`);
|
|
82
|
+
process.exit(2);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
// Run the server if this file is executed directly.
|
|
86
|
+
// Use realpath so the comparison works when npm/npx installs the bin as a
|
|
87
|
+
// symlink into node_modules/.bin (the literal `file://${argv[1]}` compare
|
|
88
|
+
// fails for symlinked invocations and on macOS where /tmp -> /private/tmp).
|
|
89
|
+
const isMainModule = (() => {
|
|
90
|
+
const argv1 = process.argv[1];
|
|
91
|
+
if (!argv1) {
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
return realpathSync(argv1) === ENTRY;
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return import.meta.url === `file://${argv1}`;
|
|
99
|
+
}
|
|
100
|
+
})();
|
|
101
|
+
if (isMainModule) {
|
|
102
|
+
main(process.argv[2]).catch((error) => {
|
|
103
|
+
process.stderr.write(`FoundryVTT MCP Server startup failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);
|
|
104
|
+
process.exit(1);
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview The MCP stdio server facade shared by the all-in-one mode
|
|
3
|
+
* and the relay.
|
|
4
|
+
*
|
|
5
|
+
* `tools/list` and `resources/list` are static and answered locally; only
|
|
6
|
+
* `tools/call` and `resources/read` go to the backend. Imports stay light on
|
|
7
|
+
* purpose: the relay must answer `initialize` without loading Socket.IO or
|
|
8
|
+
* Playwright.
|
|
9
|
+
*/
|
|
10
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
11
|
+
import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
|
|
12
|
+
import { tryGetConfig } from './config/index.js';
|
|
13
|
+
import { packageVersion } from './shared/version.js';
|
|
14
|
+
import { getAllTools } from './tools/definitions.js';
|
|
15
|
+
import { getAllResources } from './tools/resources.js';
|
|
16
|
+
import { logger } from './utils/logger.js';
|
|
17
|
+
import { withBareErrors } from './utils/mcp-errors.js';
|
|
18
|
+
export function createMcpServer(backend) {
|
|
19
|
+
// Answers `initialize` even with no usable configuration yet: tool calls
|
|
20
|
+
// then say what is missing (see the relay and the all-in-one server).
|
|
21
|
+
const loaded = tryGetConfig();
|
|
22
|
+
const server = new Server({
|
|
23
|
+
name: 'config' in loaded ? loaded.config.serverName : 'foundryvtt-mcp',
|
|
24
|
+
version: packageVersion(),
|
|
25
|
+
}, {
|
|
26
|
+
capabilities: {
|
|
27
|
+
resources: {},
|
|
28
|
+
tools: {},
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
// List available tools
|
|
32
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
33
|
+
logger.info('Listing available tools');
|
|
34
|
+
return {
|
|
35
|
+
tools: getAllTools(),
|
|
36
|
+
};
|
|
37
|
+
});
|
|
38
|
+
// List available resources
|
|
39
|
+
server.setRequestHandler(ListResourcesRequestSchema, async () => {
|
|
40
|
+
logger.info('Listing available resources');
|
|
41
|
+
return {
|
|
42
|
+
resources: getAllResources(),
|
|
43
|
+
};
|
|
44
|
+
});
|
|
45
|
+
// Handle tool calls. Errors leave with their bare message: the client adds
|
|
46
|
+
// the "MCP error <code>: " prefix itself (see withBareErrors).
|
|
47
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
48
|
+
const { name, arguments: args } = request.params;
|
|
49
|
+
return withBareErrors(() => backend.callTool(name, args || {}));
|
|
50
|
+
});
|
|
51
|
+
// Handle resource reads
|
|
52
|
+
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
53
|
+
return withBareErrors(() => backend.readResource(request.params.uri));
|
|
54
|
+
});
|
|
55
|
+
return server;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Pre-connect banner — emitted on stderr so the stdio JSON-RPC channel on
|
|
59
|
+
* stdout stays clean once StdioServerTransport.connect() takes it over.
|
|
60
|
+
* The smoke test (scripts/smoke-test.js) keys on this string to verify the
|
|
61
|
+
* binary loads without crashing at construction time, before any network
|
|
62
|
+
* call to FoundryVTT.
|
|
63
|
+
*/
|
|
64
|
+
export const STARTUP_BANNER = '🎲 FoundryVTT MCP Server starting...\n';
|
|
65
|
+
//# sourceMappingURL=mcp-server.js.map
|