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
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. While it mentions executing 'arbitrary Python code' and suggests a step-by-step approach, it lacks critical details: it doesn't specify security implications, whether the code runs in a sandbox, what permissions are required, how errors are handled, or what the execution environment entails (e.g., Blender version, available modules). For a tool that executes arbitrary code with zero annotation coverage, 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 and front-loaded: the first sentence states the core purpose, followed by a usage tip and parameter list. There's no wasted text, and it's structured for clarity. However, the parameter section could be more integrated, and the step-by-step advice, while useful, slightly detracts from pure conciseness.

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 (executing arbitrary code is high-risk), no annotations, no output schema, and low schema coverage (0%), the description is incomplete. It misses critical context: safety warnings, execution limits, error handling, and output details. For such a powerful tool, the description should provide more comprehensive guidance to ensure safe and effective use.

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. It lists one parameter ('code: The Python code to execute'), which adds basic meaning beyond the schema's title 'Code.' However, it doesn't provide any details on code format, constraints (e.g., length, imports), examples, or expected behavior (e.g., return values, output capture). With one parameter and low coverage, the description adds minimal value over the schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Execute arbitrary Python code in Blender' - this is a specific verb ('Execute') + resource ('Python code in Blender'). It distinguishes from siblings like 'download_polyhaven_asset' or 'get_scene_info' by focusing on code execution rather than asset management or information retrieval. However, it doesn't explicitly differentiate from potential code-related siblings that might exist.

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 provides some implied usage guidance with 'Make sure to do it step-by-step by breaking it into smaller chunks,' which suggests best practices for using this tool. However, it doesn't explicitly state when to use this tool versus alternatives (like whether to use this for simple operations vs. complex scripts), nor does it mention any prerequisites or exclusions. The guidance is helpful but incomplete.

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/spranjal3301/final-year-project'

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