How the AI Element Filter Queries Revit Elements by Specific Criteria in revit-mcp
The AI element filter provides a type-safe, JSON-RPC interface that allows AI assistants to query Revit elements by category, type, visibility, spatial bounds, and family parameters without requiring direct Revit API knowledge.
The revit-mcp repository implements a Model Context Protocol (MCP) server that bridges AI assistants with Autodesk Revit. At the core of this integration sits the AI element filter, a sophisticated querying mechanism that translates high-level filter criteria into precise Revit API calls through a dynamic tool registration system and TCP socket communication.
Architecture of the AI Element Filter
The implementation spans three distinct layers that handle discovery, validation, and execution. Understanding these layers reveals how the AI element filter maintains type safety while remaining flexible enough to support complex spatial and categorical queries.
Dynamic Tool Registration
The server discovers the AI element filter automatically at startup through a dynamic registration system. In src/tools/register.ts, the server scans the src/tools directory, dynamically imports each module, and invokes any exported function whose name starts with register. For the AI element filter, this calls registerAIElementFilterTool, which binds the tool to the MCP server instance without requiring manual imports or static configuration.
Type-Safe Schema Definition
The tool definition resides in src/tools/ai_element_filter.ts, where lines 10-70 declare a strict Zod schema that validates all incoming requests before they reach Revit. The server.tool("ai_element_filter", …) registration exposes the following optional filter parameters:
filterCategory– Built-in Revit category such asOST_WallsorOST_FloorsfilterElementType– Element type name (class or database name) like"Wall"filterFamilySymbolId– NumericElementIdof a specific family typeincludeTypes– Boolean to return type objects (wall types, door types); defaults tofalseincludeInstances– Boolean to return placed instances; defaults totruefilterVisibleInCurrentView– Restrict to elements visible in the active view (instances only)boundingBoxMin/boundingBoxMax– 3-D bounding box corners in millimeters; only elements intersecting the box are returnedmaxElements– Upper limit on results (default 50, values above 50 discouraged)
This schema ensures that malformed requests fail fast with clear validation errors before consuming Revit resources.
Revit Communication Pipeline
When the AI element filter receives a valid request, the handler (lines 72-102) delegates execution to withRevitConnection from src/utils/ConnectionManager.ts. This utility manages the lifecycle of a RevitClientConnection implemented in src/utils/SocketClient.ts.
The communication flow follows these steps:
- Socket Establishment –
RevitClientConnectionopens a TCP socket to the Revit plug-in atlocalhost:8080 - JSON-RPC Serialization – The client sends a request formatted as
{"method":"ai_element_filter","params":<args>} - Revit Execution – The Revit side processes the request, executing the actual element query using the supplied filters against the Revit API
- Response Parsing – The client parses the JSON result, which the tool handler formats as a pretty-printed JSON string (lines 84-89)
- Error Handling – Socket errors or Revit exceptions are caught and reported as descriptive text messages (lines 91-99)
This pipeline provides a stateless, network-transparent interface that isolates the AI assistant from Revit API complexity while maintaining robust error handling.
Querying Elements with the AI Element Filter
The AI element filter supports complex queries that combine categorical, typological, and spatial constraints. Understanding how these parameters interact helps construct efficient requests that minimize Revit processing time.
Category and Type Filtering
Use filterCategory to target built-in Revit categories and filterElementType to narrow down to specific classes. For example, querying all wall instances in the current view:
{
"tool": "ai_element_filter",
"arguments": {
"filterCategory": "OST_Walls",
"includeInstances": true,
"filterVisibleInCurrentView": true,
"maxElements": 20
}
}
When the MCP server receives this payload, it executes the handler in ai_element_filter.ts, forwards the parameters to Revit via the socket connection, and returns a JSON array of wall instances.
Spatial Bounding Box Queries
The boundingBoxMin and boundingBoxMax parameters enable 3-D spatial filtering using millimeter coordinates. This is particularly useful for retrieving elements within specific rooms or construction zones:
import { withRevitConnection } from "./utils/ConnectionManager.js";
async function getFurnitureInZone() {
const params = {
filterCategory: "OST_Furniture",
boundingBoxMin: { p0: { x: 0, y: 0, z: 0 }, p1: { x: 0, y: 0, z: 0 } },
boundingBoxMax: { p0: { x: 5000, y: 5000, z: 3000 }, p1: { x: 5000, y: 5000, z: 3000 } },
includeInstances: true,
maxElements: 50,
};
const elements = await withRevitConnection(client =>
client.sendCommand("ai_element_filter", params)
);
console.log("Found furniture:", elements);
}
This request returns all furniture elements whose geometry intersects the defined 5 m × 5 m × 3 m bounding box, demonstrating how the AI element filter combines categorical and spatial constraints.
Direct Tool Invocation
For custom server logic or testing, invoke the tool directly through the connection manager:
import { withRevitConnection } from "./utils/ConnectionManager.js";
async function getWalls() {
const params = {
filterCategory: "OST_Walls",
includeInstances: true,
maxElements: 10,
};
const elements = await withRevitConnection(client =>
client.sendCommand("ai_element_filter", params)
);
console.log("Found walls:", elements);
}
This pattern bypasses the MCP tool layer while maintaining the same validation and communication infrastructure.
Summary
The AI element filter in revit-mcp provides a robust, type-safe bridge between AI assistants and Revit element databases:
- Dynamic registration via
src/tools/register.tsautomatically discovers the tool at server startup without manual configuration - Strict validation through Zod schemas in
src/tools/ai_element_filter.tsprevents malformed requests from reaching Revit - Network-transparent execution using
withRevitConnectionandRevitClientConnectionmanages TCP sockets to the Revit plug-in atlocalhost:8080 - Comprehensive filtering supports categorical (
filterCategory,filterElementType), typological (includeTypes,includeInstances), visibility (filterVisibleInCurrentView), and spatial (boundingBoxMin,boundingBoxMax) constraints - Safe defaults limit results to 50 elements by default, with clear error handling for socket failures and Revit exceptions
Frequently Asked Questions
What is the default limit for elements returned by the AI element filter?
The AI element filter defaults to returning 50 elements via the maxElements parameter. The implementation discourages values above 50 to prevent performance degradation in Revit, though you can request fewer elements (e.g., 10 or 20) for faster response times when testing queries.
How does the AI element filter handle spatial queries with bounding boxes?
The filter accepts boundingBoxMin and boundingBoxMax parameters defined in millimeters, each containing p0 and p1 coordinate objects. When provided, the Revit plug-in performs a 3-D intersection test, returning only elements whose geometry intersects the defined volume. This enables room-specific or zone-based queries without requiring the AI to understand Revit geometry APIs.
Can the AI element filter return both type definitions and instances simultaneously?
Yes, by setting both includeTypes to true and includeInstances to true, the query returns both category-specific type objects (like wall types or door types) and their placed instances in the model. By default, includeInstances is true and includeTypes is false, optimizing for common use cases where only placed elements are needed.
What happens if Revit is not running when the AI element filter is invoked?
If the Revit plug-in is not listening on localhost:8080, the withRevitConnection utility in src/utils/ConnectionManager.ts will fail to establish the TCP socket. The error handler (lines 91-99 in ai_element_filter.ts) catches this exception and returns a descriptive text message to the AI assistant, indicating that the Revit connection is unavailable rather than crashing the server or returning empty results.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →