Skip to main content
Glama

send_code_to_revit

Execute custom C# code in Autodesk Revit to automate BIM workflows, modify project elements, and extend functionality through direct API access.

Instructions

Send C# code to Revit for execution. The code will be inserted into a template with access to the Revit Document and parameters. Your code should be written to work within the Execute method of the template.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesThe C# code to execute in Revit. This code will be inserted into the Execute method of a template with access to Document and parameters.
parametersNoOptional execution parameters that will be passed to your code

Implementation Reference

  • The asynchronous handler function that implements the core logic of the 'send_code_to_revit' tool. It prepares parameters from the input arguments, uses withRevitConnection to send the command to the Revit client, and formats the response or error as MCP content.
    async (args, extra) => {
      const params = {
        code: args.code,
        parameters: args.parameters || [],
      };
    
      try {
        const response = await withRevitConnection(async (revitClient) => {
          return await revitClient.sendCommand("send_code_to_revit", params);
        });
    
        return {
          content: [
            {
              type: "text",
              text: `Code execution successful!\nResult: ${JSON.stringify(
                response,
                null,
                2
              )}`,
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Code execution failed: ${
                error instanceof Error ? error.message : String(error)
              }`,
            },
          ],
        };
      }
    }
  • Zod schema defining the input parameters for the tool: 'code' (required string) and 'parameters' (optional array). Used in server.tool() registration.
    {
      code: z
        .string()
        .describe(
          "The C# code to execute in Revit. This code will be inserted into the Execute method of a template with access to Document and parameters."
        ),
      parameters: z
        .array(z.any())
        .optional()
        .describe(
          "Optional execution parameters that will be passed to your code"
        ),
    },
  • The registration function exported from the tool file. It calls server.tool() to register the 'send_code_to_revit' MCP tool with its name, description, input schema, and handler. This function is dynamically invoked by src/tools/register.ts.
    export function registerSendCodeToRevitTool(server: McpServer) {
      server.tool(
        "send_code_to_revit",
        "Send C# code to Revit for execution. The code will be inserted into a template with access to the Revit Document and parameters. Your code should be written to work within the Execute method of the template.",
        {
          code: z
            .string()
            .describe(
              "The C# code to execute in Revit. This code will be inserted into the Execute method of a template with access to Document and parameters."
            ),
          parameters: z
            .array(z.any())
            .optional()
            .describe(
              "Optional execution parameters that will be passed to your code"
            ),
        },
        async (args, extra) => {
          const params = {
            code: args.code,
            parameters: args.parameters || [],
          };
    
          try {
            const response = await withRevitConnection(async (revitClient) => {
              return await revitClient.sendCommand("send_code_to_revit", params);
            });
    
            return {
              content: [
                {
                  type: "text",
                  text: `Code execution successful!\nResult: ${JSON.stringify(
                    response,
                    null,
                    2
                  )}`,
                },
              ],
            };
          } catch (error) {
            return {
              content: [
                {
                  type: "text",
                  text: `Code execution failed: ${
                    error instanceof Error ? error.message : String(error)
                  }`,
                },
              ],
            };
          }
        }
      );
    }
  • Dynamic registration entrypoint that scans src/tools directory, imports tool modules like send_code_to_revit.ts, discovers and invokes their register* functions to register all MCP tools with the server.
    export async function registerTools(server: McpServer) {
      // 获取当前文件的目录路径
      const __filename = fileURLToPath(import.meta.url);
      const __dirname = path.dirname(__filename);
    
      console.error('[DEBUG] Starting tool registration from directory:', __dirname);
    
      try {
        // 读取tools目录下的所有文件
        const files = fs.readdirSync(__dirname);
        console.error(`[DEBUG] Found ${files.length} files in tools directory`);
    
        // 过滤出.ts或.js文件,但排除index文件和register文件
        const toolFiles = files.filter((file) => (file.endsWith('.ts') || file.endsWith('.js')) && file !== 'index.ts' && file !== 'index.js' && file !== 'register.ts' && file !== 'register.js');
    
        console.error(`[DEBUG] Filtered to ${toolFiles.length} tool files:`, toolFiles);
    
        // 动态导入并注册每个工具
        const registeredTools = [];
    
        for (const file of toolFiles) {
          try {
            console.error(`[DEBUG] Processing tool file: ${file}`);
            // 构建导入路径
            const importPath = `./${file.replace(/\.(ts|js)$/, '.js')}`;
            console.error(`[DEBUG] Import path: ${importPath}`);
    
            // 动态导入模块
            const module = await import(importPath);
            console.error(`[DEBUG] Module imported successfully with keys:`, Object.keys(module));
    
            // 查找并执行注册函数
            const registerFunctionName = Object.keys(module).find((key) => key.startsWith('register') && typeof module[key] === 'function');
    
            if (registerFunctionName) {
              console.error(`[DEBUG] Found register function: ${registerFunctionName}`);
              await module[registerFunctionName](server);
              console.error(`[DEBUG] Registered tool from file: ${file}`);
              registeredTools.push(file);
            } else {
              console.warn(`[DEBUG] WARNING: No register function found in file ${file}. Available exports:`, Object.keys(module));
            }
          } catch (error) {
            console.error(`[DEBUG] ERROR registering tool ${file}:`, error);
          }
        }
    
        console.error(`[DEBUG] Successfully registered ${registeredTools.length} tools:`, registeredTools);
    
        // List all registered tools by tools' names
        try {
          // This is a workaround as we don't have direct access to registry in the type definitions
          const anyServer = server as any;
          if (anyServer.registry && typeof anyServer.registry.getTools === 'function') {
            const registeredToolNames = anyServer.registry.getTools().map((t: any) => t.id);
            console.error(`[DEBUG] Server has ${registeredToolNames.length} registered tools:`, registeredToolNames);
          } else {
            console.error('[DEBUG] Could not access server registry to list tools');
          }
        } catch (err) {
          console.error('[DEBUG] Error trying to list registered tools:', err);
        }
      } catch (error) {
        console.error('[DEBUG] ERROR during tool registration process:', error);
        throw error;
      }
    }
Behavior2/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 mentions that code is inserted into a template with access to Document and parameters, but lacks details on execution safety (e.g., potential side effects, error handling, or performance impacts). For a code execution tool, this is a significant gap in transparency.

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 appropriately sized with two sentences that are front-loaded and efficient. Each sentence adds value by explaining the execution process and template context, with no redundant information. It could be slightly more structured but remains concise.

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

Completeness2/5

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

Given the complexity of executing C# code in Revit, no annotations, and no output schema, the description is incomplete. It lacks information on return values, error conditions, execution environment constraints, or integration specifics. This makes it inadequate for safe and effective tool use in a complex context.

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

Parameters3/5

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

Schema description coverage is 100%, so the schema already documents both parameters thoroughly. The description adds minimal value beyond the schema by reiterating that code is inserted into the Execute method, but does not provide additional syntax, format, or usage details for the parameters. Baseline 3 is appropriate as the schema handles most of the documentation.

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 specific action ('Send C# code to Revit for execution') and resource ('Revit'), distinguishing it from sibling tools that perform operations like filtering, creating elements, or getting document info. It precisely defines the tool's function without being tautological.

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 by specifying that code should be written for the Execute method of a template, but it does not explicitly state when to use this tool versus alternatives (e.g., other Revit automation tools or sibling tools). No exclusions or clear alternatives are mentioned, leaving usage context somewhat vague.

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/ideook/revit-mcp'

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