Skip to main content
Glama
ZedMoster

Revit MCP Server

by ZedMoster

create_levels

Create multiple building levels in Revit with batch processing, automatic unit conversion from millimeters to feet, and conflict resolution for level names.

Instructions

在Revit中创建标高,支持批量创建,遵循JSON-RPC 2.0规范。 mcp_tool使用时params不要有任何注释信息

特性:

  • 支持批量创建多个标高

  • 自动处理单位转换(毫米转英尺)

  • 自动处理标高名称冲突

  • 完善的错误处理机制

参数: ctx (Context): FastMCP上下文对象 method (str): JSON-RPC方法名,默认为"CreateLevels" params (List[Dict]): 标高参数列表,每个字典包含: - elevation (float): 标高高度(毫米) - name (str, optional): 标高名称(可选,默认为"Level_{elevation}")

返回: dict: JSON-RPC 2.0格式的响应,结构为: 成功时: { "jsonrpc": "2.0", "result": [ { "elementId": "创建的标高元素ID", "name": "标高名称", "familyName": "标高族名称" }, ... ], "id": request_id } 失败时: { "jsonrpc": "2.0", "error": { "code": int, "message": str, "data": any }, "id": request_id }

示例: # 创建多个标高 response = create_levels(ctx, params=[ {"elevation": 8000, "name": "Level_3"}, {"elevation": 12000} # 自动生成名称"Level_12000" ])

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
methodNoCreateLevels
paramsNo

Implementation Reference

  • The create_levels tool is included in the ARCHITECTURAL_TOOLS list, which groups tools for registration with the MCP server.
    ARCHITECTURAL_TOOLS = [
        create_levels, create_floor_plan_views, create_grids, create_walls, create_floors,
        create_door_windows, create_rooms, create_room_tags, create_family_instances, create_sheets
    ]
  • The register_tools function iterates over ARCHITECTURAL_TOOLS (including create_levels) and registers each tool function using the FastMCP server's tool decorator.
    def register_tools(server: FastMCP) -> None:
        """注册所有工具到MCP服务器"""
        # 注册建筑工具
        for tool in ARCHITECTURAL_TOOLS:
            server.tool()(tool)
    
        # 注册MEP工具
        for tool in MEP_TOOLS:
            server.tool()(tool)
    
        # 注册通用工具
        for tool in GENERAL_TOOLS:
            server.tool()(tool)
  • Explicit call to register_tools(mcp), which registers the create_levels tool among others on the MCP server instance.
    register_tools(mcp)
  • Utility function to get or create a persistent RevitConnection, which tool handlers like create_levels would use to send commands to the Revit plugin.
    def get_revit_connection() -> RevitConnection:
        """
        获取或创建持久的Revit连接
    
        返回:
            RevitConnection: 与Revit的连接对象
    
        异常:
            Exception: 连接失败时抛出
        """
        global _connection, _enabled
    
        if _connection is not None:
            try:
                # 测试连接是否有效
                result = _connection.send_command("get_polyhaven_status")
                _enabled = result.get("enabled", False)
                return _connection
            except Exception as e:
                logger.warning(f"现有连接已失效: {str(e)}")
                try:
                    _connection.disconnect()
                except:
                    pass
                _connection = None
    
        # 创建新连接
        if _connection is None:
            _connection = RevitConnection(host="localhost", port=_port)
            if not _connection.connect():
                logger.error("无法连接到Revit")
                _connection = None
                raise Exception(
                    "无法连接到Revit。请确保Revit插件正在运行。")
            logger.info("已创建新的持久连接到Revit")
    
        return _connection
  • Core method in RevitConnection that sends JSON-RPC commands (e.g., 'CreateLevels') to the Revit plugin; tool handlers would call this with command_type='create_levels' or similar.
    def send_command(self, command_type: str, params: Union[Dict[str, Any], List[Dict[str, Any]]] = None) -> Dict[
        str, Any]:
        """
        向Revit发送命令并返回响应
    
        参数:
            command_type (str): 命令类型
            params (Dict[str, Any] 或 List[Dict[str, Any]]): 命令参数
    
        返回:
            Dict[str, Any]: 命令响应
    
        异常:
            ConnectionError: 连接错误
            TimeoutError: 请求超时
            ValueError: 参数或响应无效
            Exception: 其他错误
        """
        # 确保连接
        if not self.sock and not self.connect():
            raise ConnectionError("无法连接到Revit")
    
        try:
            logger.info(f"发送命令: {command_type}")
            logger.debug(f"命令参数: {params}")
    
            # 导入并创建请求对象
            from .rpc import JsonRPCRequest, JsonRPCResponse
            command = JsonRPCRequest(method=command_type, params=params)
            command_json = json.dumps(command.__dict__)
    
            # 发送命令
            self.sock.sendall(command_json.encode('utf-8'))
            logger.debug("命令已发送,等待响应...")
    
            # 使用 receive_full_response 接收完整数据流
            response_data = self.receive_full_response()
            logger.debug(f"已接收 {len(response_data)} 字节数据")
    
            # 解析响应
            try:
                response_dict = json.loads(response_data.decode('utf-8'))
                response = JsonRPCResponse(
                    id=response_dict.get("id"),
                    result=response_dict.get("result"),
                    error=response_dict.get("error")
                )
            except json.JSONDecodeError as e:
                logger.error(f"无法解析Revit响应: {str(e)}")
                if response_data:
                    logger.error(f"原始响应 (前200字节): {response_data[:200]}")
                raise ValueError(f"无效的Revit响应: {str(e)}")
    
            # 处理错误
            if response.error:
                error_message = response.error.get("message", "未知错误")
                error_code = response.error.get("code", -1)
                error_data = response.error.get("data")
    
                logger.error(f"Revit错误 (代码: {error_code}): {error_message}")
                if error_data:
                    logger.error(f"错误数据: {error_data}")
    
                raise Exception(f"Revit错误: {error_message}")
    
            return response.result or {}
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It effectively describes several behavioral traits: supports batch creation, automatic unit conversion (mm to feet), automatic handling of level name conflicts, and comprehensive error handling. However, it doesn't mention permissions needed, whether the operation is destructive/reversible, or rate limits. For a creation tool with no annotations, this provides substantial behavioral context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with clear sections (特性, 参数, 返回, 示例) and front-loads the core purpose. However, it includes some extraneous information like 'mcp_tool使用时params不要有任何注释信息' which seems like implementation detail rather than user guidance. Most sentences earn their place, but there's minor redundancy in the JSON-RPC format explanation.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given this is a creation tool with no annotations, 0% schema description coverage, and no output schema, the description provides excellent completeness. It covers purpose, behavioral traits, detailed parameter semantics, return format (both success and error cases), and includes a practical example. The description fully compensates for the lack of structured metadata.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 0% description coverage and only shows generic parameter names (method, params). The description compensates fully by providing detailed parameter semantics: method defaults to 'CreateLevels', params is a list of dictionaries where each contains elevation (in mm) and optional name (with default naming convention). This adds significant meaning beyond what the bare schema provides.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: '在Revit中创建标高,支持批量创建' (Create levels in Revit, supports batch creation). It specifies the exact action (create levels), the target resource (Revit), and distinguishes it from siblings like create_walls, create_floors, etc. The description goes beyond the tool name by mentioning batch creation capability.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context through the mention of JSON-RPC 2.0 specification and Revit, but doesn't explicitly state when to use this tool versus alternatives. No guidance is provided about prerequisites, when not to use it, or comparisons with other creation tools like create_floors or create_walls. The context is clear but lacks explicit usage directives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/ZedMoster/revit-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server