Open-source Revit MCP server: let Claude and other AI assistants read and edit BIM models, with human approval on every change.
Python aecai-agentsautodeskautomationbimclaudeifcmcpmcp-servermodel-context-protocolnavisworksrevitrevit-addinrevit-apirhino
Implement B6: Navisworks bridge switch v2
A. Sam Mohammad84a86228e64b
diff --git a/packages/navisworks-bridge-addin/NavisworksBridge.csproj b/packages/navisworks-bridge-addin/NavisworksBridge.csprojindex 34a40f9..fdaf6f5 100644--- a/packages/navisworks-bridge-addin/NavisworksBridge.csproj+++ b/packages/navisworks-bridge-addin/NavisworksBridge.csproj@@ -39,5 +39,6 @@</ItemGroup><ItemGroup>+ <PackageReference Include="System.Text.Json" Version="8.0.0" /></ItemGroup></Project>diff --git a/packages/navisworks-bridge-addin/src/BridgeCommandAttribute.cs b/packages/navisworks-bridge-addin/src/BridgeCommandAttribute.csnew file mode 100644index 0000000..b76a3a7--- /dev/null+++ b/packages/navisworks-bridge-addin/src/BridgeCommandAttribute.cs@@ -0,0 +1,19 @@+using System;++namespace NavisworksBridge+{+ [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]+ public sealed class BridgeCommandAttribute : Attribute+ {+ public string Name { get; }+ public bool IsMutating { get; set; }+ public bool ConfirmationRequired { get; set; }++ public BridgeCommandAttribute(string name)+ {+ Name = name;+ IsMutating = true;+ ConfirmationRequired = false;+ }+ }+}diff --git a/packages/navisworks-bridge-addin/src/BridgeCommandFactory.cs b/packages/navisworks-bridge-addin/src/BridgeCommandFactory.csnew file mode 100644index 0000000..fe0bbdc--- /dev/null+++ b/packages/navisworks-bridge-addin/src/BridgeCommandFactory.cs@@ -0,0 +1,86 @@+using System;+using System.Collections.Generic;+using System.Linq;+using System.Text.Json;+using Autodesk.Navisworks.Api;+using Application = Autodesk.Navisworks.Api.Application;++namespace NavisworksBridge+{+ public static class BridgeCommandFactory+ {+ private static readonly Dictionary<string, Func<JsonElement, object>> _handlers = new();+ private static readonly List<object> _capabilities = new();+ private static readonly List<string> _catalog = new();++ static BridgeCommandFactory()+ {+ var methods = typeof(BridgeCommandFactory).GetMethods(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);+ foreach (var method in methods)+ {+ var attr = (BridgeCommandAttribute)Attribute.GetCustomAttribute(method, typeof(BridgeCommandAttribute));+ if (attr != null)+ {+ var func = CreateHandlerDelegate(method);+ _handlers[attr.Name] = func;+ _catalog.Add(attr.Name);++ _capabilities.Add(new+ {+ name = attr.Name,+ is_mutating = attr.IsMutating,+ confirmation_required = attr.ConfirmationRequired+ });+ }+ }+ }++ private static Func<JsonElement, object> CreateHandlerDelegate(System.Reflection.MethodInfo method)+ {+ var parameters = method.GetParameters();+ if (parameters.Length == 0)+ {+ return (payload) => method.Invoke(null, null);+ }+ else if (parameters.Length == 1)+ {+ return (payload) => method.Invoke(null, new object[] { payload });+ }+ throw new InvalidOperationException($"Method {method.Name} has invalid parameters.");+ }++ public static object Execute(string tool, JsonElement payload)+ {+ if (_handlers.TryGetValue(tool, out var handler))+ {+ try+ {+ return handler(payload);+ }+ catch (System.Reflection.TargetInvocationException ex)+ {+ throw ex.InnerException ?? ex;+ }+ }+ return new { status = "error", message = $"Unknown tool: {tool}" };+ }++ public static List<string> GetToolCatalog() => _catalog;++ public static object GetCapabilities() => _capabilities;++ [BridgeCommand("navisworks.health", IsMutating = false)]+ private static object ExecuteHealth()+ {+ var doc = Application.ActiveDocument;+ return new+ {+ status = "healthy",+ application = "navisworks",+ title = doc.Title ?? "",+ fileName = doc.FileName ?? "",+ modelsCount = doc.Models.Count+ };+ }+ }+}diff --git a/packages/navisworks-bridge-addin/src/BridgeServer.cs b/packages/navisworks-bridge-addin/src/BridgeServer.csindex 52c1f47..92435a2 100644--- a/packages/navisworks-bridge-addin/src/BridgeServer.cs+++ b/packages/navisworks-bridge-addin/src/BridgeServer.cs@@ -1,100 +1,297 @@using System;using System.IO;using System.Net;+using System.Text;+using System.Text.Json;+using System.Threading;using System.Threading.Tasks;using System.Windows.Threading;-using Autodesk.Navisworks.Api;-using Application = Autodesk.Navisworks.Api.Application;namespace NavisworksBridge{public class BridgeServer{- private HttpListener? _listener;- private bool _isRunning;+ private readonly HttpListener _listener;private readonly Dispatcher _dispatcher;+ private CancellationTokenSource _cts = new();+ private readonly DateTime _startTime = DateTime.UtcNow;+ private Task? _listenerTask;+ private int _totalRequests = 0;+ private int _activeConnections = 0;+ private SemaphoreSlim _concurrencySemaphore = new(10, 10);+ private const long MaxRequestSizeBytes = 5 * 1024 * 1024; // 5 MBpublic BridgeServer(Dispatcher dispatcher){_dispatcher = dispatcher;+ _listener = new HttpListener();+ SessionToken = Guid.NewGuid().ToString("N") + Guid.NewGuid().ToString("N");++ var legacyEnv = Environment.GetEnvironmentVariable("MCP_NAVISWORKS_LEGACY_PORT");+ LegacyMode = string.IsNullOrEmpty(legacyEnv) || legacyEnv.ToLower() == "true" || legacyEnv == "1";}+ public string SessionToken { get; }+ public int Port { get; private set; }+ public string RegistryFilePath { get; private set; }+ public bool LegacyMode { get; }++ public bool IsListening { get; private set; }+ public bool IsRunning => IsListening;+ public int ActiveConnections => _activeConnections;+ public int TotalRequests => _totalRequests;+ public double UptimeSeconds => (DateTime.UtcNow - _startTime).TotalSeconds;+public void Start(){- _listener = new HttpListener();- _listener.Prefixes.Add("http://127.0.0.1:3002/");- _listener.Start();- _isRunning = true;- Task.Run(ListenAsync);+ if (IsListening) return;++ try+ {+ if (_cts.IsCancellationRequested)+ _cts = new CancellationTokenSource();++ if (LegacyMode)+ {+ Port = 3002;+ }+ else+ {+ var tcp = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0);+ tcp.Start();+ Port = ((IPEndPoint)tcp.LocalEndpoint).Port;+ tcp.Stop();+ }++ var prefix = $"http://127.0.0.1:{Port}/";+ _listener.Prefixes.Clear();+ _listener.Prefixes.Add(prefix);++ _listener.Start();+ _listenerTask = Task.Run(ListenerLoop, _cts.Token);+ IsListening = true;++ WriteRegistryFile(prefix);+ }+ catch (Exception ex)+ {+ IsListening = false;+ throw new InvalidOperationException("Failed to start listener", ex);+ }}public void Stop(){- _isRunning = false;- _listener?.Stop();+ if (!IsListening) return;++ try+ {+ _cts.Cancel();+ _listener.Stop();+ IsListening = false;++ if (!string.IsNullOrEmpty(RegistryFilePath) && File.Exists(RegistryFilePath))+ {+ try { File.Delete(RegistryFilePath); } catch { }+ }+ }+ catch (Exception)+ {+ // ignore+ }}- private async Task ListenAsync()+ private async Task ListenerLoop(){- while (_isRunning && _listener != null && _listener.IsListening)+ while (!_cts.Token.IsCancellationRequested){try{var context = await _listener.GetContextAsync();- ProcessRequest(context);+ _ = Task.Run(() => HandleRequest(context), _cts.Token);+ }+ catch (HttpListenerException) when (_cts.Token.IsCancellationRequested)+ {+ break;}catch (Exception){- // Listener stopped or error+ // ignore}}}- private void ProcessRequest(HttpListenerContext context)+ private async Task HandleRequest(HttpListenerContext context){- if (context.Request.Url.AbsolutePath == "/health")+ Interlocked.Increment(ref _activeConnections);+ Interlocked.Increment(ref _totalRequests);++ try{- SendJsonResponse(context, "{\"status\":\"healthy\",\"application\":\"navisworks\"}");+ await _concurrencySemaphore.WaitAsync(_cts.Token);+ }+ catch (OperationCanceledException)+ {+ Interlocked.Decrement(ref _activeConnections);return;}- if (context.Request.Url.AbsolutePath == "/execute" && context.Request.HttpMethod == "POST")- {- using var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding);- var requestBody = reader.ReadToEnd();-- _dispatcher.Invoke(() =>- {- try- {- var doc = Application.ActiveDocument;- // For now, just return active document title as proof of concept- string title = doc.Title?.Replace("\"", "\\\"") ?? "";- string fileName = doc.FileName?.Replace("\"", "\\\"") ?? "";- string jsonResponse = "{\"status\":\"success\",\"title\":\"" + title + "\",\"fileName\":\"" + fileName + "\",\"modelsCount\":" + doc.Models.Count + "}";- SendJsonResponse(context, jsonResponse);- }- catch (Exception ex)- {- string errMsg = ex.Message.Replace("\"", "\\\"");- SendJsonResponse(context, "{\"status\":\"error\",\"message\":\"" + errMsg + "\"}");- }- });- return;+ try+ {+ if (context.Request.ContentLength64 > MaxRequestSizeBytes)+ {+ Respond(context, 413, new { error = "Payload too large" });+ return;+ }++ var path = context.Request.Url?.AbsolutePath ?? "/";++ if (path == "/health")+ {+ await HandleHealth(context);+ }+ else if (path == "/tools")+ {+ await HandleTools(context);+ }+ else if (path == "/capabilities")+ {+ await HandleCapabilities(context);+ }+ else if (path == "/execute" && context.Request.HttpMethod == "POST")+ {+ await HandleExecute(context);+ }+ else+ {+ Respond(context, 404, new { error = "Not found" });+ }+ }+ catch (Exception ex)+ {+ Respond(context, 500, new { error = ex.Message });}+ finally+ {+ _concurrencySemaphore.Release();+ Interlocked.Decrement(ref _activeConnections);+ }+ }- // Not found- context.Response.StatusCode = 404;- context.Response.Close();+ private async Task HandleExecute(HttpListenerContext context)+ {+ if (!LegacyMode)+ {+ var authHeader = context.Request.Headers["Authorization"];+ if (string.IsNullOrEmpty(authHeader) || authHeader != $"Bearer {SessionToken}")+ {+ Respond(context, 401, new { error = "Unauthorized" });+ return;+ }+ }++ using var reader = new StreamReader(context.Request.InputStream);+ var body = await reader.ReadToEndAsync();+ var doc = JsonDocument.Parse(body);+ var root = doc.RootElement;++ var requestId = root.GetProperty("request_id").GetString() ?? Guid.NewGuid().ToString();+ var tool = root.GetProperty("tool").GetString() ?? string.Empty;+ var payload = root.TryGetProperty("payload", out var p) ? p : new JsonElement();++ object result = null;+ Exception error = null;++ // Execute on Main Thread+ await _dispatcher.InvokeAsync(() =>+ {+ try+ {+ result = BridgeCommandFactory.Execute(tool, payload);+ }+ catch (Exception ex)+ {+ error = ex;+ }+ });++ if (error != null)+ {+ Respond(context, 200, new { request_id = requestId, status = "error", message = error.Message });+ }+ else+ {+ // Unpack result if it returned a raw object or dictionary+ Respond(context, 200, result);+ }+ }++ private Task HandleHealth(HttpListenerContext context)+ {+ var health = new+ {+ status = "healthy",+ version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString(),+ uptime_seconds = (DateTime.UtcNow - _startTime).TotalSeconds,+ };+ Respond(context, 200, health);+ return Task.CompletedTask;+ }++ private Task HandleTools(HttpListenerContext context)+ {+ var tools = BridgeCommandFactory.GetToolCatalog();+ Respond(context, 200, new { tools });+ return Task.CompletedTask;+ }++ private Task HandleCapabilities(HttpListenerContext context)+ {+ var tools = BridgeCommandFactory.GetCapabilities();+ Respond(context, 200, new { tools });+ return Task.CompletedTask;}- private void SendJsonResponse(HttpListenerContext context, string json)+ private void WriteRegistryFile(string endpoint){- byte[] buffer = System.Text.Encoding.UTF8.GetBytes(json);+ try+ {+ int pid = System.Diagnostics.Process.GetCurrentProcess().Id;+ var registryDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "AECModelBridge", "registry");+ Directory.CreateDirectory(registryDir);++ RegistryFilePath = Path.Combine(registryDir, $"navisworks-{pid}.json");++ var data = new+ {+ provider_id = "navisworks",+ endpoint = endpoint.TrimEnd('/'),+ pid = pid,+ host_version = "Navisworks",+ connector_version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "1.0",+ protocol_version = 2,+ capability_digest = "dynamic",+ session_token = SessionToken,+ started_at = _startTime.ToString("o")+ };++ var json = JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true });+ File.WriteAllText(RegistryFilePath, json);+ }+ catch (Exception)+ {+ // ignore+ }+ }++ private void Respond(HttpListenerContext context, int statusCode, object data)+ {+ context.Response.StatusCode = statusCode;context.Response.ContentType = "application/json";- context.Response.ContentLength64 = buffer.Length;+ var json = JsonSerializer.Serialize(data);+ var buffer = Encoding.UTF8.GetBytes(json);context.Response.OutputStream.Write(buffer, 0, buffer.Length);- context.Response.OutputStream.Close();+ context.Response.Close();}}}diff --git a/packages/navisworks-bridge-addin/src/MainPlugin.cs b/packages/navisworks-bridge-addin/src/MainPlugin.csindex 82e20fd..3618824 100644--- a/packages/navisworks-bridge-addin/src/MainPlugin.cs+++ b/packages/navisworks-bridge-addin/src/MainPlugin.cs@@ -16,11 +16,10 @@ namespace NavisworksBridge{try{- // Capture the main thread dispatchervar dispatcher = Dispatcher.CurrentDispatcher;_server = new BridgeServer(dispatcher);_server.Start();- System.Windows.Forms.MessageBox.Show("AEC Model Bridge for Navisworks started on port 3002.");+ System.Windows.Forms.MessageBox.Show($"AEC Model Bridge for Navisworks started on port {_server.Port}.\nLegacy Mode: {_server.LegacyMode}");}catch (Exception ex){