Revit MCP桥接服务

Revit MCP 是一款将 AI 编程助手(如 Claude、Cursor、Codex)与 Autodesk Revit/Dynamo 连接的生产级 MCP 服务,支持 2D CAD 自动转换为 3D BIM 模型、参数化构件创建、模型查询与碰撞检测,广泛应用于建筑工程 BIM 建模与智能化设计审查。

  • by hungpixi
  • C#
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 hungpixi/revit-mcp

使用说明

# Revit MCP — Model Context Protocol Bridge for Autodesk Revit & Dynamo

English | Tiếng Việt

A production-grade Model Context Protocol (MCP) server and high-performance native C# .NET bridge that connects frontier AI coding assistants (Claude Code, Cursor, Codex, GPT) directly to Autodesk Revit & Dynamo for automated 2D-to-3D BIM modeling, geometric reasoning, and model inspection.


📌 Table of Contents


💥 The Core Problem

In the modern Architecture, Engineering, and Construction (AEC) industry, millions of engineering hours are lost every year to manual, repetitive modeling:

  1. The 2D-to-3D Drafting Bottleneck: Architects and structural engineers receive 2D AutoCAD (.dwg) floor plans, sections, and PDF specification sheets. BIM modelers spend hundreds of tedious hours manually tracing lines, placing walls, inserting doors/windows, aligning levels, and typing dimensional parameters.
  2. Human Fatigue & Discrepancies: Manual conversion consistently introduces drafting errors, mismatched elevations, clashes between MEP and structural elements, and delayed delivery cycles.
  3. Siloed BIM APIs: While the Autodesk Revit API is comprehensive, it is bound to single-threaded C# .NET desktop runtimes. It has historically lacked native interoperability with modern Large Language Models (LLMs) and autonomous AI coding agents.

Revit MCP eliminates this bottleneck by serving as a bidirectional, real-time bridge. Through the open Model Context Protocol (MCP) standard, AI models can inspect DWG CAD vectors, query project parameters, generate parametric elements, and run structural clash checks with mathematical precision.


🏛️ System Architecture

The bridge implements a decoupled, three-tier architecture ensuring thread safety, fault isolation, and sub-millisecond local serialization:

[LLM Client: Claude Code / Cursor / Codex]
                 │ (stdio / SSE)
                 ▼
[Node.js MCP Server (revit-mcp)]
                 │ (Local IPC / TCP Socket)
                 ▼
