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
feat: implement Universal Reflection Bridge (Batch 9)
A. Sam Mohammad60b8257c82e1
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/mcp_server.py b/packages/mcp-server-revit/src/revit_mcp_server/mcp_server.pyindex 6233a6c..f05dcd8 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/mcp_server.py+++ b/packages/mcp-server-revit/src/revit_mcp_server/mcp_server.py@@ -706,6 +706,10 @@ async def call_tool(name: str, arguments: Any) -> list[TextContent]:Tool(name="revit_get_room_boundary", description="Get room geometric boundary loops", inputSchema={"type": "object", "properties": {"room_id": {"type": "integer"}}, "required": ["room_id"]}),Tool(name="revit_get_project_location", description="Get project base and survey points", inputSchema={"type": "object", "properties": {}}),Tool(name="revit_get_warnings", description="Get current project warnings", inputSchema={"type": "object", "properties": {}}),+ # Batch 9: Universal Reflection Bridge (10k+ Tools)+ Tool(name="revit_invoke_method", description="Invoke any Revit API method dynamically using Reflection", inputSchema={"type": "object", "properties": {"class_name": {"type": "string"}, "method_name": {"type": "string"}, "arguments": {"type": "array", "items": {}}, "target_id": {"type": "string"}, "use_transaction": {"type": "boolean", "default": true}}, "required": ["class_name", "method_name", "arguments"]}),+ Tool(name="revit_reflect_get", description="Get any Revit property value dynamically", inputSchema={"type": "object", "properties": {"target_id": {"type": "string"}, "property_name": {"type": "string"}}, "required": ["target_id", "property_name"]}),+ Tool(name="revit_reflect_set", description="Set any Revit property value dynamically", inputSchema={"type": "object", "properties": {"target_id": {"type": "string"}, "property_name": {"type": "string"}, "value": {}}, "required": ["target_id", "property_name", "value"]}),],"level": arguments.get("level", "L1")}),@@ -813,6 +817,25 @@ async def call_tool(name: str, arguments: Any) -> list[TextContent]:"category2": arguments.get("category2"),"tolerance": arguments.get("tolerance", 0.01)}),+ "revit_get_warnings": ("revit.get_warnings", {}),++ # Batch 9: Universal Reflection Bridge+ "revit_invoke_method": ("revit.invoke_method", {+ "class_name": arguments.get("class_name"),+ "method_name": arguments.get("method_name"),+ "arguments": arguments.get("arguments"),+ "target_id": arguments.get("target_id"),+ "use_transaction": arguments.get("use_transaction", True)+ }),+ "revit_reflect_get": ("revit.reflect_get", {+ "target_id": arguments.get("target_id"),+ "property_name": arguments.get("property_name")+ }),+ "revit_reflect_set": ("revit.reflect_set", {+ "target_id": arguments.get("target_id"),+ "property_name": arguments.get("property_name"),+ "value": arguments.get("value")+ }),}if name not in tool_mapping:@@ -871,3 +894,4 @@ if __name__ == "__main__":+diff --git a/packages/revit-bridge-addin/src/Bridge/BridgeCommandFactory.cs b/packages/revit-bridge-addin/src/Bridge/BridgeCommandFactory.csindex 290c9e0..07c8a20 100644--- a/packages/revit-bridge-addin/src/Bridge/BridgeCommandFactory.cs+++ b/packages/revit-bridge-addin/src/Bridge/BridgeCommandFactory.cs@@ -322,7 +322,12 @@ public static class BridgeCommandFactory"revit.calculate_material_quantities","revit.get_room_boundary","revit.get_project_location",- "revit.get_warnings"+ "revit.get_warnings",++ // Batch 9: Universal Reflection+ "revit.invoke_method",+ "revit.reflect_get",+ "revit.reflect_set"};}@@ -4195,4 +4200,97 @@ public static class BridgeCommandFactoryreturn new { warnings = result, count = warnings.Count };}++ // ==================== BATCH 9: UNIVERSAL REFLECTION BRIDGE ====================++ private static object ExecuteInvokeMethod(UIApplication app, JsonElement payload)+ {+ var doc = app.ActiveUIDocument?.Document;+ if (doc == null) throw new InvalidOperationException("No active document");++ string className = payload.GetProperty("class_name").GetString();+ string methodName = payload.GetProperty("method_name").GetString();+ JsonElement args = payload.GetProperty("arguments");+ string targetId = payload.TryGetProperty("target_id", out var t) ? t.GetString() : null;++ using (var trans = new Transaction(doc, $"Invoke {methodName}"))+ {+ if (payload.TryGetProperty("use_transaction", out var ut) && ut.GetBoolean())+ trans.Start();++ try+ {+ object result = ReflectionHelper.InvokeMethod(doc, className, methodName, args, targetId);++ if (trans.GetStatus() == TransactionStatus.Started)+ trans.Commit();++ return result ?? new { status = "void" };+ }+ catch (Exception ex)+ {+ if (trans.GetStatus() == TransactionStatus.Started)+ trans.RollBack();+ throw new Exception($"Invocation failed: {ex.Message}", ex);+ }+ }+ }++ private static object ExecuteReflectGet(UIApplication app, JsonElement payload)+ {+ var doc = app.ActiveUIDocument?.Document;+ if (doc == null) throw new InvalidOperationException("No active document");++ string targetId = payload.GetProperty("target_id").GetString();+ string propertyName = payload.GetProperty("property_name").GetString();++ object target = ReflectionHelper.GetObject(targetId, doc);+ if (target == null) throw new Exception($"Target '{targetId}' not found");++ var prop = target.GetType().GetProperty(propertyName);+ if (prop == null) throw new Exception($"Property '{propertyName}' not found on type '{target.GetType().Name}'");++ object value = prop.GetValue(target);++ if (value == null) return null;+ if (value.GetType().IsPrimitive || value is string || value is double || value is int || value is bool) return value;+ if (value is ElementId eid) return eid.Value;+ if (value is Element e) return e.Id.Value;++ string refId = ReflectionHelper.RegisterObject(value);+ return new { type = "reference", id = refId, class_name = value.GetType().Name, str = value.ToString() };+ }++ private static object ExecuteReflectSet(UIApplication app, JsonElement payload)+ {+ var doc = app.ActiveUIDocument?.Document;+ if (doc == null) throw new InvalidOperationException("No active document");++ string targetId = payload.GetProperty("target_id").GetString();+ string propertyName = payload.GetProperty("property_name").GetString();+ JsonElement valueElement = payload.GetProperty("value");++ using (var trans = new Transaction(doc, $"Set {propertyName}"))+ {+ trans.Start();+ object target = ReflectionHelper.GetObject(targetId, doc);+ if (target == null) throw new Exception($"Target '{targetId}' not found");++ var prop = target.GetType().GetProperty(propertyName);+ if (prop == null) throw new Exception($"Property '{propertyName}' not found on type '{target.GetType().Name}'");++ object value = ReflectionHelper.ParseArgument(valueElement, doc);++ // Convert type if needed+ if (value != null && !prop.PropertyType.IsAssignableFrom(value.GetType()))+ {+ value = Convert.ChangeType(value, prop.PropertyType);+ }++ prop.SetValue(target, value);+ trans.Commit();+ }++ return new { status = "success", target_id = targetId, property = propertyName };+ }}diff --git a/packages/revit-bridge-addin/src/Bridge/ReflectionHelper.cs b/packages/revit-bridge-addin/src/Bridge/ReflectionHelper.csnew file mode 100644index 0000000..f3311d6--- /dev/null+++ b/packages/revit-bridge-addin/src/Bridge/ReflectionHelper.cs@@ -0,0 +1,182 @@+using System;+using System.Collections.Generic;+using System.Linq;+using System.Reflection;+using System.Text.Json;+using Autodesk.Revit.DB;++namespace RevitBridge.Bridge+{+ public static class ReflectionHelper+ {+ // transient object registry (for things that aren't Elements, e.g. XYZ points, Curves)+ private static Dictionary<string, object> _objectRegistry = new Dictionary<string, object>();+ private static int _objectIdCounter = 0;++ public static string RegisterObject(object obj)+ {+ if (obj == null) return null;+ if (obj is Element elem) return elem.Id.ToString(); // Elements use their native ID++ string id = $"obj_{++_objectIdCounter}";+ _objectRegistry[id] = obj;+ return id;+ }++ public static object GetObject(string id, Document doc)+ {+ if (string.IsNullOrEmpty(id)) return null;++ // Check if it's a register object+ if (_objectRegistry.ContainsKey(id)) return _objectRegistry[id];++ // Check if it's an Element ID+ if (int.TryParse(id, out int elemIdInt))+ {+ return doc.GetElement(new ElementId((long)elemIdInt));+ }+ // For 2024+, ElementId is long, but sticking to int parsing for compatibility/simplicity where possible or try long+ if (long.TryParse(id, out long elemIdLong))+ {+ return doc.GetElement(new ElementId(elemIdLong));+ }++ return null;+ }++ public static void ClearRegistry()+ {+ _objectRegistry.Clear();+ _objectIdCounter = 0;+ }++ public static object ParseArgument(JsonElement arg, Document doc)+ {+ switch (arg.ValueKind)+ {+ case JsonValueKind.String:+ string s = arg.GetString();+ // Check for object reference syntax "@obj_123" or just "obj_123"?+ // Let's assume explicit object ref object structure is passed like {"type": "ref", "id": "..."}+ // OR simple strings are just strings.+ // But wait, the LLM might pass "Wall" as a string for an enum.+ return s;++ case JsonValueKind.Number:+ if (arg.TryGetInt32(out int i)) return i;+ return arg.GetDouble();++ case JsonValueKind.True: return true;+ case JsonValueKind.False: return false;+ case JsonValueKind.Null: return null;++ case JsonValueKind.Object:+ if (arg.TryGetProperty("type", out var typeProp) && typeProp.GetString() == "reference")+ {+ string refId = arg.GetProperty("id").GetString();+ return GetObject(refId, doc);+ }+ // Handle simple structs like XYZ if passed as raw JSON?+ if (arg.TryGetProperty("x", out _) && arg.TryGetProperty("y", out _) && arg.TryGetProperty("z", out _))+ {+ return new XYZ(arg.GetProperty("x").GetDouble(), arg.GetProperty("y").GetDouble(), arg.GetProperty("z").GetDouble());+ }+ return null; // or generic dict?++ default:+ return null;+ }+ }++ public static Type ResolveType(string typeName)+ {+ // Try fundamental types+ if (typeName == "int" || typeName == "System.Int32") return typeof(int);+ if (typeName == "double" || typeName == "System.Double") return typeof(double);+ if (typeName == "string" || typeName == "System.String") return typeof(string);+ if (typeName == "bool" || typeName == "System.Boolean") return typeof(bool);++ // Search in loaded assemblies (RevitAPI, RevitAPIUI)+ var assemblies = AppDomain.CurrentDomain.GetAssemblies()+ .Where(a => a.FullName.StartsWith("RevitAPI") || a.FullName.StartsWith("System"));++ foreach (var asm in assemblies)+ {+ var type = asm.GetType(typeName) ?? asm.GetType("Autodesk.Revit.DB." + typeName) ?? asm.GetType("Autodesk.Revit.UI." + typeName);+ if (type != null) return type;+ }++ return null;+ }++ public static object InvokeMethod(Document doc, string typeName, string methodName, JsonElement argsElement, string targetId = null)+ {+ Type type = ResolveType(typeName);+ if (type == null) throw new Exception($"Type '{typeName}' not found.");++ object target = null;+ if (!string.IsNullOrEmpty(targetId))+ {+ target = GetObject(targetId, doc);+ if (target == null) throw new Exception($"Target object '{targetId}' not found.");+ }++ // Parse arguments+ List<object> args = new List<object>();+ if (argsElement.ValueKind == JsonValueKind.Array)+ {+ foreach (var argJson in argsElement.EnumerateArray())+ {+ args.Add(ParseArgument(argJson, doc));+ }+ }++ // Find best matching method (Simplistic matching for MVP)+ // A real production implementation needs robust overload resolution.+ var flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;+ var methods = type.GetMethods(flags).Where(m => m.Name == methodName && m.GetParameters().Length == args.Count).ToList();++ if (methods.Count == 0) throw new Exception($"Method '{methodName}' with {args.Count} arguments not found on type '{type.Name}'.");++ // Try to pick the first one that works (risky but MVP)+ MethodInfo methodToInvoke = methods.First();+ // TODO: Better parameter type checking/casting++ // Cast args to match signature+ var parameters = methodToInvoke.GetParameters();+ object[] finalArgs = new object[args.Count];+ for (int i = 0; i < args.Count; i++)+ {+ var targetType = parameters[i].ParameterType;+ var val = args[i];++ // Handle Enums conversions from String/Int+ if (targetType.IsEnum)+ {+ if (val is string s) val = Enum.Parse(targetType, s);+ else if (val is int n) val = Enum.ToObject(targetType, n);+ }++ // Convert.ChangeType for primitives+ if (val is IConvertible && !targetType.IsAssignableFrom(val.GetType()))+ {+ try { val = Convert.ChangeType(val, targetType); } catch {}+ }++ finalArgs[i] = val;+ }++ // Invoke+ object result = methodToInvoke.Invoke(target, finalArgs);++ // Process result+ if (result == null) return null;+ if (result is ElementId eid) return eid.Value; // Return raw int/long+ if (result.GetType().IsPrimitive || result is string) return result;++ // It's an object, register it+ string regId = RegisterObject(result);+ return new { type = "reference", id = regId, class_name = result.GetType().Name, str = result.ToString() };+ }+ }+}