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

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

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}
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 the return includes a success/failure message, output, and screenshot, but lacks critical details like security implications, execution environment constraints, error handling, or performance impacts for arbitrary code execution in FreeCAD.

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 and front-loaded with the core purpose, followed by structured Arg and Return sections. Every sentence adds value, though the return details could be slightly more concise.

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

Completeness3/5

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

Given the tool's complexity (executing arbitrary code) and lack of annotations, the description is moderately complete but has gaps. It covers purpose and return values (aided by the output schema), but misses critical behavioral context like safety warnings or usage constraints, making it inadequate for full understanding.

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

Parameters4/5

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

The description adds meaningful context for the single parameter ('code: The Python code to execute'), which is essential since schema description coverage is 0%. It clarifies the parameter's purpose beyond the schema's basic type and title, though it could provide more on code format or restrictions.

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 ('Execute arbitrary Python code') and the target resource/environment ('in FreeCAD'), distinguishing it from sibling tools that handle documents, objects, parts, and views rather than code execution. It uses precise verb+resource phrasing.

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

Usage Guidelines2/5

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

No guidance is provided on when to use this tool versus alternatives. The description does not mention prerequisites, limitations, or scenarios where other tools might be more appropriate, such as using sibling tools for specific object manipulations instead of raw code execution.

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

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