@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,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Default mode: a lightweight MCP stdio relay.
|
|
3
|
+
*
|
|
4
|
+
* Answers `initialize`, `tools/list` and `resources/list` itself, at once,
|
|
5
|
+
* and forwards `tools/call` / `resources/read` to the shared process,
|
|
6
|
+
* starting it when needed. MCP clients may start and stop relays freely;
|
|
7
|
+
* the FoundryVTT connection lives in the shared process.
|
|
8
|
+
*
|
|
9
|
+
* A relay starts and answers even with no usable configuration: each tool
|
|
10
|
+
* call then says what is missing, and re-reads the configuration, so writing
|
|
11
|
+
* the configuration file is enough — no client restart.
|
|
12
|
+
*/
|
|
13
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
14
|
+
import { CallToolResultSchema, ErrorCode, McpError, ReadResourceResultSchema, } from '@modelcontextprotocol/sdk/types.js';
|
|
15
|
+
import { createMcpServer, STARTUP_BANNER } from '../mcp-server.js';
|
|
16
|
+
import { logger } from '../utils/logger.js';
|
|
17
|
+
import { OutdatedRelayNotice } from './build-order.js';
|
|
18
|
+
import { IgnoredConfigNotice } from './config-notice.js';
|
|
19
|
+
import { DaemonLink } from './daemon-link.js';
|
|
20
|
+
import { resolveSharedPaths } from './paths.js';
|
|
21
|
+
import { PROTOCOL_VERSION } from './protocol.js';
|
|
22
|
+
import { RelayConfig } from './relay-config.js';
|
|
23
|
+
import { RotatingLog } from './rotating-log.js';
|
|
24
|
+
import { spawnDaemon } from './spawn.js';
|
|
25
|
+
import { loadOrCreateToken } from './token.js';
|
|
26
|
+
import { buildVersion } from './version.js';
|
|
27
|
+
export async function runRelay(entry) {
|
|
28
|
+
process.stderr.write(STARTUP_BANNER);
|
|
29
|
+
const paths = resolveSharedPaths();
|
|
30
|
+
// stderr stays the MCP client's log; relay.log keeps a history across clients.
|
|
31
|
+
const log = new RotatingLog(paths.relayLog);
|
|
32
|
+
logger.addSink((line) => log.write(line));
|
|
33
|
+
const version = buildVersion();
|
|
34
|
+
// A relay older than the shared process is served (see build-order.ts),
|
|
35
|
+
// with its startup tool list: its first tool result says so.
|
|
36
|
+
const notice = new OutdatedRelayNotice(version);
|
|
37
|
+
// Served with the shared process's settings instead of its own: said once too.
|
|
38
|
+
const configNotice = new IgnoredConfigNotice();
|
|
39
|
+
// Re-read before each handshake, and before each call while unusable.
|
|
40
|
+
const relayConfig = new RelayConfig((message) => logger.warn(`[relay ${process.pid}] ${message}`));
|
|
41
|
+
const link = new DaemonLink({
|
|
42
|
+
endpoint: paths.endpoint,
|
|
43
|
+
logFile: paths.daemonLog,
|
|
44
|
+
hello: () => {
|
|
45
|
+
const token = loadOrCreateToken(paths.tokenFile);
|
|
46
|
+
return {
|
|
47
|
+
type: 'hello',
|
|
48
|
+
protocol: PROTOCOL_VERSION,
|
|
49
|
+
role: 'relay',
|
|
50
|
+
version,
|
|
51
|
+
token,
|
|
52
|
+
pid: process.pid,
|
|
53
|
+
...relayConfig.helloFields(token),
|
|
54
|
+
};
|
|
55
|
+
},
|
|
56
|
+
spawnDaemon: () => spawnDaemon(entry),
|
|
57
|
+
onConnected: (connection) => {
|
|
58
|
+
if (notice.connected(connection.serverVersion)) {
|
|
59
|
+
logger.warn(`[relay ${process.pid}] this relay (v${version}) is older than the shared process (v${connection.serverVersion}); restart the MCP client to load the current tool list`);
|
|
60
|
+
}
|
|
61
|
+
configNotice.connected(connection.ignoredConfig);
|
|
62
|
+
},
|
|
63
|
+
log: (message) => logger.info(`[relay ${process.pid}] ${message}`),
|
|
64
|
+
});
|
|
65
|
+
const server = createMcpServer({
|
|
66
|
+
callTool: async (name, args) => {
|
|
67
|
+
const config = relayConfig.usable();
|
|
68
|
+
if (config instanceof Error) {
|
|
69
|
+
return { isError: true, content: [{ type: 'text', text: config.message }] };
|
|
70
|
+
}
|
|
71
|
+
const result = CallToolResultSchema.parse(await link.call('tool', name, args));
|
|
72
|
+
const texts = [notice.take(), configNotice.take()].filter((t) => t !== null);
|
|
73
|
+
// Some clients join text blocks without a separator: start on its own paragraph.
|
|
74
|
+
return texts.length > 0
|
|
75
|
+
? {
|
|
76
|
+
...result,
|
|
77
|
+
content: [
|
|
78
|
+
...result.content,
|
|
79
|
+
...texts.map((text) => ({ type: 'text', text: `\n\n${text}` })),
|
|
80
|
+
],
|
|
81
|
+
}
|
|
82
|
+
: result;
|
|
83
|
+
},
|
|
84
|
+
readResource: async (uri) => {
|
|
85
|
+
const config = relayConfig.usable();
|
|
86
|
+
if (config instanceof Error) {
|
|
87
|
+
throw new McpError(ErrorCode.InvalidRequest, config.message);
|
|
88
|
+
}
|
|
89
|
+
return ReadResourceResultSchema.parse(await link.call('resource', uri));
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
const exit = (reason) => {
|
|
93
|
+
logger.info(`[relay ${process.pid}] ${reason}; exiting`);
|
|
94
|
+
link.close();
|
|
95
|
+
process.exit(0);
|
|
96
|
+
};
|
|
97
|
+
process.stdin.on('end', () => exit('stdin closed by the MCP client'));
|
|
98
|
+
process.stdin.on('close', () => exit('stdin closed by the MCP client'));
|
|
99
|
+
process.on('SIGINT', () => exit('received SIGINT'));
|
|
100
|
+
process.on('SIGTERM', () => exit('received SIGTERM'));
|
|
101
|
+
process.on('uncaughtException', (error) => {
|
|
102
|
+
logger.error('Uncaught exception in relay:', error);
|
|
103
|
+
process.exit(1);
|
|
104
|
+
});
|
|
105
|
+
process.on('unhandledRejection', (reason) => {
|
|
106
|
+
logger.error('Unhandled rejection in relay:', { reason: String(reason) });
|
|
107
|
+
process.exit(1);
|
|
108
|
+
});
|
|
109
|
+
await server.connect(new StdioServerTransport());
|
|
110
|
+
logger.info(`[relay ${process.pid}] FoundryVTT MCP relay started (v${version})`);
|
|
111
|
+
// Warm up in the background: when the client starts, the shared process
|
|
112
|
+
// (FoundryVTT connection, module bridge, headless GM session) should be
|
|
113
|
+
// up before the first tool call. Failures are retried by that call. With
|
|
114
|
+
// no usable configuration there is nothing to start: calls will say so.
|
|
115
|
+
if (relayConfig.usable() instanceof Error) {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
link.ensureConnected().then((connection) => logger.info(`[relay ${process.pid}] connected to shared process ${connection.serverPid}`), (error) => logger.warn(`[relay ${process.pid}] shared process not available yet: ${error instanceof Error ? error.message : error}`));
|
|
119
|
+
}
|
|
120
|
+
//# sourceMappingURL=relay.js.map
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Append-only log file rotated by size: `x.log` → `x.log.1` →
|
|
3
|
+
* … → `x.log.<keep>`, the oldest being dropped.
|
|
4
|
+
*
|
|
5
|
+
* Several processes may write the same file (every relay appends to
|
|
6
|
+
* `relay.log`), so the size is read from disk on each write and every file
|
|
7
|
+
* operation tolerates losing a race. Logging never throws.
|
|
8
|
+
*/
|
|
9
|
+
import { appendFileSync, renameSync, rmSync, statSync } from 'node:fs';
|
|
10
|
+
export class RotatingLog {
|
|
11
|
+
file;
|
|
12
|
+
maxBytes;
|
|
13
|
+
keep;
|
|
14
|
+
constructor(file, maxBytes = 5 * 1024 * 1024, keep = 3) {
|
|
15
|
+
this.file = file;
|
|
16
|
+
this.maxBytes = maxBytes;
|
|
17
|
+
this.keep = keep;
|
|
18
|
+
}
|
|
19
|
+
write(line) {
|
|
20
|
+
const text = line.endsWith('\n') ? line : `${line}\n`;
|
|
21
|
+
try {
|
|
22
|
+
if (this.size() + Buffer.byteLength(text) > this.maxBytes) {
|
|
23
|
+
this.rotate();
|
|
24
|
+
}
|
|
25
|
+
appendFileSync(this.file, text);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
// A full disk or a locked file must not take the process down.
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
size() {
|
|
32
|
+
try {
|
|
33
|
+
return statSync(this.file).size;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return 0;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
rotate() {
|
|
40
|
+
rmSync(`${this.file}.${this.keep}`, { force: true });
|
|
41
|
+
for (let i = this.keep - 1; i >= 1; i--) {
|
|
42
|
+
try {
|
|
43
|
+
renameSync(`${this.file}.${i}`, `${this.file}.${i + 1}`);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
// missing generation, or another process rotated first
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
renameSync(this.file, `${this.file}.1`);
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
// another process rotated first
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=rotating-log.js.map
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Starting the shared process so it outlives the relay.
|
|
3
|
+
*
|
|
4
|
+
* The relay starts `daemon-launch`, which starts `daemon` and exits at once.
|
|
5
|
+
* A direct detached child keeps the relay as its parent pid, so a tree kill
|
|
6
|
+
* of the relay (`taskkill /T`) takes it down too; through the short-lived
|
|
7
|
+
* launcher the shared process is orphaned and out of reach of a tree kill.
|
|
8
|
+
* Detached children also leave the MCP client's kill-on-close Job Object
|
|
9
|
+
* (verified with Claude desktop on Windows by the Phase 0 spike, commit 7647d5f).
|
|
10
|
+
*/
|
|
11
|
+
import { spawn } from 'node:child_process';
|
|
12
|
+
/**
|
|
13
|
+
* Re-runs this program detached with `role` as its first argument: same
|
|
14
|
+
* Node binary and flags (so `tsx` keeps working), same entry script, same
|
|
15
|
+
* environment and working directory (so configuration resolves the same way).
|
|
16
|
+
*/
|
|
17
|
+
export function spawnDetachedRole(entry, role) {
|
|
18
|
+
const child = spawn(process.execPath, [...process.execArgv, entry, role], {
|
|
19
|
+
detached: true,
|
|
20
|
+
stdio: 'ignore',
|
|
21
|
+
windowsHide: true,
|
|
22
|
+
env: process.env,
|
|
23
|
+
cwd: process.cwd(),
|
|
24
|
+
});
|
|
25
|
+
child.on('error', () => {
|
|
26
|
+
// Reported by the relay as "did not become available" with the log path.
|
|
27
|
+
});
|
|
28
|
+
child.unref();
|
|
29
|
+
}
|
|
30
|
+
/** Relay side: start the shared process through the launcher. */
|
|
31
|
+
export function spawnDaemon(entry) {
|
|
32
|
+
spawnDetachedRole(entry, 'daemon-launch');
|
|
33
|
+
}
|
|
34
|
+
/** `daemon-launch`: start the shared process and exit immediately. */
|
|
35
|
+
export function runDaemonLauncher(entry) {
|
|
36
|
+
spawnDetachedRole(entry, 'daemon');
|
|
37
|
+
process.exit(0);
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=spawn.js.map
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview The state file the shared process writes once it holds the
|
|
3
|
+
* endpoint: `{ pid, version, startedAt, endpoint, logFile }`.
|
|
4
|
+
*/
|
|
5
|
+
import { readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
export const DaemonStateSchema = z.object({
|
|
8
|
+
pid: z.number().int(),
|
|
9
|
+
version: z.string(),
|
|
10
|
+
startedAt: z.string(),
|
|
11
|
+
endpoint: z.string(),
|
|
12
|
+
logFile: z.string(),
|
|
13
|
+
});
|
|
14
|
+
export function writeStateFile(file, state) {
|
|
15
|
+
writeFileSync(file, `${JSON.stringify(state, null, 2)}\n`);
|
|
16
|
+
}
|
|
17
|
+
/** The state left by a running (or crashed) shared process, or `null`. */
|
|
18
|
+
export function readStateFile(file) {
|
|
19
|
+
try {
|
|
20
|
+
const parsed = DaemonStateSchema.safeParse(JSON.parse(readFileSync(file, 'utf8')));
|
|
21
|
+
return parsed.success ? parsed.data : null;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** Removes the state file if it still describes process `pid`. */
|
|
28
|
+
export function removeStateFile(file, pid) {
|
|
29
|
+
if (readStateFile(file)?.pid === pid) {
|
|
30
|
+
rmSync(file, { force: true });
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
//# sourceMappingURL=state-file.js.map
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview The shared secret relays present to the shared process.
|
|
3
|
+
*
|
|
4
|
+
* The IPC endpoint is reachable by any local process of the same user (and,
|
|
5
|
+
* for a misconfigured pipe ACL, possibly others); the token keeps a stray
|
|
6
|
+
* client from driving FoundryVTT through it. Owner-only file mode on POSIX;
|
|
7
|
+
* on Windows the file inherits the per-user ACL of `%LOCALAPPDATA%`.
|
|
8
|
+
*/
|
|
9
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
10
|
+
import { linkSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
11
|
+
const TOKEN_PATTERN = /^[0-9a-f]{64}$/;
|
|
12
|
+
/** Reads the token, or `null` when none has been created yet (or it is malformed). */
|
|
13
|
+
export function readExistingToken(file) {
|
|
14
|
+
try {
|
|
15
|
+
const token = readFileSync(file, 'utf8').trim();
|
|
16
|
+
return TOKEN_PATTERN.test(token) ? token : null;
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Returns the token, creating it on first use. The token is written to a
|
|
24
|
+
* private temp file and hard-linked into place: the link either appears
|
|
25
|
+
* complete or fails with EEXIST, so concurrent relays/daemons never read a
|
|
26
|
+
* half-written file and all agree on a single value.
|
|
27
|
+
*/
|
|
28
|
+
export function loadOrCreateToken(file) {
|
|
29
|
+
const existing = readExistingToken(file);
|
|
30
|
+
if (existing) {
|
|
31
|
+
return existing;
|
|
32
|
+
}
|
|
33
|
+
const token = randomBytes(32).toString('hex');
|
|
34
|
+
const temp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
35
|
+
writeFileSync(temp, token, { encoding: 'utf8', mode: 0o600 });
|
|
36
|
+
try {
|
|
37
|
+
linkSync(temp, file);
|
|
38
|
+
return token;
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
if (error.code !== 'EEXIST') {
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
const raced = readExistingToken(file);
|
|
45
|
+
if (raced) {
|
|
46
|
+
return raced;
|
|
47
|
+
}
|
|
48
|
+
// A malformed file left by hand: replace it.
|
|
49
|
+
renameSync(temp, file);
|
|
50
|
+
return token;
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
rmSync(temp, { force: true });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/** Constant-time token comparison. */
|
|
57
|
+
export function tokensMatch(expected, provided) {
|
|
58
|
+
const a = Buffer.from(expected, 'utf8');
|
|
59
|
+
const b = Buffer.from(provided, 'utf8');
|
|
60
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=token.js.map
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview The package name and version, read from `package.json` at runtime.
|
|
3
|
+
*
|
|
4
|
+
* `src/shared/` and `dist/shared/` sit at the same depth, so the same
|
|
5
|
+
* relative path works from sources (tests, tsx) and from the build.
|
|
6
|
+
*/
|
|
7
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
let cachedPackage = null;
|
|
10
|
+
function readPackage() {
|
|
11
|
+
if (cachedPackage === null) {
|
|
12
|
+
let raw = null;
|
|
13
|
+
try {
|
|
14
|
+
raw = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
// the defaults below
|
|
18
|
+
}
|
|
19
|
+
const pkg = raw;
|
|
20
|
+
const isObject = typeof pkg === 'object' && pkg !== null;
|
|
21
|
+
const name = isObject && 'name' in pkg ? pkg.name : undefined;
|
|
22
|
+
const version = isObject && 'version' in pkg ? pkg.version : undefined;
|
|
23
|
+
cachedPackage = {
|
|
24
|
+
name: typeof name === 'string' ? name : 'foundryvtt-mcp',
|
|
25
|
+
version: typeof version === 'string' ? version : '0.0.0-unknown',
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
return cachedPackage;
|
|
29
|
+
}
|
|
30
|
+
export function packageVersion() {
|
|
31
|
+
return readPackage().version;
|
|
32
|
+
}
|
|
33
|
+
/** The npm package name, e.g. for `npm install -g <name>`. */
|
|
34
|
+
export function packageName() {
|
|
35
|
+
return readPackage().name;
|
|
36
|
+
}
|
|
37
|
+
let cachedBuild = null;
|
|
38
|
+
/**
|
|
39
|
+
* The package version plus a build stamp (this compiled file's mtime, which
|
|
40
|
+
* every `npm run build` rewrites). Compared at the relay handshake, so a
|
|
41
|
+
* rebuild without a version bump still replaces a shared process running
|
|
42
|
+
* the previous code.
|
|
43
|
+
*/
|
|
44
|
+
export function buildVersion() {
|
|
45
|
+
if (cachedBuild === null) {
|
|
46
|
+
let stamp = 'unknown';
|
|
47
|
+
try {
|
|
48
|
+
stamp = Math.trunc(statSync(fileURLToPath(import.meta.url)).mtimeMs).toString(36);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
// keep "unknown": relays and shared process then compare package versions only
|
|
52
|
+
}
|
|
53
|
+
cachedBuild = `${packageVersion()}+${stamp}`;
|
|
54
|
+
}
|
|
55
|
+
return cachedBuild;
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=version.js.map
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Base tool interface and implementation
|
|
3
|
+
*
|
|
4
|
+
* This module provides the foundation for the tool system with automatic
|
|
5
|
+
* schema validation and consistent interface design.
|
|
6
|
+
*/
|
|
7
|
+
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
|
|
8
|
+
import Ajv from 'ajv';
|
|
9
|
+
import { redactToolArgs } from '../utils/log-args.js';
|
|
10
|
+
import { logger } from '../utils/logger.js';
|
|
11
|
+
/**
|
|
12
|
+
* Base tool class with automatic validation
|
|
13
|
+
*/
|
|
14
|
+
export class BaseTool {
|
|
15
|
+
static ajv = new Ajv({
|
|
16
|
+
allErrors: true,
|
|
17
|
+
verbose: true,
|
|
18
|
+
strict: true,
|
|
19
|
+
});
|
|
20
|
+
/**
|
|
21
|
+
* Execute the tool with automatic validation
|
|
22
|
+
*/
|
|
23
|
+
async execute(args, context) {
|
|
24
|
+
logger.debug(`Executing tool: ${this.name}`, { args: redactToolArgs(args) });
|
|
25
|
+
// Validate input arguments against schema
|
|
26
|
+
this.validateArgs(args);
|
|
27
|
+
try {
|
|
28
|
+
return await this.executeValidated(args, context);
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
logger.error(`Tool execution failed: ${this.name}`, error);
|
|
32
|
+
if (error instanceof McpError) {
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
throw new McpError(ErrorCode.InternalError, `Tool execution failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Validate arguments against the tool's schema
|
|
40
|
+
*/
|
|
41
|
+
validateArgs(args) {
|
|
42
|
+
const validate = BaseTool.ajv.compile(this.inputSchema);
|
|
43
|
+
const valid = validate(args);
|
|
44
|
+
if (!valid) {
|
|
45
|
+
const errors = validate.errors
|
|
46
|
+
?.map((err) => {
|
|
47
|
+
const instancePath = err.instancePath || 'root';
|
|
48
|
+
return `${instancePath}: ${err.message}`;
|
|
49
|
+
})
|
|
50
|
+
.join(', ') || 'Unknown validation error';
|
|
51
|
+
throw new McpError(ErrorCode.InvalidParams, `Invalid parameters for tool '${this.name}': ${errors}`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Helper method to create a text response
|
|
56
|
+
*/
|
|
57
|
+
createTextResponse(text) {
|
|
58
|
+
return {
|
|
59
|
+
content: [
|
|
60
|
+
{
|
|
61
|
+
type: 'text',
|
|
62
|
+
text,
|
|
63
|
+
},
|
|
64
|
+
],
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Helper method to create an error response
|
|
69
|
+
*/
|
|
70
|
+
createErrorResponse(error) {
|
|
71
|
+
return this.createTextResponse(`❌ **Error**: ${error.message}`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
//# sourceMappingURL=base.js.map
|