How View Information Tools Retrieve Current View Metadata in Revit: A Technical Deep Dive

The get_current_view_info tool in revit-mcp retrieves current view metadata by sending a JSON-RPC 2.0 command over a TCP socket to the Revit add-in, which returns the active view's properties including view type, name, and scale.

Understanding how view information tools retrieve current view metadata in Revit is essential for building reliable MCP integrations. The revit-mcp server bridges the Model Context Protocol with Autodesk Revit through a sophisticated TCP-based command pipeline. This article examines the complete execution flow from tool registration to JSON response formatting, referencing the actual implementation in the mcp-servers-for-revit/revit-mcp repository.

Architecture Overview: From MCP Tool to Revit Add-in

The retrieval process follows a five-stage pipeline that abstracts socket complexity behind a clean async/await interface. When an MCP client invokes the tool, the server delegates the work to a transient TCP connection rather than maintaining persistent state.

The architecture separates concerns across three utility layers: tool registration (src/tools/get_current_view_info.ts), connection lifecycle management (src/utils/ConnectionManager.ts), and low-level socket protocol handling (src/utils/SocketClient.ts). This separation allows the tool handler to remain agnostic of JSON-RPC framing and TCP buffering details.

Step-by-Step: How get_current_view_info Fetches Metadata

Tool Registration in get_current_view_info.ts

The registerGetCurrentViewInfoTool function binds the tool to the MCP server instance. Located in src/tools/get_current_view_info.ts, this registration defines the tool schema and handler logic.

export function registerGetCurrentViewInfoTool(server: McpServer) {
  server.tool(
    "get_current_view_info",
    "获取 Revit 当前活动视图的详细信息,包括视图类型、名称、比例等属性。",
    {},
    async (args, extra) => {
      try {
        const response = await withRevitConnection(async revitClient => {
          return await revitClient.sendCommand("get_current_view_info", {});
        });

        return {
          content: [{ type: "text", text: JSON.stringify(response, null, 2) }],
        };
      } catch (error) {
        return {
          content: [{ type: "text", text: `get current view info failed: ${error instanceof Error ? error.message : String(error)}` }],
        };
      }
    }
  );
}

The handler wraps the operation in withRevitConnection, ensuring the socket is available before sending the command and guaranteeing cleanup afterward.

Connection Management via withRevitConnection

The withRevitConnection utility in src/utils/ConnectionManager.ts implements the resource acquisition pattern. It instantiates a RevitClientConnection, verifies TCP connectivity to localhost:8080, yields the client to the operation function, and finally disconnects regardless of success or failure.

export async function withRevitConnection<T>(operation: (client: RevitClientConnection) => Promise<T>): Promise<T> {
  const revitClient = new RevitClientConnection("localhost", 8080);
  try {
    if (!revitClient.isConnected) {
      await new Promise<void>((resolve, reject) => {
        // Connection setup with timeout handling
        revitClient.connect();
      });
    }
    return await operation(revitClient);
  } finally {
    revitClient.disconnect();
  }
}

This pattern prevents socket leaks and handles reconnection scenarios gracefully.

JSON-RPC Command Transmission

Once connected, revitClient.sendCommand constructs a standards-compliant JSON-RPC 2.0 request. The implementation in src/utils/SocketClient.ts generates a unique request ID, registers a callback to handle the asynchronous response, and serializes the command to the TCP stream.

public sendCommand(command: string, params: any = {}): Promise<any> {
  return new Promise((resolve, reject) => {
    if (!this.isConnected) this.connect();

    const requestId = this.generateRequestId();
    const commandObj = {
      jsonrpc: "2.0",
      method: command,
      params,
      id: requestId,
    };

    this.responseCallbacks.set(requestId, (responseData) => {
      const response = JSON.parse(responseData);
      if (response.error) reject(new Error(response.error.message));
      else resolve(response.result);
    });

    this.socket.write(JSON.stringify(commandObj));
    // Timeout handling omitted for brevity
  });
}

The Revit add-in receives this payload, queries the active view's metadata, and returns a JSON-RPC response where the result field contains the view properties.

Response Parsing and MCP Formatting

The SocketClient buffers incoming TCP data, parses the JSON, and matches responses to pending requests using the request ID. Once the promise resolves with response.result, the tool handler in get_current_view_info.ts formats the data as a pretty-printed JSON string within an MCP content object.

If the Revit add-in returns an error or the connection fails, the catch block returns a structured error message instead of raw stack traces, ensuring clean MCP protocol compliance.

Key Implementation Details

  • Transient Connections: Each tool invocation creates a fresh TCP socket to avoid state corruption and handle Revit restarts gracefully.
  • Request-ID Correlation: The JSON-RPC id field ensures responses match their requests even when multiple commands are in flight.
  • Automatic Reconnection: withRevitConnection detects stale sockets and re-establishes the link to localhost:8080 before transmitting.
  • Protocol Abstraction: Tool handlers remain unaware of TCP buffering, JSON framing, or socket error recovery; they interact only with Promise-based sendCommand calls.

Code Example: Calling the Tool

To retrieve current view metadata from an MCP client, invoke the tool with empty arguments:

{
  "tool": "get_current_view_info",
  "args": {}
}

The server returns a structured response containing the active view's metadata:

{
  "content": [
    {
      "type": "text",
      "text": "{\n  \"viewId\": \"3d\",\n  \"viewName\": \"3D View\",\n  \"viewType\": \"ThreeD\",\n  \"scale\": 1,\n  \"detailLevel\": \"Fine\"\n}"
    }
  ]
}

Summary

  • The revit-mcp server retrieves current view metadata by delegating to a Revit add-in via TCP socket communication.
  • The get_current_view_info tool is registered in src/tools/get_current_view_info.ts and handles MCP protocol formatting.
  • withRevitConnection in src/utils/ConnectionManager.ts manages the socket lifecycle, ensuring reliable connections to localhost:8080.
  • sendCommand in src/utils/SocketClient.ts implements JSON-RPC 2.0 framing, request-ID tracking, and asynchronous response handling.
  • The tool returns pretty-printed JSON containing view properties such as viewType, viewName, and scale, or a structured error message if the Revit connection fails.

Frequently Asked Questions

What protocol does revit-mcp use to communicate with Revit?

The server uses JSON-RPC 2.0 over a raw TCP socket. Commands are serialized as JSON objects containing jsonrpc, method, params, and id fields, then transmitted to the Revit add-in listening on localhost:8080. Responses follow the same protocol structure, with results or errors encapsulated in the result or error fields respectively.

How does the tool handle connection failures to the Revit add-in?

The withRevitConnection utility implements a try-finally pattern that guarantees socket cleanup. If the TCP connection to localhost:8080 cannot be established, the Promise rejects with a connection error, which the tool handler catches and formats into a readable MCP error message. The socket is explicitly disconnected in the finally block to prevent resource leaks regardless of success or failure.

Can I retrieve view metadata for views other than the current active view?

The current implementation of get_current_view_info specifically queries the active view as determined by the Revit API context. The tool accepts no parameters (params: {}), so it cannot target specific view IDs or names. To retrieve metadata for inactive views, the codebase would need a separate tool that accepts a viewId parameter and iterates the Revit document's view collection.

Where is the get_current_view_info tool registered in the codebase?

Tool registration occurs in src/tools/get_current_view_info.ts within the registerGetCurrentViewInfoTool function. This module exports the registration function, which is then dynamically loaded by src/tools/register.ts at server startup. The registration binds the tool name, description, schema, and handler to the MCP server instance defined in src/index.ts.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →