@akiojin/unity-mcp-server 2.33.0 → 2.37.1

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 (26) hide show
  1. package/README.md +30 -5
  2. package/package.json +9 -4
  3. package/src/core/config.js +241 -242
  4. package/src/core/projectInfo.js +15 -0
  5. package/src/core/transports/HybridStdioServerTransport.js +78 -75
  6. package/src/handlers/addressables/AddressablesAnalyzeToolHandler.js +45 -47
  7. package/src/handlers/addressables/AddressablesBuildToolHandler.js +32 -33
  8. package/src/handlers/addressables/AddressablesManageToolHandler.js +74 -75
  9. package/src/handlers/component/ComponentFieldSetToolHandler.js +419 -419
  10. package/src/handlers/index.js +437 -437
  11. package/src/handlers/input/InputGamepadToolHandler.js +162 -0
  12. package/src/handlers/input/InputKeyboardToolHandler.js +127 -0
  13. package/src/handlers/input/InputMouseToolHandler.js +188 -0
  14. package/src/handlers/input/InputSystemControlToolHandler.js +63 -64
  15. package/src/handlers/input/InputTouchToolHandler.js +178 -0
  16. package/src/handlers/playmode/PlaymodePlayToolHandler.js +36 -23
  17. package/src/handlers/playmode/PlaymodeStopToolHandler.js +32 -21
  18. package/src/handlers/test/TestGetStatusToolHandler.js +37 -10
  19. package/src/handlers/test/TestRunToolHandler.js +36 -35
  20. package/src/lsp/LspProcessManager.js +18 -12
  21. package/src/utils/editorState.js +42 -0
  22. package/src/utils/testResultsCache.js +70 -0
  23. package/src/handlers/input/InputGamepadSimulateToolHandler.js +0 -116
  24. package/src/handlers/input/InputKeyboardSimulateToolHandler.js +0 -79
  25. package/src/handlers/input/InputMouseSimulateToolHandler.js +0 -107
  26. package/src/handlers/input/InputTouchSimulateToolHandler.js +0 -142
