-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.js
More file actions
431 lines (383 loc) · 12.9 KB
/
index.js
File metadata and controls
431 lines (383 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
#!/usr/bin/env node
/**
* UE5 MCP Server
*
* Bridges MCP-compatible AI clients to Unreal Engine 5's editor via HTTP REST API.
* The UnrealClaude plugin runs an HTTP server (default port 3000) with editor manipulation tools.
*
* Environment Variables:
* UNREAL_MCP_URL - Base URL for Unreal MCP server (default: http://localhost:3000)
* MCP_REQUEST_TIMEOUT_MS - HTTP request timeout in milliseconds (default: 30000)
* INJECT_CONTEXT - Enable automatic context injection on tool calls (default: false)
* MCP_TOOL_CACHE_TTL_MS - TTL for tool list cache in milliseconds (default: 30000)
*/
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
// Dynamic context loader for UE 5.7 API documentation
import {
getContextForTool,
getContextForQuery,
listCategories,
getCategoryInfo,
loadContextForCategory,
} from "./context-loader.js";
// Extracted library functions
import {
log,
fetchUnrealTools as _fetchUnrealTools,
executeUnrealTool as _executeUnrealTool,
executeUnrealToolAsync as _executeUnrealToolAsync,
checkUnrealConnection as _checkUnrealConnection,
convertToMCPSchema,
convertAnnotations,
formatToolResponse as _formatToolResponse,
} from "./lib.js";
// Tool router for mega-tool collapsing
import {
classifyTool,
resolveUnrealTool,
categorizeToolForStatus,
ROUTER_TOOL_SCHEMA,
} from "./tool-router.js";
// Configuration with defaults
const CONFIG = {
unrealMcpUrl: process.env.UNREAL_MCP_URL || "http://localhost:3000",
requestTimeoutMs: parseInt(process.env.MCP_REQUEST_TIMEOUT_MS, 10) || 30000,
injectContext: process.env.INJECT_CONTEXT === "true",
asyncEnabled: process.env.MCP_ASYNC_ENABLED !== "false",
asyncTimeoutMs: parseInt(process.env.MCP_ASYNC_TIMEOUT_MS, 10) || 300000,
pollIntervalMs: parseInt(process.env.MCP_POLL_INTERVAL_MS, 10) || 2000,
toolCacheTtlMs: parseInt(process.env.MCP_TOOL_CACHE_TTL_MS, 10) || 30000,
};
// Bind CONFIG values to library functions for convenience
const fetchUnrealTools = () => _fetchUnrealTools(CONFIG.unrealMcpUrl, CONFIG.requestTimeoutMs);
const executeUnrealTool = (toolName, args) => _executeUnrealTool(CONFIG.unrealMcpUrl, CONFIG.requestTimeoutMs, toolName, args);
const checkUnrealConnection = () => _checkUnrealConnection(CONFIG.unrealMcpUrl, CONFIG.requestTimeoutMs);
const formatToolResponse = (toolName, result) =>
_formatToolResponse(toolName, result, CONFIG.injectContext ? getContextForTool : null);
// Create the MCP server
const server = new Server(
{
name: "ue5-mcp-server",
version: "1.4.1",
},
{
capabilities: {
tools: {},
},
}
);
// Cache for tools with TTL (avoids re-fetching the full tool list on every list_tools call)
let toolCache = { tools: [], timestamp: 0 };
// Handle list_tools request
server.setRequestHandler(ListToolsRequestSchema, async () => {
const status = await checkUnrealConnection();
if (!status.connected) {
log.info("Unreal not connected", { reason: status.reason });
return {
tools: [
{
name: "unreal_status",
description: "Check if Unreal Editor is running with the plugin. Currently: NOT CONNECTED. Please start Unreal Editor with the plugin enabled.",
inputSchema: {
type: "object",
properties: {},
},
},
],
};
}
let unrealTools;
const cacheAge = Date.now() - toolCache.timestamp;
if (toolCache.tools.length > 0 && cacheAge < CONFIG.toolCacheTtlMs) {
unrealTools = toolCache.tools;
log.debug("Using cached tool list", { ageMs: cacheAge });
} else {
unrealTools = await fetchUnrealTools();
toolCache = { tools: unrealTools, timestamp: Date.now() };
}
const mcpTools = [];
// 1. Status first
mcpTools.push({
name: "unreal_status",
description: `Check Unreal Editor connection status. Currently: CONNECTED to ${status.projectName || "Unknown Project"} (${status.engineVersion || "Unknown"})`,
inputSchema: { type: "object", properties: {} },
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
});
// 2. Simple tools only (mega and hidden filtered out)
for (const tool of toolCache.tools) {
if (classifyTool(tool.name) === "simple") {
mcpTools.push({
name: `unreal_${tool.name}`,
description: tool.description,
inputSchema: convertToMCPSchema(tool.parameters, true),
annotations: convertAnnotations(tool.annotations),
});
}
}
// 3. Router tool (static schema for all mega-tools)
mcpTools.push(ROUTER_TOOL_SCHEMA);
// 4. Context tool last
mcpTools.push({
name: "unreal_get_ue_context",
description: `Get UE 5.7 API context. Categories: ${listCategories().join(", ")}`,
inputSchema: {
type: "object",
properties: {
category: {
type: "string",
description: `Specific category to load: ${listCategories().join(", ")}`,
},
query: {
type: "string",
description: "Search query to find relevant context (e.g., 'state machine transitions', 'async loading')",
},
},
},
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
});
log.info("Tools listed", { exposed: mcpTools.length, cached: toolCache.tools.length, connected: true });
return { tools: mcpTools };
});
// Handle call_tool request
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
// Handle UE context request
if (name === "unreal_get_ue_context") {
const { category, query } = args || {};
let result = null;
let matchedCategories = [];
if (category) {
const content = loadContextForCategory(category);
if (content) {
result = content;
matchedCategories = [category];
} else {
return {
content: [
{
type: "text",
text: `Unknown category: ${category}. Available categories: ${listCategories().join(", ")}`,
},
],
isError: true,
};
}
}
else if (query) {
const queryResult = getContextForQuery(query);
if (queryResult) {
result = queryResult.content;
matchedCategories = queryResult.categories;
} else {
return {
content: [
{
type: "text",
text: `No context found for query: "${query}". Try categories: ${listCategories().join(", ")}`,
},
],
isError: false,
};
}
}
else {
const categoryList = listCategories().map((cat) => {
const info = getCategoryInfo(cat);
return `- **${cat}**: Keywords: ${info.keywords.slice(0, 5).join(", ")}...`;
});
return {
content: [
{
type: "text",
text: `# Available UE 5.7 Context Categories\n\n${categoryList.join("\n")}\n\nUse \`category\` param for specific context or \`query\` to search by keywords.`,
},
],
};
}
log.info("UE context loaded", { categories: matchedCategories });
return {
content: [
{
type: "text",
text: `# UE 5.7 Context: ${matchedCategories.join(", ")}\n\n${result}`,
},
],
};
}
// Handle status check (lightweight — uses cached tools, no context probe)
if (name === "unreal_status") {
const status = await checkUnrealConnection();
if (status.connected) {
// Use cached tool list instead of re-fetching
const unrealTools = toolCache.tools;
const categories = {};
for (const tool of unrealTools) {
const category = categorizeToolForStatus(tool.name);
categories[category] = (categories[category] || 0) + 1;
}
const contextCategories = listCategories();
const simpleCount = unrealTools.filter(t => classifyTool(t.name) === "simple").length;
const response = {
connected: true,
project: status.projectName,
engine: status.engineVersion,
context_categories: contextCategories.length,
tool_summary: categories,
total_tools: unrealTools.length,
exposed_tools: simpleCount + 3, // simple tools + status + router + context
message: "Unreal Editor connected. All tools operational.",
};
return {
content: [
{
type: "text",
text: JSON.stringify(response, null, 2),
},
],
};
} else {
return {
content: [
{
type: "text",
text: JSON.stringify({
connected: false,
reason: status.reason,
message: "Unreal Editor is not running or the plugin is not enabled. Please start Unreal Editor with the plugin.",
}, null, 2),
},
],
isError: true,
};
}
}
// Router tool — dispatches to underlying mega-tool
if (name === "unreal_ue") {
const { domain, operation, params: routerParams } = args || {};
if (!domain || !operation) {
return {
content: [{ type: "text", text: "Error: unreal_ue requires 'domain' and 'operation' parameters." }],
isError: true,
};
}
const targetTool = resolveUnrealTool(domain, operation);
if (!targetTool) {
return {
content: [{
type: "text",
text: `Error: Unknown domain "${domain}". Valid domains: blueprint, anim, character, enhanced_input, material, asset`,
}],
isError: true,
};
}
const unrealArgs = { operation, ...(routerParams || {}) };
log.info("Router dispatch", { domain, operation, targetTool });
const progressToken = request.params._meta?.progressToken;
const onProgress = progressToken
? ({ progress, total, message }) => {
server.notification({
method: "notifications/progress",
params: { progressToken, progress, total: total || 0, message },
});
}
: undefined;
let result;
if (CONFIG.asyncEnabled) {
result = await _executeUnrealToolAsync(
CONFIG.unrealMcpUrl,
CONFIG.requestTimeoutMs,
targetTool,
unrealArgs,
{ onProgress, pollIntervalMs: CONFIG.pollIntervalMs, asyncTimeoutMs: CONFIG.asyncTimeoutMs }
);
} else {
result = await executeUnrealTool(targetTool, unrealArgs);
}
return formatToolResponse(targetTool, result);
}
// Strip "unreal_" prefix to get actual tool name
if (!name.startsWith("unreal_")) {
return {
content: [
{
type: "text",
text: `Unknown tool: ${name}`,
},
],
isError: true,
};
}
const toolName = name.substring(7);
// Tools excluded from auto-async: task_* tools and read-only tools
const isTaskTool = toolName.startsWith("task_");
const cachedTool = toolCache.tools.find(t => t.name === toolName);
const isReadOnly = cachedTool?.annotations?.readOnlyHint === true;
let result;
if (CONFIG.asyncEnabled && !isTaskTool && !isReadOnly) {
const progressToken = request.params._meta?.progressToken;
const onProgress = progressToken
? ({ progress, total, message }) => {
server.notification({
method: "notifications/progress",
params: { progressToken, progress, total: total || 0, message },
});
}
: undefined;
result = await _executeUnrealToolAsync(
CONFIG.unrealMcpUrl,
CONFIG.requestTimeoutMs,
toolName,
args,
{
onProgress,
pollIntervalMs: CONFIG.pollIntervalMs,
asyncTimeoutMs: CONFIG.asyncTimeoutMs,
}
);
} else {
result = await executeUnrealTool(toolName, args);
}
const response = formatToolResponse(toolName, result);
if (CONFIG.injectContext && result.success) {
log.debug("Injected context for tool", { tool: toolName });
}
return response;
});
// Start the server
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
const categories = listCategories();
const testContext = loadContextForCategory("animation");
const contextStatus = testContext ? `OK (${categories.length} categories loaded)` : "FAILED";
log.info("UE5 MCP Server started", {
version: "1.4.1",
unrealUrl: CONFIG.unrealMcpUrl,
timeoutMs: CONFIG.requestTimeoutMs,
asyncEnabled: CONFIG.asyncEnabled,
asyncTimeoutMs: CONFIG.asyncTimeoutMs,
pollIntervalMs: CONFIG.pollIntervalMs,
contextInjection: CONFIG.injectContext,
contextSystem: contextStatus,
contextCategories: categories,
});
}
main().catch((error) => {
log.error("Fatal error", { error: error.message, stack: error.stack });
process.exit(1);
});