diff --git a/Editor/MCPConnectionManager.cs b/Editor/MCPConnectionManager.cs
index 63887d8..05f229c 100644
--- a/Editor/MCPConnectionManager.cs
+++ b/Editor/MCPConnectionManager.cs
@@ -11,7 +11,7 @@ public class MCPConnectionManager
{
private static readonly string ComponentName = "MCPConnectionManager";
private ClientWebSocket webSocket;
- private Uri serverUri = new Uri("ws://localhost:8080"); // Changed to allow changing
+ private Uri serverUri = new Uri("ws://localhost:5010"); // Changed to allow changing
private readonly CancellationTokenSource cts = new CancellationTokenSource();
private bool isConnected = false;
private float reconnectTimer = 0f;
diff --git a/Editor/UI/MCPDebugWindow.cs b/Editor/UI/MCPDebugWindow.cs
index 0407c83..196fca6 100644
--- a/Editor/UI/MCPDebugWindow.cs
+++ b/Editor/UI/MCPDebugWindow.cs
@@ -88,7 +88,7 @@ public void CreateGUI()
// Set default port if empty
if (serverPortField != null && string.IsNullOrWhiteSpace(serverPortField.value))
{
- serverPortField.value = "8080";
+ serverPortField.value = "5010";
}
// Setup UI events
@@ -113,7 +113,7 @@ private void CreateFallbackUI(VisualElement root)
// Removed serverUrlField - only using port field as requested
- serverPortField = new TextField("Port (Default: 8080)") { value = "8080" };
+ serverPortField = new TextField("Port (Default: 5010)") { value = "5010" };
root.Add(serverPortField);
var connectButton = new Button(OnConnectClicked) { text = "Connect" };
@@ -240,10 +240,10 @@ private void OnConnectClicked()
// Get the server port from the text field
string portText = serverPortField.value;
- // If port is empty, default to 8080
+ // If port is empty, default to 5010
if (string.IsNullOrWhiteSpace(portText))
{
- portText = "8080";
+ portText = "5010";
serverPortField.value = portText;
}
diff --git a/Editor/UI/MCPDebugWindow.uxml b/Editor/UI/MCPDebugWindow.uxml
index e312a67..3da51b0 100644
--- a/Editor/UI/MCPDebugWindow.uxml
+++ b/Editor/UI/MCPDebugWindow.uxml
@@ -17,7 +17,7 @@
-
+
diff --git a/mcpServer/.dockerignore b/mcpServer/.dockerignore
new file mode 100644
index 0000000..8f17d07
--- /dev/null
+++ b/mcpServer/.dockerignore
@@ -0,0 +1,8 @@
+node_modules
+npm-debug.log
+.git
+.github
+.vscode
+*.md
+build/
+.env
diff --git a/mcpServer/.env.example b/mcpServer/.env.example
new file mode 100644
index 0000000..63b45c8
--- /dev/null
+++ b/mcpServer/.env.example
@@ -0,0 +1,4 @@
+# Unity MCP Server Configuration
+
+# WebSocket port for Unity Editor connection
+MCP_WEBSOCKET_PORT=5010
diff --git a/mcpServer/Dockerfile b/mcpServer/Dockerfile
new file mode 100644
index 0000000..182538a
--- /dev/null
+++ b/mcpServer/Dockerfile
@@ -0,0 +1,26 @@
+FROM node:18-alpine
+
+# Create app directory
+WORKDIR /app
+
+# Copy package.json and package-lock.json
+COPY package*.json ./
+
+# Install dependencies
+RUN npm install
+
+# Copy source code and TypeScript config
+COPY tsconfig.json ./
+COPY src/ ./src/
+
+# Build the application
+RUN npm run build
+
+# Default environment variable
+ENV MCP_WEBSOCKET_PORT=5010
+
+# Expose the port dynamically using the environment variable
+EXPOSE ${MCP_WEBSOCKET_PORT}
+
+# Command to run the MCP server
+CMD ["sh", "-c", "node build/index.js"]
diff --git a/mcpServer/Dockerfile.meta b/mcpServer/Dockerfile.meta
new file mode 100644
index 0000000..382fd58
--- /dev/null
+++ b/mcpServer/Dockerfile.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 09523e3291be5b84791e3cf5824f41cd
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/mcpServer/build/filesystemTools.js b/mcpServer/build/filesystemTools.js
new file mode 100644
index 0000000..b5eb77d
--- /dev/null
+++ b/mcpServer/build/filesystemTools.js
@@ -0,0 +1,471 @@
+import fs from 'fs/promises';
+import path from 'path';
+import { createTwoFilesPatch } from 'diff';
+import { minimatch } from 'minimatch';
+import { ReadFileArgsSchema, ReadMultipleFilesArgsSchema, WriteFileArgsSchema, EditFileArgsSchema, ListDirectoryArgsSchema, DirectoryTreeArgsSchema, SearchFilesArgsSchema, GetFileInfoArgsSchema, FindAssetsByTypeArgsSchema, ListScriptsArgsSchema } from './toolDefinitions.js';
+// Helper functions
+// Updated validatePath function to properly handle empty paths
+async function validatePath(requestedPath, assetRootPath) {
+ // If path is empty or just quotes, use the asset root path directly
+ if (!requestedPath || requestedPath.trim() === '' || requestedPath.trim() === '""' || requestedPath.trim() === "''") {
+ return assetRootPath;
+ }
+ // Clean the path to remove any unexpected quotes or escape characters
+ let cleanPath = requestedPath.replace(/['"\\]/g, '');
+ // Handle empty path after cleaning
+ if (!cleanPath || cleanPath.trim() === '') {
+ return assetRootPath;
+ }
+ // Normalize path to handle both Windows and Unix-style paths
+ const normalized = path.normalize(cleanPath);
+ // For relative paths, join with asset root path
+ // Only check for absolute paths using path.isAbsolute - all other paths are considered relative
+ let absolute;
+ if (path.isAbsolute(normalized)) {
+ absolute = normalized;
+ // Additional check: if the absolute path is outside the project and doesn't exist,
+ // try treating it as a relative path first
+ if (!absolute.startsWith(assetRootPath)) {
+ const tryRelative = path.join(assetRootPath, normalized);
+ try {
+ await fs.access(tryRelative);
+ // If we can access it as a relative path, use that instead
+ absolute = tryRelative;
+ }
+ catch {
+ // If we can't access it as a relative path either, keep the original absolute path
+ // and let the next check handle the potential error
+ }
+ }
+ }
+ else {
+ absolute = path.join(assetRootPath, normalized);
+ }
+ const resolvedPath = path.resolve(absolute);
+ // Ensure we don't escape out of the Unity project folder
+ // Special case for empty path: it should always resolve to the project root
+ if (!resolvedPath.startsWith(assetRootPath) && requestedPath.trim() !== '') {
+ throw new Error(`Access denied: Path ${requestedPath} is outside the Unity project directory`);
+ }
+ return resolvedPath;
+}
+async function getFileStats(filePath) {
+ const stats = await fs.stat(filePath);
+ return {
+ size: stats.size,
+ created: stats.birthtime,
+ modified: stats.mtime,
+ accessed: stats.atime,
+ isDirectory: stats.isDirectory(),
+ isFile: stats.isFile(),
+ permissions: stats.mode.toString(8).slice(-3),
+ };
+}
+async function searchFiles(rootPath, pattern, excludePatterns = []) {
+ const results = [];
+ async function search(currentPath) {
+ const entries = await fs.readdir(currentPath, { withFileTypes: true });
+ for (const entry of entries) {
+ const fullPath = path.join(currentPath, entry.name);
+ try {
+ // Check if path matches any exclude pattern
+ const relativePath = path.relative(rootPath, fullPath);
+ const shouldExclude = excludePatterns.some(pattern => {
+ const globPattern = pattern.includes('*') ? pattern : `**/${pattern}/**`;
+ return minimatch(relativePath, globPattern, { dot: true });
+ });
+ if (shouldExclude) {
+ continue;
+ }
+ if (entry.name.toLowerCase().includes(pattern.toLowerCase())) {
+ results.push(fullPath);
+ }
+ if (entry.isDirectory()) {
+ await search(fullPath);
+ }
+ }
+ catch (error) {
+ // Skip invalid paths during search
+ continue;
+ }
+ }
+ }
+ await search(rootPath);
+ return results;
+}
+function normalizeLineEndings(text) {
+ return text.replace(/\r\n/g, '\n');
+}
+function createUnifiedDiff(originalContent, newContent, filepath = 'file') {
+ // Ensure consistent line endings for diff
+ const normalizedOriginal = normalizeLineEndings(originalContent);
+ const normalizedNew = normalizeLineEndings(newContent);
+ return createTwoFilesPatch(filepath, filepath, normalizedOriginal, normalizedNew, 'original', 'modified');
+}
+async function applyFileEdits(filePath, edits, dryRun = false) {
+ // Read file content and normalize line endings
+ const content = normalizeLineEndings(await fs.readFile(filePath, 'utf-8'));
+ // Apply edits sequentially
+ let modifiedContent = content;
+ for (const edit of edits) {
+ const normalizedOld = normalizeLineEndings(edit.oldText);
+ const normalizedNew = normalizeLineEndings(edit.newText);
+ // If exact match exists, use it
+ if (modifiedContent.includes(normalizedOld)) {
+ modifiedContent = modifiedContent.replace(normalizedOld, normalizedNew);
+ continue;
+ }
+ // Otherwise, try line-by-line matching with flexibility for whitespace
+ const oldLines = normalizedOld.split('\n');
+ const contentLines = modifiedContent.split('\n');
+ let matchFound = false;
+ for (let i = 0; i <= contentLines.length - oldLines.length; i++) {
+ const potentialMatch = contentLines.slice(i, i + oldLines.length);
+ // Compare lines with normalized whitespace
+ const isMatch = oldLines.every((oldLine, j) => {
+ const contentLine = potentialMatch[j];
+ return oldLine.trim() === contentLine.trim();
+ });
+ if (isMatch) {
+ // Preserve original indentation of first line
+ const originalIndent = contentLines[i].match(/^\s*/)?.[0] || '';
+ const newLines = normalizedNew.split('\n').map((line, j) => {
+ if (j === 0)
+ return originalIndent + line.trimStart();
+ // For subsequent lines, try to preserve relative indentation
+ const oldIndent = oldLines[j]?.match(/^\s*/)?.[0] || '';
+ const newIndent = line.match(/^\s*/)?.[0] || '';
+ if (oldIndent && newIndent) {
+ const relativeIndent = newIndent.length - oldIndent.length;
+ return originalIndent + ' '.repeat(Math.max(0, relativeIndent)) + line.trimStart();
+ }
+ return line;
+ });
+ contentLines.splice(i, oldLines.length, ...newLines);
+ modifiedContent = contentLines.join('\n');
+ matchFound = true;
+ break;
+ }
+ }
+ if (!matchFound) {
+ throw new Error(`Could not find exact match for edit:\n${edit.oldText}`);
+ }
+ }
+ // Create unified diff
+ const diff = createUnifiedDiff(content, modifiedContent, filePath);
+ // Format diff with appropriate number of backticks
+ let numBackticks = 3;
+ while (diff.includes('`'.repeat(numBackticks))) {
+ numBackticks++;
+ }
+ const formattedDiff = `${'`'.repeat(numBackticks)}diff\n${diff}${'`'.repeat(numBackticks)}\n\n`;
+ if (!dryRun) {
+ await fs.writeFile(filePath, modifiedContent, 'utf-8');
+ }
+ return formattedDiff;
+}
+async function buildDirectoryTree(currentPath, assetRootPath, maxDepth = 5, currentDepth = 0) {
+ if (currentDepth >= maxDepth) {
+ return [{ name: "...", type: "directory" }];
+ }
+ const validPath = await validatePath(currentPath, assetRootPath);
+ const entries = await fs.readdir(validPath, { withFileTypes: true });
+ const result = [];
+ for (const entry of entries) {
+ const entryData = {
+ name: entry.name,
+ type: entry.isDirectory() ? 'directory' : 'file'
+ };
+ if (entry.isDirectory()) {
+ const subPath = path.join(currentPath, entry.name);
+ entryData.children = await buildDirectoryTree(subPath, assetRootPath, maxDepth, currentDepth + 1);
+ }
+ result.push(entryData);
+ }
+ return result;
+}
+// Function to recognize Unity asset types based on file extension
+function getUnityAssetType(filePath) {
+ const ext = path.extname(filePath).toLowerCase();
+ // Common Unity asset types
+ const assetTypes = {
+ '.unity': 'Scene',
+ '.prefab': 'Prefab',
+ '.mat': 'Material',
+ '.fbx': 'Model',
+ '.cs': 'Script',
+ '.anim': 'Animation',
+ '.controller': 'Animator Controller',
+ '.asset': 'ScriptableObject',
+ '.png': 'Texture',
+ '.jpg': 'Texture',
+ '.jpeg': 'Texture',
+ '.tga': 'Texture',
+ '.wav': 'Audio',
+ '.mp3': 'Audio',
+ '.ogg': 'Audio',
+ '.shader': 'Shader',
+ '.compute': 'Compute Shader',
+ '.ttf': 'Font',
+ '.otf': 'Font',
+ '.physicMaterial': 'Physics Material',
+ '.mask': 'Avatar Mask',
+ '.playable': 'Playable',
+ '.mixer': 'Audio Mixer',
+ '.renderTexture': 'Render Texture',
+ '.lighting': 'Lighting Settings',
+ '.shadervariants': 'Shader Variants',
+ '.spriteatlas': 'Sprite Atlas',
+ '.guiskin': 'GUI Skin',
+ '.flare': 'Flare',
+ '.brush': 'Brush',
+ '.overrideController': 'Animator Override Controller',
+ '.preset': 'Preset',
+ '.terrainlayer': 'Terrain Layer',
+ '.signal': 'Signal',
+ '.signalasset': 'Signal Asset',
+ '.giparams': 'Global Illumination Parameters',
+ '.cubemap': 'Cubemap',
+ };
+ return assetTypes[ext] || 'Other';
+}
+// Handler function to process filesystem tools
+export async function handleFilesystemTool(name, args, projectPath) {
+ switch (name) {
+ case "read_file": {
+ const parsed = ReadFileArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+ const validPath = await validatePath(parsed.data.path, projectPath);
+ const content = await fs.readFile(validPath, "utf-8");
+ return {
+ content: [{ type: "text", text: content }],
+ };
+ }
+ case "read_multiple_files": {
+ const parsed = ReadMultipleFilesArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+ const results = await Promise.all(parsed.data.paths.map(async (filePath) => {
+ try {
+ const validPath = await validatePath(filePath, projectPath);
+ const content = await fs.readFile(validPath, "utf-8");
+ return `${filePath}:\n${content}\n`;
+ }
+ catch (error) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ return `${filePath}: Error - ${errorMessage}`;
+ }
+ }));
+ return {
+ content: [{ type: "text", text: results.join("\n---\n") }],
+ };
+ }
+ case "write_file": {
+ const parsed = WriteFileArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+ const validPath = await validatePath(parsed.data.path, projectPath);
+ // Ensure directory exists
+ const dirPath = path.dirname(validPath);
+ await fs.mkdir(dirPath, { recursive: true });
+ await fs.writeFile(validPath, parsed.data.content, "utf-8");
+ return {
+ content: [{ type: "text", text: `Successfully wrote to ${parsed.data.path}` }],
+ };
+ }
+ case "edit_file": {
+ const parsed = EditFileArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+ const validPath = await validatePath(parsed.data.path, projectPath);
+ const result = await applyFileEdits(validPath, parsed.data.edits, parsed.data.dryRun);
+ return {
+ content: [{ type: "text", text: result }],
+ };
+ }
+ case "list_directory": {
+ const parsed = ListDirectoryArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+ const validPath = await validatePath(parsed.data.path, projectPath);
+ const entries = await fs.readdir(validPath, { withFileTypes: true });
+ const formatted = entries
+ .map((entry) => {
+ if (entry.isDirectory()) {
+ return `[DIR] ${entry.name}`;
+ }
+ else {
+ // For files, detect Unity asset type
+ const filePath = path.join(validPath, entry.name);
+ const assetType = getUnityAssetType(filePath);
+ return `[${assetType}] ${entry.name}`;
+ }
+ })
+ .join("\n");
+ return {
+ content: [{ type: "text", text: formatted }],
+ };
+ }
+ case "directory_tree": {
+ const parsed = DirectoryTreeArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+ const treeData = await buildDirectoryTree(parsed.data.path, projectPath, parsed.data.maxDepth);
+ return {
+ content: [{ type: "text", text: JSON.stringify(treeData, null, 2) }],
+ };
+ }
+ case "search_files": {
+ const parsed = SearchFilesArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+ const validPath = await validatePath(parsed.data.path, projectPath);
+ const results = await searchFiles(validPath, parsed.data.pattern, parsed.data.excludePatterns);
+ return {
+ content: [{
+ type: "text",
+ text: results.length > 0
+ ? `Found ${results.length} results:\n${results.join("\n")}`
+ : "No matches found"
+ }],
+ };
+ }
+ case "get_file_info": {
+ const parsed = GetFileInfoArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+ const validPath = await validatePath(parsed.data.path, projectPath);
+ const info = await getFileStats(validPath);
+ // Also get Unity-specific info if it's an asset file
+ const additionalInfo = {};
+ if (info.isFile) {
+ additionalInfo.assetType = getUnityAssetType(validPath);
+ }
+ const formattedInfo = Object.entries({ ...info, ...additionalInfo })
+ .map(([key, value]) => `${key}: ${value}`)
+ .join("\n");
+ return {
+ content: [{ type: "text", text: formattedInfo }],
+ };
+ }
+ case "find_assets_by_type": {
+ const parsed = FindAssetsByTypeArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+ const validPath = await validatePath(parsed.data.searchPath, projectPath);
+ const results = [];
+ const targetType = parsed.data.assetType.toLowerCase();
+ // Recursive function to search for assets
+ async function searchAssets(dir) {
+ const entries = await fs.readdir(dir, { withFileTypes: true });
+ for (const entry of entries) {
+ const fullPath = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ await searchAssets(fullPath);
+ }
+ else {
+ const assetType = getUnityAssetType(fullPath);
+ if (assetType.toLowerCase() === targetType) {
+ results.push(fullPath);
+ }
+ }
+ }
+ }
+ await searchAssets(validPath);
+ return {
+ content: [{
+ type: "text",
+ text: results.length > 0
+ ? `Found ${results.length} ${parsed.data.assetType} assets:\n${results.join("\n")}`
+ : `No ${parsed.data.assetType} assets found`
+ }],
+ };
+ }
+ case "list_scripts": {
+ const parsed = ListScriptsArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+ const validPath = await validatePath(parsed.data.path, projectPath);
+ const scripts = [];
+ // Recursive function to find C# scripts
+ async function findScripts(dir) {
+ const entries = await fs.readdir(dir, { withFileTypes: true });
+ for (const entry of entries) {
+ const fullPath = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ await findScripts(fullPath);
+ }
+ else if (path.extname(entry.name).toLowerCase() === '.cs') {
+ scripts.push({
+ path: fullPath,
+ name: entry.name
+ });
+ }
+ }
+ }
+ await findScripts(validPath);
+ const formattedScripts = scripts.map(s => `${s.name} (${s.path})`).join("\n");
+ return {
+ content: [{
+ type: "text",
+ text: scripts.length > 0
+ ? `Found ${scripts.length} C# scripts:\n${formattedScripts}`
+ : "No C# scripts found"
+ }],
+ };
+ }
+ default:
+ return {
+ content: [{ type: "text", text: `Unknown tool: ${name}` }],
+ isError: true,
+ };
+ }
+}
+// Register filesystem tools with the MCP server
+// This function is now only a stub that doesn't actually do anything
+// since all tools are registered in toolDefinitions.ts
+export function registerFilesystemTools(server, wsHandler) {
+ // This function is now deprecated as tool registration has moved to toolDefinitions.ts
+ console.log("Filesystem tools are now registered in toolDefinitions.ts");
+}
diff --git a/mcpServer/build/filesystemTools.js.meta b/mcpServer/build/filesystemTools.js.meta
new file mode 100644
index 0000000..48de2f2
--- /dev/null
+++ b/mcpServer/build/filesystemTools.js.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: d452cf7a25e80b84db532653e3b1f3e5
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/mcpServer/build/index.js b/mcpServer/build/index.js
index bd2898a..c33d999 100644
--- a/mcpServer/build/index.js
+++ b/mcpServer/build/index.js
@@ -3,6 +3,8 @@ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { WebSocketHandler } from './websocketHandler.js';
import { registerTools } from './toolDefinitions.js';
+import { registerFilesystemTools } from './filesystemTools.js';
+import path from 'path';
class UnityMCPServer {
server;
wsHandler;
@@ -10,22 +12,57 @@ class UnityMCPServer {
// Initialize MCP Server
this.server = new Server({
name: 'unity-mcp-server',
- version: '0.1.0',
+ version: '0.2.0',
}, {
capabilities: {
tools: {},
},
});
+ // Get port from environment variable or use default
+ // Add port range to try if the default port is taken
+ let wsPort = parseInt(process.env.MCP_WEBSOCKET_PORT || '5010');
+ // Determine Unity project path - with improved path sanitization
+ let projectPath = process.env.UNITY_PROJECT_PATH || (() => {
+ // Get the current working directory
+ const cwd = path.resolve(process.cwd());
+ // Find the Assets directory in the path
+ const assetsIndex = cwd.indexOf('Assets');
+ // If Assets is found, truncate the path to include Assets
+ if (assetsIndex !== -1) {
+ return cwd.substring(0, assetsIndex + 'Assets'.length);
+ }
+ // If Assets is not found, return the original path
+ return cwd;
+ })();
+ // Sanitize the path to remove any unexpected characters
+ projectPath = projectPath.replace(/["']/g, '');
+ // Fix potential issue with backslashes being removed
+ projectPath = path.normalize(projectPath);
+ // Make sure path ends with a directory separator if it's missing
+ if (!projectPath.endsWith(path.sep)) {
+ projectPath += path.sep;
+ }
+ console.error(`[Unity MCP] Using project path: ${projectPath}`);
+ // Set the environment variable for other modules to use
+ process.env.UNITY_PROJECT_PATH = projectPath;
// Initialize WebSocket Handler for Unity communication
- this.wsHandler = new WebSocketHandler(8080);
+ // It will automatically try different ports if the initial one is taken
+ this.wsHandler = new WebSocketHandler(wsPort);
// Register MCP tools
registerTools(this.server, this.wsHandler);
+ // Register filesystem tools to access Unity project files
+ registerFilesystemTools(this.server, this.wsHandler);
// Error handling
this.server.onerror = (error) => console.error('[MCP Error]', error);
process.on('SIGINT', async () => {
await this.cleanup();
process.exit(0);
});
+ // Also handle SIGTERM for clean Docker container shutdown
+ process.on('SIGTERM', async () => {
+ await this.cleanup();
+ process.exit(0);
+ });
}
async cleanup() {
console.error('Cleaning up resources...');
@@ -37,6 +74,7 @@ class UnityMCPServer {
const transport = new StdioServerTransport();
await this.server.connect(transport);
console.error('[Unity MCP] Server running and ready to accept connections');
+ console.error('[Unity MCP] WebSocket server listening on port', this.wsHandler.port);
}
}
// Start the server
diff --git a/mcpServer/build/toolDefinitions.js b/mcpServer/build/toolDefinitions.js
index a3c1863..cd4177f 100644
--- a/mcpServer/build/toolDefinitions.js
+++ b/mcpServer/build/toolDefinitions.js
@@ -1,9 +1,59 @@
+import { z } from 'zod';
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
+import { zodToJsonSchema } from 'zod-to-json-schema';
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
+import path from 'path';
+// Import handleFilesystemTool using ES module syntax instead of require
+import { handleFilesystemTool } from './filesystemTools.js';
+// File operation schemas - defined here to be used in tool definitions
+export const ReadFileArgsSchema = z.object({
+ path: z.string().describe('Path to the file to read. Can be absolute or relative to Unity project Assets folder. If empty, defaults to the Assets folder.'),
+});
+export const ReadMultipleFilesArgsSchema = z.object({
+ paths: z.array(z.string()).describe('Array of file paths to read. Paths can be absolute or relative to Unity project Assets folder.'),
+});
+export const WriteFileArgsSchema = z.object({
+ path: z.string().describe('Path to the file to write. Can be absolute or relative to Unity project Assets folder. If empty, defaults to the Assets folder.'),
+ content: z.string().describe('Content to write to the file'),
+});
+export const EditOperation = z.object({
+ oldText: z.string().describe('Text to search for - must match exactly'),
+ newText: z.string().describe('Text to replace with')
+});
+export const EditFileArgsSchema = z.object({
+ path: z.string().describe('Path to the file to edit. Can be absolute or relative to Unity project Assets folder. If empty, defaults to the Assets folder.'),
+ edits: z.array(EditOperation).describe('Array of edit operations to apply'),
+ dryRun: z.boolean().default(false).describe('Preview changes using git-style diff format')
+});
+export const ListDirectoryArgsSchema = z.object({
+ path: z.string().describe('Path to the directory to list. Can be absolute or relative to Unity project Assets folder. If empty, defaults to the Assets folder. Example: "Scenes" will list all files in the Assets/Scenes directory.'),
+});
+export const DirectoryTreeArgsSchema = z.object({
+ path: z.string().describe('Path to the directory to get tree of. Can be absolute or relative to Unity project Assets folder. If empty, defaults to the Assets folder. Example: "Prefabs" will show the tree for Assets/Prefabs.'),
+ maxDepth: z.number().optional().default(5).describe('Maximum depth to traverse'),
+});
+export const SearchFilesArgsSchema = z.object({
+ path: z.string().describe('Path to search from. Can be absolute or relative to Unity project Assets folder. If empty, defaults to the Assets folder. Example: "Scripts" will search within Assets/Scripts.'),
+ pattern: z.string().describe('Pattern to search for'),
+ excludePatterns: z.array(z.string()).optional().default([]).describe('Patterns to exclude')
+});
+export const GetFileInfoArgsSchema = z.object({
+ path: z.string().describe('Path to the file to get info for. Can be absolute or relative to Unity project Assets folder. If empty, defaults to the Assets folder.'),
+});
+export const FindAssetsByTypeArgsSchema = z.object({
+ assetType: z.string().describe('Type of assets to find (e.g., "Material", "Prefab", "Scene")'),
+ searchPath: z.string().optional().default("Assets").describe('Directory to search in. Can be absolute or relative to Unity project Assets folder. Example: "Materials" will search in Assets/Materials.'),
+});
+export const ListScriptsArgsSchema = z.object({
+ path: z.string().optional().default("Scripts").describe('Path to look for scripts in. Can be absolute or relative to Unity project Assets folder. If empty, defaults to the Assets/Scripts folder.'),
+});
export function registerTools(server, wsHandler) {
- // List all available tools
+ // Determine project root path from environment variable or default to parent of Assets folder
+ const projectPath = process.env.UNITY_PROJECT_PATH || path.resolve(process.cwd());
+ // List all available tools (both Unity and filesystem tools)
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [
+ // Unity Editor tools
{
name: 'get_current_scene_info',
description: 'Retrieve information about the current scene in Unity Editor with configurable detail level',
@@ -162,6 +212,77 @@ export function registerTools(server, wsHandler) {
type: 'object',
description: 'Returns detailed information about the current Unity Editor state, project settings, and environment'
}
+ },
+ // Filesystem tools - defined alongside Unity tools
+ {
+ name: "read_file",
+ description: "Read the contents of a file from the Unity project. Paths are relative to the project's Assets folder unless specified as absolute. For example, use 'Scenes/MainScene.unity' to read Assets/Scenes/MainScene.unity.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'file'],
+ inputSchema: zodToJsonSchema(ReadFileArgsSchema),
+ },
+ {
+ name: "read_multiple_files",
+ description: "Read the contents of multiple files from the Unity project simultaneously.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'file', 'batch'],
+ inputSchema: zodToJsonSchema(ReadMultipleFilesArgsSchema),
+ },
+ {
+ name: "write_file",
+ description: "Create a new file or completely overwrite an existing file in the Unity project.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'file', 'write'],
+ inputSchema: zodToJsonSchema(WriteFileArgsSchema),
+ },
+ {
+ name: "edit_file",
+ description: "Make precise edits to a text file in the Unity project. Returns a git-style diff showing changes.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'file', 'edit'],
+ inputSchema: zodToJsonSchema(EditFileArgsSchema),
+ },
+ {
+ name: "list_directory",
+ description: "Get a listing of all files and directories in a specified path in the Unity project. Paths are relative to the Assets folder unless absolute. For example, use 'Scenes' to list all files in Assets/Scenes directory. Use empty string to list the Assets folder.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'directory', 'list'],
+ inputSchema: zodToJsonSchema(ListDirectoryArgsSchema),
+ },
+ {
+ name: "directory_tree",
+ description: "Get a recursive tree view of files and directories in the Unity project as a JSON structure.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'directory', 'tree'],
+ inputSchema: zodToJsonSchema(DirectoryTreeArgsSchema),
+ },
+ {
+ name: "search_files",
+ description: "Recursively search for files and directories matching a pattern in the Unity project.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'search'],
+ inputSchema: zodToJsonSchema(SearchFilesArgsSchema),
+ },
+ {
+ name: "get_file_info",
+ description: "Retrieve detailed metadata about a file or directory in the Unity project.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'file', 'metadata'],
+ inputSchema: zodToJsonSchema(GetFileInfoArgsSchema),
+ },
+ {
+ name: "find_assets_by_type",
+ description: "Find all Unity assets of a specified type (e.g., Material, Prefab, Script) in the project.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'assets', 'search'],
+ inputSchema: zodToJsonSchema(FindAssetsByTypeArgsSchema),
+ },
+ {
+ name: "list_scripts",
+ description: "List all C# script files in the project, useful for understanding the codebase structure.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'scripts', 'list'],
+ inputSchema: zodToJsonSchema(ListScriptsArgsSchema),
}
],
}));
@@ -203,7 +324,25 @@ export function registerTools(server, wsHandler) {
};
}
}
- // For all other tools, verify connection first
+ // Check if this is a filesystem tool
+ const filesystemTools = [
+ "read_file", "read_multiple_files", "write_file", "edit_file",
+ "list_directory", "directory_tree", "search_files", "get_file_info",
+ "find_assets_by_type", "list_scripts"
+ ];
+ if (filesystemTools.includes(name)) {
+ try {
+ return await handleFilesystemTool(name, args, projectPath);
+ }
+ catch (error) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ return {
+ content: [{ type: "text", text: `Error: ${errorMessage}` }],
+ isError: true,
+ };
+ }
+ }
+ // For all other tools (Unity-specific), verify connection first
if (!wsHandler.isConnected()) {
throw new McpError(ErrorCode.InternalError, 'Unity Editor is not connected. Please first verify the connection using the verify_connection tool, ' +
'and ensure the Unity Editor is running with the MCP plugin and that the WebSocket connection is established.');
diff --git a/mcpServer/build/types.js b/mcpServer/build/types.js
index edf59fe..415aa85 100644
--- a/mcpServer/build/types.js
+++ b/mcpServer/build/types.js
@@ -1,2 +1,13 @@
// MCP Server Types for Unity Integration
-export {};
+export var SceneInfoDetail;
+(function (SceneInfoDetail) {
+ SceneInfoDetail["RootObjectsOnly"] = "RootObjectsOnly";
+ SceneInfoDetail["FullHierarchy"] = "FullHierarchy";
+})(SceneInfoDetail || (SceneInfoDetail = {}));
+export var GameObjectInfoDetail;
+(function (GameObjectInfoDetail) {
+ GameObjectInfoDetail["BasicInfo"] = "BasicInfo";
+ GameObjectInfoDetail["IncludeComponents"] = "IncludeComponents";
+ GameObjectInfoDetail["IncludeChildren"] = "IncludeChildren";
+ GameObjectInfoDetail["IncludeComponentsAndChildren"] = "IncludeComponentsAndChildren";
+})(GameObjectInfoDetail || (GameObjectInfoDetail = {}));
diff --git a/mcpServer/build/websocketHandler.js b/mcpServer/build/websocketHandler.js
index 3b252cd..ac3e261 100644
--- a/mcpServer/build/websocketHandler.js
+++ b/mcpServer/build/websocketHandler.js
@@ -1,6 +1,7 @@
import { WebSocketServer, WebSocket } from 'ws';
export class WebSocketHandler {
wsServer;
+ port;
unityConnection = null;
editorState = {
activeGameObjects: [],
@@ -15,13 +16,14 @@ export class WebSocketHandler {
lastHeartbeat = 0;
connectionEstablished = false;
pendingRequests = {};
- constructor(port = 8080) {
+ constructor(port = 5010) {
+ this.port = port;
// Initialize WebSocket Server
this.wsServer = new WebSocketServer({ port });
this.setupWebSocketServer();
}
setupWebSocketServer() {
- console.error('[Unity MCP] WebSocket server starting on port 8080');
+ console.error(`[Unity MCP] WebSocket server starting on port ${this.port}`);
this.wsServer.on('listening', () => {
console.error('[Unity MCP] WebSocket server is listening for connections');
});
@@ -81,7 +83,7 @@ export class WebSocketHandler {
console.error('[Unity MCP] Error sending handshake:', error);
}
}
- // Rename from sendHeartbeat to sendPing for consistency with protocol
+ // Renamed from sendHeartbeat to sendPing for consistency with protocol
sendPing() {
try {
if (this.unityConnection && this.unityConnection.readyState === WebSocket.OPEN) {
@@ -134,7 +136,8 @@ export class WebSocketHandler {
}
break;
default:
- console.error('[Unity MCP] Unknown message type:', message.type);
+ console.error('[Unity MCP] Unknown message type:');
+ break;
}
}
addLogEntry(logEntry) {
@@ -152,10 +155,12 @@ export class WebSocketHandler {
// Start timing the command execution
this.commandStartTime = Date.now();
// Send the command to Unity
- this.unityConnection.send(JSON.stringify({
- type: 'executeEditorCommand',
- data: { code }
- }));
+ if (this.unityConnection) {
+ this.unityConnection.send(JSON.stringify({
+ type: 'executeEditorCommand',
+ data: { code }
+ }));
+ }
// Wait for result with timeout
return await Promise.race([
new Promise((resolve, reject) => {
@@ -230,7 +235,7 @@ export class WebSocketHandler {
return true;
}
requestEditorState() {
- if (!this.isConnected()) {
+ if (!this.isConnected() || !this.unityConnection) {
return;
}
try {
@@ -245,7 +250,7 @@ export class WebSocketHandler {
}
}
async requestSceneInfo(detailLevel) {
- if (!this.isConnected()) {
+ if (!this.isConnected() || !this.unityConnection) {
throw new Error('Unity Editor is not connected');
}
const requestId = crypto.randomUUID();
@@ -275,7 +280,7 @@ export class WebSocketHandler {
return responsePromise;
}
async requestGameObjectsInfo(instanceIDs, detailLevel) {
- if (!this.isConnected()) {
+ if (!this.isConnected() || !this.unityConnection) {
throw new Error('Unity Editor is not connected');
}
const requestId = crypto.randomUUID();
@@ -305,6 +310,23 @@ export class WebSocketHandler {
}));
return responsePromise;
}
+ // Support for file system tools by adding a method to send generic messages
+ async sendMessage(message) {
+ if (this.unityConnection && this.unityConnection.readyState === WebSocket.OPEN) {
+ const messageStr = typeof message === 'string' ? message : JSON.stringify(message);
+ return new Promise((resolve, reject) => {
+ this.unityConnection.send(messageStr, (err) => {
+ if (err) {
+ reject(err);
+ }
+ else {
+ resolve();
+ }
+ });
+ });
+ }
+ return Promise.resolve();
+ }
async close() {
if (this.unityConnection) {
this.unityConnection.close();
diff --git a/mcpServer/docker-compose.yml b/mcpServer/docker-compose.yml
new file mode 100644
index 0000000..fd318cc
--- /dev/null
+++ b/mcpServer/docker-compose.yml
@@ -0,0 +1,13 @@
+version: '3.8'
+
+services:
+ unity-mcp-server:
+ build: .
+ ports:
+ - "${MCP_WEBSOCKET_PORT:-5010}:${MCP_WEBSOCKET_PORT:-5010}"
+ environment:
+ - MCP_WEBSOCKET_PORT=${MCP_WEBSOCKET_PORT:-5010}
+ restart: unless-stopped
+ volumes:
+ # Optional volume for persisting data if needed
+ - ./logs:/app/logs
diff --git a/mcpServer/docker-compose.yml.meta b/mcpServer/docker-compose.yml.meta
new file mode 100644
index 0000000..3a23cc0
--- /dev/null
+++ b/mcpServer/docker-compose.yml.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 8368306bf6b173448bd61e24127aa30a
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/mcpServer/package-lock.json b/mcpServer/package-lock.json
index fc4b612..4e27235 100644
--- a/mcpServer/package-lock.json
+++ b/mcpServer/package-lock.json
@@ -8,29 +8,58 @@
"name": "unity-mcp-server",
"version": "0.1.0",
"dependencies": {
- "@modelcontextprotocol/sdk": "0.6.0",
- "ws": "^8.16.0"
+ "@modelcontextprotocol/sdk": "1.7.0",
+ "diff": "^5.1.0",
+ "minimatch": "^9.0.3",
+ "ws": "^8.16.0",
+ "zod": "^3.22.4",
+ "zod-to-json-schema": "^3.22.1"
},
"bin": {
"unity-mcp-server": "build/index.js"
},
"devDependencies": {
+ "@types/diff": "^5.0.8",
+ "@types/minimatch": "^5.1.2",
"@types/node": "^20.11.24",
"@types/ws": "^8.5.10",
"typescript": "^5.3.3"
}
},
"node_modules/@modelcontextprotocol/sdk": {
- "version": "0.6.0",
- "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-0.6.0.tgz",
- "integrity": "sha512-9rsDudGhDtMbvxohPoMMyAUOmEzQsOK+XFchh6gZGqo8sx9sBuZQs+CUttXqa8RZXKDaJRCN2tUtgGof7jRkkw==",
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.7.0.tgz",
+ "integrity": "sha512-IYPe/FLpvF3IZrd/f5p5ffmWhMc3aEMuM2wGJASDqC2Ge7qatVCdbfPx3n/5xFeb19xN0j/911M2AaFuircsWA==",
"license": "MIT",
"dependencies": {
"content-type": "^1.0.5",
+ "cors": "^2.8.5",
+ "eventsource": "^3.0.2",
+ "express": "^5.0.1",
+ "express-rate-limit": "^7.5.0",
+ "pkce-challenge": "^4.1.0",
"raw-body": "^3.0.0",
- "zod": "^3.23.8"
+ "zod": "^3.23.8",
+ "zod-to-json-schema": "^3.24.1"
+ },
+ "engines": {
+ "node": ">=18"
}
},
+ "node_modules/@types/diff": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/@types/diff/-/diff-5.2.3.tgz",
+ "integrity": "sha512-K0Oqlrq3kQMaO2RhfrNQX5trmt+XLyom88zS0u84nnIcLvFnRUMRRHmrGny5GSM+kNO9IZLARsdQHDzkhAgmrQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/minimatch": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-5.1.2.tgz",
+ "integrity": "sha512-K0VQKziLUWkVKiRVrx4a40iPaxTUefQmjtkQofBkYRcoaaL/8rhwDWww9qWbrgicNOgnpIsMxyNIUM4+n6dUIA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/node": {
"version": "20.17.24",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.17.24.tgz",
@@ -51,6 +80,104 @@
"@types/node": "*"
}
},
+ "node_modules/accepts": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-types": "^3.0.0",
+ "negotiator": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/balanced-match": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
+ "license": "MIT"
+ },
+ "node_modules/body-parser": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.1.0.tgz",
+ "integrity": "sha512-/hPxh61E+ll0Ujp24Ilm64cykicul1ypfwjVttduAiEdtnJFvLePSrIPk+HMImtNv5270wOGCb1Tns2rybMkoQ==",
+ "license": "MIT",
+ "dependencies": {
+ "bytes": "^3.1.2",
+ "content-type": "^1.0.5",
+ "debug": "^4.4.0",
+ "http-errors": "^2.0.0",
+ "iconv-lite": "^0.5.2",
+ "on-finished": "^2.4.1",
+ "qs": "^6.14.0",
+ "raw-body": "^3.0.0",
+ "type-is": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/body-parser/node_modules/debug": {
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz",
+ "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/body-parser/node_modules/iconv-lite": {
+ "version": "0.5.2",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.5.2.tgz",
+ "integrity": "sha512-kERHXvpSaB4aU3eANwidg79K8FlrN77m8G9V+0vOR3HYaRifrlwMEpT7ZBJqLSEIHnEgJTHcWK82wwLwwKwtag==",
+ "license": "MIT",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/body-parser/node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/body-parser/node_modules/qs": {
+ "version": "6.14.0",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz",
+ "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "side-channel": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=0.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/brace-expansion": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz",
+ "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==",
+ "license": "MIT",
+ "dependencies": {
+ "balanced-match": "^1.0.0"
+ }
+ },
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@@ -60,6 +187,47 @@
"node": ">= 0.8"
}
},
+ "node_modules/call-bind-apply-helpers": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/call-bound": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "get-intrinsic": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/content-disposition": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.0.tgz",
+ "integrity": "sha512-Au9nRL8VNUut/XSzbQA38+M78dzP4D+eqg3gfJHMIHHYa3bg067xj1KxMUWj+VULbiZMowKngFFbKczUrNJ1mg==",
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "5.2.1"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/content-type": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
@@ -69,6 +237,54 @@
"node": ">= 0.6"
}
},
+ "node_modules/cookie": {
+ "version": "0.7.1",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz",
+ "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/cookie-signature": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.6.0"
+ }
+ },
+ "node_modules/cors": {
+ "version": "2.8.5",
+ "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
+ "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==",
+ "license": "MIT",
+ "dependencies": {
+ "object-assign": "^4",
+ "vary": "^1"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/debug": {
+ "version": "4.3.6",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.6.tgz",
+ "integrity": "sha512-O/09Bd4Z1fBrU4VzkhFqVgpPzaGbw6Sm9FEkBT1A/YBXQFGuuSxa1dN2nxgxS34JmKXqYx8CZAwEVoJFImUXIg==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "2.1.2"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
@@ -78,6 +294,318 @@
"node": ">= 0.8"
}
},
+ "node_modules/destroy": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
+ "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8",
+ "npm": "1.2.8000 || >= 1.4.16"
+ }
+ },
+ "node_modules/diff": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/diff/-/diff-5.2.0.tgz",
+ "integrity": "sha512-uIFDxqpRZGZ6ThOk84hEfqWoHx2devRFvpTZcTHur85vImfaxUbTW9Ryh4CpCuDnToOP1CEtXKIgytHBPVff5A==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.3.1"
+ }
+ },
+ "node_modules/dunder-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "gopd": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/ee-first": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
+ "license": "MIT"
+ },
+ "node_modules/encodeurl": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
+ "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/es-define-property": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-errors": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-object-atoms": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/escape-html": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
+ "license": "MIT"
+ },
+ "node_modules/etag": {
+ "version": "1.8.1",
+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/eventsource": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.5.tgz",
+ "integrity": "sha512-LT/5J605bx5SNyE+ITBDiM3FxffBiq9un7Vx0EwMDM3vg8sWKx/tO2zC+LMqZ+smAM0F2hblaDZUVZF0te2pSw==",
+ "license": "MIT",
+ "dependencies": {
+ "eventsource-parser": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/eventsource-parser": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.0.tgz",
+ "integrity": "sha512-T1C0XCUimhxVQzW4zFipdx0SficT651NnkR0ZSH3yQwh+mFMdLfgjABVi4YtMTtaL4s168593DaoaRLMqryavA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/express": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/express/-/express-5.0.1.tgz",
+ "integrity": "sha512-ORF7g6qGnD+YtUG9yx4DFoqCShNMmUKiXuT5oWMHiOvt/4WFbHC6yCwQMTSBMno7AqntNCAzzcnnjowRkTL9eQ==",
+ "license": "MIT",
+ "dependencies": {
+ "accepts": "^2.0.0",
+ "body-parser": "^2.0.1",
+ "content-disposition": "^1.0.0",
+ "content-type": "~1.0.4",
+ "cookie": "0.7.1",
+ "cookie-signature": "^1.2.1",
+ "debug": "4.3.6",
+ "depd": "2.0.0",
+ "encodeurl": "~2.0.0",
+ "escape-html": "~1.0.3",
+ "etag": "~1.8.1",
+ "finalhandler": "^2.0.0",
+ "fresh": "2.0.0",
+ "http-errors": "2.0.0",
+ "merge-descriptors": "^2.0.0",
+ "methods": "~1.1.2",
+ "mime-types": "^3.0.0",
+ "on-finished": "2.4.1",
+ "once": "1.4.0",
+ "parseurl": "~1.3.3",
+ "proxy-addr": "~2.0.7",
+ "qs": "6.13.0",
+ "range-parser": "~1.2.1",
+ "router": "^2.0.0",
+ "safe-buffer": "5.2.1",
+ "send": "^1.1.0",
+ "serve-static": "^2.1.0",
+ "setprototypeof": "1.2.0",
+ "statuses": "2.0.1",
+ "type-is": "^2.0.0",
+ "utils-merge": "1.0.1",
+ "vary": "~1.1.2"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
+ "node_modules/express-rate-limit": {
+ "version": "7.5.0",
+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.5.0.tgz",
+ "integrity": "sha512-eB5zbQh5h+VenMPM3fh+nw1YExi5nMr6HUCR62ELSP11huvxm/Uir1H1QEyTkk5QX6A58pX6NmaTMceKZ0Eodg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/express-rate-limit"
+ },
+ "peerDependencies": {
+ "express": "^4.11 || 5 || ^5.0.0-beta.1"
+ }
+ },
+ "node_modules/finalhandler": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.0.tgz",
+ "integrity": "sha512-/t88Ty3d5JWQbWYgaOGCCYfXRwV1+be02WqYYlL6h0lEiUAMPM8o8qKGO01YIkOHzka2up08wvgYD0mDiI+q3Q==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.0",
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "on-finished": "^2.4.1",
+ "parseurl": "^1.3.3",
+ "statuses": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/finalhandler/node_modules/debug": {
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz",
+ "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/finalhandler/node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/forwarded": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/fresh": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",
+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/function-bind": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-intrinsic": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "es-define-property": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.1.1",
+ "function-bind": "^1.1.2",
+ "get-proto": "^1.0.1",
+ "gopd": "^1.2.0",
+ "has-symbols": "^1.1.0",
+ "hasown": "^2.0.2",
+ "math-intrinsics": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+ "license": "MIT",
+ "dependencies": {
+ "dunder-proto": "^1.0.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/gopd": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-symbols": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/hasown": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
+ "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/http-errors": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
@@ -112,6 +640,217 @@
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
+ "node_modules/ipaddr.js": {
+ "version": "1.9.1",
+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/is-promise": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
+ "license": "MIT"
+ },
+ "node_modules/math-intrinsics": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/media-typer": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",
+ "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/merge-descriptors": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/methods": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
+ "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mime-db": {
+ "version": "1.54.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mime-types": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.0.tgz",
+ "integrity": "sha512-XqoSHeCGjVClAmoGFG3lVFqQFRIrTVw2OH3axRqAcfaw+gHWIfnASS92AV+Rl/mk0MupgZTRHQOjxY6YVnzK5w==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "^1.53.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/minimatch": {
+ "version": "9.0.5",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz",
+ "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==",
+ "license": "ISC",
+ "dependencies": {
+ "brace-expansion": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=16 || 14 >=14.17"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
+ "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==",
+ "license": "MIT"
+ },
+ "node_modules/negotiator": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
+ "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/object-inspect": {
+ "version": "1.13.4",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/on-finished": {
+ "version": "2.4.1",
+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
+ "license": "MIT",
+ "dependencies": {
+ "ee-first": "1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/once": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+ "license": "ISC",
+ "dependencies": {
+ "wrappy": "1"
+ }
+ },
+ "node_modules/parseurl": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/path-to-regexp": {
+ "version": "8.2.0",
+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.2.0.tgz",
+ "integrity": "sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/pkce-challenge": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-4.1.0.tgz",
+ "integrity": "sha512-ZBmhE1C9LcPoH9XZSdwiPtbPHZROwAnMy+kIFQVrnMCxY4Cudlz3gBOpzilgc0jOgRaiT3sIWfpMomW2ar2orQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/proxy-addr": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
+ "license": "MIT",
+ "dependencies": {
+ "forwarded": "0.2.0",
+ "ipaddr.js": "1.9.1"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/qs": {
+ "version": "6.13.0",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz",
+ "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "side-channel": "^1.0.6"
+ },
+ "engines": {
+ "node": ">=0.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/range-parser": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
+ "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/raw-body": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.0.tgz",
@@ -127,18 +866,198 @@
"node": ">= 0.8"
}
},
+ "node_modules/router": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/router/-/router-2.1.0.tgz",
+ "integrity": "sha512-/m/NSLxeYEgWNtyC+WtNHCF7jbGxOibVWKnn+1Psff4dJGOfoXP+MuC/f2CwSmyiHdOIzYnYFp4W6GxWfekaLA==",
+ "license": "MIT",
+ "dependencies": {
+ "is-promise": "^4.0.0",
+ "parseurl": "^1.3.3",
+ "path-to-regexp": "^8.0.0"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
+ "node_modules/safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
+ "node_modules/send": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/send/-/send-1.1.0.tgz",
+ "integrity": "sha512-v67WcEouB5GxbTWL/4NeToqcZiAWEq90N888fczVArY8A79J0L4FD7vj5hm3eUMua5EpoQ59wa/oovY6TLvRUA==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.3.5",
+ "destroy": "^1.2.0",
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "etag": "^1.8.1",
+ "fresh": "^0.5.2",
+ "http-errors": "^2.0.0",
+ "mime-types": "^2.1.35",
+ "ms": "^2.1.3",
+ "on-finished": "^2.4.1",
+ "range-parser": "^1.2.1",
+ "statuses": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
+ "node_modules/send/node_modules/fresh": {
+ "version": "0.5.2",
+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
+ "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/send/node_modules/mime-db": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/send/node_modules/mime-types": {
+ "version": "2.1.35",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "1.52.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/send/node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/serve-static": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.1.0.tgz",
+ "integrity": "sha512-A3We5UfEjG8Z7VkDv6uItWw6HY2bBSBJT1KtVESn6EOoOr2jAxNhxWCLY3jDE2WcuHXByWju74ck3ZgLwL8xmA==",
+ "license": "MIT",
+ "dependencies": {
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "parseurl": "^1.3.3",
+ "send": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
"node_modules/setprototypeof": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
"license": "ISC"
},
+ "node_modules/side-channel": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
+ "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "object-inspect": "^1.13.3",
+ "side-channel-list": "^1.0.0",
+ "side-channel-map": "^1.0.1",
+ "side-channel-weakmap": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-list": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",
+ "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "object-inspect": "^1.13.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-map": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-weakmap": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3",
+ "side-channel-map": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/statuses": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
@@ -157,6 +1076,20 @@
"node": ">=0.6"
}
},
+ "node_modules/type-is": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.0.tgz",
+ "integrity": "sha512-gd0sGezQYCbWSbkZr75mln4YBidWUN60+devscpLF5mtRDUpiaTvKpBNrdaCvel1NdR2k6vclXybU5fBd2i+nw==",
+ "license": "MIT",
+ "dependencies": {
+ "content-type": "^1.0.5",
+ "media-typer": "^1.1.0",
+ "mime-types": "^3.0.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/typescript": {
"version": "5.8.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.2.tgz",
@@ -187,6 +1120,30 @@
"node": ">= 0.8"
}
},
+ "node_modules/utils-merge": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
+ "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4.0"
+ }
+ },
+ "node_modules/vary": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/wrappy": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+ "license": "ISC"
+ },
"node_modules/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.1.tgz",
@@ -216,6 +1173,15 @@
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
+ },
+ "node_modules/zod-to-json-schema": {
+ "version": "3.24.4",
+ "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.24.4.tgz",
+ "integrity": "sha512-0uNlcvgabyrni9Ag8Vghj21drk7+7tp7VTwwR7KxxXXc/3pbXz2PHlDgj3cICahgF1kHm4dExBFj7BXrZJXzig==",
+ "license": "ISC",
+ "peerDependencies": {
+ "zod": "^3.24.1"
+ }
}
}
}
diff --git a/mcpServer/package.json b/mcpServer/package.json
index 26bfaf3..726da6f 100644
--- a/mcpServer/package.json
+++ b/mcpServer/package.json
@@ -16,12 +16,18 @@
"inspector": "npx @modelcontextprotocol/inspector build/index.js"
},
"dependencies": {
- "@modelcontextprotocol/sdk": "0.6.0",
- "ws": "^8.16.0"
+ "@modelcontextprotocol/sdk": "1.7.0",
+ "ws": "^8.16.0",
+ "diff": "^5.1.0",
+ "minimatch": "^9.0.3",
+ "zod": "^3.22.4",
+ "zod-to-json-schema": "^3.22.1"
},
"devDependencies": {
"@types/node": "^20.11.24",
"@types/ws": "^8.5.10",
+ "@types/diff": "^5.0.8",
+ "@types/minimatch": "^5.1.2",
"typescript": "^5.3.3"
}
}
\ No newline at end of file
diff --git a/mcpServer/src/filesystemTools.ts b/mcpServer/src/filesystemTools.ts
new file mode 100644
index 0000000..b84b4cc
--- /dev/null
+++ b/mcpServer/src/filesystemTools.ts
@@ -0,0 +1,594 @@
+import { Server } from '@modelcontextprotocol/sdk/server/index.js';
+import { WebSocketHandler } from './websocketHandler.js';
+import fs from 'fs/promises';
+import path from 'path';
+import { z } from 'zod';
+import { createTwoFilesPatch } from 'diff';
+import { minimatch } from 'minimatch';
+import {
+ ReadFileArgsSchema,
+ ReadMultipleFilesArgsSchema,
+ WriteFileArgsSchema,
+ EditFileArgsSchema,
+ ListDirectoryArgsSchema,
+ DirectoryTreeArgsSchema,
+ SearchFilesArgsSchema,
+ GetFileInfoArgsSchema,
+ FindAssetsByTypeArgsSchema,
+ ListScriptsArgsSchema
+} from './toolDefinitions.js';
+
+// Interface definitions
+interface FileInfo {
+ size: number;
+ created: Date;
+ modified: Date;
+ accessed: Date;
+ isDirectory: boolean;
+ isFile: boolean;
+ permissions: string;
+}
+
+interface TreeEntry {
+ name: string;
+ type: 'file' | 'directory';
+ children?: TreeEntry[];
+}
+
+// Helper functions
+// Updated validatePath function to properly handle empty paths
+async function validatePath(requestedPath: string, assetRootPath: string): Promise {
+ // If path is empty or just quotes, use the asset root path directly
+ if (!requestedPath || requestedPath.trim() === '' || requestedPath.trim() === '""' || requestedPath.trim() === "''") {
+ return assetRootPath;
+ }
+
+ // Clean the path to remove any unexpected quotes or escape characters
+ let cleanPath = requestedPath.replace(/['"\\]/g, '');
+
+ // Handle empty path after cleaning
+ if (!cleanPath || cleanPath.trim() === '') {
+ return assetRootPath;
+ }
+
+ // Normalize path to handle both Windows and Unix-style paths
+ const normalized = path.normalize(cleanPath);
+
+ // For relative paths, join with asset root path
+ // Only check for absolute paths using path.isAbsolute - all other paths are considered relative
+ let absolute;
+ if (path.isAbsolute(normalized)) {
+ absolute = normalized;
+
+ // Additional check: if the absolute path is outside the project and doesn't exist,
+ // try treating it as a relative path first
+ if (!absolute.startsWith(assetRootPath)) {
+ const tryRelative = path.join(assetRootPath, normalized);
+ try {
+ await fs.access(tryRelative);
+ // If we can access it as a relative path, use that instead
+ absolute = tryRelative;
+ } catch {
+ // If we can't access it as a relative path either, keep the original absolute path
+ // and let the next check handle the potential error
+ }
+ }
+ } else {
+ absolute = path.join(assetRootPath, normalized);
+ }
+
+ const resolvedPath = path.resolve(absolute);
+
+ // Ensure we don't escape out of the Unity project folder
+ // Special case for empty path: it should always resolve to the project root
+ if (!resolvedPath.startsWith(assetRootPath) && requestedPath.trim() !== '') {
+ throw new Error(`Access denied: Path ${requestedPath} is outside the Unity project directory`);
+ }
+
+ return resolvedPath;
+}
+
+async function getFileStats(filePath: string): Promise {
+ const stats = await fs.stat(filePath);
+ return {
+ size: stats.size,
+ created: stats.birthtime,
+ modified: stats.mtime,
+ accessed: stats.atime,
+ isDirectory: stats.isDirectory(),
+ isFile: stats.isFile(),
+ permissions: stats.mode.toString(8).slice(-3),
+ };
+}
+
+async function searchFiles(
+ rootPath: string,
+ pattern: string,
+ excludePatterns: string[] = []
+): Promise {
+ const results: string[] = [];
+
+ async function search(currentPath: string) {
+ const entries = await fs.readdir(currentPath, { withFileTypes: true });
+
+ for (const entry of entries) {
+ const fullPath = path.join(currentPath, entry.name);
+
+ try {
+ // Check if path matches any exclude pattern
+ const relativePath = path.relative(rootPath, fullPath);
+ const shouldExclude = excludePatterns.some(pattern => {
+ const globPattern = pattern.includes('*') ? pattern : `**/${pattern}/**`;
+ return minimatch(relativePath, globPattern, { dot: true });
+ });
+
+ if (shouldExclude) {
+ continue;
+ }
+
+ if (entry.name.toLowerCase().includes(pattern.toLowerCase())) {
+ results.push(fullPath);
+ }
+
+ if (entry.isDirectory()) {
+ await search(fullPath);
+ }
+ } catch (error) {
+ // Skip invalid paths during search
+ continue;
+ }
+ }
+ }
+
+ await search(rootPath);
+ return results;
+}
+
+function normalizeLineEndings(text: string): string {
+ return text.replace(/\r\n/g, '\n');
+}
+
+function createUnifiedDiff(originalContent: string, newContent: string, filepath: string = 'file'): string {
+ // Ensure consistent line endings for diff
+ const normalizedOriginal = normalizeLineEndings(originalContent);
+ const normalizedNew = normalizeLineEndings(newContent);
+
+ return createTwoFilesPatch(
+ filepath,
+ filepath,
+ normalizedOriginal,
+ normalizedNew,
+ 'original',
+ 'modified'
+ );
+}
+
+async function applyFileEdits(
+ filePath: string,
+ edits: Array<{oldText: string, newText: string}>,
+ dryRun = false
+): Promise {
+ // Read file content and normalize line endings
+ const content = normalizeLineEndings(await fs.readFile(filePath, 'utf-8'));
+
+ // Apply edits sequentially
+ let modifiedContent = content;
+ for (const edit of edits) {
+ const normalizedOld = normalizeLineEndings(edit.oldText);
+ const normalizedNew = normalizeLineEndings(edit.newText);
+
+ // If exact match exists, use it
+ if (modifiedContent.includes(normalizedOld)) {
+ modifiedContent = modifiedContent.replace(normalizedOld, normalizedNew);
+ continue;
+ }
+
+ // Otherwise, try line-by-line matching with flexibility for whitespace
+ const oldLines = normalizedOld.split('\n');
+ const contentLines = modifiedContent.split('\n');
+ let matchFound = false;
+
+ for (let i = 0; i <= contentLines.length - oldLines.length; i++) {
+ const potentialMatch = contentLines.slice(i, i + oldLines.length);
+
+ // Compare lines with normalized whitespace
+ const isMatch = oldLines.every((oldLine, j) => {
+ const contentLine = potentialMatch[j];
+ return oldLine.trim() === contentLine.trim();
+ });
+
+ if (isMatch) {
+ // Preserve original indentation of first line
+ const originalIndent = contentLines[i].match(/^\s*/)?.[0] || '';
+ const newLines = normalizedNew.split('\n').map((line, j) => {
+ if (j === 0) return originalIndent + line.trimStart();
+ // For subsequent lines, try to preserve relative indentation
+ const oldIndent = oldLines[j]?.match(/^\s*/)?.[0] || '';
+ const newIndent = line.match(/^\s*/)?.[0] || '';
+ if (oldIndent && newIndent) {
+ const relativeIndent = newIndent.length - oldIndent.length;
+ return originalIndent + ' '.repeat(Math.max(0, relativeIndent)) + line.trimStart();
+ }
+ return line;
+ });
+
+ contentLines.splice(i, oldLines.length, ...newLines);
+ modifiedContent = contentLines.join('\n');
+ matchFound = true;
+ break;
+ }
+ }
+
+ if (!matchFound) {
+ throw new Error(`Could not find exact match for edit:\n${edit.oldText}`);
+ }
+ }
+
+ // Create unified diff
+ const diff = createUnifiedDiff(content, modifiedContent, filePath);
+
+ // Format diff with appropriate number of backticks
+ let numBackticks = 3;
+ while (diff.includes('`'.repeat(numBackticks))) {
+ numBackticks++;
+ }
+ const formattedDiff = `${'`'.repeat(numBackticks)}diff\n${diff}${'`'.repeat(numBackticks)}\n\n`;
+
+ if (!dryRun) {
+ await fs.writeFile(filePath, modifiedContent, 'utf-8');
+ }
+
+ return formattedDiff;
+}
+
+async function buildDirectoryTree(currentPath: string, assetRootPath: string, maxDepth: number = 5, currentDepth: number = 0): Promise {
+ if (currentDepth >= maxDepth) {
+ return [{ name: "...", type: "directory" }];
+ }
+
+ const validPath = await validatePath(currentPath, assetRootPath);
+ const entries = await fs.readdir(validPath, { withFileTypes: true });
+ const result: TreeEntry[] = [];
+
+ for (const entry of entries) {
+ const entryData: TreeEntry = {
+ name: entry.name,
+ type: entry.isDirectory() ? 'directory' : 'file'
+ };
+
+ if (entry.isDirectory()) {
+ const subPath = path.join(currentPath, entry.name);
+ entryData.children = await buildDirectoryTree(subPath, assetRootPath, maxDepth, currentDepth + 1);
+ }
+
+ result.push(entryData);
+ }
+
+ return result;
+}
+
+// Function to recognize Unity asset types based on file extension
+function getUnityAssetType(filePath: string): string {
+ const ext = path.extname(filePath).toLowerCase();
+
+ // Common Unity asset types
+ const assetTypes: Record = {
+ '.unity': 'Scene',
+ '.prefab': 'Prefab',
+ '.mat': 'Material',
+ '.fbx': 'Model',
+ '.cs': 'Script',
+ '.anim': 'Animation',
+ '.controller': 'Animator Controller',
+ '.asset': 'ScriptableObject',
+ '.png': 'Texture',
+ '.jpg': 'Texture',
+ '.jpeg': 'Texture',
+ '.tga': 'Texture',
+ '.wav': 'Audio',
+ '.mp3': 'Audio',
+ '.ogg': 'Audio',
+ '.shader': 'Shader',
+ '.compute': 'Compute Shader',
+ '.ttf': 'Font',
+ '.otf': 'Font',
+ '.physicMaterial': 'Physics Material',
+ '.mask': 'Avatar Mask',
+ '.playable': 'Playable',
+ '.mixer': 'Audio Mixer',
+ '.renderTexture': 'Render Texture',
+ '.lighting': 'Lighting Settings',
+ '.shadervariants': 'Shader Variants',
+ '.spriteatlas': 'Sprite Atlas',
+ '.guiskin': 'GUI Skin',
+ '.flare': 'Flare',
+ '.brush': 'Brush',
+ '.overrideController': 'Animator Override Controller',
+ '.preset': 'Preset',
+ '.terrainlayer': 'Terrain Layer',
+ '.signal': 'Signal',
+ '.signalasset': 'Signal Asset',
+ '.giparams': 'Global Illumination Parameters',
+ '.cubemap': 'Cubemap',
+ };
+
+ return assetTypes[ext] || 'Other';
+}
+
+// Handler function to process filesystem tools
+export async function handleFilesystemTool(name: string, args: any, projectPath: string) {
+ switch (name) {
+ case "read_file": {
+ const parsed = ReadFileArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+
+ const validPath = await validatePath(parsed.data.path, projectPath);
+ const content = await fs.readFile(validPath, "utf-8");
+ return {
+ content: [{ type: "text", text: content }],
+ };
+ }
+
+ case "read_multiple_files": {
+ const parsed = ReadMultipleFilesArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+
+ const results = await Promise.all(
+ parsed.data.paths.map(async (filePath: string) => {
+ try {
+ const validPath = await validatePath(filePath, projectPath);
+ const content = await fs.readFile(validPath, "utf-8");
+ return `${filePath}:\n${content}\n`;
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ return `${filePath}: Error - ${errorMessage}`;
+ }
+ }),
+ );
+ return {
+ content: [{ type: "text", text: results.join("\n---\n") }],
+ };
+ }
+
+ case "write_file": {
+ const parsed = WriteFileArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+
+ const validPath = await validatePath(parsed.data.path, projectPath);
+
+ // Ensure directory exists
+ const dirPath = path.dirname(validPath);
+ await fs.mkdir(dirPath, { recursive: true });
+
+ await fs.writeFile(validPath, parsed.data.content, "utf-8");
+ return {
+ content: [{ type: "text", text: `Successfully wrote to ${parsed.data.path}` }],
+ };
+ }
+
+ case "edit_file": {
+ const parsed = EditFileArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+
+ const validPath = await validatePath(parsed.data.path, projectPath);
+ const result = await applyFileEdits(validPath, parsed.data.edits, parsed.data.dryRun);
+ return {
+ content: [{ type: "text", text: result }],
+ };
+ }
+
+ case "list_directory": {
+ const parsed = ListDirectoryArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+
+ const validPath = await validatePath(parsed.data.path, projectPath);
+ const entries = await fs.readdir(validPath, { withFileTypes: true });
+ const formatted = entries
+ .map((entry) => {
+ if (entry.isDirectory()) {
+ return `[DIR] ${entry.name}`;
+ } else {
+ // For files, detect Unity asset type
+ const filePath = path.join(validPath, entry.name);
+ const assetType = getUnityAssetType(filePath);
+ return `[${assetType}] ${entry.name}`;
+ }
+ })
+ .join("\n");
+ return {
+ content: [{ type: "text", text: formatted }],
+ };
+ }
+
+ case "directory_tree": {
+ const parsed = DirectoryTreeArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+
+ const treeData = await buildDirectoryTree(parsed.data.path, projectPath, parsed.data.maxDepth);
+ return {
+ content: [{ type: "text", text: JSON.stringify(treeData, null, 2) }],
+ };
+ }
+
+ case "search_files": {
+ const parsed = SearchFilesArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+
+ const validPath = await validatePath(parsed.data.path, projectPath);
+ const results = await searchFiles(validPath, parsed.data.pattern, parsed.data.excludePatterns);
+ return {
+ content: [{
+ type: "text",
+ text: results.length > 0
+ ? `Found ${results.length} results:\n${results.join("\n")}`
+ : "No matches found"
+ }],
+ };
+ }
+
+ case "get_file_info": {
+ const parsed = GetFileInfoArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+
+ const validPath = await validatePath(parsed.data.path, projectPath);
+ const info = await getFileStats(validPath);
+
+ // Also get Unity-specific info if it's an asset file
+ const additionalInfo: Record = {};
+ if (info.isFile) {
+ additionalInfo.assetType = getUnityAssetType(validPath);
+ }
+
+ const formattedInfo = Object.entries({ ...info, ...additionalInfo })
+ .map(([key, value]) => `${key}: ${value}`)
+ .join("\n");
+
+ return {
+ content: [{ type: "text", text: formattedInfo }],
+ };
+ }
+
+ case "find_assets_by_type": {
+ const parsed = FindAssetsByTypeArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+
+ const validPath = await validatePath(parsed.data.searchPath, projectPath);
+
+ const results: string[] = [];
+ const targetType = parsed.data.assetType.toLowerCase();
+
+ // Recursive function to search for assets
+ async function searchAssets(dir: string) {
+ const entries = await fs.readdir(dir, { withFileTypes: true });
+
+ for (const entry of entries) {
+ const fullPath = path.join(dir, entry.name);
+
+ if (entry.isDirectory()) {
+ await searchAssets(fullPath);
+ } else {
+ const assetType = getUnityAssetType(fullPath);
+ if (assetType.toLowerCase() === targetType) {
+ results.push(fullPath);
+ }
+ }
+ }
+ }
+
+ await searchAssets(validPath);
+
+ return {
+ content: [{
+ type: "text",
+ text: results.length > 0
+ ? `Found ${results.length} ${parsed.data.assetType} assets:\n${results.join("\n")}`
+ : `No ${parsed.data.assetType} assets found`
+ }],
+ };
+ }
+
+ case "list_scripts": {
+ const parsed = ListScriptsArgsSchema.safeParse(args);
+ if (!parsed.success) {
+ return {
+ content: [{ type: "text", text: `Invalid arguments: ${parsed.error}` }],
+ isError: true
+ };
+ }
+
+ const validPath = await validatePath(parsed.data.path, projectPath);
+
+ const scripts: Array<{path: string, name: string}> = [];
+
+ // Recursive function to find C# scripts
+ async function findScripts(dir: string) {
+ const entries = await fs.readdir(dir, { withFileTypes: true });
+
+ for (const entry of entries) {
+ const fullPath = path.join(dir, entry.name);
+
+ if (entry.isDirectory()) {
+ await findScripts(fullPath);
+ } else if (path.extname(entry.name).toLowerCase() === '.cs') {
+ scripts.push({
+ path: fullPath,
+ name: entry.name
+ });
+ }
+ }
+ }
+
+ await findScripts(validPath);
+
+ const formattedScripts = scripts.map(s => `${s.name} (${s.path})`).join("\n");
+
+ return {
+ content: [{
+ type: "text",
+ text: scripts.length > 0
+ ? `Found ${scripts.length} C# scripts:\n${formattedScripts}`
+ : "No C# scripts found"
+ }],
+ };
+ }
+
+ default:
+ return {
+ content: [{ type: "text", text: `Unknown tool: ${name}` }],
+ isError: true,
+ };
+ }
+}
+
+// Register filesystem tools with the MCP server
+// This function is now only a stub that doesn't actually do anything
+// since all tools are registered in toolDefinitions.ts
+export function registerFilesystemTools(server: Server, wsHandler: WebSocketHandler) {
+ // This function is now deprecated as tool registration has moved to toolDefinitions.ts
+ console.log("Filesystem tools are now registered in toolDefinitions.ts");
+}
diff --git a/mcpServer/src/filesystemTools.ts.meta b/mcpServer/src/filesystemTools.ts.meta
new file mode 100644
index 0000000..b50448a
--- /dev/null
+++ b/mcpServer/src/filesystemTools.ts.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 0879cebd8d062b0499f111626e8de524
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/mcpServer/src/index.ts b/mcpServer/src/index.ts
index 04d6b36..ca72282 100644
--- a/mcpServer/src/index.ts
+++ b/mcpServer/src/index.ts
@@ -3,6 +3,8 @@ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { WebSocketHandler } from './websocketHandler.js';
import { registerTools } from './toolDefinitions.js';
+import { registerFilesystemTools } from './filesystemTools.js';
+import path from 'path';
class UnityMCPServer {
private server: Server;
@@ -13,7 +15,7 @@ class UnityMCPServer {
this.server = new Server(
{
name: 'unity-mcp-server',
- version: '0.1.0',
+ version: '0.2.0',
},
{
capabilities: {
@@ -22,11 +24,49 @@ class UnityMCPServer {
}
);
+ // Get port from environment variable or use default
+ // Add port range to try if the default port is taken
+ let wsPort = parseInt(process.env.MCP_WEBSOCKET_PORT || '5010');
+
+ // Determine Unity project path - with improved path sanitization
+ let projectPath = process.env.UNITY_PROJECT_PATH || (() => {
+ // Get the current working directory
+ const cwd = path.resolve(process.cwd());
+ // Find the Assets directory in the path
+ const assetsIndex = cwd.indexOf('Assets');
+ // If Assets is found, truncate the path to include Assets
+ if (assetsIndex !== -1) {
+ return cwd.substring(0, assetsIndex + 'Assets'.length);
+ }
+ // If Assets is not found, return the original path
+ return cwd;
+ })();
+
+ // Sanitize the path to remove any unexpected characters
+ projectPath = projectPath.replace(/["']/g, '');
+
+ // Fix potential issue with backslashes being removed
+ projectPath = path.normalize(projectPath);
+
+ // Make sure path ends with a directory separator if it's missing
+ if (!projectPath.endsWith(path.sep)) {
+ projectPath += path.sep;
+ }
+
+ console.error(`[Unity MCP] Using project path: ${projectPath}`);
+
+ // Set the environment variable for other modules to use
+ process.env.UNITY_PROJECT_PATH = projectPath;
+
// Initialize WebSocket Handler for Unity communication
- this.wsHandler = new WebSocketHandler(8080);
+ // It will automatically try different ports if the initial one is taken
+ this.wsHandler = new WebSocketHandler(wsPort);
// Register MCP tools
registerTools(this.server, this.wsHandler);
+
+ // Register filesystem tools to access Unity project files
+ registerFilesystemTools(this.server, this.wsHandler);
// Error handling
this.server.onerror = (error) => console.error('[MCP Error]', error);
@@ -34,6 +74,12 @@ class UnityMCPServer {
await this.cleanup();
process.exit(0);
});
+
+ // Also handle SIGTERM for clean Docker container shutdown
+ process.on('SIGTERM', async () => {
+ await this.cleanup();
+ process.exit(0);
+ });
}
private async cleanup() {
@@ -47,6 +93,7 @@ class UnityMCPServer {
const transport = new StdioServerTransport();
await this.server.connect(transport);
console.error('[Unity MCP] Server running and ready to accept connections');
+ console.error('[Unity MCP] WebSocket server listening on port', this.wsHandler.port);
}
}
diff --git a/mcpServer/src/toolDefinitions.ts b/mcpServer/src/toolDefinitions.ts
index 6db2899..f8059e6 100644
--- a/mcpServer/src/toolDefinitions.ts
+++ b/mcpServer/src/toolDefinitions.ts
@@ -2,15 +2,76 @@ import { z } from 'zod';
import { WebSocketHandler } from './websocketHandler.js';
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
+import { zodToJsonSchema } from 'zod-to-json-schema';
import {
CallToolRequestSchema,
ListToolsRequestSchema
} from '@modelcontextprotocol/sdk/types.js';
+import path from 'path';
+// Import handleFilesystemTool using ES module syntax instead of require
+import { handleFilesystemTool } from './filesystemTools.js';
+
+// File operation schemas - defined here to be used in tool definitions
+export const ReadFileArgsSchema = z.object({
+ path: z.string().describe('Path to the file to read. Can be absolute or relative to Unity project Assets folder. If empty, defaults to the Assets folder.'),
+});
+
+export const ReadMultipleFilesArgsSchema = z.object({
+ paths: z.array(z.string()).describe('Array of file paths to read. Paths can be absolute or relative to Unity project Assets folder.'),
+});
+
+export const WriteFileArgsSchema = z.object({
+ path: z.string().describe('Path to the file to write. Can be absolute or relative to Unity project Assets folder. If empty, defaults to the Assets folder.'),
+ content: z.string().describe('Content to write to the file'),
+});
+
+export const EditOperation = z.object({
+ oldText: z.string().describe('Text to search for - must match exactly'),
+ newText: z.string().describe('Text to replace with')
+});
+
+export const EditFileArgsSchema = z.object({
+ path: z.string().describe('Path to the file to edit. Can be absolute or relative to Unity project Assets folder. If empty, defaults to the Assets folder.'),
+ edits: z.array(EditOperation).describe('Array of edit operations to apply'),
+ dryRun: z.boolean().default(false).describe('Preview changes using git-style diff format')
+});
+
+export const ListDirectoryArgsSchema = z.object({
+ path: z.string().describe('Path to the directory to list. Can be absolute or relative to Unity project Assets folder. If empty, defaults to the Assets folder. Example: "Scenes" will list all files in the Assets/Scenes directory.'),
+});
+
+export const DirectoryTreeArgsSchema = z.object({
+ path: z.string().describe('Path to the directory to get tree of. Can be absolute or relative to Unity project Assets folder. If empty, defaults to the Assets folder. Example: "Prefabs" will show the tree for Assets/Prefabs.'),
+ maxDepth: z.number().optional().default(5).describe('Maximum depth to traverse'),
+});
+
+export const SearchFilesArgsSchema = z.object({
+ path: z.string().describe('Path to search from. Can be absolute or relative to Unity project Assets folder. If empty, defaults to the Assets folder. Example: "Scripts" will search within Assets/Scripts.'),
+ pattern: z.string().describe('Pattern to search for'),
+ excludePatterns: z.array(z.string()).optional().default([]).describe('Patterns to exclude')
+});
+
+export const GetFileInfoArgsSchema = z.object({
+ path: z.string().describe('Path to the file to get info for. Can be absolute or relative to Unity project Assets folder. If empty, defaults to the Assets folder.'),
+});
+
+export const FindAssetsByTypeArgsSchema = z.object({
+ assetType: z.string().describe('Type of assets to find (e.g., "Material", "Prefab", "Scene")'),
+ searchPath: z.string().optional().default("Assets").describe('Directory to search in. Can be absolute or relative to Unity project Assets folder. Example: "Materials" will search in Assets/Materials.'),
+});
+
+export const ListScriptsArgsSchema = z.object({
+ path: z.string().optional().default("Scripts").describe('Path to look for scripts in. Can be absolute or relative to Unity project Assets folder. If empty, defaults to the Assets/Scripts folder.'),
+});
export function registerTools(server: Server, wsHandler: WebSocketHandler) {
- // List all available tools
+ // Determine project root path from environment variable or default to parent of Assets folder
+ const projectPath = process.env.UNITY_PROJECT_PATH || path.resolve(process.cwd());
+
+ // List all available tools (both Unity and filesystem tools)
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [
+ // Unity Editor tools
{
name: 'get_current_scene_info',
description: 'Retrieve information about the current scene in Unity Editor with configurable detail level',
@@ -169,6 +230,78 @@ export function registerTools(server: Server, wsHandler: WebSocketHandler) {
type: 'object',
description: 'Returns detailed information about the current Unity Editor state, project settings, and environment'
}
+ },
+
+ // Filesystem tools - defined alongside Unity tools
+ {
+ name: "read_file",
+ description: "Read the contents of a file from the Unity project. Paths are relative to the project's Assets folder unless specified as absolute. For example, use 'Scenes/MainScene.unity' to read Assets/Scenes/MainScene.unity.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'file'],
+ inputSchema: zodToJsonSchema(ReadFileArgsSchema),
+ },
+ {
+ name: "read_multiple_files",
+ description: "Read the contents of multiple files from the Unity project simultaneously.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'file', 'batch'],
+ inputSchema: zodToJsonSchema(ReadMultipleFilesArgsSchema),
+ },
+ {
+ name: "write_file",
+ description: "Create a new file or completely overwrite an existing file in the Unity project.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'file', 'write'],
+ inputSchema: zodToJsonSchema(WriteFileArgsSchema),
+ },
+ {
+ name: "edit_file",
+ description: "Make precise edits to a text file in the Unity project. Returns a git-style diff showing changes.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'file', 'edit'],
+ inputSchema: zodToJsonSchema(EditFileArgsSchema),
+ },
+ {
+ name: "list_directory",
+ description: "Get a listing of all files and directories in a specified path in the Unity project. Paths are relative to the Assets folder unless absolute. For example, use 'Scenes' to list all files in Assets/Scenes directory. Use empty string to list the Assets folder.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'directory', 'list'],
+ inputSchema: zodToJsonSchema(ListDirectoryArgsSchema),
+ },
+ {
+ name: "directory_tree",
+ description: "Get a recursive tree view of files and directories in the Unity project as a JSON structure.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'directory', 'tree'],
+ inputSchema: zodToJsonSchema(DirectoryTreeArgsSchema),
+ },
+ {
+ name: "search_files",
+ description: "Recursively search for files and directories matching a pattern in the Unity project.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'search'],
+ inputSchema: zodToJsonSchema(SearchFilesArgsSchema),
+ },
+ {
+ name: "get_file_info",
+ description: "Retrieve detailed metadata about a file or directory in the Unity project.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'file', 'metadata'],
+ inputSchema: zodToJsonSchema(GetFileInfoArgsSchema),
+ },
+ {
+ name: "find_assets_by_type",
+ description: "Find all Unity assets of a specified type (e.g., Material, Prefab, Script) in the project.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'assets', 'search'],
+ inputSchema: zodToJsonSchema(FindAssetsByTypeArgsSchema),
+ },
+ {
+ name: "list_scripts",
+ description: "List all C# script files in the project, useful for understanding the codebase structure.",
+ category: "Filesystem",
+ tags: ['unity', 'filesystem', 'scripts', 'list'],
+ inputSchema: zodToJsonSchema(ListScriptsArgsSchema),
}
],
}));
@@ -214,7 +347,26 @@ export function registerTools(server: Server, wsHandler: WebSocketHandler) {
}
}
- // For all other tools, verify connection first
+ // Check if this is a filesystem tool
+ const filesystemTools = [
+ "read_file", "read_multiple_files", "write_file", "edit_file",
+ "list_directory", "directory_tree", "search_files", "get_file_info",
+ "find_assets_by_type", "list_scripts"
+ ];
+
+ if (filesystemTools.includes(name)) {
+ try {
+ return await handleFilesystemTool(name, args, projectPath);
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ return {
+ content: [{ type: "text", text: `Error: ${errorMessage}` }],
+ isError: true,
+ };
+ }
+ }
+
+ // For all other tools (Unity-specific), verify connection first
if (!wsHandler.isConnected()) {
throw new McpError(
ErrorCode.InternalError,
diff --git a/mcpServer/src/types.ts b/mcpServer/src/types.ts
index a84f3fb..403cb14 100644
--- a/mcpServer/src/types.ts
+++ b/mcpServer/src/types.ts
@@ -2,20 +2,18 @@
// Unity Editor State representation
export interface UnityEditorState {
- activeGameObjects: string[];
- selectedObjects: string[];
+ activeGameObjects: any[];
+ selectedObjects: any[];
playModeState: string;
sceneHierarchy: any;
- // Removed projectStructure property
- timestamp?: string;
- // Enhanced project information fields
+ projectName?: string;
+ unityVersion?: string;
renderPipeline?: string;
buildTarget?: string;
- projectName?: string;
graphicsDeviceType?: string;
- unityVersion?: string;
currentSceneName?: string;
currentScenePath?: string;
+ timestamp?: string;
availableMenuItems?: string[];
}
@@ -129,6 +127,61 @@ export type ServerMessage =
// Command result handling
export interface CommandPromise {
- resolve: (value: any) => void;
+ resolve: (data?: any) => void;
reject: (reason?: any) => void;
+}
+
+export interface TreeEntry {
+ name: string;
+ type: 'file' | 'directory';
+ children?: TreeEntry[];
+}
+
+export interface MCPSceneInfo {
+ name: string;
+ path: string;
+ rootGameObjects: any[];
+ buildIndex: number;
+ isDirty: boolean;
+ isLoaded: boolean;
+}
+
+export interface MCPTransformInfo {
+ position: { x: number, y: number, z: number };
+ rotation: { x: number, y: number, z: number };
+ localPosition: { x: number, y: number, z: number };
+ localRotation: { x: number, y: number, z: number };
+ localScale: { x: number, y: number, z: number };
+}
+
+export interface MCPComponentInfo {
+ type: string;
+ isEnabled: boolean;
+ instanceID: number;
+}
+
+export interface MCPGameObjectDetail {
+ name: string;
+ instanceID: number;
+ path: string;
+ active: boolean;
+ activeInHierarchy: boolean;
+ tag: string;
+ layer: number;
+ layerName: string;
+ isStatic: boolean;
+ transform: MCPTransformInfo;
+ components: MCPComponentInfo[];
+}
+
+export enum SceneInfoDetail {
+ RootObjectsOnly = 'RootObjectsOnly',
+ FullHierarchy = 'FullHierarchy'
+}
+
+export enum GameObjectInfoDetail {
+ BasicInfo = 'BasicInfo',
+ IncludeComponents = 'IncludeComponents',
+ IncludeChildren = 'IncludeChildren',
+ IncludeComponentsAndChildren = 'IncludeComponentsAndChildren'
}
\ No newline at end of file
diff --git a/mcpServer/src/websocketHandler.ts b/mcpServer/src/websocketHandler.ts
index 7b303f8..6a02dc5 100644
--- a/mcpServer/src/websocketHandler.ts
+++ b/mcpServer/src/websocketHandler.ts
@@ -8,6 +8,7 @@ import {
export class WebSocketHandler {
private wsServer: WebSocketServer;
+ public readonly port: number;
private unityConnection: WebSocket | null = null;
private editorState: UnityEditorState = {
activeGameObjects: [],
@@ -28,24 +29,26 @@ export class WebSocketHandler {
type: string;
}> = {};
- constructor(port: number = 8080) {
+ constructor(port: number = 5010) {
+ this.port = port;
+
// Initialize WebSocket Server
this.wsServer = new WebSocketServer({ port });
this.setupWebSocketServer();
}
private setupWebSocketServer() {
- console.error('[Unity MCP] WebSocket server starting on port 8080');
+ console.error(`[Unity MCP] WebSocket server starting on port ${this.port}`);
this.wsServer.on('listening', () => {
console.error('[Unity MCP] WebSocket server is listening for connections');
});
-
+
this.wsServer.on('error', (error) => {
console.error('[Unity MCP] WebSocket server error:', error);
});
-
- this.wsServer.on('connection', (ws: WebSocket) => {
+
+ this.wsServer.on('connection', (ws) => {
console.error('[Unity MCP] Unity Editor connected');
this.unityConnection = ws;
this.connectionEstablished = true;
@@ -53,25 +56,26 @@ export class WebSocketHandler {
// Send a simple handshake message to verify connection
this.sendHandshake();
-
- ws.on('message', (data: Buffer) => {
+
+ ws.on('message', (data) => {
try {
// Update heartbeat on any message
this.lastHeartbeat = Date.now();
- const message = JSON.parse(data.toString()) as UnityMessage;
+ const message = JSON.parse(data.toString());
console.error('[Unity MCP] Received message type:', message.type);
+
this.handleUnityMessage(message);
} catch (error) {
console.error('[Unity MCP] Error handling message:', error);
}
});
-
+
ws.on('error', (error) => {
console.error('[Unity MCP] WebSocket error:', error);
this.connectionEstablished = false;
});
-
+
ws.on('close', () => {
console.error('[Unity MCP] Unity Editor disconnected');
this.unityConnection = null;
@@ -103,7 +107,7 @@ export class WebSocketHandler {
}
}
- // Rename from sendHeartbeat to sendPing for consistency with protocol
+ // Renamed from sendHeartbeat to sendPing for consistency with protocol
private sendPing() {
try {
if (this.unityConnection && this.unityConnection.readyState === WebSocket.OPEN) {
@@ -162,7 +166,8 @@ export class WebSocketHandler {
break;
default:
- console.error('[Unity MCP] Unknown message type:', (message as any).type);
+ console.error('[Unity MCP] Unknown message type:');
+ break;
}
}
@@ -184,10 +189,12 @@ export class WebSocketHandler {
this.commandStartTime = Date.now();
// Send the command to Unity
- this.unityConnection!.send(JSON.stringify({
- type: 'executeEditorCommand',
- data: { code }
- }));
+ if (this.unityConnection) {
+ this.unityConnection.send(JSON.stringify({
+ type: 'executeEditorCommand',
+ data: { code }
+ }));
+ }
// Wait for result with timeout
return await Promise.race([
@@ -292,12 +299,12 @@ export class WebSocketHandler {
}
public requestEditorState() {
- if (!this.isConnected()) {
+ if (!this.isConnected() || !this.unityConnection) {
return;
}
try {
- this.unityConnection!.send(JSON.stringify({
+ this.unityConnection.send(JSON.stringify({
type: 'requestEditorState',
data: {}
}));
@@ -308,7 +315,7 @@ export class WebSocketHandler {
}
public async requestSceneInfo(detailLevel: string): Promise {
- if (!this.isConnected()) {
+ if (!this.isConnected() || !this.unityConnection) {
throw new Error('Unity Editor is not connected');
}
@@ -332,7 +339,7 @@ export class WebSocketHandler {
});
// Send the request to Unity
- this.unityConnection!.send(JSON.stringify({
+ this.unityConnection.send(JSON.stringify({
type: 'getSceneInfo',
data: {
requestId,
@@ -344,7 +351,7 @@ export class WebSocketHandler {
}
public async requestGameObjectsInfo(instanceIDs: number[], detailLevel: string): Promise {
- if (!this.isConnected()) {
+ if (!this.isConnected() || !this.unityConnection) {
throw new Error('Unity Editor is not connected');
}
@@ -368,7 +375,7 @@ export class WebSocketHandler {
});
// Send the request to Unity
- this.unityConnection!.send(JSON.stringify({
+ this.unityConnection.send(JSON.stringify({
type: 'getGameObjectsInfo',
data: {
requestId,
@@ -380,7 +387,25 @@ export class WebSocketHandler {
return responsePromise;
}
- public async close(): Promise {
+ // Support for file system tools by adding a method to send generic messages
+ public async sendMessage(message: string | object) {
+ if (this.unityConnection && this.unityConnection.readyState === WebSocket.OPEN) {
+ const messageStr = typeof message === 'string' ? message : JSON.stringify(message);
+
+ return new Promise((resolve, reject) => {
+ this.unityConnection!.send(messageStr, (err) => {
+ if (err) {
+ reject(err);
+ } else {
+ resolve();
+ }
+ });
+ });
+ }
+ return Promise.resolve();
+ }
+
+ public async close() {
if (this.unityConnection) {
this.unityConnection.close();
this.unityConnection = null;
diff --git a/mcpServer/tsconfig.json b/mcpServer/tsconfig.json
index 44be2a6..86c723f 100644
--- a/mcpServer/tsconfig.json
+++ b/mcpServer/tsconfig.json
@@ -9,7 +9,8 @@
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
- "resolveJsonModule": true
+ "resolveJsonModule": true,
+ "useUnknownInCatchVariables": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]