@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.
Files changed (100) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +457 -2
  3. package/dist/character/manager.js +208 -0
  4. package/dist/cli/checks.js +307 -0
  5. package/dist/cli/config-file.js +120 -0
  6. package/dist/cli/init.js +414 -0
  7. package/dist/cli/prompt.js +117 -0
  8. package/dist/cli/snippets.js +64 -0
  9. package/dist/combat/manager.js +371 -0
  10. package/dist/config/env-layers.js +49 -0
  11. package/dist/config/index.js +298 -0
  12. package/dist/config/sources.js +201 -0
  13. package/dist/core.js +481 -0
  14. package/dist/diagnostics/client.js +291 -0
  15. package/dist/diagnostics/types.js +94 -0
  16. package/dist/foundry/auth.js +224 -0
  17. package/dist/foundry/browser-detect.js +170 -0
  18. package/dist/foundry/client.js +5874 -0
  19. package/dist/foundry/dice-formula.js +154 -0
  20. package/dist/foundry/event-log.js +298 -0
  21. package/dist/foundry/headless-gm-session.js +857 -0
  22. package/dist/foundry/journal-conflicts.js +141 -0
  23. package/dist/foundry/journal-history.js +90 -0
  24. package/dist/foundry/journal-integrity.js +322 -0
  25. package/dist/foundry/message-author.js +19 -0
  26. package/dist/foundry/module-bridge.js +441 -0
  27. package/dist/foundry/types.js +52 -0
  28. package/dist/foundry/world-cache.js +386 -0
  29. package/dist/index.js +107 -0
  30. package/dist/mcp-server.js +65 -0
  31. package/dist/server.js +159 -0
  32. package/dist/shared/build-order.js +134 -0
  33. package/dist/shared/config-hash.js +62 -0
  34. package/dist/shared/config-notice.js +55 -0
  35. package/dist/shared/control.js +291 -0
  36. package/dist/shared/daemon-link.js +135 -0
  37. package/dist/shared/daemon.js +311 -0
  38. package/dist/shared/ipc-client.js +200 -0
  39. package/dist/shared/ipc-server.js +316 -0
  40. package/dist/shared/paths.js +79 -0
  41. package/dist/shared/protocol.js +230 -0
  42. package/dist/shared/relay-config.js +65 -0
  43. package/dist/shared/relay.js +120 -0
  44. package/dist/shared/rotating-log.js +57 -0
  45. package/dist/shared/spawn.js +39 -0
  46. package/dist/shared/state-file.js +33 -0
  47. package/dist/shared/token.js +62 -0
  48. package/dist/shared/version.js +57 -0
  49. package/dist/tools/base.js +74 -0
  50. package/dist/tools/definitions.js +3109 -0
  51. package/dist/tools/handlers/actor-mutations.js +128 -0
  52. package/dist/tools/handlers/actors.js +114 -0
  53. package/dist/tools/handlers/chat-mutations.js +49 -0
  54. package/dist/tools/handlers/chat.js +38 -0
  55. package/dist/tools/handlers/combat-mutations.js +215 -0
  56. package/dist/tools/handlers/combat-order.js +94 -0
  57. package/dist/tools/handlers/combat.js +51 -0
  58. package/dist/tools/handlers/compendium.js +83 -0
  59. package/dist/tools/handlers/diagnostics.js +450 -0
  60. package/dist/tools/handlers/dice.js +54 -0
  61. package/dist/tools/handlers/effects.js +103 -0
  62. package/dist/tools/handlers/events.js +50 -0
  63. package/dist/tools/handlers/generation.js +258 -0
  64. package/dist/tools/handlers/item-mutations.js +132 -0
  65. package/dist/tools/handlers/items.js +53 -0
  66. package/dist/tools/handlers/journal-mutations.js +230 -0
  67. package/dist/tools/handlers/journals.js +80 -0
  68. package/dist/tools/handlers/module-bridge.js +421 -0
  69. package/dist/tools/handlers/placeable-mutations.js +272 -0
  70. package/dist/tools/handlers/resources.js +203 -0
  71. package/dist/tools/handlers/roll-tables.js +97 -0
  72. package/dist/tools/handlers/scene-mutations.js +159 -0
  73. package/dist/tools/handlers/scenes.js +355 -0
  74. package/dist/tools/handlers/settings.js +53 -0
  75. package/dist/tools/handlers/tile-mutations.js +56 -0
  76. package/dist/tools/handlers/token-mutations.js +356 -0
  77. package/dist/tools/handlers/users.js +59 -0
  78. package/dist/tools/handlers/utils.js +48 -0
  79. package/dist/tools/handlers/wall-mutations.js +98 -0
  80. package/dist/tools/handlers/world-documents.js +222 -0
  81. package/dist/tools/handlers/world.js +92 -0
  82. package/dist/tools/index.js +25 -0
  83. package/dist/tools/new-router.js +97 -0
  84. package/dist/tools/registry.js +79 -0
  85. package/dist/tools/resources.js +63 -0
  86. package/dist/tools/router.js +688 -0
  87. package/dist/tools/tool-dependencies.js +194 -0
  88. package/dist/tools/write-tools.js +97 -0
  89. package/dist/utils/cache-instance.js +30 -0
  90. package/dist/utils/cache.js +205 -0
  91. package/dist/utils/diagnostics.js +332 -0
  92. package/dist/utils/guards.js +17 -0
  93. package/dist/utils/image-size.js +160 -0
  94. package/dist/utils/log-args.js +47 -0
  95. package/dist/utils/logger.js +203 -0
  96. package/dist/utils/mcp-errors.js +47 -0
  97. package/dist/utils/refusal.js +30 -0
  98. package/dist/utils/sanitize.js +22 -0
  99. package/dist/utils/serial-queue.js +22 -0
  100. package/package.json +124 -4
