Skip to content

Open-source Revit MCP server: let Claude and other AI assistants read and edit BIM models, with human approval on every change.

feat: Add Revit Bridge addin and Python server/client for Revit inter-process communication.

A. Sam Mohammade2468fa3ac91
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/bridge/client.py b/packages/mcp-server-revit/src/revit_mcp_server/bridge/client.py
index 6eac81d..ddd1c89 100644
--- a/packages/mcp-server-revit/src/revit_mcp_server/bridge/client.py
+++ b/packages/mcp-server-revit/src/revit_mcp_server/bridge/client.py
@@ -1,14 +1,89 @@
from __future__ import annotations
import httpx
+import time
+import uuid
+from typing import Any
+
+from ..errors import BridgeError
class BridgeClient:
- def __init__(self, base_url: str):
- self.base_url = base_url.rstrip("/")
- self.client = httpx.Client(base_url=self.base_url, timeout=30.0)
+ def __init__(self, base_url: str = "http://127.0.0.1:3000", timeout: int = 30):
+ self.base_url = base_url.rstrip('/')
+ self.timeout = timeout
+ self._tool_catalog: list[str] | None = None
+
+ def initialize(self) -> None:
+ """Check bridge health and fetch tool catalog on startup."""
+ try:
+ health = self._get("/health")
+ if health.get("status") != "healthy":
+ raise BridgeError(f"Bridge unhealthy: {health}")
+
+ tools_resp = self._get("/tools")
+ self._tool_catalog = tools_resp.get("tools", [])
+
+ except httpx.RequestError as e:
+ raise BridgeError(
+ f"Bridge unreachable at {self.base_url}. "
+ f"Ensure Revit is running with RevitMCP add-in loaded. Error: {e}"
+ ) from e
+
+ def call_tool(self, tool: str, payload: dict[str, Any]) -> dict[str, Any]:
+ """Execute a tool with retry logic."""
+ if self._tool_catalog and tool not in self._tool_catalog:
+ raise BridgeError(
+ f"Tool '{tool}' not available in bridge. "
+ f"Available tools: {', '.join(self._tool_catalog)}"
+ )
+
+ request_id = str(uuid.uuid4())
+ last_error = None
+
+ for attempt in range(3):
+ try:
+ response = self._post(
+ "/execute",
+ {"tool": tool, "payload": payload, "request_id": request_id}
+ )
+
+ if response.get("status") == "error":
+ raise BridgeError(
+ f"Bridge error: {response.get('message')}\n"
+ f"Stack: {response.get('stack_trace', 'N/A')}"
+ )
+
+ return response.get("result", {})
+
+ except httpx.RequestError as e:
+ last_error = e
+ if attempt < 2:
+ delay = 2 ** attempt # 1s, 2s
+ time.sleep(delay)
+ continue
+ raise BridgeError(
+ f"Bridge request failed after 3 attempts: {e}"
+ ) from e
+
+ raise BridgeError(f"Bridge request failed: {last_error}") from last_error
def send_tool(self, tool_name: str, payload: dict) -> dict:
- response = self.client.post("/tools", json={"tool": tool_name, "payload": payload})
- response.raise_for_status()
- return response.json()
+ """Legacy method for backward compatibility."""
+ return self.call_tool(tool_name, payload)
+
+ def _get(self, path: str) -> dict[str, Any]:
+ with httpx.Client() as client:
+ resp = client.get(f"{self.base_url}{path}", timeout=self.timeout)
+ resp.raise_for_status()
+ return resp.json()
+
+ def _post(self, path: str, data: dict[str, Any]) -> dict[str, Any]:
+ with httpx.Client() as client:
+ resp = client.post(
+ f"{self.base_url}{path}",
+ json=data,
+ timeout=self.timeout
+ )
+ resp.raise_for_status()
+ return resp.json()
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/server.py b/packages/mcp-server-revit/src/revit_mcp_server/server.py
index 1f43ea8..6808fdd 100644
--- a/packages/mcp-server-revit/src/revit_mcp_server/server.py
+++ b/packages/mcp-server-revit/src/revit_mcp_server/server.py
@@ -37,7 +37,11 @@ class MCPServer:
if not self.config.bridge_url:
raise ValueError("Bridge mode requires MCP_REVIT_BRIDGE_URL")
bridge_factory = factory or (lambda url: BridgeClient(url))
- return bridge_factory(self.config.bridge_url)
+ bridge = bridge_factory(self.config.bridge_url)
+ # Initialize bridge connection and fetch tool catalog
+ if hasattr(bridge, 'initialize'):
+ bridge.initialize()
+ return bridge
return MockBridge()
def handle_tool(self, tool_name: str, payload: dict) -> dict:
diff --git a/packages/revit-bridge-addin/RevitBridge.addin b/packages/revit-bridge-addin/RevitBridge.addin
index d62c523..bc6b0fd 100644
--- a/packages/revit-bridge-addin/RevitBridge.addin
+++ b/packages/revit-bridge-addin/RevitBridge.addin
@@ -1,11 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<RevitAddIns>
<AddIn Type="Application">
- <Name>RevitBridge</Name>
- <Assembly>$(AppData)\RevitBridge\Bridge\bin\Release\RevitBridge.dll</Assembly>
- <AddInId>00000000-0000-0000-0000-000000000000</AddInId>
+ <Name>RevitMCP Bridge</Name>
+ <Assembly>C:\ProgramData\RevitMCP\bin\RevitBridge.dll</Assembly>
+ <AddInId>6721F048-9A81-4DE6-8543-B485A6329B92</AddInId>
<FullClassName>RevitBridge.Bridge.App</FullClassName>
<VendorId>RevitMCP</VendorId>
- <VendorDescription>Revit MCP bridge add-in</VendorDescription>
+ <VendorDescription>MCP server bridge for Autodesk Revit</VendorDescription>
</AddIn>
</RevitAddIns>
diff --git a/packages/revit-bridge-addin/RevitBridge.csproj b/packages/revit-bridge-addin/RevitBridge.csproj
index 0b590ce..20f4ec1 100644
--- a/packages/revit-bridge-addin/RevitBridge.csproj
+++ b/packages/revit-bridge-addin/RevitBridge.csproj
@@ -3,11 +3,28 @@
<TargetFramework>net48</TargetFramework>
<AssemblyName>RevitBridge</AssemblyName>
<RootNamespace>RevitBridge</RootNamespace>
- <OutputType>WinExe</OutputType>
+ <OutputType>Library</OutputType>
+ <RevitVersion Condition="'$(RevitVersion)'==''">2024</RevitVersion>
+ <OutputPath>bin\$(Configuration)\$(RevitVersion)\</OutputPath>
+ <LangVersion>latest</LangVersion>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
- <Reference Include="RevitAPI" />
- <Reference Include="RevitAPIUI" />
+ <Reference Include="RevitAPI">
+ <HintPath Condition="'$(RevitVersion)'=='2024'">C:\Program Files\Autodesk\Revit 2024\RevitAPI.dll</HintPath>
+ <HintPath Condition="'$(RevitVersion)'=='2025'">C:\Program Files\Autodesk\Revit 2025\RevitAPI.dll</HintPath>
+ <Private>False</Private>
+ </Reference>
+ <Reference Include="RevitAPIUI">
+ <HintPath Condition="'$(RevitVersion)'=='2024'">C:\Program Files\Autodesk\Revit 2024\RevitAPIUI.dll</HintPath>
+ <HintPath Condition="'$(RevitVersion)'=='2025'">C:\Program Files\Autodesk\Revit 2025\RevitAPIUI.dll</HintPath>
+ <Private>False</Private>
+ </Reference>
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Serilog" Version="3.1.1" />
+ <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
</Project>
diff --git a/packages/revit-bridge-addin/RevitBridge.sln b/packages/revit-bridge-addin/RevitBridge.sln
index 3c868a2..c2dc3c5 100644
--- a/packages/revit-bridge-addin/RevitBridge.sln
+++ b/packages/revit-bridge-addin/RevitBridge.sln
@@ -1,6 +1,6 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RevitBridge", "RevitBridge.csproj", "{DEADBEEF-0000-0000-0000-000000000000}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RevitBridge", "RevitBridge.csproj", "{BAA5F4FE-0925-4F41-BAD2-9599B6889517}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -8,9 +8,9 @@ Global
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {DEADBEEF-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {DEADBEEF-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {DEADBEEF-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {DEADBEEF-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
+ {BAA5F4FE-0925-4F41-BAD2-9599B6889517}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {BAA5F4FE-0925-4F41-BAD2-9599B6889517}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {BAA5F4FE-0925-4F41-BAD2-9599B6889517}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {BAA5F4FE-0925-4F41-BAD2-9599B6889517}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
diff --git a/packages/revit-bridge-addin/src/Bridge/App.cs b/packages/revit-bridge-addin/src/Bridge/App.cs
index cabcf00..1ca300c 100644
--- a/packages/revit-bridge-addin/src/Bridge/App.cs
+++ b/packages/revit-bridge-addin/src/Bridge/App.cs
@@ -1,21 +1,81 @@
+using System;
+using System.IO;
using Autodesk.Revit.UI;
+using Serilog;
namespace RevitBridge.Bridge;
public class App : IExternalApplication
{
private BridgeServer? _server;
+ private CommandQueue? _queue;
+ private ExternalEvent? _externalEvent;
+
+ public static string? RevitVersion { get; private set; }
+ public static string? ActiveDocumentName { get; private set; }
public Result OnStartup(UIControlledApplication application)
{
- _server = new BridgeServer();
- _server.Start();
- return Result.Succeeded;
+ try
+ {
+ InitializeLogging();
+
+ RevitVersion = application.ControlledApplication.VersionNumber;
+
+ _queue = new CommandQueue();
+ var handler = new RevitCommandExecutor(_queue);
+ _externalEvent = ExternalEvent.Create(handler);
+
+ _server = new BridgeServer(_queue, _externalEvent);
+ _server.Start();
+
+ application.ControlledApplication.DocumentChanged += (sender, args) =>
+ {
+ ActiveDocumentName = args.GetDocument()?.Title;
+ };
+
+ Log.Information("RevitMCP Bridge started for Revit {Version}", RevitVersion);
+ return Result.Succeeded;
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex, "Failed to start RevitMCP Bridge");
+ return Result.Failed;
+ }
}
public Result OnShutdown(UIControlledApplication application)
{
- _server?.Stop();
- return Result.Succeeded;
+ try
+ {
+ _server?.Stop();
+ _externalEvent?.Dispose();
+ Log.Information("RevitMCP Bridge stopped");
+ Log.CloseAndFlush();
+ return Result.Succeeded;
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error during shutdown");
+ return Result.Failed;
+ }
+ }
+
+ private void InitializeLogging()
+ {
+ var logPath = Path.Combine(
+ Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
+ "RevitMCP", "Logs", "bridge.jsonl"
+ );
+
+ Directory.CreateDirectory(Path.GetDirectoryName(logPath)!);
+
+ Log.Logger = new LoggerConfiguration()
+ .WriteTo.File(
+ logPath,
+ rollingInterval: RollingInterval.Day,
+ outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
+ )
+ .CreateLogger();
}
}
diff --git a/packages/revit-bridge-addin/src/Bridge/BridgeCommandFactory.cs b/packages/revit-bridge-addin/src/Bridge/BridgeCommandFactory.cs
index 6cc5ee3..b0e86fc 100644
--- a/packages/revit-bridge-addin/src/Bridge/BridgeCommandFactory.cs
+++ b/packages/revit-bridge-addin/src/Bridge/BridgeCommandFactory.cs
@@ -1,83 +1,193 @@
using System;
+using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
+using Autodesk.Revit.DB;
+using Autodesk.Revit.UI;
namespace RevitBridge.Bridge;
-internal static class BridgeCommandFactory
+public static class BridgeCommandFactory
{
- private static readonly string[] AuditTools = new[]
+ public static object Execute(UIApplication app, string tool, JsonElement payload)
{
- "revit.model_health_summary",
- "revit.warning_triage_report",
- "revit.naming_standards_audit",
- "revit.parameter_compliance_audit",
- "revit.shared_parameter_binding_audit",
- "revit.view_template_compliance_check",
- "revit.tag_coverage_audit",
- "revit.room_space_completeness_report",
- "revit.link_monitor_report",
- "revit.coordinate_sanity_check",
- "revit.batch_place_views_on_sheets",
- "revit.titleblock_fill_from_csv",
- "revit.create_print_set",
- "revit.export_report",
- "revit.publish_package_builder",
- };
-
- public static object Execute(string tool, JsonElement payload)
+ return tool switch
+ {
+ "revit.health" => ExecuteHealth(app),
+ "revit.open_document" => ExecuteOpenDocument(app, payload),
+ "revit.list_views" => ExecuteListViews(app),
+ "revit.export_schedules" => ExecuteExportSchedules(app, payload),
+ "revit.export_pdf_by_sheet_set" => ExecuteExportPdf(app, payload),
+ _ => new { status = "error", message = $"Unknown tool: {tool}" }
+ };
+ }
+
+ public static List<string> GetToolCatalog()
{
- if (AuditTools.Contains(tool))
+ return new List<string>
{
- return new
- {
- tool,
- status = "ok",
- issues = 0,
- summary = "Audit completed",
- };
- }
+ "revit.health",
+ "revit.open_document",
+ "revit.list_views",
+ "revit.export_schedules",
+ "revit.export_pdf_by_sheet_set"
+ };
+ }
- return tool switch
+ private static object ExecuteHealth(UIApplication app)
+ {
+ var doc = app.ActiveUIDocument?.Document;
+ return new
{
- "revit.health" => new { status = "healthy", timestamp = DateTime.UtcNow },
- "revit.open_document" => new { document_id = "doc-123", title = "Model", path = @"C:\RevitProjects\demo.rvt" },
- "revit.list_views" => new { views = new[] { "Floor Plan", "3D View", "Ceiling Plan" } },
- "revit.export_schedules" => new { exported = 4, path = TryGetString(payload, "output_path") ?? @"C:\RevitProjects\schedules.csv" },
- "revit.export_quantities" => new { categories_exported = 5, path = TryGetString(payload, "output_path") ?? @"C:\RevitProjects\quantities.json" },
- "revit.baseline_export" => new { snapshot_id = $"baseline-{DateTime.UtcNow:yyyyMMddHHmmss}" },
- "revit.baseline_diff" => new { differences = new[] { "Walls added", "Rooms updated" }, baseline_a = "baseline-1", baseline_b = "baseline-2" },
- "revit.batch_create_sheets_from_csv" => new { created = TryGetInt(payload, "count") ?? 3 },
- "revit.export_pdf_by_sheet_set" => new { file_path = TryGetString(payload, "output_path") ?? @"C:\RevitProjects\printset.pdf", status = "ok" },
- "revit.export_dwg_by_sheet_set" => new { file_path = TryGetString(payload, "output_path") ?? @"C:\RevitProjects\drawings.dwg", status = "ok" },
- "revit.export_ifc_named_setup" => new { file_path = TryGetString(payload, "output_path") ?? @"C:\RevitProjects\model.ifc", status = "ok" },
- "revit.export_report" => new { issues = 0, file_path = TryGetString(payload, "output_path") ?? @"C:\RevitProjects\report.json" },
- _ => new { status = "noop", tool, payload = payload.ToString() },
+ status = "healthy",
+ revit_version = app.Application.VersionNumber,
+ revit_build = app.Application.VersionBuild,
+ active_document = doc?.Title ?? "none",
+ document_is_modified = doc?.IsModified ?? false,
+ username = app.Application.Username
};
}
- private static string? TryGetString(JsonElement payload, string key)
+ private static object ExecuteOpenDocument(UIApplication app, JsonElement payload)
{
- if (payload.ValueKind != JsonValueKind.Object)
+ var path = payload.GetProperty("path").GetString();
+ if (string.IsNullOrEmpty(path))
+ throw new ArgumentException("Missing 'path' parameter");
+
+ var docPath = new FilePath(path);
+ var openOptions = new OpenOptions();
+ var doc = app.Application.OpenDocumentFile(docPath, openOptions);
+
+ return new
{
- return null;
- }
+ path = doc.PathName,
+ title = doc.Title,
+ is_family = doc.IsFamilyDocument,
+ is_modified = doc.IsModified
+ };
+ }
- return payload.TryGetProperty(key, out var property) ? property.GetString() : null;
+ private static object ExecuteListViews(UIApplication app)
+ {
+ var doc = app.ActiveUIDocument?.Document;
+ if (doc == null)
+ throw new InvalidOperationException("No active document");
+
+ var views = new FilteredElementCollector(doc)
+ .OfClass(typeof(View))
+ .Cast<View>()
+ .Where(v => !v.IsTemplate)
+ .Select(v => new
+ {
+ id = v.Id.IntegerValue,
+ name = v.Name,
+ type = v.ViewType.ToString(),
+ scale = v.Scale,
+ detail_level = v.DetailLevel.ToString()
+ })
+ .ToList();
+
+ return new { views, count = views.Count };
}
- private static int? TryGetInt(JsonElement payload, string key)
+ private static object ExecuteExportSchedules(UIApplication app, JsonElement payload)
{
- if (payload.ValueKind != JsonValueKind.Object)
+ var doc = app.ActiveUIDocument?.Document;
+ if (doc == null)
+ throw new InvalidOperationException("No active document");
+
+ var outputPath = payload.GetProperty("output_path").GetString();
+ if (string.IsNullOrEmpty(outputPath))
+ throw new ArgumentException("Missing 'output_path' parameter");
+
+ var schedules = new FilteredElementCollector(doc)
+ .OfClass(typeof(ViewSchedule))
+ .Cast<ViewSchedule>()
+ .ToList();
+
+ var exported = new List<string>();
+
+ using (var trans = new Transaction(doc, "Export Schedules"))
{
- return null;
+ trans.Start();
+
+ foreach (var schedule in schedules)
+ {
+ try
+ {
+ var options = new ViewScheduleExportOptions
+ {
+ Title = false,
+ FieldDelimiter = ",",
+ TextQualifier = ExportTextQualifier.DoubleQuote
+ };
+
+ var filename = $"{SanitizeFileName(schedule.Name)}.csv";
+ var fullPath = System.IO.Path.Combine(outputPath, filename);
+ schedule.Export(outputPath, filename, options);
+ exported.Add(fullPath);
+ }
+ catch (Exception ex)
+ {
+ // Log error but continue with other schedules
+ Serilog.Log.Warning(ex, "Failed to export schedule {ScheduleName}", schedule.Name);
+ }
+ }
+
+ trans.Commit();
}
- if (payload.TryGetProperty(key, out var property) && property.TryGetInt32(out var value))
+ return new { schedules = exported, count = exported.Count };
+ }
+
+ private static object ExecuteExportPdf(UIApplication app, JsonElement payload)
+ {
+ var doc = app.ActiveUIDocument?.Document;
+ if (doc == null)
+ throw new InvalidOperationException("No active document");
+
+ var outputPath = payload.GetProperty("output_path").GetString();
+ if (string.IsNullOrEmpty(outputPath))
+ throw new ArgumentException("Missing 'output_path' parameter");
+
+ var sheets = new FilteredElementCollector(doc)
+ .OfClass(typeof(ViewSheet))
+ .Cast<ViewSheet>()
+ .Where(s => !s.IsPlaceholder)
+ .Select(s => s.Id)
+ .ToList();
+
+ if (sheets.Count == 0)
{
- return value;
+ return new
+ {
+ output_path = outputPath,
+ sheets_exported = 0,
+ status = "no_sheets",
+ message = "No sheets found in document"
+ };
}
- return null;
+ var options = new PDFExportOptions
+ {
+ FileName = System.IO.Path.GetFileNameWithoutExtension(outputPath),
+ Combine = true
+ };
+
+ var exportDir = System.IO.Path.GetDirectoryName(outputPath);
+ doc.Export(exportDir, sheets, options);
+
+ return new
+ {
+ output_path = outputPath,
+ sheets_exported = sheets.Count,
+ status = "exported"
+ };
+ }
+
+ private static string SanitizeFileName(string fileName)
+ {
+ var invalidChars = System.IO.Path.GetInvalidFileNameChars();
+ return new string(fileName.Select(c => invalidChars.Contains(c) ? '_' : c).ToArray());
}
}
diff --git a/packages/revit-bridge-addin/src/Bridge/BridgeServer.cs b/packages/revit-bridge-addin/src/Bridge/BridgeServer.cs
index 4f6644f..d5c8701 100644
--- a/packages/revit-bridge-addin/src/Bridge/BridgeServer.cs
+++ b/packages/revit-bridge-addin/src/Bridge/BridgeServer.cs
@@ -1,15 +1,28 @@
+using System;
using System.IO;
using System.Net;
+using System.Text;
using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+using Autodesk.Revit.UI;
+using Serilog;
namespace RevitBridge.Bridge;
public class BridgeServer
{
private readonly HttpListener _listener;
+ private readonly CommandQueue _queue;
+ private readonly ExternalEvent _externalEvent;
+ private readonly CancellationTokenSource _cts = new();
+ private readonly DateTime _startTime = DateTime.UtcNow;
+ private Task? _listenerTask;
- public BridgeServer(string prefix = "http://localhost:3000/")
+ public BridgeServer(CommandQueue queue, ExternalEvent externalEvent, string prefix = "http://127.0.0.1:3000/")
{
+ _queue = queue;
+ _externalEvent = externalEvent;
_listener = new HttpListener();
_listener.Prefixes.Add(prefix);
}
@@ -17,34 +30,129 @@ public class BridgeServer
public void Start()
{
_listener.Start();
+ _listenerTask = Task.Run(ListenerLoop, _cts.Token);
+ Log.Information("BridgeServer started on {Prefixes}", string.Join(", ", _listener.Prefixes));
}
public void Stop()
{
- if (_listener.IsListening)
+ _cts.Cancel();
+ _listener.Stop();
+ _listenerTask?.Wait(5000);
+ Log.Information("BridgeServer stopped");
+ }
+
+ private async Task ListenerLoop()
+ {
+ while (!_cts.Token.IsCancellationRequested)
{
- _listener.Stop();
+ try
+ {
+ var context = await _listener.GetContextAsync();
+ _ = Task.Run(() => HandleRequest(context), _cts.Token);
+ }
+ catch (HttpListenerException) when (_cts.Token.IsCancellationRequested)
+ {
+ break;
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Listener error");
+ }
}
}
- public void ProcessNext()
+ private async Task HandleRequest(HttpListenerContext context)
{
- if (!_listener.IsListening)
+ try
{
- return;
+ var path = context.Request.Url?.AbsolutePath ?? "/";
+
+ if (path == "/health")
+ {
+ await HandleHealth(context);
+ }
+ else if (path == "/tools")
+ {
+ await HandleTools(context);
+ }
+ else if (path == "/execute" && context.Request.HttpMethod == "POST")
+ {
+ await HandleExecute(context);
+ }
+ else
+ {
+ Respond(context, 404, new { error = "Not found" });
+ }
}
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Request handling error");
+ Respond(context, 500, new { error = ex.Message });
+ }
+ }
+
+ private async Task HandleExecute(HttpListenerContext context)
+ {
+ var startTime = DateTime.UtcNow;
- var context = _listener.GetContext();
using var reader = new StreamReader(context.Request.InputStream);
- var body = reader.ReadToEnd();
- using var doc = JsonDocument.Parse(body);
+ 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.GetProperty("payload");
- object result = BridgeCommandFactory.Execute(tool, payload);
- var buffer = JsonSerializer.SerializeToUtf8Bytes(new { status = "ok", tool, result });
+ var request = new CommandRequest
+ {
+ RequestId = requestId,
+ Tool = tool,
+ Payload = payload
+ };
+
+ Log.Information("Request received: {RequestId} {Tool} from {ClientIP}",
+ requestId, tool, context.Request.RemoteEndPoint?.Address.ToString());
+
+ _queue.Enqueue(request);
+ _externalEvent.Raise();
+
+ var response = await _queue.WaitForResponse(requestId);
+
+ Log.Information("Request completed: {RequestId} {Tool} {Status} {DurationMs}ms",
+ requestId, tool, response.Status, (DateTime.UtcNow - startTime).TotalMilliseconds);
+
+ Respond(context, 200, response);
+ }
+
+ private Task HandleHealth(HttpListenerContext context)
+ {
+ var health = new
+ {
+ status = "healthy",
+ version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString(),
+ uptime_seconds = (DateTime.UtcNow - _startTime).TotalSeconds,
+ revit_version = App.RevitVersion ?? "unknown",
+ active_document = App.ActiveDocumentName ?? "none"
+ };
+ 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 void Respond(HttpListenerContext context, int statusCode, object data)
+ {
+ context.Response.StatusCode = statusCode;
context.Response.ContentType = "application/json";
+ var json = JsonSerializer.Serialize(data);
+ var buffer = Encoding.UTF8.GetBytes(json);
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
context.Response.Close();
}
diff --git a/packages/revit-bridge-addin/src/Bridge/CommandQueue.cs b/packages/revit-bridge-addin/src/Bridge/CommandQueue.cs
new file mode 100644
index 0000000..9ab7a6b
--- /dev/null
+++ b/packages/revit-bridge-addin/src/Bridge/CommandQueue.cs
@@ -0,0 +1,71 @@
+using System;
+using System.Collections.Concurrent;
+using System.Threading.Tasks;
+using System.Text.Json;
+
+namespace RevitBridge.Bridge;
+
+public class CommandRequest
+{
+ public string RequestId { get; set; } = string.Empty;
+ public string Tool { get; set; } = string.Empty;
+ public JsonElement Payload { get; set; }
+}
+
+public class CommandResponse
+{
+ public string Status { get; set; } = "ok";
+ public string Tool { get; set; } = string.Empty;
+ public object? Result { get; set; }
+ public string? Message { get; set; }
+ public string? StackTrace { get; set; }
+}
+
+public class CommandQueue
+{
+ private readonly ConcurrentQueue<CommandRequest> _queue = new();
+ private readonly ConcurrentDictionary<string, TaskCompletionSource<CommandResponse>> _pending = new();
+
+ public void Enqueue(CommandRequest request)
+ {
+ var tcs = new TaskCompletionSource<CommandResponse>();
+ _pending[request.RequestId] = tcs;
+ _queue.Enqueue(request);
+ }
+
+ public bool TryDequeue(out CommandRequest? request)
+ {
+ return _queue.TryDequeue(out request);
+ }
+
+ public void Complete(string requestId, CommandResponse response)
+ {
+ if (_pending.TryRemove(requestId, out var tcs))
+ {
+ tcs.SetResult(response);
+ }
+ }
+
+ public async Task<CommandResponse> WaitForResponse(string requestId, int timeoutMs = 30000)
+ {
+ if (!_pending.TryGetValue(requestId, out var tcs))
+ {
+ throw new InvalidOperationException($"No pending request: {requestId}");
+ }
+
+ var timeoutTask = Task.Delay(timeoutMs);
+ var completedTask = await Task.WhenAny(tcs.Task, timeoutTask);
+
+ if (completedTask == timeoutTask)
+ {
+ _pending.TryRemove(requestId, out _);
+ return new CommandResponse
+ {
+ Status = "error",
+ Message = $"Request {requestId} timed out after {timeoutMs}ms"
+ };
+ }
+
+ return await tcs.Task;
+ }
+}
diff --git a/packages/revit-bridge-addin/src/Bridge/ExternalEventHandler.cs b/packages/revit-bridge-addin/src/Bridge/ExternalEventHandler.cs
index 43f1528..84b96f0 100644
--- a/packages/revit-bridge-addin/src/Bridge/ExternalEventHandler.cs
+++ b/packages/revit-bridge-addin/src/Bridge/ExternalEventHandler.cs
@@ -1,13 +1,56 @@
+using System;
using Autodesk.Revit.UI;
+using Serilog;
namespace RevitBridge.Bridge;
-public class ExternalEventHandler : IExternalEventHandler
+public class RevitCommandExecutor : IExternalEventHandler
{
+ private readonly CommandQueue _queue;
+
+ public RevitCommandExecutor(CommandQueue queue)
+ {
+ _queue = queue;
+ }
+
public void Execute(UIApplication app)
{
- // Placeholder executor; future iterations will queue BridgeCommandFactory requests
+ while (_queue.TryDequeue(out var request))
+ {
+ if (request == null) continue;
+
+ try
+ {
+ Log.Information("Executing {Tool} request {RequestId}", request.Tool, request.RequestId);
+
+ var result = BridgeCommandFactory.Execute(app, request.Tool, request.Payload);
+
+ var response = new CommandResponse
+ {
+ Status = "ok",
+ Tool = request.Tool,
+ Result = result
+ };
+
+ _queue.Complete(request.RequestId, response);
+ Log.Information("Completed {Tool} request {RequestId}", request.Tool, request.RequestId);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error executing {Tool} request {RequestId}", request.Tool, request.RequestId);
+
+ var errorResponse = new CommandResponse
+ {
+ Status = "error",
+ Tool = request.Tool,
+ Message = ex.Message,
+ StackTrace = ex.StackTrace
+ };
+
+ _queue.Complete(request.RequestId, errorResponse);
+ }
+ }
}
- public string GetName() => "Revit MCP Bridge Executor";
+ public string GetName() => "RevitMCP Command Executor";
}
diff --git a/scripts/build-addin.ps1 b/scripts/build-addin.ps1
index 6397f88..8e7aa58 100644
--- a/scripts/build-addin.ps1
+++ b/scripts/build-addin.ps1
@@ -1,11 +1,52 @@
param(
- [string]$RevitSdkPath = $env:REVIT_SDK
+ [string]$RevitVersion = "2024",
+ [string]$Configuration = "Release"
)
-if (-not $RevitSdkPath) {
- Write-Error "Set REVIT_SDK to the SDK root before building."
+$ErrorActionPreference = "Stop"
+
+$projectPath = "$PSScriptRoot\..\packages\revit-bridge-addin\RevitBridge.csproj"
+
+if (-not (Test-Path $projectPath)) {
+ Write-Error "Project not found: $projectPath"
exit 1
}
-Write-Host "Building Revit bridge add-in using SDK at $RevitSdkPath"
-# Placeholder: call msbuild on packages/revit-bridge-addin/RevitBridge.csproj
+# Find msbuild using vswhere
+$vsWherePath = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
+
+if (Test-Path $vsWherePath) {
+ $msbuild = & $vsWherePath -latest -requires Microsoft.Component.MSBuild -find MSBuild\**\Bin\MSBuild.exe | Select-Object -First 1
+} else {
+ # Fallback to dotnet build if vswhere not available
+ Write-Host "vswhere not found, using dotnet build..." -ForegroundColor Yellow
+ $msbuild = "dotnet"
+ $buildCommand = "build"
+}
+
+if (-not $msbuild) {
+ Write-Error "MSBuild or dotnet not found. Install Visual Studio Build Tools or .NET SDK."
+ exit 1
+}
+
+Write-Host "Building RevitBridge for Revit $RevitVersion ($Configuration)..." -ForegroundColor Cyan
+
+if ($msbuild -like "*dotnet*") {
+ & $msbuild build $projectPath `
+ -c $Configuration `
+ -p:RevitVersion=$RevitVersion `
+ -v:minimal
+} else {
+ & $msbuild $projectPath `
+ /p:Configuration=$Configuration `
+ /p:RevitVersion=$RevitVersion `
+ /v:minimal
+}
+
+if ($LASTEXITCODE -ne 0) {
+ Write-Error "Build failed with exit code $LASTEXITCODE"
+ exit $LASTEXITCODE
+}
+
+$outputPath = "packages\revit-bridge-addin\bin\$Configuration\$RevitVersion\RevitBridge.dll"
+Write-Host "Build succeeded: $outputPath" -ForegroundColor Green