Skip to main content
Glama

execute_code

Execute Python code within FreeCAD to automate CAD tasks, create 3D objects, and generate design outputs with screenshots.

Instructions

Execute arbitrary Python code in FreeCAD.

Args:
    code: The Python code to execute.

Returns:
    A message indicating the success or failure of the code execution, the output of the code execution, and a screenshot of the object.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYes

Implementation Reference

  • MCP tool handler for 'execute_code': proxies code execution to FreeCADConnection RPC, handles success/error responses, and conditionally adds a screenshot.
    @mcp.tool()
    def execute_code(ctx: Context, code: str) -> list[TextContent | ImageContent]:
        """Execute arbitrary Python code in FreeCAD.
    
        Args:
            code: The Python code to execute.
    
        Returns:
            A message indicating the success or failure of the code execution, the output of the code execution, and a screenshot of the object.
        """
        freecad = get_freecad_connection()
        try:
            res = freecad.execute_code(code)
            screenshot = freecad.get_active_screenshot()
            
            if res["success"]:
                response = [
                    TextContent(type="text", text=f"Code executed successfully: {res['message']}"),
                ]
                return add_screenshot_if_available(response, screenshot)
            else:
                response = [
                    TextContent(type="text", text=f"Failed to execute code: {res['error']}"),
                ]
                return add_screenshot_if_available(response, screenshot)
        except Exception as e:
            logger.error(f"Failed to execute code: {str(e)}")
            return [
                TextContent(type="text", text=f"Failed to execute code: {str(e)}")
            ]
  • Helper method in FreeCADConnection class that proxies the execute_code call to the XML-RPC server.
    def execute_code(self, code: str) -> dict[str, Any]:
        return self.server.execute_code(code)
  • RPC server implementation in FreeCAD addon: executes the provided Python code using exec() in a queued GUI task, captures stdout, and returns success/error with output.
    def execute_code(self, code: str) -> dict[str, Any]:
        output_buffer = io.StringIO()
        def task():
            try:
                with contextlib.redirect_stdout(output_buffer):
                    exec(code, globals())
                FreeCAD.Console.PrintMessage("Python code executed successfully.\n")
                return True
            except Exception as e:
                FreeCAD.Console.PrintError(
                    f"Error executing Python code: {e}\n"
                )
                return f"Error executing Python code: {e}\n"
    
        rpc_request_queue.put(task)
        res = rpc_response_queue.get()
        if res is True:
            return {
                "success": True,
                "message": "Python code execution scheduled. \nOutput: " + output_buffer.getvalue()
            }
        else:
            return {"success": False, "error": res}

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/heok-yongssun/freecad-mcp'

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