@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,291 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview `foundryvtt-mcp status` and `foundryvtt-mcp stop`.
|
|
3
|
+
*
|
|
4
|
+
* Connect as a `control` peer: no version/config check (so a terminal with
|
|
5
|
+
* no FoundryVTT configuration can still inspect or stop the process), and
|
|
6
|
+
* not counted as a relay for the idle timeout. Must not import the config
|
|
7
|
+
* or the logger (`config/sources.ts` resolves settings without validating).
|
|
8
|
+
*/
|
|
9
|
+
import { displayValue, KNOWN_SETTINGS, resolveSettings, summarizeSources, } from '../config/sources.js';
|
|
10
|
+
import { describeBrowser } from '../foundry/browser-detect.js';
|
|
11
|
+
import { EndpointUnavailableError, IpcConnection } from './ipc-client.js';
|
|
12
|
+
import { isEndpointAlive } from './ipc-server.js';
|
|
13
|
+
import { resolveSharedPaths } from './paths.js';
|
|
14
|
+
import { DaemonStatusSchema, PROTOCOL_VERSION, StopReplySchema, } from './protocol.js';
|
|
15
|
+
import { readStateFile } from './state-file.js';
|
|
16
|
+
import { readExistingToken } from './token.js';
|
|
17
|
+
import { buildVersion } from './version.js';
|
|
18
|
+
/** Exit code when no shared process is running. */
|
|
19
|
+
const EXIT_NOT_RUNNING = 3;
|
|
20
|
+
async function connectControl(paths) {
|
|
21
|
+
const token = readExistingToken(paths.tokenFile);
|
|
22
|
+
if (!token) {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
return await IpcConnection.connect(paths.endpoint, {
|
|
27
|
+
type: 'hello',
|
|
28
|
+
protocol: PROTOCOL_VERSION,
|
|
29
|
+
role: 'control',
|
|
30
|
+
version: buildVersion(),
|
|
31
|
+
configHash: '',
|
|
32
|
+
token,
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
if (error instanceof EndpointUnavailableError) {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function formatUptime(seconds) {
|
|
43
|
+
const h = Math.floor(seconds / 3600);
|
|
44
|
+
const m = Math.floor((seconds % 3600) / 60);
|
|
45
|
+
const s = seconds % 60;
|
|
46
|
+
return h ? `${h}h ${m}m ${s}s` : m ? `${m}m ${s}s` : `${s}s`;
|
|
47
|
+
}
|
|
48
|
+
function yesNo(value) {
|
|
49
|
+
return value ? 'yes' : 'no';
|
|
50
|
+
}
|
|
51
|
+
function formatRelays(status) {
|
|
52
|
+
const outdated = status.outdatedRelays ?? [];
|
|
53
|
+
if (outdated.length === 0) {
|
|
54
|
+
return `${status.relays} connected`;
|
|
55
|
+
}
|
|
56
|
+
return (`${status.relays} connected (${outdated.length} on an older build: ` +
|
|
57
|
+
`${outdated.map((v) => `v${v}`).join(', ')} — restart that client)`);
|
|
58
|
+
}
|
|
59
|
+
/** The lines `foundryvtt-mcp status` prints for a running shared process. */
|
|
60
|
+
export function formatStatus(status) {
|
|
61
|
+
const { bridge, headlessGm } = status;
|
|
62
|
+
const lines = [
|
|
63
|
+
'Shared process: running',
|
|
64
|
+
` PID: ${status.pid}`,
|
|
65
|
+
` Version: ${status.version}`,
|
|
66
|
+
` Uptime: ${formatUptime(status.uptimeSeconds)} (since ${status.startedAt})`,
|
|
67
|
+
` Relays: ${formatRelays(status)}`,
|
|
68
|
+
` Calls running: ${status.inFlight}`,
|
|
69
|
+
];
|
|
70
|
+
if (status.writeQueue !== undefined) {
|
|
71
|
+
lines.push(` Write queue: ${status.writeQueue} pending`);
|
|
72
|
+
}
|
|
73
|
+
lines.push(` FoundryVTT: ${formatFoundryConnection(status)}`);
|
|
74
|
+
if (status.staleCache) {
|
|
75
|
+
lines.push(` World cache: ${formatStaleCache(status.staleCache)}`);
|
|
76
|
+
}
|
|
77
|
+
if (status.account) {
|
|
78
|
+
const role = status.account.role ? ` (${status.account.role})` : '';
|
|
79
|
+
lines.push(` Account: ${status.account.name}${role}`);
|
|
80
|
+
if (status.account.warning) {
|
|
81
|
+
lines.push(` Warning: ${status.account.warning}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (status.startupError) {
|
|
85
|
+
lines.push(` Startup error: ${status.startupError}`);
|
|
86
|
+
}
|
|
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');
|
|
90
|
+
const notStarted = status.foundryConnected
|
|
91
|
+
? 'not started yet'
|
|
92
|
+
: connecting
|
|
93
|
+
? 'not started yet (connecting to FoundryVTT)'
|
|
94
|
+
: 'not started (FoundryVTT connection failed)';
|
|
95
|
+
lines.push(` Module bridge: ${formatBridge(bridge, bridgeState, notStarted)}`);
|
|
96
|
+
if (bridgeState === 'listening' && bridge?.origin) {
|
|
97
|
+
lines.push(` Bridge origin: ${bridge.origin}`);
|
|
98
|
+
}
|
|
99
|
+
lines.push(` Headless GM: ${formatHeadlessGm(headlessGm, bridgeState, notStarted)}`);
|
|
100
|
+
if (headlessGm?.browser) {
|
|
101
|
+
lines.push(` Browser: ${describeBrowser(headlessGm.browser)}`);
|
|
102
|
+
}
|
|
103
|
+
lines.push(` Endpoint: ${status.endpoint}`, ` Log: ${status.logFile}`);
|
|
104
|
+
if (status.config) {
|
|
105
|
+
lines.push('', 'Configuration of the shared process:');
|
|
106
|
+
lines.push(...formatConfig(status.config.file, status.config.settings));
|
|
107
|
+
}
|
|
108
|
+
if (status.relayConfigs && status.relayConfigs.length > 0) {
|
|
109
|
+
lines.push('', 'Clients (settings each relay declared):');
|
|
110
|
+
for (const relay of status.relayConfigs) {
|
|
111
|
+
lines.push(...formatRelayConfig(relay));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return lines;
|
|
115
|
+
}
|
|
116
|
+
/** Configuration file line, then one line per setting that is not a default. */
|
|
117
|
+
export function formatConfig(file, settings) {
|
|
118
|
+
const lines = [` File: ${formatConfigFile(file)}`];
|
|
119
|
+
if (file.warning) {
|
|
120
|
+
lines.push(` Warning: ${file.warning}`);
|
|
121
|
+
}
|
|
122
|
+
if (settings.length === 0) {
|
|
123
|
+
lines.push(' Settings: none set (defaults only)');
|
|
124
|
+
}
|
|
125
|
+
const width = Math.max(0, ...settings.map((s) => s.name.length));
|
|
126
|
+
for (const setting of settings) {
|
|
127
|
+
lines.push(` ${setting.name.padEnd(width)} = ${setting.value} (${setting.source})`);
|
|
128
|
+
}
|
|
129
|
+
return lines;
|
|
130
|
+
}
|
|
131
|
+
function formatConfigFile(file) {
|
|
132
|
+
if (file.error) {
|
|
133
|
+
return `${file.path} (${file.error})`;
|
|
134
|
+
}
|
|
135
|
+
return `${file.path} (${file.found ? 'found' : 'not found'})`;
|
|
136
|
+
}
|
|
137
|
+
function formatRelayConfig(relay) {
|
|
138
|
+
const name = ` Relay ${relay.pid ?? '(pid unknown)'} (v${relay.version}): `;
|
|
139
|
+
const lines = [
|
|
140
|
+
name +
|
|
141
|
+
(relay.sources === null
|
|
142
|
+
? 'an older build that does not declare its settings'
|
|
143
|
+
: summarizeSources(relay.sources)),
|
|
144
|
+
];
|
|
145
|
+
if (relay.ignored === null) {
|
|
146
|
+
lines.push(' served with the shared process configuration; its own differs');
|
|
147
|
+
}
|
|
148
|
+
else if (relay.ignored.length > 0) {
|
|
149
|
+
lines.push(` served with the shared process configuration; ignored: ${relay.ignored
|
|
150
|
+
.map((s) => `${s.name} (from ${s.source})`)
|
|
151
|
+
.join(', ')}`);
|
|
152
|
+
}
|
|
153
|
+
return lines;
|
|
154
|
+
}
|
|
155
|
+
/** `status` section for the configuration this command resolves itself. */
|
|
156
|
+
export function formatTerminalConfig(settings = resolveSettings()) {
|
|
157
|
+
return [
|
|
158
|
+
'',
|
|
159
|
+
'This terminal (configuration resolved by this command):',
|
|
160
|
+
...formatConfig(settings.file, KNOWN_SETTINGS.filter((name) => settings.values[name] !== undefined).map((name) => ({
|
|
161
|
+
name,
|
|
162
|
+
value: displayValue(name, settings.values[name]),
|
|
163
|
+
source: settings.sources[name],
|
|
164
|
+
}))),
|
|
165
|
+
];
|
|
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
|
+
}
|
|
189
|
+
function formatFoundryConnection(status) {
|
|
190
|
+
if (status.foundryConnected) {
|
|
191
|
+
return 'connected';
|
|
192
|
+
}
|
|
193
|
+
if (isConnecting(status)) {
|
|
194
|
+
return 'connecting…';
|
|
195
|
+
}
|
|
196
|
+
const connection = status.foundryConnection;
|
|
197
|
+
if (!connection || connection.state === 'disconnected') {
|
|
198
|
+
return connection?.error ? `not connected — ${connection.error}` : 'not connected';
|
|
199
|
+
}
|
|
200
|
+
return `not connected (${connection.state}${connection.error ? ` — ${connection.error}` : ''})`;
|
|
201
|
+
}
|
|
202
|
+
function formatBridge(bridge, state, notStarted) {
|
|
203
|
+
if (state === 'not-started') {
|
|
204
|
+
return notStarted;
|
|
205
|
+
}
|
|
206
|
+
if (!bridge || state === 'disabled') {
|
|
207
|
+
return 'disabled';
|
|
208
|
+
}
|
|
209
|
+
if (state === 'failed') {
|
|
210
|
+
return `failed to start — ${bridge.error ?? 'see the log'}`;
|
|
211
|
+
}
|
|
212
|
+
return (`listening on port ${bridge.port}, protocol v${bridge.protocol}, authenticated module connected: ` +
|
|
213
|
+
yesNo(bridge.moduleConnected) +
|
|
214
|
+
(bridge.moduleConnectedSince ? ` (since ${bridge.moduleConnectedSince})` : ''));
|
|
215
|
+
}
|
|
216
|
+
function formatHeadlessGm(headlessGm, bridgeState, notStarted) {
|
|
217
|
+
if (headlessGm?.launchError) {
|
|
218
|
+
return `browser launch failed — ${headlessGm.launchError}`;
|
|
219
|
+
}
|
|
220
|
+
if (!headlessGm && bridgeState === 'not-started') {
|
|
221
|
+
// The core is not built yet (see isConnecting).
|
|
222
|
+
return notStarted;
|
|
223
|
+
}
|
|
224
|
+
const state = headlessGm?.state ?? 'disabled';
|
|
225
|
+
if (!headlessGm || state === 'disabled') {
|
|
226
|
+
return 'disabled';
|
|
227
|
+
}
|
|
228
|
+
if (state === 'not-started') {
|
|
229
|
+
return bridgeState === 'failed'
|
|
230
|
+
? 'not started (the module bridge failed to start)'
|
|
231
|
+
: notStarted;
|
|
232
|
+
}
|
|
233
|
+
const session = headlessGm.active ? 'logged in' : (headlessGm.sessionState ?? 'not logged in');
|
|
234
|
+
return `${session} — ${headlessGm.modeText ?? headlessGm.status ?? ''}`;
|
|
235
|
+
}
|
|
236
|
+
function printLines(lines) {
|
|
237
|
+
for (const line of lines) {
|
|
238
|
+
console.log(line);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
function printNotRunning(paths) {
|
|
242
|
+
console.log('Shared process: not running');
|
|
243
|
+
const stale = readStateFile(paths.stateFile);
|
|
244
|
+
if (stale) {
|
|
245
|
+
console.log(` Stale state file from pid ${stale.pid} (v${stale.version}): ${paths.stateFile}`);
|
|
246
|
+
}
|
|
247
|
+
console.log(` Endpoint: ${paths.endpoint}`);
|
|
248
|
+
console.log(` Log: ${paths.daemonLog}`);
|
|
249
|
+
}
|
|
250
|
+
export async function runStatus(paths = resolveSharedPaths()) {
|
|
251
|
+
const connection = await connectControl(paths);
|
|
252
|
+
if (!connection) {
|
|
253
|
+
printNotRunning(paths);
|
|
254
|
+
printLines(formatTerminalConfig());
|
|
255
|
+
return EXIT_NOT_RUNNING;
|
|
256
|
+
}
|
|
257
|
+
try {
|
|
258
|
+
const status = DaemonStatusSchema.parse(await connection.request('status'));
|
|
259
|
+
printLines([...formatStatus(status), ...formatTerminalConfig()]);
|
|
260
|
+
return 0;
|
|
261
|
+
}
|
|
262
|
+
finally {
|
|
263
|
+
connection.close();
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
export async function runStop(paths = resolveSharedPaths(), waitMs = 150_000) {
|
|
267
|
+
const connection = await connectControl(paths);
|
|
268
|
+
if (!connection) {
|
|
269
|
+
printNotRunning(paths);
|
|
270
|
+
return EXIT_NOT_RUNNING;
|
|
271
|
+
}
|
|
272
|
+
let pid;
|
|
273
|
+
try {
|
|
274
|
+
({ pid } = StopReplySchema.parse(await connection.request('stop')));
|
|
275
|
+
}
|
|
276
|
+
finally {
|
|
277
|
+
connection.close();
|
|
278
|
+
}
|
|
279
|
+
console.log(`Stopping shared process ${pid} (waiting for running calls to finish)…`);
|
|
280
|
+
const deadline = Date.now() + waitMs;
|
|
281
|
+
while (Date.now() < deadline) {
|
|
282
|
+
if (!(await isEndpointAlive(paths.endpoint))) {
|
|
283
|
+
console.log('Stopped.');
|
|
284
|
+
return 0;
|
|
285
|
+
}
|
|
286
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
287
|
+
}
|
|
288
|
+
console.log(`Still running after ${Math.round(waitMs / 1000)} s; see ${paths.daemonLog}`);
|
|
289
|
+
return 1;
|
|
290
|
+
}
|
|
291
|
+
//# sourceMappingURL=control.js.map
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview A relay's link to the shared process: connects (starting the
|
|
3
|
+
* process when nobody listens), waits while it boots or while an outdated
|
|
4
|
+
* one drains, and turns IPC failures into MCP errors.
|
|
5
|
+
*/
|
|
6
|
+
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
|
|
7
|
+
import { ConnectionLostError, EndpointUnavailableError, HandshakeRejectedError, IpcConnection, RemoteError, } from './ipc-client.js';
|
|
8
|
+
import { IpcErrorCode } from './protocol.js';
|
|
9
|
+
/** Calls rejected by a draining process never started, so they may be resent. */
|
|
10
|
+
const MAX_DRAINING_RETRIES = 3;
|
|
11
|
+
export class DaemonLink {
|
|
12
|
+
options;
|
|
13
|
+
connection = null;
|
|
14
|
+
connecting = null;
|
|
15
|
+
readyTimeoutMs;
|
|
16
|
+
drainTimeoutMs;
|
|
17
|
+
respawnIntervalMs;
|
|
18
|
+
connect;
|
|
19
|
+
sleep;
|
|
20
|
+
now;
|
|
21
|
+
constructor(options) {
|
|
22
|
+
this.options = options;
|
|
23
|
+
this.readyTimeoutMs = options.readyTimeoutMs ?? 30_000;
|
|
24
|
+
// The shared process waits up to 120 s for in-flight calls, then 5 s for teardown.
|
|
25
|
+
this.drainTimeoutMs = options.drainTimeoutMs ?? 150_000;
|
|
26
|
+
this.respawnIntervalMs = options.respawnIntervalMs ?? 5000;
|
|
27
|
+
this.connect = options.connect ?? ((endpoint, hello) => IpcConnection.connect(endpoint, hello));
|
|
28
|
+
this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
29
|
+
this.now = options.now ?? Date.now;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Forwards one operation and returns its result.
|
|
33
|
+
*
|
|
34
|
+
* @throws {McpError} the remote error, or a link failure explained for the user
|
|
35
|
+
*/
|
|
36
|
+
async call(op, name, args) {
|
|
37
|
+
for (let attempt = 0;; attempt++) {
|
|
38
|
+
const connection = await this.ensureConnected();
|
|
39
|
+
try {
|
|
40
|
+
return await connection.request(op, name, args);
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (error instanceof RemoteError) {
|
|
44
|
+
if (error.code === IpcErrorCode.Draining && attempt < MAX_DRAINING_RETRIES) {
|
|
45
|
+
this.drop(connection);
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
throw new McpError(error.code, error.message, error.data);
|
|
49
|
+
}
|
|
50
|
+
if (error instanceof ConnectionLostError) {
|
|
51
|
+
// Never resend: the call may have been half-way through a write.
|
|
52
|
+
this.drop(connection);
|
|
53
|
+
throw new McpError(ErrorCode.InternalError, `The shared FoundryVTT MCP process exited during this call; its outcome is unknown. It will be restarted on the next call. Log: ${this.options.logFile}`);
|
|
54
|
+
}
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** Returns a live connection, establishing one (single-flight) if needed. */
|
|
60
|
+
ensureConnected() {
|
|
61
|
+
if (this.connection && !this.connection.isClosed) {
|
|
62
|
+
return Promise.resolve(this.connection);
|
|
63
|
+
}
|
|
64
|
+
if (!this.connecting) {
|
|
65
|
+
this.connecting = this.establish().finally(() => {
|
|
66
|
+
this.connecting = null;
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
return this.connecting;
|
|
70
|
+
}
|
|
71
|
+
close() {
|
|
72
|
+
this.connection?.close();
|
|
73
|
+
this.connection = null;
|
|
74
|
+
}
|
|
75
|
+
drop(connection) {
|
|
76
|
+
connection.close();
|
|
77
|
+
if (this.connection === connection) {
|
|
78
|
+
this.connection = null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async establish() {
|
|
82
|
+
const started = this.now();
|
|
83
|
+
let deadline = started + this.readyTimeoutMs;
|
|
84
|
+
let drainWaitGranted = false;
|
|
85
|
+
let lastSpawn = Number.NEGATIVE_INFINITY;
|
|
86
|
+
let delay = 50;
|
|
87
|
+
for (;;) {
|
|
88
|
+
try {
|
|
89
|
+
const connection = await this.connect(this.options.endpoint, this.options.hello());
|
|
90
|
+
connection.onClose(() => {
|
|
91
|
+
if (this.connection === connection) {
|
|
92
|
+
this.connection = null;
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
this.connection = connection;
|
|
96
|
+
this.options.onConnected?.(connection);
|
|
97
|
+
return connection;
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
if (error instanceof EndpointUnavailableError) {
|
|
101
|
+
if (this.now() - lastSpawn >= this.respawnIntervalMs) {
|
|
102
|
+
this.options.log?.('No shared process is listening; starting one');
|
|
103
|
+
this.options.spawnDaemon();
|
|
104
|
+
lastSpawn = this.now();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
else if (error instanceof HandshakeRejectedError) {
|
|
108
|
+
if (error.reason === 'protocol') {
|
|
109
|
+
// The shared process says which side is outdated and what to do.
|
|
110
|
+
throw new McpError(ErrorCode.InternalError, `The shared FoundryVTT MCP process refused this relay: ${error.message} Log: ${this.options.logFile}`);
|
|
111
|
+
}
|
|
112
|
+
if (error.reason === 'unauthorized') {
|
|
113
|
+
throw new McpError(ErrorCode.InternalError, `The shared FoundryVTT MCP process refused this relay (${error.reason}: ${error.message}). Stop it (foundryvtt-mcp stop, or end the process listed in its state file) and retry. Log: ${this.options.logFile}`);
|
|
114
|
+
}
|
|
115
|
+
// Outdated or shutting down: wait for it to exit, then start a fresh one.
|
|
116
|
+
if (!drainWaitGranted) {
|
|
117
|
+
this.options.log?.(`Shared process is restarting (${error.reason}); waiting`);
|
|
118
|
+
deadline = Math.max(deadline, this.now() + this.drainTimeoutMs);
|
|
119
|
+
drainWaitGranted = true;
|
|
120
|
+
}
|
|
121
|
+
lastSpawn = Number.NEGATIVE_INFINITY;
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
this.options.log?.(`Connecting to the shared process failed: ${error instanceof Error ? error.message : error}`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (this.now() >= deadline) {
|
|
128
|
+
throw new McpError(ErrorCode.InternalError, `The shared FoundryVTT MCP process did not become available within ${Math.round((this.now() - started) / 1000)} s. Log: ${this.options.logFile}`);
|
|
129
|
+
}
|
|
130
|
+
await this.sleep(delay);
|
|
131
|
+
delay = Math.min(delay * 2, 500);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
//# sourceMappingURL=daemon-link.js.map
|