[C# Native .NET Add-in / Dynamo Bridge]
                 │ (Autodesk Revit API Context)
                 ▼
[Autodesk Revit 2024+ Live Document (3D Model / BIM Elements)]

Architectural Breakdown:

Tier Component Technology Responsibility
Tier 1: Client AI Assistant Claude Code / Cursor / Codex / Claude Desktop Translates natural language prompts into standardized MCP JSON-RPC tool calls.
Tier 2: Server revit-mcp Node.js / TypeScript (MCP SDK) Validates input schemas, enforces execution bounds, manages TCP socket connections (127.0.0.1:8080), and handles async responses.
Tier 3: Plugin RevitMCPPlugin C# .NET 8.0 / Framework 4.8 + Revit API Implements IExternalEventHandler to queue commands safely into the single-threaded Revit UI thread, executing transactional modifications.
Tier 4: Host Autodesk Revit Revit 2020 – 2026+ Live Document Hosts the live BIM model, geometric kernel, family instances, parameters, and Dynamo engine.

✨ Key Features

  • ⚡ Direct Revit DOM Control: Create, modify, query, and delete native Revit elements in real time.
  • 📐 Automated 2D CAD to 3D BIM Pipeline: Link DWGs, parse layers, extract vector polylines/blocks, and generate corresponding 3D wall types, doors, and windows automatically.
  • 🔄 Thread-Safe External Event Loop: Utilizes Autodesk.Revit.UI.ExternalEvent to prevent UI thread lockups and cross-thread API exceptions.
  • 🧱 Parametric Family & Type Generation: Parse finish codes (FT, GT, P1-P5) from PDF specs or CAD blocks and instantiate native Revit family types.
  • 📊 Instant Quantification & Schedules: Query room tags, surface areas, material volumes, and structural member properties in seconds.
  • 🔍 Real-Time Clash & Quality Auditing: Automated geometric clash detection between categories (e.g., Walls vs. Ducts, Columns vs. Openings).

🛠️ Tools Provided

The MCP server exposes a rich suite of specialized tools grouped by BIM lifecycle stages:

Core Highlighted Tools

Tool Name Type Description
create_wall Write Creates parametric Revit walls given start/end coordinates, height, level ID, and wall type (Wall.Create).
query_elements_by_category Read Queries all elements in an active or specified view filtered by Category (e.g., OST_Walls, OST_Doors, OST_Rooms) with full parameter sets.
analyze_cad_layers Read Inspects linked/imported DWG files, extracting layer tables, graphics styles, block references, and vector polyline coordinates.
export_schedule_data Read Extracts tabular quantities, schedules, room finish schedules, and material takeoffs into structured JSON or CSV.
execute_dynamo_workspace Execute Headless execution of pre-configured Dynamo graph scripts (.dyn) for computational geometry workflows.

Extended BIM Tool Catalog

├── CAD & Ingestion
│   ├── link_cad_files             - Link DWG drawings with origin-to-origin positioning
│   ├── get_cad_entities           - Extract 2D polylines, curves, and text annotations
│   ├── get_cad_block_info         - Identify door/window blocks (D01-D11, W01-W10)
│   └── convert_cad_to_family      - Convert 2D block references into parametric families
│
├── Geometry & Framework
│   ├── create_level               - Generate project levels with elevations (mm/ft)
│   ├── create_grid                - Create linear or radial structural grid lines
│   ├── create_grid_intersections  - Compute column placement coordinates at grid nodes
│   └── create_structural_framing  - Place structural columns and beams automatically
│
├── Elements & Parameters
│   ├── get_element_parameters     - Read instance and type parameters
│   ├── set_element_parameters     - Update dimensions, fire ratings, comments, marks
│   ├── modify_element             - Move, rotate, pin, or mirror BIM elements
│   └── delete_element             - Safely remove elements within isolated transactions
│
└── Views, Sheets & Auditing
    ├── create_view_sheet          - Generate documentation sheets with title blocks
    ├── tag_all_rooms              - Place spatial tags in all un-tagged enclosed rooms
    ├── detect_clashes             - Execute bounding-box and solid intersection audits
    └── send_code_to_revit         - Execute sandboxed C# Roslyn scripts in Revit context

💻 Prerequisites & System Requirements

  • Operating System: Windows 10 / Windows 11 (64-bit)
  • Autodesk Revit: 2020, 2024, 2025, or 2026 (installed with valid license/trial)
  • Development Toolchains:
    • .NET SDK 8.0 and .NET Framework 4.8 / 4.8.1 Developer Pack
    • Node.js >= 18.0.0 (LTS recommended)
    • PowerShell 7+ or Windows PowerShell 5.1
  • AI Clients: Claude Desktop, Claude Code, or Cursor

🚀 Quickstart & Installation

1. Compile the C# Native Add-in

Open PowerShell and build the native Revit plugin handlers:

# Navigate to the C# project
cd tmp/revit-mcp/RevitPlugin

# Build the handlers and plugin assembly
dotnet build RevitMCPPlugin/RevitMCPPlugin.csproj -c Release

Deploy the add-in manifest to your local Revit Addins folder:

# For Revit 2024 (adjust year for 2020/2025/2026):
$AddinDir = "$env:APPDATA\Autodesk\Revit\Addins\2024"
Copy-Item RevitMCPPlugin\RevitMCPPlugin.addin $AddinDir
Copy-Item RevitMCPPlugin\bin\Release\* $AddinDir -Recurse

2. Install the Node.js MCP Server

# Navigate to the MCP server directory
cd tmp/revit-mcp/revit-mcp

# Install dependencies and compile TypeScript
npm install
npm run build

3. Configure Claude Desktop & Cursor

For Claude Desktop (%APPDATA%\Claude\claude_desktop_config.json):

{
  "mcpServers": {
    "revit-mcp": {
      "command": "node",
      "args": [
        "C:\\Projects\\revit-mcp\\revit-mcp\\build\\index.js"
      ],
      "env": {
        "REVIT_MCP_PORT": "8080",
        "REVIT_HOST": "127.0.0.1"
      }
    }
  }
}

For Cursor (.cursor/mcp.json):

{
  "mcpServers": {
    "revit": {
      "command": "node C:/Projects/revit-mcp/revit-mcp/build/index.js"
    }
  }
}

4. Launch & Verify

  1. Launch Autodesk Revit and open any architectural project or template (.rvt).
  2. The RevitMCPPlugin starts automatically on TCP port 8080 (confirm via Revit notification or status log).
  3. Test connectivity directly from CLI:
node tmp/revit-mcp/revit-ping.js
# Output: ✅ Pong! Connected to Autodesk Revit 2024 Document: "SampleHouse.rvt"

🔒 Security & Safety Boundaries

Modifying production BIM models requires strict safety guarantees to prevent corrupting active work-in-progress files:

                  ┌───────────────────────────────┐
                  │    Inbound MCP JSON-RPC       │
                  └──────────────┬────────────────┘
                                 │
                 Is operation Read or Mutating?
                                 │
           ┌─────────────────────┴─────────────────────┐
           ▼                                           ▼
┌──────────────────────┐                   ┌──────────────────────────────┐
│  READ-ONLY QUERY     │                   │  TRANSACTION COMMIT          │
├──────────────────────┤                   ├──────────────────────────────┤
│ • No Document Lock   │                   │ • Scoped Transaction Block   │
│ • Parallel Access    │                   │ • Auto-Rollback on Error     │
│ • Zero Undo Stack    │                   │ • Undo / Redo History Intact │
│ • Fast Telemetry     │                   │ • Element GUID Verification  │
└──────────────────────┘                   └──────────────────────────────┘
  1. Read-Only Queries vs. Commit Transactions:
    • Commands such as query_elements_by_category, get_element_parameters, and analyze_cad_layers run strictly outside active edit transactions. They cannot alter the document model or pollute the Undo stack.
    • Any mutating operation (create_wall, modify_element, create_level) must open a discrete, named Revit Transaction (using (Transaction t = new Transaction(doc, "AI: Create Wall"))).
    • If geometric constraints fail, the transaction is immediately aborted via t.RollBack(), leaving the user's project completely pristine.
  2. Revit Thread Safety (IExternalEventHandler):
    • The Revit API is strictly single-threaded and locks down outside of Autodesk's UI thread. Direct socket thread writes cause immediate memory crashes.
    • All inbound commands are marshaled through ExternalEvent.Raise(), ensuring execution occurs safely during Revit's native idle dispatch loop.
  3. Local Loopback Isolation:
    • The IPC TCP socket listens exclusively on 127.0.0.1. No external network exposure or unauthenticated remote endpoints are permitted.

💡 Real-World Workflow: 2D CAD to 3D BIM

Here is an example prompt you can give directly to Claude Code or Claude Desktop once connected:

"I have linked 'GroundFloor_Architectural.dwg' into Level 1. 
Please:
1. Call 'analyze_cad_layers' to identify all lines on layer 'A-WALL-EXTR' and 'A-WALL-INTR'.
2. Use 'create_wall' to instantiate 200mm Exterior Brick Walls along exterior contours.
3. Find CAD blocks named 'DOOR-900' and insert matching 900x2100 Single Flush Doors.
4. Export the resulting room areas and wall quantities via 'export_schedule_data'."

What happens behind the scenes:

  • Claude calls analyze_cad_layers → receives polygon coordinate arrays in millimeters.
  • Claude calculates room centerpoints and wall orientation vectors.
  • Claude dispatches batched create_wall transactions via Revit MCP.
  • Revit generates the 3D BIM geometry live on your screen in real time!

📁 Repository Structure

revit-mcp/
├── RevitPlugin/                         # C# Native Revit Add-in (.NET)
│   ├── Handlers/                        # Granular BIM operation handlers
│   │   ├── CADImportHandlers.cs         # DWG reading, entity extraction
│   │   ├── LevelAndGridHandlers.cs      # Level elevation and grid creators
│   │   ├── ElementQueryHandlers.cs      # Category & parameter search
│   │   ├── FamilyAndExportHandlers.cs   # Family loading, schedule exports
│   │   └── CommandRouter.cs             # JSON-RPC method dispatcher
│   └── RevitMCPPlugin/                  # Socket Server & Revit Add-in entry
│       ├── App.cs                       # IExternalApplication lifecycle
│       ├── SocketServer.cs              # High-performance async TCP listener
│       └── RevitCommandHandler.cs       # Thread-safe IExternalEventHandler
│
├── revit-mcp/                           # Node.js TypeScript MCP Server
│   ├── src/
│   │   ├── index.ts                     # MCP Server entry point (stdio)
│   │   ├── tools/                       # 35+ Type-safe MCP tool declarations
│   │   └── utils/                       # CADAnalyzer & geometry transformers
│   ├── package.json                     # Server dependencies
│   └── tsconfig.json                    # TypeScript compiler configuration
│
├── cad-link-and-list.js                 # Automation script for CAD linking
├── pdf-to-bim.js                        # PDF finish code extraction runner
├── revit-ping.js                        # Healthcheck connection validator
├── start-revit-and-wait.ps1             # Headless Revit orchestrator
├── LICENSE                              # MIT Open Source License
└── README.md                            # Comprehensive SSOT Documentation

🇻🇳 Tổng Quan (Tiếng Việt)

Cầu Nối AI (Claude/GPT) Với Autodesk Revit Qua Chuẩn MCP

Revit MCP là giải pháp mã nguồn mở hàng đầu kết nối trực tiếp các mô hình ngôn ngữ lớn (Claude Code, Cursor, Codex) với phần mềm Autodesk Revit (phiên bản 2020 đến 2026+).

Giải Pháp Đột Phá:

  • Tự động hóa 2D CAD sang 3D BIM: Thay vì kỹ sư phải dựng hình thủ công hàng trăm giờ từ bản vẽ AutoCAD (.dwg), AI tự động phân tích layer, trích xuất tọa độ polylines/block và ra lệnh cho Revit dựng tường, cửa, cột, lưới trục tự động.
  • An toàn giao dịch (Transaction Safety): Phân tách rõ ràng giữa truy vấn dữ liệu (chỉ đọc) và thay đổi mô hình (phải mở Transaction có rollback tự động). Đảm bảo không bao giờ làm hỏng hay treo file Revit đang làm việc.
  • Đa nền tảng AI: Hỗ trợ mọi AI Client tuân theo chuẩn Model Context Protocol (Anthropic Claude Desktop, Cursor AI, Codex CLI).

📜 Contributing & License

Contributions, issues, and feature requests are welcome! Feel free to check the issues page.

Distributed under the MIT License. See LICENSE for more information.

Built with ❤️ for AEC Engineers, Architects & Computational Designers worldwide.