# Security Considerations for execute_blender_code in Blender MCP

> Learn about execute_blender_code security considerations for Blender MCP. Understand the risks of executing arbitrary Python code and how to implement sandboxing and controls.

- Repository: [ahujasid/blender-mcp](https://github.com/ahujasid/blender-mcp)
- Tags: best-practices
- Published: 2026-04-13

---

**The `execute_blender_code` tool executes arbitrary Python code inside Blender's main interpreter, inheriting full system privileges and requiring sandboxing or strict environment controls to mitigate data loss and system compromise risks.**

The `execute_blender_code` tool provided by the `ahujasid/blender-mcp` repository creates a powerful bridge between AI assistants and Blender's Python API. Because this tool runs unsanitized code directly in Blender's process via the Model Context Protocol (MCP), understanding its security posture is critical before integrating into production pipelines.

## How execute_blender_code Works Under the Hood

### Tool Registration and MCP Exposure

In [`src/blender_mcp/server.py`](https://github.com/ahujasid/blender-mcp/blob/main/src/blender_mcp/server.py), the function is decorated with `@mcp.tool()` and wrapped with telemetry, registering it as a callable endpoint for any MCP-compatible client:

```python
@mcp.tool()
@telemetry
def execute_blender_code(code: str) -> str:
    # Implementation forwards to Blender via socket

```

This registration exposes the tool to AI agents like Claude or Cursor, allowing them to send Python code strings for execution without inherent sandboxing.

### Execution Flow and Privilege Inheritance

When triggered, the execution follows this path:

1. The MCP server receives a JSON request with type `execute_code`
2. The request forwards to the Blender addon via TCP socket (`blender.send_command`)
3. Inside [`addon.py`](https://github.com/ahujasid/blender-mcp/blob/main/addon.py), `BlenderMCPServer._execute_command_internal` dispatches to the `execute_code` handler
4. The handler runs `exec(code, globals())` in Blender's main thread

This design means code executes with the **same privileges as Blender itself**, granting unrestricted access to:
- Local file system (read/write operations)
- Network sockets (via `requests`, `socket`, or `urllib`)
- Blender's data-blocks (`bpy.data.objects`, `bpy.ops`)
- System-level Python functionality including subprocess spawning

## Security Risks and Attack Vectors

The breadth of access creates several concrete risk scenarios:

- **Data Destruction**: Malicious or buggy code can permanently delete scene assets using `bpy.ops.object.delete()` or `bpy.data.objects.remove()`
- **File System Exploitation**: Arbitrary code can read sensitive documents, overwrite system files, install persistence mechanisms, or exfiltrate data
- **Network Abuse**: HTTP requests can download malicious payloads, exfiltrate project files, or participate in DDoS attacks
- **Privilege Escalation**: The Python environment can spawn subprocesses, modify system settings, or install packages if the host OS permissions allow

## Mitigation Strategies

### Project-Recommended Safeguards

The repository explicitly documents these security measures in the README:

1. **User Awareness**: The project warns that the tool "allows running arbitrary Python code in Blender, which can be powerful but potentially dangerous" and advises always saving work before invocation
2. **Telemetry Control**: Users can disable telemetry—which could otherwise transmit code snippets—via the addon UI or by setting the `DISABLE_TELEMETRY=true` environment variable
3. **Environment Isolation**: For production or untrusted prompts, run Blender inside a virtual machine, container, or with a clean project file to limit blast radius
4. **Network Exposure**: Restrict the MCP server socket (default port 9876) to trusted clients only, avoiding public internet exposure

### Operational Best Practices

Beyond the project's recommendations, implement these controls:

- **Backup Protocol**: Maintain versioned backups of `.blend` files before any AI-assisted modification
- **Input Validation**: If extending the server, implement code whitelisting or sandboxing before forwarding to the execution layer
- **Monitoring**: Review logs where `logger.error` captures execution failures, watching for anomalous patterns that might indicate probing or attack attempts

## Code Execution Examples

### Direct Socket Client Implementation

This example demonstrates how the MCP server communicates with Blender's TCP socket:

```python
import socket
import json

def run_code_in_blender(code: str) -> str:
    with socket.create_connection(("localhost", 9876)) as sock:
        request = {
            "type": "execute_code",
            "params": {"code": code}
        }
        sock.sendall(json.dumps(request).encode("utf-8"))
        response = sock.recv(8192).decode("utf-8")
        result = json.loads(response)
        
        if result.get("status") == "error":
            raise RuntimeError(result.get("message"))
        return result.get("result", "")

# Example: Create geometry (safe operation)

run_code_in_blender("import bpy; bpy.ops.mesh.primitive_uv_sphere_add(radius=1)")

```

### MCP Tool Usage Pattern

When called through an MCP client, the payload structure looks like:

```json
{
  "type": "execute_code",
  "params": {
    "code": "import bpy; bpy.ops.object.select_all(action='SELECT')"
  }
}

```

### Safeguard Wrapper for Custom Extensions

For custom implementations, consider validation before execution:

```python
SAFE_MODULES = {"bpy", "mathutils", "math"}

def safe_exec(code: str) -> str:
    for line in code.splitlines():
        if line.strip().startswith("import"):
            mod = line.split()[1].split('.')[0]
            if mod not in SAFE_MODULES:
                raise PermissionError(f"Import of '{mod}' not allowed")
    return run_code_in_blender(code)

```

*Note: This illustrative check is not foolproof; production environments should use process isolation or dedicated sandbox libraries.*

## Summary

- **`execute_blender_code`** runs arbitrary Python via `exec()` in Blender's main thread, inheriting full system privileges
- **Critical files** include [`src/blender_mcp/server.py`](https://github.com/ahujasid/blender-mcp/blob/main/src/blender_mcp/server.py) (MCP tool definition) and [`addon.py`](https://github.com/ahujasid/blender-mcp/blob/main/addon.py) (execution handler using `exec`)
- **Primary risks** encompass data destruction, file system abuse, network exploitation, and potential privilege escalation
- **Essential mitigations** include telemetry disablement (`DISABLE_TELEMETRY=true`), sandboxed environments, pre-execution backups, and restricted network exposure

## Frequently Asked Questions

### What exactly does execute_blender_code do?

The `execute_blender_code` tool receives Python code strings from AI agents and executes them inside the running Blender process using Python's `exec()` function. This enables direct manipulation of Blender scenes but runs code with the same permissions as the Blender application itself, including file system and network access.

### Can execute_blender_code access my computer's files?

Yes. Because the code executes in Blender's Python interpreter with standard system privileges, it can read, write, or delete any files accessible to the user account running Blender. This includes documents, system files, or network-mounted drives accessible from the host environment.

### How do I disable telemetry in Blender MCP?

Set the `DISABLE_TELEMETRY=true` environment variable before starting the MCP server, or disable telemetry through the Blender addon UI. This prevents code snippets and usage data from being transmitted to external telemetry services, reducing the risk of sensitive code leakage.

### Is it safe to use execute_blender_code with Claude or Cursor?

Only use `execute_blender_code` with trusted AI clients in isolated environments. Always save your work before execution, consider running Blender inside a virtual machine or container, and avoid exposing the MCP server port to untrusted networks. The tool is safe when used with caution in controlled development environments but risky with untrusted prompts or public network exposure.