Skip to main content
Glama

execute_code

Run Python code within FreeCAD to control 3D object creation, editing, and management. Receive execution status, output, and a screenshot of the design for verification.

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 FreeCAD RPC server, handles response, adds screenshot if available.
    @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)}") ]
  • Registration of the 'execute_code' tool using FastMCP decorator.
    @mcp.tool()
  • Proxy method in FreeCADConnection class that forwards execute_code call to the XML-RPC server.
    def execute_code(self, code: str) -> dict[str, Any]: return self.server.execute_code(code)
  • Core implementation in FreeCADRPC: queues exec(code) in FreeCAD GUI thread via task queue, captures stdout, returns success/error.
    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