package/dist/server.js ADDED
@@ -0,0 +1,159 @@
1
+ /**
2
+ * @fileoverview All-in-one mode (`FOUNDRY_MCP_SHARED=false`): this stdio
3
+ * process owns its own FoundryVTT connection, module bridge and headless GM
4
+ * session, and exits when its MCP client closes stdin.
5
+ *
6
+ * Like the relay, it answers `initialize` and `tools/list` with no usable
7
+ * configuration; each tool call then says what is missing and re-reads it,
8
+ * and the first call that finds one starts the FoundryVTT connection.
9
+ */
10
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
11
+ import { ErrorCode, McpError, } from '@modelcontextprotocol/sdk/types.js';
12
+ import { resetConfig, tryGetConfig } from './config/index.js';
13
+ import { FoundryCore } from './core.js';
14
+ import { createMcpServer, STARTUP_BANNER } from './mcp-server.js';
15
+ import { logger } from './utils/logger.js';
16
+ /**
17
+ * Main FoundryVTT MCP Server class that handles all communication
18
+ * between AI models and FoundryVTT instances.
19
+ */
20
+ class FoundryMCPServer {
21
+ core = null;
22
+ booting = null;
23
+ server = createMcpServer({
24
+ callTool: async (name, args) => {
25
+ const core = await this.coreOrProblem();
26
+ if (typeof core === 'string') {
27
+ return { isError: true, content: [{ type: 'text', text: core }] };
28
+ }
29
+ return core.callTool(name, args);
30
+ },
31
+ readResource: async (uri) => {
32
+ const core = await this.coreOrProblem();
33
+ if (typeof core === 'string') {
34
+ throw new McpError(ErrorCode.InvalidRequest, core);
35
+ }
36
+ return core.readResource(uri);
37
+ },
38
+ });
39
+ /** The started core, or what keeps it from starting (the configuration is re-read). */
40
+ async coreOrProblem() {
41
+ if (this.core) {
42
+ return this.core;
43
+ }
44
+ if (!this.booting) {
45
+ resetConfig();
46
+ const loaded = tryGetConfig();
47
+ if ('error' in loaded) {
48
+ logger.warn(loaded.error.message);
49
+ return loaded.error.message;
50
+ }
51
+ this.booting = this.bootCore();
52
+ }
53
+ return this.booting;
54
+ }
55
+ async bootCore() {
56
+ const core = new FoundryCore();
57
+ try {
58
+ await core.start();
59
+ }
60
+ catch (error) {
61
+ // The next call builds a fresh core.
62
+ this.booting = null;
63
+ await core.shutdown();
64
+ throw error;
65
+ }
66
+ this.core = core;
67
+ return core;
68
+ }
69
+ /**
70
+ * Connects to FoundryVTT and starts the MCP server.
71
+ * @returns Promise that resolves when the server is running
72
+ */
73
+ async start() {
74
+ // Attach the stdio transport FIRST, before any network call. MCP
75
+ // clients spawn this process and write `initialize` on stdin right
76
+ // away; every millisecond spent connecting to FoundryVTT (a Socket.IO
77
+ // round-trip, ~0.4-1s observed) before wiring the transport is a
78
+ // millisecond the client's own handshake timeout burns with nothing
79
+ // reading stdin yet — omp's logs showed exactly this: "Transport
80
+ // closed" ~1s after spawn, matching the old connect-then-transport
81
+ // ordering. `tools/list` needs no FoundryVTT connection (getAllTools()
82
+ // is static); tool calls that do need it fail with FoundryClient's own
83
+ // "not connected" errors until the connection below resolves, rather
84
+ // than the whole process going unresponsive.
85
+ const transport = new StdioServerTransport();
86
+ await this.server.connect(transport);
87
+ logger.info('FoundryVTT MCP Server started successfully');
88
+ // With no usable configuration yet, stay up: tool calls explain it.
89
+ const core = await this.coreOrProblem();
90
+ if (typeof core === 'string') {
91
+ logger.warn('Waiting for a configuration; tool calls will say what is missing');
92
+ }
93
+ }
94
+ /**
95
+ * Gracefully shuts down the server and connections.
96
+ * @returns Promise that resolves when shutdown is complete
97
+ */
98
+ async shutdown() {
99
+ await this.core?.shutdown();
100
+ }
101
+ }
102
+ /** Maximum time graceful shutdown may take before the process is force-exited. */
103
+ const SHUTDOWN_GRACE_MS = 5000;
104
+ /**
105
+ * Creates and starts the all-in-one server.
106
+ */
107
+ export async function runAllInOne() {
108
+ const server = new FoundryMCPServer();
109
+ process.stderr.write(STARTUP_BANNER);
110
+ // Handle graceful shutdown. Several triggers can fire for the same exit
111
+ // (e.g. stdin closing, then SIGTERM), so shut down exactly once.
112
+ let shuttingDown = false;
113
+ const shutdownAndExit = async (reason) => {
114
+ if (shuttingDown) {
115
+ return;
116
+ }
117
+ shuttingDown = true;
118
+ logger.info(`${reason}, shutting down gracefully...`);
119
+ // Never let a hung cleanup step (e.g. the headless browser) keep the
120
+ // process alive: force the exit after a grace period, with a non-zero
121
+ // code so a hung shutdown is distinguishable from a clean one.
122
+ setTimeout(() => process.exit(1), SHUTDOWN_GRACE_MS).unref();
123
+ await server.shutdown();
124
+ process.exit(0);
125
+ };
126
+ process.on('SIGINT', () => {
127
+ void shutdownAndExit('Received SIGINT');
128
+ });
129
+ process.on('SIGTERM', () => {
130
+ void shutdownAndExit('Received SIGTERM');
131
+ });
132
+ // MCP stdio clients signal shutdown by closing the server's stdin. On
133
+ // Windows no SIGTERM follows when the client exits, so without this the
134
+ // process lingers (kept alive by the Socket.IO connection, the module
135
+ // bridge's WebSocket server and the headless browser), keeps the bridge
136
+ // port bound and leaves the next instance without a module bridge.
137
+ process.stdin.on('end', () => {
138
+ void shutdownAndExit('stdin closed by the MCP client');
139
+ });
140
+ process.stdin.on('close', () => {
141
+ void shutdownAndExit('stdin closed by the MCP client');
142
+ });
143
+ process.on('uncaughtException', (error) => {
144
+ logger.error('Uncaught exception:', error);
145
+ process.exit(1);
146
+ });
147
+ process.on('unhandledRejection', (reason, promise) => {
148
+ logger.error('Unhandled rejection at:', { promise, reason });
149
+ process.exit(1);
150
+ });
151
+ try {
152
+ await server.start();
153
+ }
154
+ catch (error) {
155
+ logger.error('Failed to start FoundryVTT MCP Server:', error);
156
+ process.exit(1);
157
+ }
158
+ }
159
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1,134 @@
1
+ /**
2
+ * @fileoverview Ordering connector builds: by package version, then by
3
+ * build stamp.
4
+ *
5
+ * A relay computes its version once, at startup, but starts the shared
6
+ * process from the files on disk — so after a rebuild an old relay can
7
+ * never find a shared process of its own version. If every mismatch
8
+ * restarted the shared process, that relay would restart it over and over.
9
+ * The shared process therefore restarts only for a strictly newer relay:
10
+ * each restart then yields a strictly newer process, which bounds them.
11
+ *
12
+ * The package version decides first: npm stamps each install with the time
13
+ * it was extracted, so a 2.0.0 extracted after a 2.1.0 (npx cache, a second
14
+ * prefix) carries the later stamp. The stamp only orders two builds of the
15
+ * same version, e.g. a clone rebuilt without a version bump.
16
+ */
17
+ /** The build stamp of a {@link buildVersion} string (`<version>+<base-36 mtime>`), or `null`. */
18
+ export function buildStamp(version) {
19
+ const stamp = /\+([0-9a-z]+)$/.exec(version)?.[1];
20
+ if (!stamp || stamp === 'unknown') {
21
+ return null;
22
+ }
23
+ const value = Number.parseInt(stamp, 36);
24
+ return Number.isSafeInteger(value) ? value : null;
25
+ }
26
+ const SEMVER = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+.*)?$/;
27
+ /** Semver precedence of the package versions of two builds (build stamps ignored), or `null`. */
28
+ function compareVersions(a, b) {
29
+ const ma = SEMVER.exec(a);
30
+ const mb = SEMVER.exec(b);
31
+ if (!ma || !mb) {
32
+ return null;
33
+ }
34
+ for (const i of [1, 2, 3]) {
35
+ const diff = Number(ma[i]) - Number(mb[i]);
36
+ if (diff !== 0) {
37
+ return Math.sign(diff);
38
+ }
39
+ }
40
+ const pa = ma[4];
41
+ const pb = mb[4];
42
+ // A release ranks above its pre-releases.
43
+ if (pa === undefined || pb === undefined) {
44
+ return pa === pb ? 0 : pa === undefined ? 1 : -1;
45
+ }
46
+ const ia = pa.split('.');
47
+ const ib = pb.split('.');
48
+ for (let i = 0; i < Math.min(ia.length, ib.length); i++) {
49
+ const x = ia[i];
50
+ const y = ib[i];
51
+ if (x === y) {
52
+ continue;
53
+ }
54
+ const nx = /^\d+$/.test(x);
55
+ const ny = /^\d+$/.test(y);
56
+ if (nx && ny) {
57
+ return Math.sign(Number(x) - Number(y));
58
+ }
59
+ // Numeric identifiers rank below alphanumeric ones.
60
+ if (nx !== ny) {
61
+ return nx ? -1 : 1;
62
+ }
63
+ return x < y ? -1 : 1;
64
+ }
65
+ return Math.sign(ia.length - ib.length);
66
+ }
67
+ /**
68
+ * How build `a` compares to build `b`: by package version (semver), then,
69
+ * for the same version, by build stamp. `unknown` when a version is not
70
+ * semver, or when two builds of the same version have no readable or
71
+ * distinct stamps: callers must then leave things as they are.
72
+ */
73
+ export function compareBuilds(a, b) {
74
+ if (a === b) {
75
+ return 'same';
76
+ }
77
+ const byVersion = compareVersions(a, b);
78
+ if (byVersion === null) {
79
+ return 'unknown';
80
+ }
81
+ if (byVersion !== 0) {
82
+ return byVersion > 0 ? 'newer' : 'older';
83
+ }
84
+ const stampA = buildStamp(a);
85
+ const stampB = buildStamp(b);
86
+ if (stampA === null || stampB === null || stampA === stampB) {
87
+ return 'unknown';
88
+ }
89
+ return stampA > stampB ? 'newer' : 'older';
90
+ }
91
+ /**
92
+ * Relay side of {@link outdatedRelayNotice}: armed by a connection to a
93
+ * shared process of another build, taken by the next tool result. A
94
+ * reconnection to a process of the same build does not arm it again.
95
+ */
96
+ export class OutdatedRelayNotice {
97
+ relayVersion;
98
+ pending = null;
99
+ notifiedFor = null;
100
+ constructor(relayVersion) {
101
+ this.relayVersion = relayVersion;
102
+ }
103
+ /** Records the build of a new connection; returns the notice when it arms one. */
104
+ connected(serverVersion) {
105
+ const notice = outdatedRelayNotice(this.relayVersion, serverVersion);
106
+ if (notice === null || serverVersion === this.notifiedFor) {
107
+ this.pending = null;
108
+ return null;
109
+ }
110
+ this.notifiedFor = serverVersion;
111
+ this.pending = notice;
112
+ return notice;
113
+ }
114
+ /** The notice for this tool result, at most once per arming. */
115
+ take() {
116
+ const notice = this.pending;
117
+ this.pending = null;
118
+ return notice;
119
+ }
120
+ }
121
+ /**
122
+ * Notice appended once to a relay's first tool result when the shared
123
+ * process runs another build: the relay keeps working, but its tool list
124
+ * is the one it loaded at startup.
125
+ */
126
+ export function outdatedRelayNotice(relayVersion, serverVersion) {
127
+ if (relayVersion === serverVersion) {
128
+ return null;
129
+ }
130
+ return (`ℹ️ This MCP client runs an older connector build (v${relayVersion}) than the shared ` +
131
+ `process (v${serverVersion}). It keeps working, but restart the client (fully quit ` +
132
+ 'Claude desktop, or restart Claude Code) to load the current tool list.');
133
+ }
134
+ //# sourceMappingURL=build-order.js.map
@@ -0,0 +1,62 @@
1
+ /**
2
+ * @fileoverview Fingerprint of the settings that define the FoundryVTT
3
+ * connection, compared at the relay handshake (see `mismatchDecision` in
4
+ * `daemon.ts`).
5
+ *
6
+ * Only {@link IDENTITY_SETTINGS} count: a relay whose LOG_LEVEL, timeouts or
7
+ * idle delay differ is served as it is, with the shared process's values.
8
+ * They are compared as validated values, so `true` and `TRUE`… compare as
9
+ * FoundryVTT MCP reads them, not as typed.
10
+ *
11
+ * The settings include the FoundryVTT password. A plain hash of it could be
12
+ * brute-forced offline if it ever leaked, so the fingerprint and the
13
+ * per-setting digests are HMACs keyed by the per-user IPC token. Even so
14
+ * they are never logged nor shown by `status`.
15
+ */
16
+ import { createHmac } from 'node:crypto';
17
+ /** The settings that define the connection, with how to read each from a configuration. */
18
+ export const IDENTITY_SETTINGS = {
19
+ FOUNDRY_URL: (c) => c.foundry.url,
20
+ FOUNDRY_USERNAME: (c) => c.foundry.username,
21
+ FOUNDRY_PASSWORD: (c) => c.foundry.password,
22
+ FOUNDRY_USER_ID: (c) => c.foundry.userId,
23
+ FOUNDRY_API_KEY: (c) => c.foundry.apiKey,
24
+ FOUNDRY_SOCKET_PATH: (c) => c.foundry.socketPath,
25
+ FOUNDRY_WRITE_ENABLED: (c) => c.foundry.writeEnabled,
26
+ FOUNDRY_MODULE_BRIDGE_ENABLED: (c) => c.moduleBridge.enabled,
27
+ FOUNDRY_MODULE_BRIDGE_PORT: (c) => c.moduleBridge.port,
28
+ FOUNDRY_HEADLESS_GM_ENABLED: (c) => c.headlessGm.enabled,
29
+ FOUNDRY_HEADLESS_GM_USERNAME: (c) => c.headlessGm.username,
30
+ FOUNDRY_HEADLESS_GM_PASSWORD: (c) => c.headlessGm.password,
31
+ FOUNDRY_HEADLESS_GM_EXECUTABLE_PATH: (c) => c.headlessGm.executablePath,
32
+ FOUNDRY_DATA_PATH: (c) => c.assets.dataPath,
33
+ };
34
+ function identityValues(config) {
35
+ return Object.keys(IDENTITY_SETTINGS)
36
+ .sort()
37
+ .map((name) => [name, IDENTITY_SETTINGS[name](config) ?? null]);
38
+ }
39
+ /** HMAC of the identity settings: equal when, and only when, they all are. */
40
+ export function configFingerprint(config, token) {
41
+ return createHmac('sha256', token)
42
+ .update(JSON.stringify(identityValues(config)))
43
+ .digest('hex');
44
+ }
45
+ /**
46
+ * One HMAC per identity setting, so the shared process can tell which
47
+ * settings of a relay differ from its own without receiving any value.
48
+ */
49
+ export function configDigests(config, token) {
50
+ const digests = {};
51
+ for (const [name, value] of identityValues(config)) {
52
+ digests[name] = createHmac('sha256', token)
53
+ .update(JSON.stringify([name, value]))
54
+ .digest('hex');
55
+ }
56
+ return digests;
57
+ }
58
+ /** Identity settings whose digests differ (all of them when `theirs` is unknown). */
59
+ export function differingSettings(ours, theirs) {
60
+ return Object.keys(IDENTITY_SETTINGS).filter((name) => theirs === undefined || ours[name] !== theirs[name]);
61
+ }
62
+ //# sourceMappingURL=config-hash.js.map
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @fileoverview Note appended to a relay's first tool result when the
3
+ * shared process serves it with the configuration it already runs, ignoring
4
+ * some of this relay's own settings ("the file is authoritative", see
5
+ * `mismatchDecision` in daemon.ts).
6
+ */
7
+ function origin(source) {
8
+ switch (source) {
9
+ case 'env':
10
+ return "this client's env block (or the system environment)";
11
+ case '.env':
12
+ return 'the .env file of its working directory';
13
+ case 'file':
14
+ return 'the configuration file';
15
+ case 'default':
16
+ return 'the default value';
17
+ }
18
+ }
19
+ /** The note text; `null` when nothing is ignored. */
20
+ export function ignoredConfigNotice(ignored) {
21
+ if (!ignored) {
22
+ return null;
23
+ }
24
+ const file = ignored.configFile ? ` (${ignored.configFile})` : '';
25
+ const which = ignored.settings.length > 0
26
+ ? ignored.settings.map((s) => `${s.name} from ${origin(s.source)}`).join('; ')
27
+ : 'some settings';
28
+ return (`ℹ️ This MCP client's own settings are ignored: the shared process serves every client with ` +
29
+ `the configuration it started with${file}, and this client's differ — ${which}. Remove them ` +
30
+ "from this client's env block, or put the same values in the configuration file and run " +
31
+ '`node dist/index.js stop`. `node dist/index.js status` lists the settings of each client.');
32
+ }
33
+ /** Arms the note once per distinct set of ignored settings; hands it out once. */
34
+ export class IgnoredConfigNotice {
35
+ pending = null;
36
+ armedFor = null;
37
+ connected(ignored) {
38
+ const notice = ignoredConfigNotice(ignored);
39
+ if (notice === null) {
40
+ this.armedFor = null;
41
+ this.pending = null;
42
+ return;
43
+ }
44
+ if (notice !== this.armedFor) {
45
+ this.armedFor = notice;
46
+ this.pending = notice;
47
+ }
48
+ }
49
+ take() {
50
+ const notice = this.pending;
51
+ this.pending = null;
52
+ return notice;
53
+ }
54
+ }
55
+ //# sourceMappingURL=config-notice.js.map