@g33ks/foundryvtt-mcp 0.0.0-stage → 2.0.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 (96) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +468 -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 +410 -0
  7. package/dist/cli/prompt.js +117 -0
  8. package/dist/cli/snippets.js +49 -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 +415 -0
  14. package/dist/diagnostics/client.js +353 -0
  15. package/dist/diagnostics/types.js +94 -0
  16. package/dist/foundry/auth.js +220 -0
  17. package/dist/foundry/browser-detect.js +170 -0
  18. package/dist/foundry/client.js +5555 -0
  19. package/dist/foundry/dice-formula.js +154 -0
  20. package/dist/foundry/event-log.js +299 -0
  21. package/dist/foundry/headless-gm-session.js +740 -0
  22. package/dist/foundry/journal-history.js +90 -0
  23. package/dist/foundry/journal-integrity.js +306 -0
  24. package/dist/foundry/module-bridge.js +413 -0
  25. package/dist/foundry/types.js +52 -0
  26. package/dist/foundry/world-cache.js +386 -0
  27. package/dist/index.js +107 -0
  28. package/dist/mcp-server.js +63 -0
  29. package/dist/server.js +159 -0
  30. package/dist/shared/build-order.js +134 -0
  31. package/dist/shared/config-hash.js +62 -0
  32. package/dist/shared/config-notice.js +55 -0
  33. package/dist/shared/control.js +255 -0
  34. package/dist/shared/daemon-link.js +135 -0
  35. package/dist/shared/daemon.js +313 -0
  36. package/dist/shared/ipc-client.js +200 -0
  37. package/dist/shared/ipc-server.js +316 -0
  38. package/dist/shared/paths.js +79 -0
  39. package/dist/shared/protocol.js +230 -0
  40. package/dist/shared/relay-config.js +65 -0
  41. package/dist/shared/relay.js +120 -0
  42. package/dist/shared/rotating-log.js +57 -0
  43. package/dist/shared/spawn.js +39 -0
  44. package/dist/shared/state-file.js +33 -0
  45. package/dist/shared/token.js +62 -0
  46. package/dist/shared/version.js +57 -0
  47. package/dist/tools/base.js +74 -0
  48. package/dist/tools/definitions.js +3109 -0
  49. package/dist/tools/handlers/actor-mutations.js +128 -0
  50. package/dist/tools/handlers/actors.js +114 -0
  51. package/dist/tools/handlers/chat-mutations.js +49 -0
  52. package/dist/tools/handlers/chat.js +36 -0
  53. package/dist/tools/handlers/combat-mutations.js +215 -0
  54. package/dist/tools/handlers/combat-order.js +94 -0
  55. package/dist/tools/handlers/combat.js +51 -0
  56. package/dist/tools/handlers/compendium.js +83 -0
  57. package/dist/tools/handlers/diagnostics.js +438 -0
  58. package/dist/tools/handlers/dice.js +54 -0
  59. package/dist/tools/handlers/effects.js +103 -0
  60. package/dist/tools/handlers/events.js +50 -0
  61. package/dist/tools/handlers/generation.js +258 -0
  62. package/dist/tools/handlers/item-mutations.js +132 -0
  63. package/dist/tools/handlers/items.js +53 -0
  64. package/dist/tools/handlers/journal-mutations.js +230 -0
  65. package/dist/tools/handlers/journals.js +80 -0
  66. package/dist/tools/handlers/module-bridge.js +421 -0
  67. package/dist/tools/handlers/placeable-mutations.js +272 -0
  68. package/dist/tools/handlers/resources.js +203 -0
  69. package/dist/tools/handlers/roll-tables.js +97 -0
  70. package/dist/tools/handlers/scene-mutations.js +159 -0
  71. package/dist/tools/handlers/scenes.js +355 -0
  72. package/dist/tools/handlers/settings.js +53 -0
  73. package/dist/tools/handlers/tile-mutations.js +56 -0
  74. package/dist/tools/handlers/token-mutations.js +356 -0
  75. package/dist/tools/handlers/users.js +59 -0
  76. package/dist/tools/handlers/utils.js +47 -0
  77. package/dist/tools/handlers/wall-mutations.js +98 -0
  78. package/dist/tools/handlers/world-documents.js +222 -0
  79. package/dist/tools/handlers/world.js +92 -0
  80. package/dist/tools/index.js +25 -0
  81. package/dist/tools/new-router.js +97 -0
  82. package/dist/tools/registry.js +79 -0
  83. package/dist/tools/resources.js +63 -0
  84. package/dist/tools/router.js +688 -0
  85. package/dist/tools/write-tools.js +97 -0
  86. package/dist/utils/cache-instance.js +30 -0
  87. package/dist/utils/cache.js +205 -0
  88. package/dist/utils/diagnostics.js +332 -0
  89. package/dist/utils/guards.js +17 -0
  90. package/dist/utils/image-size.js +160 -0
  91. package/dist/utils/log-args.js +47 -0
  92. package/dist/utils/logger.js +203 -0
  93. package/dist/utils/refusal.js +30 -0
  94. package/dist/utils/sanitize.js +22 -0
  95. package/dist/utils/serial-queue.js +22 -0
  96. package/package.json +124 -4
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @fileoverview Which tools change game state.
3
+ *
4
+ * Their calls are serialised through one queue (see {@link FoundryCore}):
5
+ * clients (and, in shared mode, several clients) may fire tool calls in
6
+ * parallel, and a read-modify-write such as a journal page append must not
7
+ * interleave with another write. Reads keep running in parallel.
8
+ *
9
+ * Every `*MutationTools` definition group is covered by a unit test; tools
10
+ * that mutate from a mixed group are listed by hand below.
11
+ */
12
+ export const WRITE_TOOLS = new Set([
13
+ // actorMutationTools
14
+ 'update_actor_attributes',
15
+ 'create_world_actor',
16
+ 'create_full_actor',
17
+ 'delete_world_actor',
18
+ // itemMutationTools
19
+ 'create_actor_item',
20
+ 'update_actor_item',
21
+ 'delete_actor_item',
22
+ // sceneMutationTools
23
+ 'create_scene',
24
+ 'switch_scene',
25
+ 'delete_scene',
26
+ 'set_scene_lighting',
27
+ 'reset_fog',
28
+ 'set_scene_weather',
29
+ // wallMutationTools (list_walls is a read)
30
+ 'create_wall',
31
+ 'delete_wall',
32
+ 'set_door_state',
33
+ // tileMutationTools
34
+ 'create_tile',
35
+ 'delete_tile',
36
+ // placeableMutationTools
37
+ 'create_light',
38
+ 'update_light',
39
+ 'delete_light',
40
+ 'create_sound',
41
+ 'delete_sound',
42
+ 'create_note',
43
+ 'delete_note',
44
+ 'create_drawing',
45
+ 'delete_drawing',
46
+ 'create_template',
47
+ 'delete_template',
48
+ // combatMutationTools
49
+ 'next_turn',
50
+ 'end_combat',
51
+ 'set_initiative',
52
+ 'start_combat',
53
+ // tokenMutationTools
54
+ 'move_token',
55
+ 'apply_status_effect',
56
+ 'spawn_token',
57
+ 'delete_token',
58
+ 'move_token_pathfind',
59
+ 'move_tokens',
60
+ 'update_token_vision',
61
+ // chatMutationTools
62
+ 'send_chat_message',
63
+ // journalMutationTools
64
+ 'create_journal_entry',
65
+ 'update_journal_page',
66
+ 'add_journal_page',
67
+ 'update_journal_entry',
68
+ 'delete_journal_entry',
69
+ // worldDocumentMutationTools
70
+ 'create_folder',
71
+ 'create_macro',
72
+ 'delete_macro',
73
+ 'create_playlist',
74
+ 'set_playlist_state',
75
+ 'delete_playlist',
76
+ 'set_document_ownership',
77
+ // mixed groups
78
+ 'create_actor_effect',
79
+ 'update_actor_effect',
80
+ 'delete_actor_effect',
81
+ 'create_region',
82
+ 'delete_region',
83
+ 'create_roll_table',
84
+ 'delete_roll_table',
85
+ 'set_world_setting',
86
+ 'set_user_role',
87
+ 'roll_and_post',
88
+ 'import_compendium_actor',
89
+ 'set_target',
90
+ 'ping_canvas',
91
+ 'set_pause',
92
+ 'upload_asset',
93
+ ]);
94
+ export function isWriteTool(name) {
95
+ return WRITE_TOOLS.has(name);
96
+ }
97
+ //# sourceMappingURL=write-tools.js.map
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @fileoverview Global cache instance singleton
3
+ *
4
+ * This module provides a singleton cache instance that's configured
5
+ * from the application configuration.
6
+ */
7
+ import { config } from '../config/index.js';
8
+ import { CacheService } from './cache.js';
9
+ /**
10
+ * Global cache instance
11
+ * Initialized with configuration from config system
12
+ */
13
+ export const cache = new CacheService(config?.cache || {
14
+ enabled: false,
15
+ ttlSeconds: 300,
16
+ maxSize: 1000,
17
+ });
18
+ /**
19
+ * Cache key generators for consistent naming
20
+ */
21
+ export const CacheKeys = {
22
+ worldInfo: () => 'world:info',
23
+ actor: (id) => `actor:${id}`,
24
+ actorSearch: (query, type, limit) => `actor:search:${query}:${type || 'all'}:${limit || 10}`,
25
+ item: (id) => `item:${id}`,
26
+ itemSearch: (query, type, rarity, limit) => `item:search:${query}:${type || 'all'}:${rarity || 'all'}:${limit || 10}`,
27
+ scene: (id) => (id ? `scene:${id}` : 'scene:current'),
28
+ rule: (query, system) => `rule:${query}:${system || 'default'}`,
29
+ };
30
+ //# sourceMappingURL=cache-instance.js.map
@@ -0,0 +1,205 @@
1
+ /**
2
+ * @fileoverview Caching utility with TTL (Time To Live) support
3
+ *
4
+ * This module provides a simple in-memory cache with automatic expiration
5
+ * and configurable size limits to improve performance for quasi-static data.
6
+ */
7
+ import { logger } from './logger.js';
8
+ /**
9
+ * Simple in-memory cache with TTL and LRU eviction
10
+ */
11
+ export class CacheService {
12
+ config;
13
+ cache = new Map();
14
+ stats = {
15
+ hits: 0,
16
+ misses: 0,
17
+ evictions: 0,
18
+ };
19
+ cleanupInterval;
20
+ constructor(config) {
21
+ this.config = config;
22
+ if (config.enabled) {
23
+ logger.info('Cache service initialized', {
24
+ ttlSeconds: config.ttlSeconds,
25
+ maxSize: config.maxSize,
26
+ });
27
+ // Clean up expired entries periodically
28
+ this.cleanupInterval = setInterval(() => {
29
+ try {
30
+ this.cleanup();
31
+ }
32
+ catch (err) {
33
+ logger.warn('Cache cleanup error', { error: err instanceof Error ? err.message : err });
34
+ }
35
+ }, Math.max((config.ttlSeconds * 1000) / 4, 30000));
36
+ }
37
+ }
38
+ /**
39
+ * Get a value from the cache
40
+ */
41
+ get(key) {
42
+ if (!this.config.enabled) {
43
+ return undefined;
44
+ }
45
+ const entry = this.cache.get(key);
46
+ if (!entry) {
47
+ this.stats.misses++;
48
+ logger.debug('Cache miss', { key });
49
+ return undefined;
50
+ }
51
+ // Check if entry has expired
52
+ const now = Date.now();
53
+ if (now - entry.timestamp > entry.ttl * 1000) {
54
+ this.cache.delete(key);
55
+ this.stats.misses++;
56
+ logger.debug('Cache expired', { key, age: now - entry.timestamp });
57
+ return undefined;
58
+ }
59
+ // Update access metadata
60
+ entry.accessCount++;
61
+ entry.lastAccessed = now;
62
+ this.stats.hits++;
63
+ logger.debug('Cache hit', { key, accessCount: entry.accessCount });
64
+ return entry.value;
65
+ }
66
+ /**
67
+ * Set a value in the cache with custom TTL
68
+ */
69
+ set(key, value, customTtlSeconds) {
70
+ if (!this.config.enabled) {
71
+ return;
72
+ }
73
+ const ttl = customTtlSeconds ?? this.config.ttlSeconds;
74
+ const now = Date.now();
75
+ // Ensure cache doesn't exceed max size
76
+ if (this.cache.size >= this.config.maxSize && !this.cache.has(key)) {
77
+ this.evictLeastRecentlyUsed();
78
+ }
79
+ const entry = {
80
+ value,
81
+ timestamp: now,
82
+ ttl,
83
+ accessCount: 0,
84
+ lastAccessed: now,
85
+ };
86
+ this.cache.set(key, entry);
87
+ logger.debug('Cache set', { key, ttl, size: this.cache.size });
88
+ }
89
+ /**
90
+ * Delete a specific key from the cache
91
+ */
92
+ delete(key) {
93
+ const deleted = this.cache.delete(key);
94
+ if (deleted) {
95
+ logger.debug('Cache deleted', { key });
96
+ }
97
+ return deleted;
98
+ }
99
+ /**
100
+ * Clear all entries from the cache
101
+ */
102
+ clear() {
103
+ const size = this.cache.size;
104
+ this.cache.clear();
105
+ this.stats.hits = 0;
106
+ this.stats.misses = 0;
107
+ this.stats.evictions = 0;
108
+ logger.info('Cache cleared', { previousSize: size });
109
+ }
110
+ /**
111
+ * Get or set a value using a factory function
112
+ */
113
+ async getOrSet(key, factory, customTtlSeconds) {
114
+ if (!this.config.enabled) {
115
+ return await factory();
116
+ }
117
+ const cached = this.get(key);
118
+ if (cached !== undefined) {
119
+ return cached;
120
+ }
121
+ const value = await factory();
122
+ this.set(key, value, customTtlSeconds);
123
+ return value;
124
+ }
125
+ /**
126
+ * Get cache statistics
127
+ */
128
+ getStats() {
129
+ const total = this.stats.hits + this.stats.misses;
130
+ const hitRate = total > 0 ? this.stats.hits / total : 0;
131
+ return {
132
+ hits: this.stats.hits,
133
+ misses: this.stats.misses,
134
+ hitRate: Math.round(hitRate * 100) / 100,
135
+ size: this.cache.size,
136
+ maxSize: this.config.maxSize,
137
+ evictions: this.stats.evictions,
138
+ };
139
+ }
140
+ /**
141
+ * Check if cache is enabled
142
+ */
143
+ isEnabled() {
144
+ return this.config.enabled;
145
+ }
146
+ /**
147
+ * Destroy the cache service and release resources
148
+ */
149
+ destroy() {
150
+ if (this.cleanupInterval) {
151
+ clearInterval(this.cleanupInterval);
152
+ this.cleanupInterval = undefined;
153
+ }
154
+ this.cache.clear();
155
+ logger.info('Cache service destroyed');
156
+ }
157
+ /**
158
+ * Get cache keys (for debugging)
159
+ */
160
+ getKeys() {
161
+ return Array.from(this.cache.keys());
162
+ }
163
+ /**
164
+ * Cleanup expired entries
165
+ */
166
+ cleanup() {
167
+ const now = Date.now();
168
+ let cleaned = 0;
169
+ for (const [key, entry] of this.cache.entries()) {
170
+ if (now - entry.timestamp > entry.ttl * 1000) {
171
+ this.cache.delete(key);
172
+ cleaned++;
173
+ }
174
+ }
175
+ if (cleaned > 0) {
176
+ logger.debug('Cache cleanup completed', {
177
+ cleaned,
178
+ remaining: this.cache.size,
179
+ });
180
+ }
181
+ }
182
+ /**
183
+ * Evict least recently used entry
184
+ */
185
+ evictLeastRecentlyUsed() {
186
+ let lruKey;
187
+ let lruTime = Date.now(); // Start with current time
188
+ // Find the entry with the oldest lastAccessed time
189
+ for (const [key, entry] of this.cache.entries()) {
190
+ if (entry.lastAccessed <= lruTime) {
191
+ lruTime = entry.lastAccessed;
192
+ lruKey = key;
193
+ }
194
+ }
195
+ if (lruKey) {
196
+ this.cache.delete(lruKey);
197
+ this.stats.evictions++;
198
+ logger.debug('Cache evicted LRU entry', {
199
+ key: lruKey,
200
+ age: Date.now() - lruTime,
201
+ });
202
+ }
203
+ }
204
+ }
205
+ //# sourceMappingURL=cache.js.map
@@ -0,0 +1,332 @@
1
+ /**
2
+ * @fileoverview Diagnostic utilities for enhanced user experience
3
+ *
4
+ * Provides smart error analysis, problem detection, and actionable suggestions
5
+ * to help users troubleshoot and resolve common issues.
6
+ */
7
+ import { config } from '../config/index.js';
8
+ import { ApiStatusResponseSchema } from '../diagnostics/types.js';
9
+ import { logger } from './logger.js';
10
+ const REPO_URL = 'https://github.com/G33ks/foundryvtt-mcp';
11
+ /**
12
+ * Enhanced diagnostic system for FoundryVTT MCP integration
13
+ */
14
+ export class DiagnosticSystem {
15
+ foundryClient;
16
+ constructor(foundryClient) {
17
+ this.foundryClient = foundryClient;
18
+ }
19
+ /**
20
+ * Diagnose why a specific feature isn't working
21
+ */
22
+ async diagnoseFeatureProblem(feature) {
23
+ logger.debug(`Diagnosing problem with feature: ${feature}`);
24
+ try {
25
+ // Test basic connectivity
26
+ const isConnected = await this.foundryClient.testConnection();
27
+ if (!isConnected) {
28
+ return this.createConnectivityDiagnostic();
29
+ }
30
+ // Test REST API availability
31
+ const hasRestApi = await this.testRestApiAvailability();
32
+ if (!hasRestApi && this.requiresRestApi(feature)) {
33
+ return this.createRestApiDiagnostic(feature);
34
+ }
35
+ // Test authentication
36
+ const authResult = await this.testAuthentication();
37
+ if (!authResult.valid) {
38
+ return this.createAuthenticationDiagnostic(authResult);
39
+ }
40
+ // Feature-specific diagnostics
41
+ return await this.createFeatureSpecificDiagnostic(feature);
42
+ }
43
+ catch (error) {
44
+ logger.error('Error during diagnosis:', error);
45
+ return this.createGenericErrorDiagnostic(error);
46
+ }
47
+ }
48
+ /**
49
+ * Perform comprehensive health check
50
+ */
51
+ async performHealthCheck() {
52
+ logger.info('Performing system health check');
53
+ const report = {
54
+ connectivity: { status: 'offline', emoji: '❌', details: 'Not tested' },
55
+ authentication: { method: 'none', status: 'untested', emoji: '❓' },
56
+ features: {
57
+ diceRolling: false,
58
+ actorSearch: false,
59
+ itemSearch: false,
60
+ sceneData: false,
61
+ diagnostics: false,
62
+ },
63
+ restApiAvailable: false,
64
+ websocketAvailable: false,
65
+ };
66
+ try {
67
+ // Test connectivity
68
+ const isConnected = await this.foundryClient.testConnection();
69
+ if (isConnected) {
70
+ report.connectivity = {
71
+ status: 'connected',
72
+ emoji: '✅',
73
+ details: `Connected to ${config.foundry.url}`,
74
+ };
75
+ }
76
+ else {
77
+ report.connectivity = {
78
+ status: 'offline',
79
+ emoji: '❌',
80
+ details: `Cannot reach ${config.foundry.url}`,
81
+ };
82
+ return report; // Early return if not connected
83
+ }
84
+ // Test REST API
85
+ report.restApiAvailable = await this.testRestApiAvailability();
86
+ // Test authentication
87
+ const authResult = await this.testAuthentication();
88
+ report.authentication = {
89
+ method: config.foundry.apiKey ? 'api-key' : 'credentials',
90
+ status: authResult.valid ? 'valid' : 'invalid',
91
+ emoji: authResult.valid ? '✅' : '❌',
92
+ };
93
+ // Test individual features
94
+ report.features.diceRolling = await this.testDiceRolling();
95
+ report.features.actorSearch = await this.testActorSearch();
96
+ report.features.itemSearch = await this.testItemSearch();
97
+ report.features.sceneData = await this.testSceneData();
98
+ report.features.diagnostics = report.restApiAvailable;
99
+ // Update connectivity status based on feature availability
100
+ if (report.restApiAvailable) {
101
+ report.connectivity.status = 'connected';
102
+ }
103
+ else if (report.features.diceRolling) {
104
+ report.connectivity.status = 'limited';
105
+ report.connectivity.emoji = '⚠️';
106
+ report.connectivity.details += ' (Limited functionality - REST API not available)';
107
+ }
108
+ }
109
+ catch (error) {
110
+ logger.error('Health check failed:', error);
111
+ report.connectivity = {
112
+ status: 'offline',
113
+ emoji: '❌',
114
+ details: `Health check failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
115
+ };
116
+ }
117
+ return report;
118
+ }
119
+ /**
120
+ * Format health report for user display
121
+ */
122
+ formatHealthReport(report) {
123
+ let output = '🏥 **FoundryVTT MCP Health Check**\n\n';
124
+ output += `**Connection**: ${report.connectivity.status.toUpperCase()} ${report.connectivity.emoji}\n`;
125
+ output += ` ${report.connectivity.details}\n\n`;
126
+ output += `**Authentication**: ${report.authentication.method.toUpperCase()} ${report.authentication.emoji}\n`;
127
+ if (report.authentication.status === 'invalid') {
128
+ output += ` ⚠️ Authentication failed - check your credentials\n`;
129
+ }
130
+ output += '\n';
131
+ output += `**Available Features**:\n`;
132
+ output += ` • Dice Rolling: ${report.features.diceRolling ? '✅ Working' : '❌ Failed'}\n`;
133
+ output += ` • Actor Search: ${report.features.actorSearch ? '✅ Full access' : '⚠️ Limited/None'}\n`;
134
+ output += ` • Item Search: ${report.features.itemSearch ? '✅ Full access' : '⚠️ Limited/None'}\n`;
135
+ output += ` • Scene Data: ${report.features.sceneData ? '✅ Real data' : '⚠️ Mock data only'}\n`;
136
+ output += ` • System Diagnostics: ${report.features.diagnostics ? '✅ Available' : '❌ Unavailable'}\n\n`;
137
+ if (!report.restApiAvailable) {
138
+ output += '💡 **Unlock Full Features**:\n';
139
+ output += ' → Install the "Foundry Local REST API" module in FoundryVTT\n';
140
+ output += ' → Enable the module and configure API key\n';
141
+ output += ` → See setup guide: ${REPO_URL}/blob/main/docs/guides/configuration.md#optional-diagnostics-tools\n\n`;
142
+ }
143
+ if (report.connectivity.status === 'offline') {
144
+ output += '🔧 **Troubleshooting Steps**:\n';
145
+ output += ' 1. Ensure FoundryVTT is running and accessible\n';
146
+ output +=
147
+ ' 2. Check FOUNDRY_URL in the configuration file (`foundryvtt-mcp status` shows it)\n';
148
+ output += ' 3. Verify network connectivity\n';
149
+ output += ' 4. Check the configuration with: `foundryvtt-mcp init --check`\n';
150
+ }
151
+ return output;
152
+ }
153
+ /**
154
+ * Create diagnostic for connectivity issues
155
+ */
156
+ createConnectivityDiagnostic() {
157
+ return {
158
+ explanation: 'Unable to connect to FoundryVTT server.',
159
+ suggestions: "• **Check if FoundryVTT is running** - Start FoundryVTT and ensure it's accessible\n" +
160
+ `• **Verify server URL** - Check that \`${config.foundry.url}\` is correct\n` +
161
+ '• **Test connectivity** - Run `foundryvtt-mcp init --check` for a step-by-step check\n' +
162
+ '• **Check firewall** - Ensure no firewall is blocking the connection',
163
+ severity: 'critical',
164
+ canContinue: false,
165
+ documentationUrl: `${REPO_URL}/blob/main/TROUBLESHOOTING.md#connection-issues`,
166
+ };
167
+ }
168
+ /**
169
+ * Create diagnostic for REST API issues
170
+ */
171
+ createRestApiDiagnostic(feature) {
172
+ return {
173
+ explanation: `${feature.charAt(0).toUpperCase() + feature.slice(1)} search requires the REST API module for full functionality.`,
174
+ suggestions: '• **Install REST API module** - Get it from the FoundryVTT module browser\n' +
175
+ "• **Enable the module** - Activate it in your world's module settings\n" +
176
+ '• **Configure API key** - Generate and copy the API key from module settings\n' +
177
+ '• **Set the key** - Set FOUNDRY_API_KEY in the configuration file\n' +
178
+ '• **Restart the connector** - Run `foundryvtt-mcp stop`; the next call uses the new configuration',
179
+ severity: 'warning',
180
+ canContinue: true,
181
+ documentationUrl: `${REPO_URL}/blob/main/docs/guides/configuration.md#optional-diagnostics-tools`,
182
+ };
183
+ }
184
+ /**
185
+ * Create diagnostic for authentication issues
186
+ */
187
+ createAuthenticationDiagnostic(_authResult) {
188
+ const isApiKey = !!config.foundry.apiKey;
189
+ return {
190
+ explanation: `Authentication failed using ${isApiKey ? 'API key' : 'username/password'}.`,
191
+ suggestions: isApiKey
192
+ ? "• **Check API key** - Verify the key is correct and hasn't expired\n" +
193
+ '• **Regenerate key** - Generate a new API key in FoundryVTT module settings\n' +
194
+ '• **Module status** - Ensure the REST API module is enabled and running\n' +
195
+ '• **Restart FoundryVTT** - Sometimes a restart resolves authentication issues'
196
+ : '• **Check credentials** - Verify username and password are correct\n' +
197
+ '• **User permissions** - Ensure the user has required permissions\n' +
198
+ '• **Case sensitivity** - Check for typos in username (case-sensitive)\n' +
199
+ '• **User status** - Make sure the user account is active',
200
+ severity: 'error',
201
+ canContinue: false,
202
+ documentationUrl: `${REPO_URL}/blob/main/TROUBLESHOOTING.md#authentication-issues`,
203
+ };
204
+ }
205
+ /**
206
+ * Create feature-specific diagnostic
207
+ */
208
+ async createFeatureSpecificDiagnostic(feature) {
209
+ return {
210
+ explanation: `Connected with full access, but no ${feature} data found.`,
211
+ suggestions: `• **Check data exists** - Verify that ${feature} exist in your FoundryVTT world\n` +
212
+ '• **User permissions** - Ensure you have permission to view this data\n' +
213
+ '• **Module conflicts** - Check if other modules might be interfering\n' +
214
+ `• **Direct test** - Try accessing ${feature} directly in FoundryVTT`,
215
+ severity: 'info',
216
+ canContinue: true,
217
+ documentationUrl: `${REPO_URL}/blob/main/TROUBLESHOOTING.md#empty-search-results`,
218
+ };
219
+ }
220
+ /**
221
+ * Create generic error diagnostic
222
+ */
223
+ createGenericErrorDiagnostic(_error) {
224
+ return {
225
+ explanation: 'An unexpected error occurred during diagnosis.',
226
+ suggestions: '• **Check logs** - Review server logs for detailed error information\n' +
227
+ '• **Restart services** - Try restarting both FoundryVTT and the MCP server\n' +
228
+ '• **Update software** - Ensure all components are up to date\n' +
229
+ '• **Report issue** - If problem persists, report it on GitHub',
230
+ severity: 'error',
231
+ canContinue: false,
232
+ documentationUrl: `${REPO_URL}/issues`,
233
+ };
234
+ }
235
+ /**
236
+ * Test if feature requires REST API
237
+ */
238
+ requiresRestApi(feature) {
239
+ return ['actors', 'items', 'diagnostics'].includes(feature);
240
+ }
241
+ /**
242
+ * Test REST API availability
243
+ */
244
+ async testRestApiAvailability() {
245
+ try {
246
+ const response = await this.foundryClient.get('/api/status');
247
+ return (response?.data !== null &&
248
+ response?.data !== undefined &&
249
+ ApiStatusResponseSchema.parse(response.data).status === 'ok');
250
+ }
251
+ catch (error) {
252
+ logger.debug('REST API not available:', error);
253
+ return false;
254
+ }
255
+ }
256
+ /**
257
+ * Test authentication
258
+ */
259
+ async testAuthentication() {
260
+ try {
261
+ if (config.foundry.apiKey) {
262
+ // Test API key authentication
263
+ const response = await this.foundryClient.get('/api/world');
264
+ return { valid: !!response };
265
+ }
266
+ else {
267
+ // Test credential authentication (via WebSocket)
268
+ await this.foundryClient.connect();
269
+ return { valid: this.foundryClient.isConnected() };
270
+ }
271
+ }
272
+ catch (error) {
273
+ return {
274
+ valid: false,
275
+ error: error instanceof Error ? error.message : 'Unknown authentication error',
276
+ };
277
+ }
278
+ }
279
+ /**
280
+ * Test dice rolling functionality
281
+ */
282
+ async testDiceRolling() {
283
+ try {
284
+ const result = await this.foundryClient.rollDice('1d20', 'Health check test');
285
+ return typeof result.total === 'number';
286
+ }
287
+ catch (error) {
288
+ logger.debug('Dice rolling test failed:', error);
289
+ return false;
290
+ }
291
+ }
292
+ /**
293
+ * Test actor search functionality
294
+ */
295
+ async testActorSearch() {
296
+ try {
297
+ const result = await this.foundryClient.searchActors({ limit: 1 });
298
+ return Array.isArray(result.actors);
299
+ }
300
+ catch (error) {
301
+ logger.debug('Actor search test failed:', error);
302
+ return false;
303
+ }
304
+ }
305
+ /**
306
+ * Test item search functionality
307
+ */
308
+ async testItemSearch() {
309
+ try {
310
+ const result = await this.foundryClient.searchItems({ limit: 1 });
311
+ return Array.isArray(result.items);
312
+ }
313
+ catch (error) {
314
+ logger.debug('Item search test failed:', error);
315
+ return false;
316
+ }
317
+ }
318
+ /**
319
+ * Test scene data functionality
320
+ */
321
+ async testSceneData() {
322
+ try {
323
+ const result = await this.foundryClient.getCurrentScene();
324
+ return !!result && typeof result.name === 'string';
325
+ }
326
+ catch (error) {
327
+ logger.debug('Scene data test failed:', error);
328
+ return false;
329
+ }
330
+ }
331
+ }
332
+ //# sourceMappingURL=diagnostics.js.map
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @fileoverview Canonical runtime type guards shared across the server.
3
+ */
4
+ /**
5
+ * Narrows an unknown value to a plain keyed object.
6
+ *
7
+ * Arrays are excluded: every caller here uses this before reading named fields
8
+ * off a FoundryVTT document payload, and an array would satisfy `typeof ===
9
+ * 'object'` while having none of them.
10
+ *
11
+ * This proves only that the value is an object — its fields stay `unknown` and
12
+ * must each be checked (or parsed with Zod at the boundary) before use.
13
+ */
14
+ export function isRecord(value) {
15
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
16
+ }
17
+ //# sourceMappingURL=guards.js.map