@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
@@ -0,0 +1,203 @@
1
+ /**
2
+ * @fileoverview Centralized logging utility for FoundryVTT MCP Server
3
+ *
4
+ * This module provides a structured logging system with configurable log levels
5
+ * and consistent formatting across the application. It respects the LOG_LEVEL
6
+ * environment variable for controlling verbosity.
7
+ *
8
+ * @version 0.1.0
9
+ * @author FoundryVTT MCP Team
10
+ */
11
+ import { config } from '../config/index.js';
12
+ /**
13
+ * Centralized logger class for structured application logging
14
+ *
15
+ * Provides methods for different log levels and automatically filters
16
+ * messages based on the configured minimum log level.
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * import { logger } from './utils/logger.js';
21
+ *
22
+ * logger.info('Server starting...');
23
+ * logger.error('Connection failed:', error);
24
+ * logger.debug('Detailed debug info', { data: someObject });
25
+ * ```
26
+ */
27
+ export class Logger {
28
+ logLevel;
29
+ sinks = [];
30
+ levels = {
31
+ debug: 0,
32
+ info: 1,
33
+ warn: 2,
34
+ error: 3,
35
+ };
36
+ /**
37
+ * Creates a new Logger instance
38
+ *
39
+ * @param logLevel - Minimum log level to display (default: 'info'), or a
40
+ * function resolving it on first use; while it returns `null` (no usable
41
+ * configuration yet) messages are filtered at `info` and it is asked again
42
+ */
43
+ constructor(logLevel = 'info') {
44
+ this.logLevel = logLevel;
45
+ }
46
+ /** Overrides the configured level (`init` keeps its terminal output to its own messages). */
47
+ setLevel(level) {
48
+ this.logLevel = level;
49
+ }
50
+ /**
51
+ * Also writes every emitted line to `sink` (e.g. a log file). The shared
52
+ * process runs detached with no stderr, so its sink is the only output.
53
+ */
54
+ addSink(sink) {
55
+ this.sinks.push(sink);
56
+ }
57
+ emit(write, line) {
58
+ write(line);
59
+ for (const sink of this.sinks) {
60
+ sink(line);
61
+ }
62
+ }
63
+ level() {
64
+ if (typeof this.logLevel === 'function') {
65
+ const resolved = this.logLevel();
66
+ if (resolved === null) {
67
+ return 'info';
68
+ }
69
+ this.logLevel = resolved;
70
+ }
71
+ return this.logLevel;
72
+ }
73
+ /**
74
+ * Determines if a message should be logged based on current log level
75
+ *
76
+ * @private
77
+ * @param level - The log level to check
78
+ * @returns True if the message should be logged, false otherwise
79
+ */
80
+ shouldLog(level) {
81
+ return this.levels[level] >= this.levels[this.level()];
82
+ }
83
+ /**
84
+ * Formats a log message with timestamp, level, and optional metadata
85
+ *
86
+ * @private
87
+ * @param level - The log level
88
+ * @param message - The main log message
89
+ * @param meta - Optional metadata object
90
+ * @returns Formatted log message string
91
+ */
92
+ formatMessage(level, message, meta) {
93
+ const timestamp = new Date().toISOString();
94
+ const metaStr = meta ? ` ${JSON.stringify(meta)}` : '';
95
+ return `[${timestamp}] ${level.toUpperCase()}: ${message}${metaStr}`;
96
+ }
97
+ /**
98
+ * Logs a debug message (lowest priority)
99
+ *
100
+ * Used for detailed information that's only needed when debugging issues.
101
+ * Only shown when LOG_LEVEL is set to 'debug'.
102
+ *
103
+ * Note: In an MCP stdio server, all log output MUST be written to stderr
104
+ * (via console.error) so that stdout remains clean for JSON-RPC messages.
105
+ *
106
+ * @param message - The debug message
107
+ * @param meta - Optional metadata object
108
+ * @example
109
+ * ```typescript
110
+ * logger.debug('Processing user request', { userId: '123', action: 'search' });
111
+ * ```
112
+ */
113
+ debug(message, meta) {
114
+ if (this.shouldLog('debug')) {
115
+ this.emit(console.error, this.formatMessage('debug', message, meta));
116
+ }
117
+ }
118
+ /**
119
+ * Logs an informational message
120
+ *
121
+ * Used for general information about application flow and important events.
122
+ * Shown when LOG_LEVEL is 'debug' or 'info'.
123
+ *
124
+ * Note: In an MCP stdio server, all log output MUST be written to stderr
125
+ * (via console.error) so that stdout remains clean for JSON-RPC messages.
126
+ *
127
+ * @param message - The info message
128
+ * @param meta - Optional metadata object
129
+ * @example
130
+ * ```typescript
131
+ * logger.info('Server started successfully', { port: 3000 });
132
+ * ```
133
+ */
134
+ info(message, meta) {
135
+ if (this.shouldLog('info')) {
136
+ this.emit(console.error, this.formatMessage('info', message, meta));
137
+ }
138
+ }
139
+ /**
140
+ * Logs a warning message
141
+ *
142
+ * Used for potentially problematic situations that don't prevent operation
143
+ * but should be noted. Shown when LOG_LEVEL is 'debug', 'info', or 'warn'.
144
+ *
145
+ * @param message - The warning message
146
+ * @param meta - Optional metadata object
147
+ * @example
148
+ * ```typescript
149
+ * logger.warn('Deprecated API endpoint used', { endpoint: '/old-api' });
150
+ * ```
151
+ */
152
+ warn(message, meta) {
153
+ if (this.shouldLog('warn')) {
154
+ this.emit(console.warn, this.formatMessage('warn', message, meta));
155
+ }
156
+ }
157
+ /**
158
+ * Logs an error message (highest priority)
159
+ *
160
+ * Used for error conditions and exceptions that affect application operation.
161
+ * Always shown regardless of LOG_LEVEL setting.
162
+ *
163
+ * @param message - The error message
164
+ * @param error - Optional error object or metadata
165
+ * @example
166
+ * ```typescript
167
+ * logger.error('Database connection failed', error);
168
+ * logger.error('Invalid user input', { input: userData, validation: errors });
169
+ * ```
170
+ */
171
+ error(message, error) {
172
+ if (this.shouldLog('error')) {
173
+ const errorDetails = error instanceof Error ? { message: error.message, stack: error.stack } : error;
174
+ this.emit(console.error, this.formatMessage('error', message, errorDetails));
175
+ }
176
+ }
177
+ }
178
+ /**
179
+ * Global logger instance
180
+ *
181
+ * Pre-configured logger instance ready for use throughout the application.
182
+ * Respects the LOG_LEVEL environment variable for filtering messages.
183
+ *
184
+ * @example
185
+ * ```typescript
186
+ * import { logger } from './utils/logger.js';
187
+ *
188
+ * logger.info('Application starting');
189
+ * logger.error('Something went wrong', error);
190
+ * ```
191
+ */
192
+ // The level is resolved on first use, not at import: importing the logger must
193
+ // not validate the whole configuration (`status`/`stop` run without one), and
194
+ // logging must never fail or exit while there is none (`info` meanwhile).
195
+ export const logger = new Logger(() => {
196
+ try {
197
+ return config.logLevel;
198
+ }
199
+ catch {
200
+ return null;
201
+ }
202
+ });
203
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @fileoverview MCP errors on their way to a client.
3
+ *
4
+ * `McpError` puts "MCP error <code>: " in front of its message, and the
5
+ * SDK's `Protocol` sends `error.message` as it is in the JSON-RPC error; the
6
+ * client's SDK then builds its own `McpError`, which adds the prefix a second
7
+ * time (G33ks/foundryvtt-mcp#15). The message
8
+ * on the wire must therefore be the bare text.
9
+ */
10
+ import { McpError } from '@modelcontextprotocol/sdk/types.js';
11
+ /** McpError prefixes its message with "MCP error <code>: "; this is the text without it. */
12
+ export function bareMessage(error) {
13
+ return error.message.replace(/^MCP error -?\d+: /, '');
14
+ }
15
+ /**
16
+ * An error as the SDK sends it: `Protocol` reads `code` (a safe integer),
17
+ * `message` and `data` from whatever a handler throws (SDK 1.32.2,
18
+ * dist/esm/shared/protocol.js:426-428), so a plain `Error` with those
19
+ * fields reaches the client unchanged.
20
+ */
21
+ export class WireError extends Error {
22
+ code;
23
+ data;
24
+ name = 'WireError';
25
+ constructor(code, message, data) {
26
+ super(message);
27
+ this.code = code;
28
+ this.data = data;
29
+ }
30
+ }
31
+ /**
32
+ * Runs a request handler; an `McpError` it throws leaves with its bare
33
+ * message, its code and its data, so the client shows one prefix. Any other
34
+ * error is left to the SDK.
35
+ */
36
+ export async function withBareErrors(handler) {
37
+ try {
38
+ return await handler();
39
+ }
40
+ catch (error) {
41
+ if (error instanceof McpError) {
42
+ throw new WireError(error.code, bareMessage(error), error.data);
43
+ }
44
+ throw error;
45
+ }
46
+ }
47
+ //# sourceMappingURL=mcp-errors.js.map
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @fileoverview Expected refusals: a tool call turned down by design (a
3
+ * missing or outdated journal page version, …), as opposed to a failure.
4
+ *
5
+ * The caller still gets an error, but the log gets one warn line without a
6
+ * stack instead of the error lines a failure produces.
7
+ */
8
+ import { McpError } from '@modelcontextprotocol/sdk/types.js';
9
+ /** Thrown below the handlers (e.g. by `FoundryClient`) for an expected refusal. */
10
+ export class RefusedError extends Error {
11
+ name = 'RefusedError';
12
+ }
13
+ /** `McpError.data` marking an expected refusal. */
14
+ const REFUSAL_DATA = { refusal: true };
15
+ /** An `McpError` for an expected refusal. */
16
+ export function refusalError(code, message) {
17
+ return new McpError(code, message, REFUSAL_DATA);
18
+ }
19
+ /** True for a {@link RefusedError} or an `McpError` built by {@link refusalError}. */
20
+ export function isRefusal(error) {
21
+ if (error instanceof RefusedError) {
22
+ return true;
23
+ }
24
+ if (!(error instanceof McpError)) {
25
+ return false;
26
+ }
27
+ const data = error.data;
28
+ return typeof data === 'object' && data !== null && 'refusal' in data && data.refusal === true;
29
+ }
30
+ //# sourceMappingURL=refusal.js.map
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @fileoverview Sanitization utilities for safe string processing.
3
+ */
4
+ /**
5
+ * Strips HTML tags from a string iteratively to prevent incomplete multi-character sanitization bypasses.
6
+ *
7
+ * @param input - The raw input string containing potential HTML tags
8
+ * @returns Clean plain text with all HTML tags stripped
9
+ */
10
+ export function stripHtml(input) {
11
+ if (!input) {
12
+ return '';
13
+ }
14
+ let prev = '';
15
+ let curr = input;
16
+ while (curr !== prev) {
17
+ prev = curr;
18
+ curr = curr.replace(/<[^<>]*>/g, '');
19
+ }
20
+ return curr;
21
+ }
22
+ //# sourceMappingURL=sanitize.js.map
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @fileoverview Runs async tasks one at a time, in submission order.
3
+ */
4
+ export class SerialQueue {
5
+ tail = Promise.resolve();
6
+ pendingCount = 0;
7
+ /** Tasks submitted and not yet settled, the running one included. */
8
+ get pending() {
9
+ return this.pendingCount;
10
+ }
11
+ /** Runs `task` after every previously submitted task has settled. */
12
+ run(task) {
13
+ this.pendingCount++;
14
+ const result = this.tail.then(task).finally(() => {
15
+ this.pendingCount--;
16
+ });
17
+ // A failed task must not block the ones queued behind it.
18
+ this.tail = result.catch(() => undefined);
19
+ return result;
20
+ }
21
+ }
22
+ //# sourceMappingURL=serial-queue.js.map
package/package.json CHANGED
@@ -1,6 +1,126 @@
1
1
  {
2
2
  "name": "@g33ks/foundryvtt-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.1.0",
4
+ "description": "Model Context Protocol server for FoundryVTT integration",
5
+ "bin": {
6
+ "foundryvtt-mcp": "dist/index.js"
7
+ },
8
+ "type": "module",
9
+ "scripts": {
10
+ "build": "tsc && node -e \"require('node:fs').chmodSync('dist/index.js', 0o755)\"",
11
+ "dev": "tsx watch src/index.ts",
12
+ "start": "node dist/index.js",
13
+ "smoke": "node scripts/smoke-test.js",
14
+ "smoke:dotenv": "node scripts/smoke-dotenv.js",
15
+ "smoke:pack": "node scripts/smoke-pack.js",
16
+ "stress:shared": "node scripts/stress-shared.js",
17
+ "check:bridge-security": "node scripts/check-bridge-security.js",
18
+ "bridge:package": "node scripts/package-bridge.js",
19
+ "test": "vitest run",
20
+ "test:watch": "vitest --watch",
21
+ "test:coverage": "vitest run --coverage",
22
+ "test:ui": "vitest --ui",
23
+ "test:e2e": "playwright test",
24
+ "test:e2e:ui": "playwright test --ui",
25
+ "test:e2e:headed": "playwright test --headed",
26
+ "test:e2e:debug": "playwright test --debug",
27
+ "test:e2e:report": "playwright show-report",
28
+ "test:integration": "vitest run --config vitest.integration.config.ts",
29
+ "test:integration:watch": "vitest --watch --config vitest.integration.config.ts",
30
+ "test:integration:ui": "vitest --ui --config vitest.integration.config.ts",
31
+ "test:integration:docker": "docker compose -f docker-compose.test.yml up -d --wait && npm run test:integration; docker compose -f docker-compose.test.yml down -v",
32
+ "lint": "biome check src",
33
+ "lint:fix": "biome check --write src",
34
+ "format": "biome format --write src",
35
+ "clean": "rimraf dist",
36
+ "setup": "npm run clean && npm run build && node dist/index.js init --check",
37
+ "prepare": "husky",
38
+ "prepublishOnly": "npm run clean && npm run build"
39
+ },
40
+ "keywords": [
41
+ "foundry",
42
+ "vtt",
43
+ "mcp",
44
+ "ai",
45
+ "tabletop",
46
+ "rpg",
47
+ "foundryvtt",
48
+ "foundry-vtt",
49
+ "model-context-protocol",
50
+ "mcp-server",
51
+ "claude"
52
+ ],
53
+ "author": "G33ks",
54
+ "contributors": [
55
+ "Lauri Gates",
56
+ "Rafael Niehaus"
57
+ ],
58
+ "license": "MIT",
59
+ "repository": {
60
+ "type": "git",
61
+ "url": "https://github.com/G33ks/foundryvtt-mcp.git"
62
+ },
63
+ "homepage": "https://github.com/G33ks/foundryvtt-mcp#readme",
64
+ "bugs": {
65
+ "url": "https://github.com/G33ks/foundryvtt-mcp/issues"
66
+ },
67
+ "publishConfig": {
68
+ "access": "public"
69
+ },
70
+ "files": [
71
+ "dist/**/*.js",
72
+ "README.md",
73
+ "LICENSE"
74
+ ],
75
+ "dependencies": {
76
+ "@modelcontextprotocol/sdk": "^1.32.2",
77
+ "ajv": "^8.20.0",
78
+ "axios": "^1.21.0",
79
+ "dotenv": "^18.0.9",
80
+ "playwright-core": "^1.63.0",
81
+ "socket.io-client": "^4.8.3",
82
+ "ws": "^8.21.0",
83
+ "zod": "^4.6.7"
84
+ },
85
+ "devDependencies": {
86
+ "@biomejs/biome": "^2.5.0",
87
+ "@playwright/test": "^1.61.0",
88
+ "@types/node": "^22.20.5",
89
+ "@types/ws": "^8.18.1",
90
+ "husky": "^9.1.7",
91
+ "lint-staged": "^17.0.7",
92
+ "rimraf": "^6.1.4",
93
+ "tsx": "^4.22.4",
94
+ "typescript": "^6.0.3",
95
+ "vitest": "^4.1.12"
96
+ },
97
+ "engines": {
98
+ "node": ">=22"
99
+ },
100
+ "overrides": {
101
+ "@hono/node-server": "^2.1.6",
102
+ "hono": "^4.13.16",
103
+ "express-rate-limit": "^8.5.1",
104
+ "ip-address": "^10.7.6",
105
+ "path-to-regexp": "^8.4.2",
106
+ "fast-uri": "^3.1.9",
107
+ "socket.io-parser": "^4.2.7",
108
+ "vite": "^7.3.7",
109
+ "rollup": "^4.60.3",
110
+ "postcss": "^8.5.23",
111
+ "nanoid": "^3.3.16",
112
+ "picomatch": "^4.0.4",
113
+ "brace-expansion": "^5.0.12",
114
+ "form-data": "^4.0.6",
115
+ "ws": "$ws",
116
+ "qs": "^6.17.1"
117
+ },
118
+ "lint-staged": {
119
+ "src/**/*.{ts,tsx,js,jsx}": [
120
+ "biome check --write"
121
+ ],
122
+ "src/**/*.{json,css,md}": [
123
+ "biome format --write"
124
+ ]
125
+ }
126
+ }