@@ -1,242 +1,241 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import { findUpSync } from 'find-up';
4
-
5
- /**
6
- * Shallow merge utility (simple objects only)
7
- */
8
- function merge(a, b) {
9
- const out = { ...a };
10
- for (const [k, v] of Object.entries(b || {})) {
11
- if (v && typeof v === 'object' && !Array.isArray(v) && a[k] && typeof a[k] === 'object') {
12
- out[k] = { ...a[k], ...v };
13
- } else {
14
- out[k] = v;
15
- }
16
- }
17
- return out;
18
- }
19
-
20
- /**
21
- * Base configuration for Unity MCP Server Server
22
- */
23
- const envUnityHost =
24
- process.env.UNITY_UNITY_HOST ||
25
- process.env.UNITY_BIND_HOST ||
26
- process.env.UNITY_HOST ||
27
- null;
28
-
29
- const envMcpHost =
30
- process.env.UNITY_MCP_HOST ||
31
- process.env.UNITY_CLIENT_HOST ||
32
- process.env.UNITY_HOST ||
33
- null;
34
-
35
- const envBindHost = process.env.UNITY_BIND_HOST || null;
36
-
37
- const baseConfig = {
38
- // Unity connection settings
39
- unity: {
40
- unityHost: envUnityHost,
41
- mcpHost: envMcpHost,
42
- bindHost: envBindHost,
43
- port: parseInt(process.env.UNITY_PORT || '', 10) || 6400,
44
- reconnectDelay: 1000,
45
- maxReconnectDelay: 30000,
46
- reconnectBackoffMultiplier: 2,
47
- commandTimeout: 30000,
48
- },
49
-
50
- // Server settings
51
- server: {
52
- name: 'unity-mcp-server',
53
- version: '0.1.0',
54
- description: 'MCP server for Unity Editor integration',
55
- },
56
-
57
- // Logging settings
58
- logging: {
59
- level: process.env.LOG_LEVEL || 'info',
60
- prefix: '[Unity MCP Server]',
61
- },
62
-
63
- // Write queue removed: all edits go through structured Roslyn tools.
64
-
65
- // Search-related defaults and engine selection
66
- search: {
67
- // detail alias: 'compact' maps to returnMode 'snippets'
68
- defaultDetail: (process.env.SEARCH_DEFAULT_DETAIL || 'compact').toLowerCase(), // compact|metadata|snippets|full
69
- engine: (process.env.SEARCH_ENGINE || 'naive').toLowerCase(), // naive|treesitter (future)
70
- },
71
-
72
- // LSP client defaults
73
- lsp: {
74
- requestTimeoutMs: Number(process.env.LSP_REQUEST_TIMEOUT_MS || 60000),
75
- },
76
-
77
- // Indexing (code index) settings
78
- indexing: {
79
- // Enable periodic incremental index updates (polling watcher)
80
- watch: (process.env.INDEX_WATCH || 'false').toLowerCase() === 'true',
81
- // Polling interval (ms)
82
- intervalMs: Number(process.env.INDEX_WATCH_INTERVAL_MS || 15000),
83
- // Build options
84
- concurrency: Number(process.env.INDEX_CONCURRENCY || 8),
85
- retry: Number(process.env.INDEX_RETRY || 2),
86
- reportEvery: Number(process.env.INDEX_REPORT_EVERY || 500),
87
- },
88
- };
89
-
90
- /**
91
- * External config resolution (no legacy compatibility):
92
- * Priority:
93
- * 1) UNITY_MCP_CONFIG (explicit file path)
94
- * 2) ./.unity/config.json (project-local)
95
- * 3) ~/.unity/config.json (user-global)
96
- * If none found, create ./.unity/config.json with defaults.
97
- */
98
- function ensureDefaultProjectConfig(baseDir) {
99
- const dir = path.resolve(baseDir, '.unity');
100
- const file = path.join(dir, 'config.json');
101
-
102
- try {
103
- if (!fs.existsSync(dir)) {
104
- fs.mkdirSync(dir, { recursive: true });
105
- }
106
-
107
- if (!fs.existsSync(file)) {
108
- const inferredRoot = fs.existsSync(path.join(baseDir, 'Assets')) ? baseDir : '';
109
- const defaultConfig = {
110
- unity: {
111
- unityHost: 'localhost',
112
- mcpHost: 'localhost',
113
- port: 6400,
114
- },
115
- project: {
116
- root: inferredRoot ? inferredRoot.replace(/\\/g, '/') : '',
117
- },
118
- };
119
- fs.writeFileSync(file, `${JSON.stringify(defaultConfig, null, 2)}\n`, 'utf8');
120
- }
121
- return file;
122
- } catch (error) {
123
- return null;
124
- }
125
- }
126
-
127
- function loadExternalConfig() {
128
- const explicitPath = process.env.UNITY_MCP_CONFIG;
129
-
130
- const projectPath = findUpSync((directory) => {
131
- const candidate = path.resolve(directory, '.unity', 'config.json');
132
- return fs.existsSync(candidate) ? candidate : undefined;
133
- }, { cwd: process.cwd() });
134
- const homeDir = process.env.HOME || process.env.USERPROFILE || '';
135
- const userPath = homeDir ? path.resolve(homeDir, '.unity', 'config.json') : null;
136
-
137
- const candidates = [explicitPath, projectPath, userPath].filter(Boolean);
138
- for (const p of candidates) {
139
- try {
140
- if (p && fs.existsSync(p)) {
141
- const raw = fs.readFileSync(p, 'utf8');
142
- const json = JSON.parse(raw);
143
- const out = json && typeof json === 'object' ? json : {};
144
- out.__configPath = p;
145
- return out;
146
- }
147
- } catch (e) {
148
- return { __configLoadError: `${p}: ${e.message}` };
149
- }
150
- }
151
- const fallbackPath = ensureDefaultProjectConfig(process.cwd());
152
- if (fallbackPath && fs.existsSync(fallbackPath)) {
153
- try {
154
- const raw = fs.readFileSync(fallbackPath, 'utf8');
155
- const json = JSON.parse(raw);
156
- const out = json && typeof json === 'object' ? json : {};
157
- out.__configPath = fallbackPath;
158
- out.__configGenerated = true;
159
- return out;
160
- } catch (e) {
161
- return { __configLoadError: `${fallbackPath}: ${e.message}` };
162
- }
163
- }
164
- return {};
165
- }
166
-
167
- const external = loadExternalConfig();
168
- export const config = merge(baseConfig, external);
169
-
170
- const normalizeUnityConfig = () => {
171
- const unityConfig = config.unity || (config.unity = {});
172
-
173
- // Legacy aliases coming from config files or env vars
174
- const legacyHost = unityConfig.host;
175
- const legacyClientHost = unityConfig.clientHost;
176
- const legacyBindHost = unityConfig.bindHost;
177
-
178
- if (!unityConfig.unityHost) {
179
- unityConfig.unityHost = legacyBindHost || legacyHost || envUnityHost || 'localhost';
180
- }
181
-
182
- if (!unityConfig.mcpHost) {
183
- unityConfig.mcpHost = legacyClientHost || envMcpHost || legacyHost || unityConfig.unityHost;
184
- }
185
-
186
- // Keep bindHost for backwards compatibility with legacy code paths
187
- if (!unityConfig.bindHost) {
188
- unityConfig.bindHost = legacyBindHost || envBindHost || unityConfig.unityHost;
189
- }
190
-
191
- // Maintain legacy properties so older handlers keep working
192
- unityConfig.host = unityConfig.unityHost;
193
- unityConfig.clientHost = unityConfig.mcpHost;
194
- };
195
-
196
- normalizeUnityConfig();
197
-
198
- // Workspace root detection: directory that contains .unity/config.json used
199
- const initialCwd = process.cwd();
200
- let workspaceRoot = initialCwd;
201
- try {
202
- if (config.__configPath) {
203
- const cfgDir = path.dirname(config.__configPath); // <workspace>/.unity
204
- workspaceRoot = path.dirname(cfgDir); // <workspace>
205
- }
206
- } catch {}
207
- export const WORKSPACE_ROOT = workspaceRoot;
208
-
209
- /**
210
- * Logger utility
211
- * IMPORTANT: In MCP servers, all stdout output must be JSON-RPC protocol messages.
212
- * Logging must go to stderr to avoid breaking the protocol.
213
- */
214
- export const logger = {
215
- info: (message, ...args) => {
216
- if (['info', 'debug'].includes(config.logging.level)) {
217
- console.error(`${config.logging.prefix} ${message}`, ...args);
218
- }
219
- },
220
-
221
- warn: (message, ...args) => {
222
- if (['info', 'debug', 'warn'].includes(config.logging.level)) {
223
- console.error(`${config.logging.prefix} WARN: ${message}`, ...args);
224
- }
225
- },
226
-
227
- error: (message, ...args) => {
228
- console.error(`${config.logging.prefix} ERROR: ${message}`, ...args);
229
- },
230
-
231
- debug: (message, ...args) => {
232
- if (config.logging.level === 'debug') {
233
- console.error(`${config.logging.prefix} DEBUG: ${message}`, ...args);
234
- }
235
- }
236
- };
237
-
238
- // Late log if external config failed to load
239
- if (config.__configLoadError) {
240
- console.error(`${baseConfig.logging.prefix} WARN: Failed to load external config: ${config.__configLoadError}`);
241
- delete config.__configLoadError;
242
- }
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { findUpSync } from 'find-up';
4
+
5
+ /**
6
+ * Shallow merge utility (simple objects only)
7
+ */
8
+ function merge(a, b) {
9
+ const out = { ...a };
10
+ for (const [k, v] of Object.entries(b || {})) {
11
+ if (v && typeof v === 'object' && !Array.isArray(v) && a[k] && typeof a[k] === 'object') {
12
+ out[k] = { ...a[k], ...v };
13
+ } else {
14
+ out[k] = v;
15
+ }
16
+ }
17
+ return out;
18
+ }
19
+
20
+ /**
21
+ * Base configuration for Unity MCP Server Server
22
+ */
23
+ const envUnityHost =
24
+ process.env.UNITY_UNITY_HOST || process.env.UNITY_BIND_HOST || process.env.UNITY_HOST || null;
25
+
26
+ const envMcpHost =
27
+ process.env.UNITY_MCP_HOST || process.env.UNITY_CLIENT_HOST || process.env.UNITY_HOST || null;
28
+
29
+ const envBindHost = process.env.UNITY_BIND_HOST || null;
30
+
31
+ const baseConfig = {
32
+ // Unity connection settings
33
+ unity: {
34
+ unityHost: envUnityHost,
35
+ mcpHost: envMcpHost,
36
+ bindHost: envBindHost,
37
+ port: parseInt(process.env.UNITY_PORT || '', 10) || 6400,
38
+ reconnectDelay: 1000,
39
+ maxReconnectDelay: 30000,
40
+ reconnectBackoffMultiplier: 2,
41
+ commandTimeout: 30000
42
+ },
43
+
44
+ // Server settings
45
+ server: {
46
+ name: 'unity-mcp-server',
47
+ version: '0.1.0',
48
+ description: 'MCP server for Unity Editor integration'
49
+ },
50
+
51
+ // Logging settings
52
+ logging: {
53
+ level: process.env.LOG_LEVEL || 'info',
54
+ prefix: '[Unity MCP Server]'
55
+ },
56
+
57
+ // Write queue removed: all edits go through structured Roslyn tools.
58
+
59
+ // Search-related defaults and engine selection
60
+ search: {
61
+ // detail alias: 'compact' maps to returnMode 'snippets'
62
+ defaultDetail: (process.env.SEARCH_DEFAULT_DETAIL || 'compact').toLowerCase(), // compact|metadata|snippets|full
63
+ engine: (process.env.SEARCH_ENGINE || 'naive').toLowerCase() // naive|treesitter (future)
64
+ },
65
+
66
+ // LSP client defaults
67
+ lsp: {
68
+ requestTimeoutMs: Number(process.env.LSP_REQUEST_TIMEOUT_MS || 60000)
69
+ },
70
+
71
+ // Indexing (code index) settings
72
+ indexing: {
73
+ // Enable periodic incremental index updates (polling watcher)
74
+ watch: (process.env.INDEX_WATCH || 'false').toLowerCase() === 'true',
75
+ // Polling interval (ms)
76
+ intervalMs: Number(process.env.INDEX_WATCH_INTERVAL_MS || 15000),
77
+ // Build options
78
+ concurrency: Number(process.env.INDEX_CONCURRENCY || 8),
79
+ retry: Number(process.env.INDEX_RETRY || 2),
80
+ reportEvery: Number(process.env.INDEX_REPORT_EVERY || 500)
81
+ }
82
+ };
83
+
84
+ /**
85
+ * External config resolution (no legacy compatibility):
86
+ * Priority:
87
+ * 1) UNITY_MCP_CONFIG (explicit file path)
88
+ * 2) ./.unity/config.json (project-local)
89
+ * 3) ~/.unity/config.json (user-global)
90
+ * If none found, create ./.unity/config.json with defaults.
91
+ */
92
+ function ensureDefaultProjectConfig(baseDir) {
93
+ const dir = path.resolve(baseDir, '.unity');
94
+ const file = path.join(dir, 'config.json');
95
+
96
+ try {
97
+ if (!fs.existsSync(dir)) {
98
+ fs.mkdirSync(dir, { recursive: true });
99
+ }
100
+
101
+ if (!fs.existsSync(file)) {
102
+ const inferredRoot = fs.existsSync(path.join(baseDir, 'Assets')) ? baseDir : '';
103
+ const defaultConfig = {
104
+ unity: {
105
+ unityHost: 'localhost',
106
+ mcpHost: 'localhost',
107
+ port: 6400
108
+ },
109
+ project: {
110
+ root: inferredRoot ? inferredRoot.replace(/\\/g, '/') : ''
111
+ }
112
+ };
113
+ fs.writeFileSync(file, `${JSON.stringify(defaultConfig, null, 2)}\n`, 'utf8');
114
+ }
115
+ return file;
116
+ } catch (error) {
117
+ return null;
118
+ }
119
+ }
120
+
121
+ function loadExternalConfig() {
122
+ const explicitPath = process.env.UNITY_MCP_CONFIG;
123
+
124
+ const projectPath = findUpSync(
125
+ directory => {
126
+ const candidate = path.resolve(directory, '.unity', 'config.json');
127
+ return fs.existsSync(candidate) ? candidate : undefined;
128
+ },
129
+ { cwd: process.cwd() }
130
+ );
131
+ const homeDir = process.env.HOME || process.env.USERPROFILE || '';
132
+ const userPath = homeDir ? path.resolve(homeDir, '.unity', 'config.json') : null;
133
+
134
+ const candidates = [explicitPath, projectPath, userPath].filter(Boolean);
135
+ for (const p of candidates) {
136
+ try {
137
+ if (p && fs.existsSync(p)) {
138
+ const raw = fs.readFileSync(p, 'utf8');
139
+ const json = JSON.parse(raw);
140
+ const out = json && typeof json === 'object' ? json : {};
141
+ out.__configPath = p;
142
+ return out;
143
+ }
144
+ } catch (e) {
145
+ return { __configLoadError: `${p}: ${e.message}` };
146
+ }
147
+ }
148
+ const fallbackPath = ensureDefaultProjectConfig(process.cwd());
149
+ if (fallbackPath && fs.existsSync(fallbackPath)) {
150
+ try {
151
+ const raw = fs.readFileSync(fallbackPath, 'utf8');
152
+ const json = JSON.parse(raw);
153
+ const out = json && typeof json === 'object' ? json : {};
154
+ out.__configPath = fallbackPath;
155
+ out.__configGenerated = true;
156
+ return out;
157
+ } catch (e) {
158
+ return { __configLoadError: `${fallbackPath}: ${e.message}` };
159
+ }
160
+ }
161
+ return {};
162
+ }
163
+
164
+ const external = loadExternalConfig();
165
+ export const config = merge(baseConfig, external);
166
+
167
+ const normalizeUnityConfig = () => {
168
+ const unityConfig = config.unity || (config.unity = {});
169
+
170
+ // Legacy aliases coming from config files or env vars
171
+ const legacyHost = unityConfig.host;
172
+ const legacyClientHost = unityConfig.clientHost;
173
+ const legacyBindHost = unityConfig.bindHost;
174
+
175
+ if (!unityConfig.unityHost) {
176
+ unityConfig.unityHost = legacyBindHost || legacyHost || envUnityHost || 'localhost';
177
+ }
178
+
179
+ if (!unityConfig.mcpHost) {
180
+ unityConfig.mcpHost = legacyClientHost || envMcpHost || legacyHost || unityConfig.unityHost;
181
+ }
182
+
183
+ // Keep bindHost for backwards compatibility with legacy code paths
184
+ if (!unityConfig.bindHost) {
185
+ unityConfig.bindHost = legacyBindHost || envBindHost || unityConfig.unityHost;
186
+ }
187
+
188
+ // Maintain legacy properties so older handlers keep working
189
+ unityConfig.host = unityConfig.unityHost;
190
+ unityConfig.clientHost = unityConfig.mcpHost;
191
+ };
192
+
193
+ normalizeUnityConfig();
194
+
195
+ // Workspace root detection: directory that contains .unity/config.json used
196
+ const initialCwd = process.cwd();
197
+ let workspaceRoot = initialCwd;
198
+ try {
199
+ if (config.__configPath) {
200
+ const cfgDir = path.dirname(config.__configPath); // <workspace>/.unity
201
+ workspaceRoot = path.dirname(cfgDir); // <workspace>
202
+ }
203
+ } catch {}
204
+ export const WORKSPACE_ROOT = workspaceRoot;
205
+
206
+ /**
207
+ * Logger utility
208
+ * IMPORTANT: In MCP servers, all stdout output must be JSON-RPC protocol messages.
209
+ * Logging must go to stderr to avoid breaking the protocol.
210
+ */
211
+ export const logger = {
212
+ info: (message, ...args) => {
213
+ if (['info', 'debug'].includes(config.logging.level)) {
214
+ console.error(`${config.logging.prefix} ${message}`, ...args);
215
+ }
216
+ },
217
+
218
+ warn: (message, ...args) => {
219
+ if (['info', 'debug', 'warn'].includes(config.logging.level)) {
220
+ console.error(`${config.logging.prefix} WARN: ${message}`, ...args);
221
+ }
222
+ },
223
+
224
+ error: (message, ...args) => {
225
+ console.error(`${config.logging.prefix} ERROR: ${message}`, ...args);
226
+ },
227
+
228
+ debug: (message, ...args) => {
229
+ if (config.logging.level === 'debug') {
230
+ console.error(`${config.logging.prefix} DEBUG: ${message}`, ...args);
231
+ }
232
+ }
233
+ };
234
+
235
+ // Late log if external config failed to load
236
+ if (config.__configLoadError) {
237
+ console.error(
238
+ `${baseConfig.logging.prefix} WARN: Failed to load external config: ${config.__configLoadError}`
239
+ );
240
+ delete config.__configLoadError;
241
+ }
@@ -18,6 +18,21 @@ export class ProjectInfoProvider {
18
18
 
19
19
  async get() {
20
20
  if (this.cached) return this.cached;
21
+ // Env-driven project root override (primarily for tests)
22
+ const envRootRaw = process.env.UNITY_PROJECT_ROOT;
23
+ if (typeof envRootRaw === 'string' && envRootRaw.trim().length > 0) {
24
+ const envRoot = envRootRaw.trim();
25
+ const projectRoot = normalize(path.resolve(envRoot));
26
+ const codeIndexRoot = normalize(resolveDefaultCodeIndexRoot(projectRoot));
27
+ this.cached = {
28
+ projectRoot,
29
+ assetsPath: normalize(path.join(projectRoot, 'Assets')),
30
+ packagesPath: normalize(path.join(projectRoot, 'Packages')),
31
+ codeIndexRoot
32
+ };
33
+ return this.cached;
34
+ }
35
+
21
36
  // Config-driven project root (no env fallback)
22
37
  const cfgRootRaw = config?.project?.root;
23
38
  if (typeof cfgRootRaw === 'string' && cfgRootRaw.trim().length > 0) {