Skip to main content
Glama

execute_blender_code

Run Python code directly in Blender to automate 3D modeling tasks, control materials, manipulate objects, and create scenes through step-by-step execution.

Instructions

Execute arbitrary Python code in Blender. Make sure to do it step-by-step by breaking it into smaller chunks.

Parameters:

  • code: The Python code to execute

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYes

Implementation Reference

  • The primary handler function implementing the 'execute_blender_code' tool. It sends the provided Python code to the Blender connection for execution and handles errors.
    @mcp.tool()
    def execute_blender_code(ctx: Context, code: str) -> str:
        """
        Execute arbitrary Python code in Blender. Make sure to do it step-by-step by breaking it into smaller chunks.
        
        Parameters:
        - code: The Python code to execute
        """
        try:
            # Get the global connection
            blender = get_blender_connection()
            
            result = blender.send_command("execute_code", {"code": code})
            return f"Code executed successfully: {result.get('result', '')}"
        except Exception as e:
            logger.error(f"Error executing code: {str(e)}")
            return f"Error executing code: {str(e)}"
  • The docstring within the handler provides the tool schema, describing the purpose, parameters (code: str), and usage notes.
    """
    Execute arbitrary Python code in Blender. Make sure to do it step-by-step by breaking it into smaller chunks.
    
    Parameters:
    - code: The Python code to execute
    """
  • The @mcp.tool() decorator registers the function as an MCP tool named 'execute_blender_code' based on its name.
    @mcp.tool()
  • Supporting helper function that manages the persistent connection to Blender, called within the handler to obtain the connection instance.
    def get_blender_connection():
        """Get or create a persistent Blender connection"""
        global _blender_connection, _polyhaven_enabled  # Add _polyhaven_enabled to globals
        
        # If we have an existing connection, check if it's still valid
        if _blender_connection is not None:
            try:
                # First check if PolyHaven is enabled by sending a ping command
                result = _blender_connection.send_command("get_polyhaven_status")
                # Store the PolyHaven status globally
                _polyhaven_enabled = result.get("enabled", False)
                return _blender_connection
            except Exception as e:
                # Connection is dead, close it and create a new one
                logger.warning(f"Existing connection is no longer valid: {str(e)}")
                try:
                    _blender_connection.disconnect()
                except:
                    pass
                _blender_connection = None
        
        # Create a new connection if needed
        if _blender_connection is None:
            _blender_connection = BlenderConnection(host="localhost", port=9876)
            if not _blender_connection.connect():
                logger.error("Failed to connect to Blender")
                _blender_connection = None
                raise Exception("Could not connect to Blender. Make sure the Blender addon is running.")
            logger.info("Created new persistent connection to Blender")
        
        return _blender_connection

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

B3.2/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the burden falls on the description. It does disclose that the tool can run arbitrary Python code, which implies broad power and risk, and the 'step-by-step' warning hints that long or complex executions need caution. However, it does not mention possible destructive scene mutations, absence of undo, execution limits, or error behavior, so the disclosure is only partially complete.

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 short and front-loaded with the core purpose. The step-by-step instruction is useful, and the parameter note is simple. The phrase 'step-by-step by breaking it into smaller chunks' is slightly redundant, but overall the text is efficient and easy to scan.

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?

For an arbitrary code execution tool with no annotations and no output schema, the description leaves important gaps: there is no indication of what the tool returns, how failures surface, what Python objects are available in scope, or whether the execution mutates the Blender scene permanently. The minimal description does not give an agent enough context to safely and correctly invoke this powerful tool in varied situations.

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

Parameters2/5

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

Schema description coverage is 0%, so the description must compensate. The line 'code: The Python code to execute' adds only marginally more than the schema property title 'Code' and the tool name itself. It does not explain expected code environment details such as whether Blender's bpy module is pre-imported, how results or errors are returned, or whether there are execution limits.

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 a specific action and resource: 'Execute arbitrary Python code in Blender.' The word 'arbitrary' signals this is a general-purpose escape hatch, and no sibling tool has the same role, so an agent can immediately distinguish it from the other scene, asset, and model-generation tools.

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?

There is no guidance on when to prefer this tool over the many specialized sibling tools. The instruction to break work into smaller chunks is about how to structure execution, not about choosing this tool over alternatives. The only implied guidance is that 'arbitrary' means it can be used for tasks the other tools don't cover, but that is not made explicit.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.