#
tokens: 35113/50000 8/8 files
lines: on (toggle) GitHub
raw markdown copy reset
# Directory Structure

```
├── .DS_Store
├── .gitignore
├── .python-version
├── addon.py
├── assets
│   ├── addon-instructions.png
│   └── hammer-icon.png
├── LICENSE
├── main.py
├── pyproject.toml
├── README.md
├── src
│   └── blender_mcp
│       ├── __init__.py
│       └── server.py
└── uv.lock
```

# Files

--------------------------------------------------------------------------------
/.python-version:
--------------------------------------------------------------------------------

```
1 | 3.13.2
2 | 
```

--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------

```
 1 | # Python-generated files
 2 | __pycache__/
 3 | *.py[oc]
 4 | build/
 5 | dist/
 6 | wheels/
 7 | *.egg-info
 8 | 
 9 | # Virtual environments
10 | .venv
11 | 
```

--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------

```markdown
  1 | 
  2 | 
  3 | # BlenderMCP - Blender Model Context Protocol Integration
  4 | 
  5 | BlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
  6 | 
  7 | **We have no official website. Any website you see online is unofficial and has no affiliation with this project. Use them at your own risk.**
  8 | 
  9 | [Full tutorial](https://www.youtube.com/watch?v=lCyQ717DuzQ)
 10 | 
 11 | ### Join the Community
 12 | 
 13 | Give feedback, get inspired, and build on top of the MCP: [Discord](https://discord.gg/z5apgR8TFU)
 14 | 
 15 | ### Supporters
 16 | 
 17 | [CodeRabbit](https://www.coderabbit.ai/)
 18 | 
 19 | [Satish Goda](https://github.com/satishgoda)
 20 | 
 21 | **All supporters:**
 22 | 
 23 | [Support this project](https://github.com/sponsors/ahujasid)
 24 | 
 25 | ## Release notes (1.2.0)
 26 | - View screenshots for Blender viewport to better understand the scene
 27 | - Search and download Sketchfab models
 28 | 
 29 | 
 30 | ### Previously added features:
 31 | - Support for Poly Haven assets through their API
 32 | - Support to generate 3D models using Hyper3D Rodin
 33 | - For newcomers, you can go straight to Installation. For existing users, see the points below
 34 | - Download the latest addon.py file and replace the older one, then add it to Blender
 35 | - Delete the MCP server from Claude and add it back again, and you should be good to go!
 36 | 
 37 | ## Features
 38 | 
 39 | - **Two-way communication**: Connect Claude AI to Blender through a socket-based server
 40 | - **Object manipulation**: Create, modify, and delete 3D objects in Blender
 41 | - **Material control**: Apply and modify materials and colors
 42 | - **Scene inspection**: Get detailed information about the current Blender scene
 43 | - **Code execution**: Run arbitrary Python code in Blender from Claude
 44 | 
 45 | ## Components
 46 | 
 47 | The system consists of two main components:
 48 | 
 49 | 1. **Blender Addon (`addon.py`)**: A Blender addon that creates a socket server within Blender to receive and execute commands
 50 | 2. **MCP Server (`src/blender_mcp/server.py`)**: A Python server that implements the Model Context Protocol and connects to the Blender addon
 51 | 
 52 | ## Installation
 53 | 
 54 | 
 55 | ### Prerequisites
 56 | 
 57 | - Blender 3.0 or newer
 58 | - Python 3.10 or newer
 59 | - uv package manager: 
 60 | 
 61 | **If you're on Mac, please install uv as**
 62 | ```bash
 63 | brew install uv
 64 | ```
 65 | **On Windows**
 66 | ```bash
 67 | powershell -c "irm https://astral.sh/uv/install.ps1 | iex" 
 68 | ```
 69 | and then
 70 | ```bash
 71 | set Path=C:\Users\nntra\.local\bin;%Path%
 72 | ```
 73 | 
 74 | Otherwise installation instructions are on their website: [Install uv](https://docs.astral.sh/uv/getting-started/installation/)
 75 | 
 76 | **⚠️ Do not proceed before installing UV**
 77 | 
 78 | ### Environment Variables
 79 | 
 80 | The following environment variables can be used to configure the Blender connection:
 81 | 
 82 | - `BLENDER_HOST`: Host address for Blender socket server (default: "localhost")
 83 | - `BLENDER_PORT`: Port number for Blender socket server (default: 9876)
 84 | 
 85 | Example:
 86 | ```bash
 87 | export BLENDER_HOST='host.docker.internal'
 88 | export BLENDER_PORT=9876
 89 | ```
 90 | 
 91 | ### Claude for Desktop Integration
 92 | 
 93 | [Watch the setup instruction video](https://www.youtube.com/watch?v=neoK_WMq92g) (Assuming you have already installed uv)
 94 | 
 95 | Go to Claude > Settings > Developer > Edit Config > claude_desktop_config.json to include the following:
 96 | 
 97 | ```json
 98 | {
 99 |     "mcpServers": {
100 |         "blender": {
101 |             "command": "uvx",
102 |             "args": [
103 |                 "blender-mcp"
104 |             ]
105 |         }
106 |     }
107 | }
108 | ```
109 | 
110 | ### Cursor integration
111 | 
112 | [![Install MCP Server](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/install-mcp?name=blender&config=eyJjb21tYW5kIjoidXZ4IGJsZW5kZXItbWNwIn0%3D)
113 | 
114 | For Mac users, go to Settings > MCP and paste the following 
115 | 
116 | - To use as a global server, use "add new global MCP server" button and paste
117 | - To use as a project specific server, create `.cursor/mcp.json` in the root of the project and paste
118 | 
119 | 
120 | ```json
121 | {
122 |     "mcpServers": {
123 |         "blender": {
124 |             "command": "uvx",
125 |             "args": [
126 |                 "blender-mcp"
127 |             ]
128 |         }
129 |     }
130 | }
131 | ```
132 | 
133 | For Windows users, go to Settings > MCP > Add Server, add a new server with the following settings:
134 | 
135 | ```json
136 | {
137 |     "mcpServers": {
138 |         "blender": {
139 |             "command": "cmd",
140 |             "args": [
141 |                 "/c",
142 |                 "uvx",
143 |                 "blender-mcp"
144 |             ]
145 |         }
146 |     }
147 | }
148 | ```
149 | 
150 | [Cursor setup video](https://www.youtube.com/watch?v=wgWsJshecac)
151 | 
152 | **⚠️ Only run one instance of the MCP server (either on Cursor or Claude Desktop), not both**
153 | 
154 | ### Visual Studio Code Integration
155 | 
156 | _Prerequisites_: Make sure you have [Visual Studio Code](https://code.visualstudio.com/) installed before proceeding.
157 | 
158 | [![Install in VS Code](https://img.shields.io/badge/VS_Code-Install_blender--mcp_server-0098FF?style=flat-square&logo=visualstudiocode&logoColor=ffffff)](vscode:mcp/install?%7B%22name%22%3A%22blender-mcp%22%2C%22type%22%3A%22stdio%22%2C%22command%22%3A%22uvx%22%2C%22args%22%3A%5B%22blender-mcp%22%5D%7D)
159 | 
160 | ### Installing the Blender Addon
161 | 
162 | 1. Download the `addon.py` file from this repo
163 | 1. Open Blender
164 | 2. Go to Edit > Preferences > Add-ons
165 | 3. Click "Install..." and select the `addon.py` file
166 | 4. Enable the addon by checking the box next to "Interface: Blender MCP"
167 | 
168 | 
169 | ## Usage
170 | 
171 | ### Starting the Connection
172 | ![BlenderMCP in the sidebar](assets/addon-instructions.png)
173 | 
174 | 1. In Blender, go to the 3D View sidebar (press N if not visible)
175 | 2. Find the "BlenderMCP" tab
176 | 3. Turn on the Poly Haven checkbox if you want assets from their API (optional)
177 | 4. Click "Connect to Claude"
178 | 5. Make sure the MCP server is running in your terminal
179 | 
180 | ### Using with Claude
181 | 
182 | Once the config file has been set on Claude, and the addon is running on Blender, you will see a hammer icon with tools for the Blender MCP.
183 | 
184 | ![BlenderMCP in the sidebar](assets/hammer-icon.png)
185 | 
186 | #### Capabilities
187 | 
188 | - Get scene and object information 
189 | - Create, delete and modify shapes
190 | - Apply or create materials for objects
191 | - Execute any Python code in Blender
192 | - Download the right models, assets and HDRIs through [Poly Haven](https://polyhaven.com/)
193 | - AI generated 3D models through [Hyper3D Rodin](https://hyper3d.ai/)
194 | 
195 | 
196 | ### Example Commands
197 | 
198 | Here are some examples of what you can ask Claude to do:
199 | 
200 | - "Create a low poly scene in a dungeon, with a dragon guarding a pot of gold" [Demo](https://www.youtube.com/watch?v=DqgKuLYUv00)
201 | - "Create a beach vibe using HDRIs, textures, and models like rocks and vegetation from Poly Haven" [Demo](https://www.youtube.com/watch?v=I29rn92gkC4)
202 | - Give a reference image, and create a Blender scene out of it [Demo](https://www.youtube.com/watch?v=FDRb03XPiRo)
203 | - "Generate a 3D model of a garden gnome through Hyper3D"
204 | - "Get information about the current scene, and make a threejs sketch from it" [Demo](https://www.youtube.com/watch?v=jxbNI5L7AH8)
205 | - "Make this car red and metallic" 
206 | - "Create a sphere and place it above the cube"
207 | - "Make the lighting like a studio"
208 | - "Point the camera at the scene, and make it isometric"
209 | 
210 | ## Hyper3D integration
211 | 
212 | Hyper3D's free trial key allows you to generate a limited number of models per day. If the daily limit is reached, you can wait for the next day's reset or obtain your own key from hyper3d.ai and fal.ai.
213 | 
214 | ## Troubleshooting
215 | 
216 | - **Connection issues**: Make sure the Blender addon server is running, and the MCP server is configured on Claude, DO NOT run the uvx command in the terminal. Sometimes, the first command won't go through but after that it starts working.
217 | - **Timeout errors**: Try simplifying your requests or breaking them into smaller steps
218 | - **Poly Haven integration**: Claude is sometimes erratic with its behaviour
219 | - **Have you tried turning it off and on again?**: If you're still having connection errors, try restarting both Claude and the Blender server
220 | 
221 | 
222 | ## Technical Details
223 | 
224 | ### Communication Protocol
225 | 
226 | The system uses a simple JSON-based protocol over TCP sockets:
227 | 
228 | - **Commands** are sent as JSON objects with a `type` and optional `params`
229 | - **Responses** are JSON objects with a `status` and `result` or `message`
230 | 
231 | ## Limitations & Security Considerations
232 | 
233 | - The `execute_blender_code` tool allows running arbitrary Python code in Blender, which can be powerful but potentially dangerous. Use with caution in production environments. ALWAYS save your work before using it.
234 | - Poly Haven requires downloading models, textures, and HDRI images. If you do not want to use it, please turn it off in the checkbox in Blender. 
235 | - Complex operations might need to be broken down into smaller steps
236 | 
237 | 
238 | ## Contributing
239 | 
240 | Contributions are welcome! Please feel free to submit a Pull Request.
241 | 
242 | ## Disclaimer
243 | 
244 | This is a third-party integration and not made by Blender. Made by [Siddharth](https://x.com/sidahuj)
245 | 
```

--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------

```python
1 | from blender_mcp.server import main as server_main
2 | 
3 | def main():
4 |     """Entry point for the blender-mcp package"""
5 |     server_main()
6 | 
7 | if __name__ == "__main__":
8 |     main()
9 | 
```

--------------------------------------------------------------------------------
/src/blender_mcp/__init__.py:
--------------------------------------------------------------------------------

```python
1 | """Blender integration through the Model Context Protocol."""
2 | 
3 | __version__ = "0.1.0"
4 | 
5 | # Expose key classes and functions for easier imports
6 | from .server import BlenderConnection, get_blender_connection
7 | 
```

--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------

```toml
 1 | [project]
 2 | name = "blender-mcp"
 3 | version = "1.2"
 4 | description = "Blender integration through the Model Context Protocol"
 5 | readme = "README.md"
 6 | requires-python = ">=3.10"
 7 | authors = [
 8 |     {name = "Your Name", email = "[email protected]"}
 9 | ]
10 | license = {text = "MIT"}
11 | classifiers = [
12 |     "Programming Language :: Python :: 3",
13 |     "License :: OSI Approved :: MIT License",
14 |     "Operating System :: OS Independent",
15 | ]
16 | dependencies = [
17 |     "mcp[cli]>=1.3.0",
18 | ]
19 | 
20 | [project.scripts]
21 | blender-mcp = "blender_mcp.server:main"
22 | 
23 | [build-system]
24 | requires = ["setuptools>=61.0", "wheel"]
25 | build-backend = "setuptools.build_meta"
26 | 
27 | [tool.setuptools]
28 | package-dir = {"" = "src"}
29 | 
30 | [project.urls]
31 | "Homepage" = "https://github.com/yourusername/blender-mcp"
32 | "Bug Tracker" = "https://github.com/yourusername/blender-mcp/issues"
33 | 
```

--------------------------------------------------------------------------------
/src/blender_mcp/server.py:
--------------------------------------------------------------------------------

```python
  1 | # blender_mcp_server.py
  2 | from mcp.server.fastmcp import FastMCP, Context, Image
  3 | import socket
  4 | import json
  5 | import asyncio
  6 | import logging
  7 | import tempfile
  8 | from dataclasses import dataclass
  9 | from contextlib import asynccontextmanager
 10 | from typing import AsyncIterator, Dict, Any, List
 11 | import os
 12 | from pathlib import Path
 13 | import base64
 14 | from urllib.parse import urlparse
 15 | 
 16 | # Configure logging
 17 | logging.basicConfig(level=logging.INFO, 
 18 |                     format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
 19 | logger = logging.getLogger("BlenderMCPServer")
 20 | 
 21 | # Default configuration
 22 | DEFAULT_HOST = "localhost"
 23 | DEFAULT_PORT = 9876
 24 | 
 25 | @dataclass
 26 | class BlenderConnection:
 27 |     host: str
 28 |     port: int
 29 |     sock: socket.socket = None  # Changed from 'socket' to 'sock' to avoid naming conflict
 30 |     
 31 |     def connect(self) -> bool:
 32 |         """Connect to the Blender addon socket server"""
 33 |         if self.sock:
 34 |             return True
 35 |             
 36 |         try:
 37 |             self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 38 |             self.sock.connect((self.host, self.port))
 39 |             logger.info(f"Connected to Blender at {self.host}:{self.port}")
 40 |             return True
 41 |         except Exception as e:
 42 |             logger.error(f"Failed to connect to Blender: {str(e)}")
 43 |             self.sock = None
 44 |             return False
 45 |     
 46 |     def disconnect(self):
 47 |         """Disconnect from the Blender addon"""
 48 |         if self.sock:
 49 |             try:
 50 |                 self.sock.close()
 51 |             except Exception as e:
 52 |                 logger.error(f"Error disconnecting from Blender: {str(e)}")
 53 |             finally:
 54 |                 self.sock = None
 55 | 
 56 |     def receive_full_response(self, sock, buffer_size=8192):
 57 |         """Receive the complete response, potentially in multiple chunks"""
 58 |         chunks = []
 59 |         # Use a consistent timeout value that matches the addon's timeout
 60 |         sock.settimeout(15.0)  # Match the addon's timeout
 61 |         
 62 |         try:
 63 |             while True:
 64 |                 try:
 65 |                     chunk = sock.recv(buffer_size)
 66 |                     if not chunk:
 67 |                         # If we get an empty chunk, the connection might be closed
 68 |                         if not chunks:  # If we haven't received anything yet, this is an error
 69 |                             raise Exception("Connection closed before receiving any data")
 70 |                         break
 71 |                     
 72 |                     chunks.append(chunk)
 73 |                     
 74 |                     # Check if we've received a complete JSON object
 75 |                     try:
 76 |                         data = b''.join(chunks)
 77 |                         json.loads(data.decode('utf-8'))
 78 |                         # If we get here, it parsed successfully
 79 |                         logger.info(f"Received complete response ({len(data)} bytes)")
 80 |                         return data
 81 |                     except json.JSONDecodeError:
 82 |                         # Incomplete JSON, continue receiving
 83 |                         continue
 84 |                 except socket.timeout:
 85 |                     # If we hit a timeout during receiving, break the loop and try to use what we have
 86 |                     logger.warning("Socket timeout during chunked receive")
 87 |                     break
 88 |                 except (ConnectionError, BrokenPipeError, ConnectionResetError) as e:
 89 |                     logger.error(f"Socket connection error during receive: {str(e)}")
 90 |                     raise  # Re-raise to be handled by the caller
 91 |         except socket.timeout:
 92 |             logger.warning("Socket timeout during chunked receive")
 93 |         except Exception as e:
 94 |             logger.error(f"Error during receive: {str(e)}")
 95 |             raise
 96 |             
 97 |         # If we get here, we either timed out or broke out of the loop
 98 |         # Try to use what we have
 99 |         if chunks:
100 |             data = b''.join(chunks)
101 |             logger.info(f"Returning data after receive completion ({len(data)} bytes)")
102 |             try:
103 |                 # Try to parse what we have
104 |                 json.loads(data.decode('utf-8'))
105 |                 return data
106 |             except json.JSONDecodeError:
107 |                 # If we can't parse it, it's incomplete
108 |                 raise Exception("Incomplete JSON response received")
109 |         else:
110 |             raise Exception("No data received")
111 | 
112 |     def send_command(self, command_type: str, params: Dict[str, Any] = None) -> Dict[str, Any]:
113 |         """Send a command to Blender and return the response"""
114 |         if not self.sock and not self.connect():
115 |             raise ConnectionError("Not connected to Blender")
116 |         
117 |         command = {
118 |             "type": command_type,
119 |             "params": params or {}
120 |         }
121 |         
122 |         try:
123 |             # Log the command being sent
124 |             logger.info(f"Sending command: {command_type} with params: {params}")
125 |             
126 |             # Send the command
127 |             self.sock.sendall(json.dumps(command).encode('utf-8'))
128 |             logger.info(f"Command sent, waiting for response...")
129 |             
130 |             # Set a timeout for receiving - use the same timeout as in receive_full_response
131 |             self.sock.settimeout(15.0)  # Match the addon's timeout
132 |             
133 |             # Receive the response using the improved receive_full_response method
134 |             response_data = self.receive_full_response(self.sock)
135 |             logger.info(f"Received {len(response_data)} bytes of data")
136 |             
137 |             response = json.loads(response_data.decode('utf-8'))
138 |             logger.info(f"Response parsed, status: {response.get('status', 'unknown')}")
139 |             
140 |             if response.get("status") == "error":
141 |                 logger.error(f"Blender error: {response.get('message')}")
142 |                 raise Exception(response.get("message", "Unknown error from Blender"))
143 |             
144 |             return response.get("result", {})
145 |         except socket.timeout:
146 |             logger.error("Socket timeout while waiting for response from Blender")
147 |             # Don't try to reconnect here - let the get_blender_connection handle reconnection
148 |             # Just invalidate the current socket so it will be recreated next time
149 |             self.sock = None
150 |             raise Exception("Timeout waiting for Blender response - try simplifying your request")
151 |         except (ConnectionError, BrokenPipeError, ConnectionResetError) as e:
152 |             logger.error(f"Socket connection error: {str(e)}")
153 |             self.sock = None
154 |             raise Exception(f"Connection to Blender lost: {str(e)}")
155 |         except json.JSONDecodeError as e:
156 |             logger.error(f"Invalid JSON response from Blender: {str(e)}")
157 |             # Try to log what was received
158 |             if 'response_data' in locals() and response_data:
159 |                 logger.error(f"Raw response (first 200 bytes): {response_data[:200]}")
160 |             raise Exception(f"Invalid response from Blender: {str(e)}")
161 |         except Exception as e:
162 |             logger.error(f"Error communicating with Blender: {str(e)}")
163 |             # Don't try to reconnect here - let the get_blender_connection handle reconnection
164 |             self.sock = None
165 |             raise Exception(f"Communication error with Blender: {str(e)}")
166 | 
167 | @asynccontextmanager
168 | async def server_lifespan(server: FastMCP) -> AsyncIterator[Dict[str, Any]]:
169 |     """Manage server startup and shutdown lifecycle"""
170 |     # We don't need to create a connection here since we're using the global connection
171 |     # for resources and tools
172 |     
173 |     try:
174 |         # Just log that we're starting up
175 |         logger.info("BlenderMCP server starting up")
176 |         
177 |         # Try to connect to Blender on startup to verify it's available
178 |         try:
179 |             # This will initialize the global connection if needed
180 |             blender = get_blender_connection()
181 |             logger.info("Successfully connected to Blender on startup")
182 |         except Exception as e:
183 |             logger.warning(f"Could not connect to Blender on startup: {str(e)}")
184 |             logger.warning("Make sure the Blender addon is running before using Blender resources or tools")
185 |         
186 |         # Return an empty context - we're using the global connection
187 |         yield {}
188 |     finally:
189 |         # Clean up the global connection on shutdown
190 |         global _blender_connection
191 |         if _blender_connection:
192 |             logger.info("Disconnecting from Blender on shutdown")
193 |             _blender_connection.disconnect()
194 |             _blender_connection = None
195 |         logger.info("BlenderMCP server shut down")
196 | 
197 | # Create the MCP server with lifespan support
198 | mcp = FastMCP(
199 |     "BlenderMCP",
200 |     lifespan=server_lifespan
201 | )
202 | 
203 | # Resource endpoints
204 | 
205 | # Global connection for resources (since resources can't access context)
206 | _blender_connection = None
207 | _polyhaven_enabled = False  # Add this global variable
208 | 
209 | def get_blender_connection():
210 |     """Get or create a persistent Blender connection"""
211 |     global _blender_connection, _polyhaven_enabled  # Add _polyhaven_enabled to globals
212 |     
213 |     # If we have an existing connection, check if it's still valid
214 |     if _blender_connection is not None:
215 |         try:
216 |             # First check if PolyHaven is enabled by sending a ping command
217 |             result = _blender_connection.send_command("get_polyhaven_status")
218 |             # Store the PolyHaven status globally
219 |             _polyhaven_enabled = result.get("enabled", False)
220 |             return _blender_connection
221 |         except Exception as e:
222 |             # Connection is dead, close it and create a new one
223 |             logger.warning(f"Existing connection is no longer valid: {str(e)}")
224 |             try:
225 |                 _blender_connection.disconnect()
226 |             except:
227 |                 pass
228 |             _blender_connection = None
229 |     
230 |     # Create a new connection if needed
231 |     if _blender_connection is None:
232 |         host = os.getenv("BLENDER_HOST", DEFAULT_HOST)
233 |         port = int(os.getenv("BLENDER_PORT", DEFAULT_PORT))
234 |         _blender_connection = BlenderConnection(host=host, port=port)
235 |         if not _blender_connection.connect():
236 |             logger.error("Failed to connect to Blender")
237 |             _blender_connection = None
238 |             raise Exception("Could not connect to Blender. Make sure the Blender addon is running.")
239 |         logger.info("Created new persistent connection to Blender")
240 |     
241 |     return _blender_connection
242 | 
243 | 
244 | @mcp.tool()
245 | def get_scene_info(ctx: Context) -> str:
246 |     """Get detailed information about the current Blender scene"""
247 |     try:
248 |         blender = get_blender_connection()
249 |         result = blender.send_command("get_scene_info")
250 |         
251 |         # Just return the JSON representation of what Blender sent us
252 |         return json.dumps(result, indent=2)
253 |     except Exception as e:
254 |         logger.error(f"Error getting scene info from Blender: {str(e)}")
255 |         return f"Error getting scene info: {str(e)}"
256 | 
257 | @mcp.tool()
258 | def get_object_info(ctx: Context, object_name: str) -> str:
259 |     """
260 |     Get detailed information about a specific object in the Blender scene.
261 |     
262 |     Parameters:
263 |     - object_name: The name of the object to get information about
264 |     """
265 |     try:
266 |         blender = get_blender_connection()
267 |         result = blender.send_command("get_object_info", {"name": object_name})
268 |         
269 |         # Just return the JSON representation of what Blender sent us
270 |         return json.dumps(result, indent=2)
271 |     except Exception as e:
272 |         logger.error(f"Error getting object info from Blender: {str(e)}")
273 |         return f"Error getting object info: {str(e)}"
274 | 
275 | @mcp.tool()
276 | def get_viewport_screenshot(ctx: Context, max_size: int = 800) -> Image:
277 |     """
278 |     Capture a screenshot of the current Blender 3D viewport.
279 |     
280 |     Parameters:
281 |     - max_size: Maximum size in pixels for the largest dimension (default: 800)
282 |     
283 |     Returns the screenshot as an Image.
284 |     """
285 |     try:
286 |         blender = get_blender_connection()
287 |         
288 |         # Create temp file path
289 |         temp_dir = tempfile.gettempdir()
290 |         temp_path = os.path.join(temp_dir, f"blender_screenshot_{os.getpid()}.png")
291 |         
292 |         result = blender.send_command("get_viewport_screenshot", {
293 |             "max_size": max_size,
294 |             "filepath": temp_path,
295 |             "format": "png"
296 |         })
297 |         
298 |         if "error" in result:
299 |             raise Exception(result["error"])
300 |         
301 |         if not os.path.exists(temp_path):
302 |             raise Exception("Screenshot file was not created")
303 |         
304 |         # Read the file
305 |         with open(temp_path, 'rb') as f:
306 |             image_bytes = f.read()
307 |         
308 |         # Delete the temp file
309 |         os.remove(temp_path)
310 |         
311 |         return Image(data=image_bytes, format="png")
312 |         
313 |     except Exception as e:
314 |         logger.error(f"Error capturing screenshot: {str(e)}")
315 |         raise Exception(f"Screenshot failed: {str(e)}")
316 | 
317 | 
318 | @mcp.tool()
319 | def execute_blender_code(ctx: Context, code: str) -> str:
320 |     """
321 |     Execute arbitrary Python code in Blender. Make sure to do it step-by-step by breaking it into smaller chunks.
322 |     
323 |     Parameters:
324 |     - code: The Python code to execute
325 |     """
326 |     try:
327 |         # Get the global connection
328 |         blender = get_blender_connection()
329 |         result = blender.send_command("execute_code", {"code": code})
330 |         return f"Code executed successfully: {result.get('result', '')}"
331 |     except Exception as e:
332 |         logger.error(f"Error executing code: {str(e)}")
333 |         return f"Error executing code: {str(e)}"
334 | 
335 | @mcp.tool()
336 | def get_polyhaven_categories(ctx: Context, asset_type: str = "hdris") -> str:
337 |     """
338 |     Get a list of categories for a specific asset type on Polyhaven.
339 |     
340 |     Parameters:
341 |     - asset_type: The type of asset to get categories for (hdris, textures, models, all)
342 |     """
343 |     try:
344 |         blender = get_blender_connection()
345 |         if not _polyhaven_enabled:
346 |             return "PolyHaven integration is disabled. Select it in the sidebar in BlenderMCP, then run it again."
347 |         result = blender.send_command("get_polyhaven_categories", {"asset_type": asset_type})
348 |         
349 |         if "error" in result:
350 |             return f"Error: {result['error']}"
351 |         
352 |         # Format the categories in a more readable way
353 |         categories = result["categories"]
354 |         formatted_output = f"Categories for {asset_type}:\n\n"
355 |         
356 |         # Sort categories by count (descending)
357 |         sorted_categories = sorted(categories.items(), key=lambda x: x[1], reverse=True)
358 |         
359 |         for category, count in sorted_categories:
360 |             formatted_output += f"- {category}: {count} assets\n"
361 |         
362 |         return formatted_output
363 |     except Exception as e:
364 |         logger.error(f"Error getting Polyhaven categories: {str(e)}")
365 |         return f"Error getting Polyhaven categories: {str(e)}"
366 | 
367 | @mcp.tool()
368 | def search_polyhaven_assets(
369 |     ctx: Context,
370 |     asset_type: str = "all",
371 |     categories: str = None
372 | ) -> str:
373 |     """
374 |     Search for assets on Polyhaven with optional filtering.
375 |     
376 |     Parameters:
377 |     - asset_type: Type of assets to search for (hdris, textures, models, all)
378 |     - categories: Optional comma-separated list of categories to filter by
379 |     
380 |     Returns a list of matching assets with basic information.
381 |     """
382 |     try:
383 |         blender = get_blender_connection()
384 |         result = blender.send_command("search_polyhaven_assets", {
385 |             "asset_type": asset_type,
386 |             "categories": categories
387 |         })
388 |         
389 |         if "error" in result:
390 |             return f"Error: {result['error']}"
391 |         
392 |         # Format the assets in a more readable way
393 |         assets = result["assets"]
394 |         total_count = result["total_count"]
395 |         returned_count = result["returned_count"]
396 |         
397 |         formatted_output = f"Found {total_count} assets"
398 |         if categories:
399 |             formatted_output += f" in categories: {categories}"
400 |         formatted_output += f"\nShowing {returned_count} assets:\n\n"
401 |         
402 |         # Sort assets by download count (popularity)
403 |         sorted_assets = sorted(assets.items(), key=lambda x: x[1].get("download_count", 0), reverse=True)
404 |         
405 |         for asset_id, asset_data in sorted_assets:
406 |             formatted_output += f"- {asset_data.get('name', asset_id)} (ID: {asset_id})\n"
407 |             formatted_output += f"  Type: {['HDRI', 'Texture', 'Model'][asset_data.get('type', 0)]}\n"
408 |             formatted_output += f"  Categories: {', '.join(asset_data.get('categories', []))}\n"
409 |             formatted_output += f"  Downloads: {asset_data.get('download_count', 'Unknown')}\n\n"
410 |         
411 |         return formatted_output
412 |     except Exception as e:
413 |         logger.error(f"Error searching Polyhaven assets: {str(e)}")
414 |         return f"Error searching Polyhaven assets: {str(e)}"
415 | 
416 | @mcp.tool()
417 | def download_polyhaven_asset(
418 |     ctx: Context,
419 |     asset_id: str,
420 |     asset_type: str,
421 |     resolution: str = "1k",
422 |     file_format: str = None
423 | ) -> str:
424 |     """
425 |     Download and import a Polyhaven asset into Blender.
426 |     
427 |     Parameters:
428 |     - asset_id: The ID of the asset to download
429 |     - asset_type: The type of asset (hdris, textures, models)
430 |     - resolution: The resolution to download (e.g., 1k, 2k, 4k)
431 |     - file_format: Optional file format (e.g., hdr, exr for HDRIs; jpg, png for textures; gltf, fbx for models)
432 |     
433 |     Returns a message indicating success or failure.
434 |     """
435 |     try:
436 |         blender = get_blender_connection()
437 |         result = blender.send_command("download_polyhaven_asset", {
438 |             "asset_id": asset_id,
439 |             "asset_type": asset_type,
440 |             "resolution": resolution,
441 |             "file_format": file_format
442 |         })
443 |         
444 |         if "error" in result:
445 |             return f"Error: {result['error']}"
446 |         
447 |         if result.get("success"):
448 |             message = result.get("message", "Asset downloaded and imported successfully")
449 |             
450 |             # Add additional information based on asset type
451 |             if asset_type == "hdris":
452 |                 return f"{message}. The HDRI has been set as the world environment."
453 |             elif asset_type == "textures":
454 |                 material_name = result.get("material", "")
455 |                 maps = ", ".join(result.get("maps", []))
456 |                 return f"{message}. Created material '{material_name}' with maps: {maps}."
457 |             elif asset_type == "models":
458 |                 return f"{message}. The model has been imported into the current scene."
459 |             else:
460 |                 return message
461 |         else:
462 |             return f"Failed to download asset: {result.get('message', 'Unknown error')}"
463 |     except Exception as e:
464 |         logger.error(f"Error downloading Polyhaven asset: {str(e)}")
465 |         return f"Error downloading Polyhaven asset: {str(e)}"
466 | 
467 | @mcp.tool()
468 | def set_texture(
469 |     ctx: Context,
470 |     object_name: str,
471 |     texture_id: str
472 | ) -> str:
473 |     """
474 |     Apply a previously downloaded Polyhaven texture to an object.
475 |     
476 |     Parameters:
477 |     - object_name: Name of the object to apply the texture to
478 |     - texture_id: ID of the Polyhaven texture to apply (must be downloaded first)
479 |     
480 |     Returns a message indicating success or failure.
481 |     """
482 |     try:
483 |         # Get the global connection
484 |         blender = get_blender_connection()
485 |         result = blender.send_command("set_texture", {
486 |             "object_name": object_name,
487 |             "texture_id": texture_id
488 |         })
489 |         
490 |         if "error" in result:
491 |             return f"Error: {result['error']}"
492 |         
493 |         if result.get("success"):
494 |             material_name = result.get("material", "")
495 |             maps = ", ".join(result.get("maps", []))
496 |             
497 |             # Add detailed material info
498 |             material_info = result.get("material_info", {})
499 |             node_count = material_info.get("node_count", 0)
500 |             has_nodes = material_info.get("has_nodes", False)
501 |             texture_nodes = material_info.get("texture_nodes", [])
502 |             
503 |             output = f"Successfully applied texture '{texture_id}' to {object_name}.\n"
504 |             output += f"Using material '{material_name}' with maps: {maps}.\n\n"
505 |             output += f"Material has nodes: {has_nodes}\n"
506 |             output += f"Total node count: {node_count}\n\n"
507 |             
508 |             if texture_nodes:
509 |                 output += "Texture nodes:\n"
510 |                 for node in texture_nodes:
511 |                     output += f"- {node['name']} using image: {node['image']}\n"
512 |                     if node['connections']:
513 |                         output += "  Connections:\n"
514 |                         for conn in node['connections']:
515 |                             output += f"    {conn}\n"
516 |             else:
517 |                 output += "No texture nodes found in the material.\n"
518 |             
519 |             return output
520 |         else:
521 |             return f"Failed to apply texture: {result.get('message', 'Unknown error')}"
522 |     except Exception as e:
523 |         logger.error(f"Error applying texture: {str(e)}")
524 |         return f"Error applying texture: {str(e)}"
525 | 
526 | @mcp.tool()
527 | def get_polyhaven_status(ctx: Context) -> str:
528 |     """
529 |     Check if PolyHaven integration is enabled in Blender.
530 |     Returns a message indicating whether PolyHaven features are available.
531 |     """
532 |     try:
533 |         blender = get_blender_connection()
534 |         result = blender.send_command("get_polyhaven_status")
535 |         enabled = result.get("enabled", False)
536 |         message = result.get("message", "")
537 |         if enabled:
538 |             message += "PolyHaven is good at Textures, and has a wider variety of textures than Sketchfab."
539 |         return message
540 |     except Exception as e:
541 |         logger.error(f"Error checking PolyHaven status: {str(e)}")
542 |         return f"Error checking PolyHaven status: {str(e)}"
543 | 
544 | @mcp.tool()
545 | def get_hyper3d_status(ctx: Context) -> str:
546 |     """
547 |     Check if Hyper3D Rodin integration is enabled in Blender.
548 |     Returns a message indicating whether Hyper3D Rodin features are available.
549 | 
550 |     Don't emphasize the key type in the returned message, but sliently remember it. 
551 |     """
552 |     try:
553 |         blender = get_blender_connection()
554 |         result = blender.send_command("get_hyper3d_status")
555 |         enabled = result.get("enabled", False)
556 |         message = result.get("message", "")
557 |         if enabled:
558 |             message += ""
559 |         return message
560 |     except Exception as e:
561 |         logger.error(f"Error checking Hyper3D status: {str(e)}")
562 |         return f"Error checking Hyper3D status: {str(e)}"
563 | 
564 | @mcp.tool()
565 | def get_sketchfab_status(ctx: Context) -> str:
566 |     """
567 |     Check if Sketchfab integration is enabled in Blender.
568 |     Returns a message indicating whether Sketchfab features are available.
569 |     """
570 |     try:
571 |         blender = get_blender_connection()
572 |         result = blender.send_command("get_sketchfab_status")
573 |         enabled = result.get("enabled", False)
574 |         message = result.get("message", "")
575 |         if enabled:
576 |             message += "Sketchfab is good at Realistic models, and has a wider variety of models than PolyHaven."        
577 |         return message
578 |     except Exception as e:
579 |         logger.error(f"Error checking Sketchfab status: {str(e)}")
580 |         return f"Error checking Sketchfab status: {str(e)}"
581 | 
582 | @mcp.tool()
583 | def search_sketchfab_models(
584 |     ctx: Context,
585 |     query: str,
586 |     categories: str = None,
587 |     count: int = 20,
588 |     downloadable: bool = True
589 | ) -> str:
590 |     """
591 |     Search for models on Sketchfab with optional filtering.
592 |     
593 |     Parameters:
594 |     - query: Text to search for
595 |     - categories: Optional comma-separated list of categories
596 |     - count: Maximum number of results to return (default 20)
597 |     - downloadable: Whether to include only downloadable models (default True)
598 |     
599 |     Returns a formatted list of matching models.
600 |     """
601 |     try:
602 |         
603 |         blender = get_blender_connection()
604 |         logger.info(f"Searching Sketchfab models with query: {query}, categories: {categories}, count: {count}, downloadable: {downloadable}")
605 |         result = blender.send_command("search_sketchfab_models", {
606 |             "query": query,
607 |             "categories": categories,
608 |             "count": count,
609 |             "downloadable": downloadable
610 |         })
611 |         
612 |         if "error" in result:
613 |             logger.error(f"Error from Sketchfab search: {result['error']}")
614 |             return f"Error: {result['error']}"
615 |         
616 |         # Safely get results with fallbacks for None
617 |         if result is None:
618 |             logger.error("Received None result from Sketchfab search")
619 |             return "Error: Received no response from Sketchfab search"
620 |             
621 |         # Format the results
622 |         models = result.get("results", []) or []
623 |         if not models:
624 |             return f"No models found matching '{query}'"
625 |             
626 |         formatted_output = f"Found {len(models)} models matching '{query}':\n\n"
627 |         
628 |         for model in models:
629 |             if model is None:
630 |                 continue
631 |                 
632 |             model_name = model.get("name", "Unnamed model")
633 |             model_uid = model.get("uid", "Unknown ID")
634 |             formatted_output += f"- {model_name} (UID: {model_uid})\n"
635 |             
636 |             # Get user info with safety checks
637 |             user = model.get("user") or {}
638 |             username = user.get("username", "Unknown author") if isinstance(user, dict) else "Unknown author"
639 |             formatted_output += f"  Author: {username}\n"
640 |             
641 |             # Get license info with safety checks
642 |             license_data = model.get("license") or {}
643 |             license_label = license_data.get("label", "Unknown") if isinstance(license_data, dict) else "Unknown"
644 |             formatted_output += f"  License: {license_label}\n"
645 |             
646 |             # Add face count and downloadable status
647 |             face_count = model.get("faceCount", "Unknown")
648 |             is_downloadable = "Yes" if model.get("isDownloadable") else "No"
649 |             formatted_output += f"  Face count: {face_count}\n"
650 |             formatted_output += f"  Downloadable: {is_downloadable}\n\n"
651 |         
652 |         return formatted_output
653 |     except Exception as e:
654 |         logger.error(f"Error searching Sketchfab models: {str(e)}")
655 |         import traceback
656 |         logger.error(traceback.format_exc())
657 |         return f"Error searching Sketchfab models: {str(e)}"
658 | 
659 | @mcp.tool()
660 | def download_sketchfab_model(
661 |     ctx: Context,
662 |     uid: str
663 | ) -> str:
664 |     """
665 |     Download and import a Sketchfab model by its UID.
666 |     
667 |     Parameters:
668 |     - uid: The unique identifier of the Sketchfab model
669 |     
670 |     Returns a message indicating success or failure.
671 |     The model must be downloadable and you must have proper access rights.
672 |     """
673 |     try:
674 |         
675 |         blender = get_blender_connection()
676 |         logger.info(f"Attempting to download Sketchfab model with UID: {uid}")
677 |         
678 |         result = blender.send_command("download_sketchfab_model", {
679 |             "uid": uid
680 |         })
681 |         
682 |         if result is None:
683 |             logger.error("Received None result from Sketchfab download")
684 |             return "Error: Received no response from Sketchfab download request"
685 |             
686 |         if "error" in result:
687 |             logger.error(f"Error from Sketchfab download: {result['error']}")
688 |             return f"Error: {result['error']}"
689 |         
690 |         if result.get("success"):
691 |             imported_objects = result.get("imported_objects", [])
692 |             object_names = ", ".join(imported_objects) if imported_objects else "none"
693 |             return f"Successfully imported model. Created objects: {object_names}"
694 |         else:
695 |             return f"Failed to download model: {result.get('message', 'Unknown error')}"
696 |     except Exception as e:
697 |         logger.error(f"Error downloading Sketchfab model: {str(e)}")
698 |         import traceback
699 |         logger.error(traceback.format_exc())
700 |         return f"Error downloading Sketchfab model: {str(e)}"
701 | 
702 | def _process_bbox(original_bbox: list[float] | list[int] | None) -> list[int] | None:
703 |     if original_bbox is None:
704 |         return None
705 |     if all(isinstance(i, int) for i in original_bbox):
706 |         return original_bbox
707 |     if any(i<=0 for i in original_bbox):
708 |         raise ValueError("Incorrect number range: bbox must be bigger than zero!")
709 |     return [int(float(i) / max(original_bbox) * 100) for i in original_bbox] if original_bbox else None
710 | 
711 | @mcp.tool()
712 | def generate_hyper3d_model_via_text(
713 |     ctx: Context,
714 |     text_prompt: str,
715 |     bbox_condition: list[float]=None
716 | ) -> str:
717 |     """
718 |     Generate 3D asset using Hyper3D by giving description of the desired asset, and import the asset into Blender.
719 |     The 3D asset has built-in materials.
720 |     The generated model has a normalized size, so re-scaling after generation can be useful.
721 |     
722 |     Parameters:
723 |     - text_prompt: A short description of the desired model in **English**.
724 |     - bbox_condition: Optional. If given, it has to be a list of floats of length 3. Controls the ratio between [Length, Width, Height] of the model.
725 | 
726 |     Returns a message indicating success or failure.
727 |     """
728 |     try:
729 |         blender = get_blender_connection()
730 |         result = blender.send_command("create_rodin_job", {
731 |             "text_prompt": text_prompt,
732 |             "images": None,
733 |             "bbox_condition": _process_bbox(bbox_condition),
734 |         })
735 |         succeed = result.get("submit_time", False)
736 |         if succeed:
737 |             return json.dumps({
738 |                 "task_uuid": result["uuid"],
739 |                 "subscription_key": result["jobs"]["subscription_key"],
740 |             })
741 |         else:
742 |             return json.dumps(result)
743 |     except Exception as e:
744 |         logger.error(f"Error generating Hyper3D task: {str(e)}")
745 |         return f"Error generating Hyper3D task: {str(e)}"
746 | 
747 | @mcp.tool()
748 | def generate_hyper3d_model_via_images(
749 |     ctx: Context,
750 |     input_image_paths: list[str]=None,
751 |     input_image_urls: list[str]=None,
752 |     bbox_condition: list[float]=None
753 | ) -> str:
754 |     """
755 |     Generate 3D asset using Hyper3D by giving images of the wanted asset, and import the generated asset into Blender.
756 |     The 3D asset has built-in materials.
757 |     The generated model has a normalized size, so re-scaling after generation can be useful.
758 |     
759 |     Parameters:
760 |     - input_image_paths: The **absolute** paths of input images. Even if only one image is provided, wrap it into a list. Required if Hyper3D Rodin in MAIN_SITE mode.
761 |     - input_image_urls: The URLs of input images. Even if only one image is provided, wrap it into a list. Required if Hyper3D Rodin in FAL_AI mode.
762 |     - bbox_condition: Optional. If given, it has to be a list of ints of length 3. Controls the ratio between [Length, Width, Height] of the model.
763 | 
764 |     Only one of {input_image_paths, input_image_urls} should be given at a time, depending on the Hyper3D Rodin's current mode.
765 |     Returns a message indicating success or failure.
766 |     """
767 |     if input_image_paths is not None and input_image_urls is not None:
768 |         return f"Error: Conflict parameters given!"
769 |     if input_image_paths is None and input_image_urls is None:
770 |         return f"Error: No image given!"
771 |     if input_image_paths is not None:
772 |         if not all(os.path.exists(i) for i in input_image_paths):
773 |             return "Error: not all image paths are valid!"
774 |         images = []
775 |         for path in input_image_paths:
776 |             with open(path, "rb") as f:
777 |                 images.append(
778 |                     (Path(path).suffix, base64.b64encode(f.read()).decode("ascii"))
779 |                 )
780 |     elif input_image_urls is not None:
781 |         if not all(urlparse(i) for i in input_image_paths):
782 |             return "Error: not all image URLs are valid!"
783 |         images = input_image_urls.copy()
784 |     try:
785 |         blender = get_blender_connection()
786 |         result = blender.send_command("create_rodin_job", {
787 |             "text_prompt": None,
788 |             "images": images,
789 |             "bbox_condition": _process_bbox(bbox_condition),
790 |         })
791 |         succeed = result.get("submit_time", False)
792 |         if succeed:
793 |             return json.dumps({
794 |                 "task_uuid": result["uuid"],
795 |                 "subscription_key": result["jobs"]["subscription_key"],
796 |             })
797 |         else:
798 |             return json.dumps(result)
799 |     except Exception as e:
800 |         logger.error(f"Error generating Hyper3D task: {str(e)}")
801 |         return f"Error generating Hyper3D task: {str(e)}"
802 | 
803 | @mcp.tool()
804 | def poll_rodin_job_status(
805 |     ctx: Context,
806 |     subscription_key: str=None,
807 |     request_id: str=None,
808 | ):
809 |     """
810 |     Check if the Hyper3D Rodin generation task is completed.
811 | 
812 |     For Hyper3D Rodin mode MAIN_SITE:
813 |         Parameters:
814 |         - subscription_key: The subscription_key given in the generate model step.
815 | 
816 |         Returns a list of status. The task is done if all status are "Done".
817 |         If "Failed" showed up, the generating process failed.
818 |         This is a polling API, so only proceed if the status are finally determined ("Done" or "Canceled").
819 | 
820 |     For Hyper3D Rodin mode FAL_AI:
821 |         Parameters:
822 |         - request_id: The request_id given in the generate model step.
823 | 
824 |         Returns the generation task status. The task is done if status is "COMPLETED".
825 |         The task is in progress if status is "IN_PROGRESS".
826 |         If status other than "COMPLETED", "IN_PROGRESS", "IN_QUEUE" showed up, the generating process might be failed.
827 |         This is a polling API, so only proceed if the status are finally determined ("COMPLETED" or some failed state).
828 |     """
829 |     try:
830 |         blender = get_blender_connection()
831 |         kwargs = {}
832 |         if subscription_key:
833 |             kwargs = {
834 |                 "subscription_key": subscription_key,
835 |             }
836 |         elif request_id:
837 |             kwargs = {
838 |                 "request_id": request_id,
839 |             }
840 |         result = blender.send_command("poll_rodin_job_status", kwargs)
841 |         return result
842 |     except Exception as e:
843 |         logger.error(f"Error generating Hyper3D task: {str(e)}")
844 |         return f"Error generating Hyper3D task: {str(e)}"
845 | 
846 | @mcp.tool()
847 | def import_generated_asset(
848 |     ctx: Context,
849 |     name: str,
850 |     task_uuid: str=None,
851 |     request_id: str=None,
852 | ):
853 |     """
854 |     Import the asset generated by Hyper3D Rodin after the generation task is completed.
855 | 
856 |     Parameters:
857 |     - name: The name of the object in scene
858 |     - task_uuid: For Hyper3D Rodin mode MAIN_SITE: The task_uuid given in the generate model step.
859 |     - request_id: For Hyper3D Rodin mode FAL_AI: The request_id given in the generate model step.
860 | 
861 |     Only give one of {task_uuid, request_id} based on the Hyper3D Rodin Mode!
862 |     Return if the asset has been imported successfully.
863 |     """
864 |     try:
865 |         blender = get_blender_connection()
866 |         kwargs = {
867 |             "name": name
868 |         }
869 |         if task_uuid:
870 |             kwargs["task_uuid"] = task_uuid
871 |         elif request_id:
872 |             kwargs["request_id"] = request_id
873 |         result = blender.send_command("import_generated_asset", kwargs)
874 |         return result
875 |     except Exception as e:
876 |         logger.error(f"Error generating Hyper3D task: {str(e)}")
877 |         return f"Error generating Hyper3D task: {str(e)}"
878 | 
879 | @mcp.prompt()
880 | def asset_creation_strategy() -> str:
881 |     """Defines the preferred strategy for creating assets in Blender"""
882 |     return """When creating 3D content in Blender, always start by checking if integrations are available:
883 | 
884 |     0. Before anything, always check the scene from get_scene_info()
885 |     1. First use the following tools to verify if the following integrations are enabled:
886 |         1. PolyHaven
887 |             Use get_polyhaven_status() to verify its status
888 |             If PolyHaven is enabled:
889 |             - For objects/models: Use download_polyhaven_asset() with asset_type="models"
890 |             - For materials/textures: Use download_polyhaven_asset() with asset_type="textures"
891 |             - For environment lighting: Use download_polyhaven_asset() with asset_type="hdris"
892 |         2. Sketchfab
893 |             Sketchfab is good at Realistic models, and has a wider variety of models than PolyHaven.
894 |             Use get_sketchfab_status() to verify its status
895 |             If Sketchfab is enabled:
896 |             - For objects/models: First search using search_sketchfab_models() with your query
897 |             - Then download specific models using download_sketchfab_model() with the UID
898 |             - Note that only downloadable models can be accessed, and API key must be properly configured
899 |             - Sketchfab has a wider variety of models than PolyHaven, especially for specific subjects
900 |         3. Hyper3D(Rodin)
901 |             Hyper3D Rodin is good at generating 3D models for single item.
902 |             So don't try to:
903 |             1. Generate the whole scene with one shot
904 |             2. Generate ground using Hyper3D
905 |             3. Generate parts of the items separately and put them together afterwards
906 | 
907 |             Use get_hyper3d_status() to verify its status
908 |             If Hyper3D is enabled:
909 |             - For objects/models, do the following steps:
910 |                 1. Create the model generation task
911 |                     - Use generate_hyper3d_model_via_images() if image(s) is/are given
912 |                     - Use generate_hyper3d_model_via_text() if generating 3D asset using text prompt
913 |                     If key type is free_trial and insufficient balance error returned, tell the user that the free trial key can only generated limited models everyday, they can choose to:
914 |                     - Wait for another day and try again
915 |                     - Go to hyper3d.ai to find out how to get their own API key
916 |                     - Go to fal.ai to get their own private API key
917 |                 2. Poll the status
918 |                     - Use poll_rodin_job_status() to check if the generation task has completed or failed
919 |                 3. Import the asset
920 |                     - Use import_generated_asset() to import the generated GLB model the asset
921 |                 4. After importing the asset, ALWAYS check the world_bounding_box of the imported mesh, and adjust the mesh's location and size
922 |                     Adjust the imported mesh's location, scale, rotation, so that the mesh is on the right spot.
923 | 
924 |                 You can reuse assets previous generated by running python code to duplicate the object, without creating another generation task.
925 | 
926 |     3. Always check the world_bounding_box for each item so that:
927 |         - Ensure that all objects that should not be clipping are not clipping.
928 |         - Items have right spatial relationship.
929 |     
930 |     4. Recommended asset source priority:
931 |         - For specific existing objects: First try Sketchfab, then PolyHaven
932 |         - For generic objects/furniture: First try PolyHaven, then Sketchfab
933 |         - For custom or unique items not available in libraries: Use Hyper3D Rodin
934 |         - For environment lighting: Use PolyHaven HDRIs
935 |         - For materials/textures: Use PolyHaven textures
936 | 
937 |     Only fall back to scripting when:
938 |     - PolyHaven, Sketchfab, and Hyper3D are all disabled
939 |     - A simple primitive is explicitly requested
940 |     - No suitable asset exists in any of the libraries
941 |     - Hyper3D Rodin failed to generate the desired asset
942 |     - The task specifically requires a basic material/color
943 |     """
944 | 
945 | # Main execution
946 | 
947 | def main():
948 |     """Run the MCP server"""
949 |     mcp.run()
950 | 
951 | if __name__ == "__main__":
952 |     main()
```

--------------------------------------------------------------------------------
/addon.py:
--------------------------------------------------------------------------------

```python
   1 | # Code created by Siddharth Ahuja: www.github.com/ahujasid © 2025
   2 | 
   3 | import bpy
   4 | import mathutils
   5 | import json
   6 | import threading
   7 | import socket
   8 | import time
   9 | import requests
  10 | import tempfile
  11 | import traceback
  12 | import os
  13 | import shutil
  14 | import zipfile
  15 | from bpy.props import StringProperty, IntProperty, BoolProperty, EnumProperty
  16 | import io
  17 | from contextlib import redirect_stdout, suppress
  18 | 
  19 | bl_info = {
  20 |     "name": "Blender MCP",
  21 |     "author": "BlenderMCP",
  22 |     "version": (1, 2),
  23 |     "blender": (3, 0, 0),
  24 |     "location": "View3D > Sidebar > BlenderMCP",
  25 |     "description": "Connect Blender to Claude via MCP",
  26 |     "category": "Interface",
  27 | }
  28 | 
  29 | RODIN_FREE_TRIAL_KEY = "k9TcfFoEhNd9cCPP2guHAHHHkctZHIRhZDywZ1euGUXwihbYLpOjQhofby80NJez"
  30 | 
  31 | # Add User-Agent as required by Poly Haven API
  32 | REQ_HEADERS = requests.utils.default_headers()
  33 | REQ_HEADERS.update({"User-Agent": "blender-mcp"})
  34 | 
  35 | class BlenderMCPServer:
  36 |     def __init__(self, host='localhost', port=9876):
  37 |         self.host = host
  38 |         self.port = port
  39 |         self.running = False
  40 |         self.socket = None
  41 |         self.server_thread = None
  42 | 
  43 |     def start(self):
  44 |         if self.running:
  45 |             print("Server is already running")
  46 |             return
  47 | 
  48 |         self.running = True
  49 | 
  50 |         try:
  51 |             # Create socket
  52 |             self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  53 |             self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  54 |             self.socket.bind((self.host, self.port))
  55 |             self.socket.listen(1)
  56 | 
  57 |             # Start server thread
  58 |             self.server_thread = threading.Thread(target=self._server_loop)
  59 |             self.server_thread.daemon = True
  60 |             self.server_thread.start()
  61 | 
  62 |             print(f"BlenderMCP server started on {self.host}:{self.port}")
  63 |         except Exception as e:
  64 |             print(f"Failed to start server: {str(e)}")
  65 |             self.stop()
  66 | 
  67 |     def stop(self):
  68 |         self.running = False
  69 | 
  70 |         # Close socket
  71 |         if self.socket:
  72 |             try:
  73 |                 self.socket.close()
  74 |             except:
  75 |                 pass
  76 |             self.socket = None
  77 | 
  78 |         # Wait for thread to finish
  79 |         if self.server_thread:
  80 |             try:
  81 |                 if self.server_thread.is_alive():
  82 |                     self.server_thread.join(timeout=1.0)
  83 |             except:
  84 |                 pass
  85 |             self.server_thread = None
  86 | 
  87 |         print("BlenderMCP server stopped")
  88 | 
  89 |     def _server_loop(self):
  90 |         """Main server loop in a separate thread"""
  91 |         print("Server thread started")
  92 |         self.socket.settimeout(1.0)  # Timeout to allow for stopping
  93 | 
  94 |         while self.running:
  95 |             try:
  96 |                 # Accept new connection
  97 |                 try:
  98 |                     client, address = self.socket.accept()
  99 |                     print(f"Connected to client: {address}")
 100 | 
 101 |                     # Handle client in a separate thread
 102 |                     client_thread = threading.Thread(
 103 |                         target=self._handle_client,
 104 |                         args=(client,)
 105 |                     )
 106 |                     client_thread.daemon = True
 107 |                     client_thread.start()
 108 |                 except socket.timeout:
 109 |                     # Just check running condition
 110 |                     continue
 111 |                 except Exception as e:
 112 |                     print(f"Error accepting connection: {str(e)}")
 113 |                     time.sleep(0.5)
 114 |             except Exception as e:
 115 |                 print(f"Error in server loop: {str(e)}")
 116 |                 if not self.running:
 117 |                     break
 118 |                 time.sleep(0.5)
 119 | 
 120 |         print("Server thread stopped")
 121 | 
 122 |     def _handle_client(self, client):
 123 |         """Handle connected client"""
 124 |         print("Client handler started")
 125 |         client.settimeout(None)  # No timeout
 126 |         buffer = b''
 127 | 
 128 |         try:
 129 |             while self.running:
 130 |                 # Receive data
 131 |                 try:
 132 |                     data = client.recv(8192)
 133 |                     if not data:
 134 |                         print("Client disconnected")
 135 |                         break
 136 | 
 137 |                     buffer += data
 138 |                     try:
 139 |                         # Try to parse command
 140 |                         command = json.loads(buffer.decode('utf-8'))
 141 |                         buffer = b''
 142 | 
 143 |                         # Execute command in Blender's main thread
 144 |                         def execute_wrapper():
 145 |                             try:
 146 |                                 response = self.execute_command(command)
 147 |                                 response_json = json.dumps(response)
 148 |                                 try:
 149 |                                     client.sendall(response_json.encode('utf-8'))
 150 |                                 except:
 151 |                                     print("Failed to send response - client disconnected")
 152 |                             except Exception as e:
 153 |                                 print(f"Error executing command: {str(e)}")
 154 |                                 traceback.print_exc()
 155 |                                 try:
 156 |                                     error_response = {
 157 |                                         "status": "error",
 158 |                                         "message": str(e)
 159 |                                     }
 160 |                                     client.sendall(json.dumps(error_response).encode('utf-8'))
 161 |                                 except:
 162 |                                     pass
 163 |                             return None
 164 | 
 165 |                         # Schedule execution in main thread
 166 |                         bpy.app.timers.register(execute_wrapper, first_interval=0.0)
 167 |                     except json.JSONDecodeError:
 168 |                         # Incomplete data, wait for more
 169 |                         pass
 170 |                 except Exception as e:
 171 |                     print(f"Error receiving data: {str(e)}")
 172 |                     break
 173 |         except Exception as e:
 174 |             print(f"Error in client handler: {str(e)}")
 175 |         finally:
 176 |             try:
 177 |                 client.close()
 178 |             except:
 179 |                 pass
 180 |             print("Client handler stopped")
 181 | 
 182 |     def execute_command(self, command):
 183 |         """Execute a command in the main Blender thread"""
 184 |         try:
 185 |             return self._execute_command_internal(command)
 186 | 
 187 |         except Exception as e:
 188 |             print(f"Error executing command: {str(e)}")
 189 |             traceback.print_exc()
 190 |             return {"status": "error", "message": str(e)}
 191 | 
 192 |     def _execute_command_internal(self, command):
 193 |         """Internal command execution with proper context"""
 194 |         cmd_type = command.get("type")
 195 |         params = command.get("params", {})
 196 | 
 197 |         # Add a handler for checking PolyHaven status
 198 |         if cmd_type == "get_polyhaven_status":
 199 |             return {"status": "success", "result": self.get_polyhaven_status()}
 200 | 
 201 |         # Base handlers that are always available
 202 |         handlers = {
 203 |             "get_scene_info": self.get_scene_info,
 204 |             "get_object_info": self.get_object_info,
 205 |             "get_viewport_screenshot": self.get_viewport_screenshot,
 206 |             "execute_code": self.execute_code,
 207 |             "get_polyhaven_status": self.get_polyhaven_status,
 208 |             "get_hyper3d_status": self.get_hyper3d_status,
 209 |             "get_sketchfab_status": self.get_sketchfab_status,
 210 |         }
 211 | 
 212 |         # Add Polyhaven handlers only if enabled
 213 |         if bpy.context.scene.blendermcp_use_polyhaven:
 214 |             polyhaven_handlers = {
 215 |                 "get_polyhaven_categories": self.get_polyhaven_categories,
 216 |                 "search_polyhaven_assets": self.search_polyhaven_assets,
 217 |                 "download_polyhaven_asset": self.download_polyhaven_asset,
 218 |                 "set_texture": self.set_texture,
 219 |             }
 220 |             handlers.update(polyhaven_handlers)
 221 | 
 222 |         # Add Hyper3d handlers only if enabled
 223 |         if bpy.context.scene.blendermcp_use_hyper3d:
 224 |             polyhaven_handlers = {
 225 |                 "create_rodin_job": self.create_rodin_job,
 226 |                 "poll_rodin_job_status": self.poll_rodin_job_status,
 227 |                 "import_generated_asset": self.import_generated_asset,
 228 |             }
 229 |             handlers.update(polyhaven_handlers)
 230 | 
 231 |         # Add Sketchfab handlers only if enabled
 232 |         if bpy.context.scene.blendermcp_use_sketchfab:
 233 |             sketchfab_handlers = {
 234 |                 "search_sketchfab_models": self.search_sketchfab_models,
 235 |                 "download_sketchfab_model": self.download_sketchfab_model,
 236 |             }
 237 |             handlers.update(sketchfab_handlers)
 238 | 
 239 |         handler = handlers.get(cmd_type)
 240 |         if handler:
 241 |             try:
 242 |                 print(f"Executing handler for {cmd_type}")
 243 |                 result = handler(**params)
 244 |                 print(f"Handler execution complete")
 245 |                 return {"status": "success", "result": result}
 246 |             except Exception as e:
 247 |                 print(f"Error in handler: {str(e)}")
 248 |                 traceback.print_exc()
 249 |                 return {"status": "error", "message": str(e)}
 250 |         else:
 251 |             return {"status": "error", "message": f"Unknown command type: {cmd_type}"}
 252 | 
 253 | 
 254 | 
 255 |     def get_scene_info(self):
 256 |         """Get information about the current Blender scene"""
 257 |         try:
 258 |             print("Getting scene info...")
 259 |             # Simplify the scene info to reduce data size
 260 |             scene_info = {
 261 |                 "name": bpy.context.scene.name,
 262 |                 "object_count": len(bpy.context.scene.objects),
 263 |                 "objects": [],
 264 |                 "materials_count": len(bpy.data.materials),
 265 |             }
 266 | 
 267 |             # Collect minimal object information (limit to first 10 objects)
 268 |             for i, obj in enumerate(bpy.context.scene.objects):
 269 |                 if i >= 10:  # Reduced from 20 to 10
 270 |                     break
 271 | 
 272 |                 obj_info = {
 273 |                     "name": obj.name,
 274 |                     "type": obj.type,
 275 |                     # Only include basic location data
 276 |                     "location": [round(float(obj.location.x), 2),
 277 |                                 round(float(obj.location.y), 2),
 278 |                                 round(float(obj.location.z), 2)],
 279 |                 }
 280 |                 scene_info["objects"].append(obj_info)
 281 | 
 282 |             print(f"Scene info collected: {len(scene_info['objects'])} objects")
 283 |             return scene_info
 284 |         except Exception as e:
 285 |             print(f"Error in get_scene_info: {str(e)}")
 286 |             traceback.print_exc()
 287 |             return {"error": str(e)}
 288 | 
 289 |     @staticmethod
 290 |     def _get_aabb(obj):
 291 |         """ Returns the world-space axis-aligned bounding box (AABB) of an object. """
 292 |         if obj.type != 'MESH':
 293 |             raise TypeError("Object must be a mesh")
 294 | 
 295 |         # Get the bounding box corners in local space
 296 |         local_bbox_corners = [mathutils.Vector(corner) for corner in obj.bound_box]
 297 | 
 298 |         # Convert to world coordinates
 299 |         world_bbox_corners = [obj.matrix_world @ corner for corner in local_bbox_corners]
 300 | 
 301 |         # Compute axis-aligned min/max coordinates
 302 |         min_corner = mathutils.Vector(map(min, zip(*world_bbox_corners)))
 303 |         max_corner = mathutils.Vector(map(max, zip(*world_bbox_corners)))
 304 | 
 305 |         return [
 306 |             [*min_corner], [*max_corner]
 307 |         ]
 308 | 
 309 | 
 310 | 
 311 |     def get_object_info(self, name):
 312 |         """Get detailed information about a specific object"""
 313 |         obj = bpy.data.objects.get(name)
 314 |         if not obj:
 315 |             raise ValueError(f"Object not found: {name}")
 316 | 
 317 |         # Basic object info
 318 |         obj_info = {
 319 |             "name": obj.name,
 320 |             "type": obj.type,
 321 |             "location": [obj.location.x, obj.location.y, obj.location.z],
 322 |             "rotation": [obj.rotation_euler.x, obj.rotation_euler.y, obj.rotation_euler.z],
 323 |             "scale": [obj.scale.x, obj.scale.y, obj.scale.z],
 324 |             "visible": obj.visible_get(),
 325 |             "materials": [],
 326 |         }
 327 | 
 328 |         if obj.type == "MESH":
 329 |             bounding_box = self._get_aabb(obj)
 330 |             obj_info["world_bounding_box"] = bounding_box
 331 | 
 332 |         # Add material slots
 333 |         for slot in obj.material_slots:
 334 |             if slot.material:
 335 |                 obj_info["materials"].append(slot.material.name)
 336 | 
 337 |         # Add mesh data if applicable
 338 |         if obj.type == 'MESH' and obj.data:
 339 |             mesh = obj.data
 340 |             obj_info["mesh"] = {
 341 |                 "vertices": len(mesh.vertices),
 342 |                 "edges": len(mesh.edges),
 343 |                 "polygons": len(mesh.polygons),
 344 |             }
 345 | 
 346 |         return obj_info
 347 | 
 348 |     def get_viewport_screenshot(self, max_size=800, filepath=None, format="png"):
 349 |         """
 350 |         Capture a screenshot of the current 3D viewport and save it to the specified path.
 351 | 
 352 |         Parameters:
 353 |         - max_size: Maximum size in pixels for the largest dimension of the image
 354 |         - filepath: Path where to save the screenshot file
 355 |         - format: Image format (png, jpg, etc.)
 356 | 
 357 |         Returns success/error status
 358 |         """
 359 |         try:
 360 |             if not filepath:
 361 |                 return {"error": "No filepath provided"}
 362 | 
 363 |             # Find the active 3D viewport
 364 |             area = None
 365 |             for a in bpy.context.screen.areas:
 366 |                 if a.type == 'VIEW_3D':
 367 |                     area = a
 368 |                     break
 369 | 
 370 |             if not area:
 371 |                 return {"error": "No 3D viewport found"}
 372 | 
 373 |             # Take screenshot with proper context override
 374 |             with bpy.context.temp_override(area=area):
 375 |                 bpy.ops.screen.screenshot_area(filepath=filepath)
 376 | 
 377 |             # Load and resize if needed
 378 |             img = bpy.data.images.load(filepath)
 379 |             width, height = img.size
 380 | 
 381 |             if max(width, height) > max_size:
 382 |                 scale = max_size / max(width, height)
 383 |                 new_width = int(width * scale)
 384 |                 new_height = int(height * scale)
 385 |                 img.scale(new_width, new_height)
 386 | 
 387 |                 # Set format and save
 388 |                 img.file_format = format.upper()
 389 |                 img.save()
 390 |                 width, height = new_width, new_height
 391 | 
 392 |             # Cleanup Blender image data
 393 |             bpy.data.images.remove(img)
 394 | 
 395 |             return {
 396 |                 "success": True,
 397 |                 "width": width,
 398 |                 "height": height,
 399 |                 "filepath": filepath
 400 |             }
 401 | 
 402 |         except Exception as e:
 403 |             return {"error": str(e)}
 404 | 
 405 |     def execute_code(self, code):
 406 |         """Execute arbitrary Blender Python code"""
 407 |         # This is powerful but potentially dangerous - use with caution
 408 |         try:
 409 |             # Create a local namespace for execution
 410 |             namespace = {"bpy": bpy}
 411 | 
 412 |             # Capture stdout during execution, and return it as result
 413 |             capture_buffer = io.StringIO()
 414 |             with redirect_stdout(capture_buffer):
 415 |                 exec(code, namespace)
 416 | 
 417 |             captured_output = capture_buffer.getvalue()
 418 |             return {"executed": True, "result": captured_output}
 419 |         except Exception as e:
 420 |             raise Exception(f"Code execution error: {str(e)}")
 421 | 
 422 | 
 423 | 
 424 |     def get_polyhaven_categories(self, asset_type):
 425 |         """Get categories for a specific asset type from Polyhaven"""
 426 |         try:
 427 |             if asset_type not in ["hdris", "textures", "models", "all"]:
 428 |                 return {"error": f"Invalid asset type: {asset_type}. Must be one of: hdris, textures, models, all"}
 429 | 
 430 |             response = requests.get(f"https://api.polyhaven.com/categories/{asset_type}", headers=REQ_HEADERS)
 431 |             if response.status_code == 200:
 432 |                 return {"categories": response.json()}
 433 |             else:
 434 |                 return {"error": f"API request failed with status code {response.status_code}"}
 435 |         except Exception as e:
 436 |             return {"error": str(e)}
 437 | 
 438 |     def search_polyhaven_assets(self, asset_type=None, categories=None):
 439 |         """Search for assets from Polyhaven with optional filtering"""
 440 |         try:
 441 |             url = "https://api.polyhaven.com/assets"
 442 |             params = {}
 443 | 
 444 |             if asset_type and asset_type != "all":
 445 |                 if asset_type not in ["hdris", "textures", "models"]:
 446 |                     return {"error": f"Invalid asset type: {asset_type}. Must be one of: hdris, textures, models, all"}
 447 |                 params["type"] = asset_type
 448 | 
 449 |             if categories:
 450 |                 params["categories"] = categories
 451 | 
 452 |             response = requests.get(url, params=params, headers=REQ_HEADERS)
 453 |             if response.status_code == 200:
 454 |                 # Limit the response size to avoid overwhelming Blender
 455 |                 assets = response.json()
 456 |                 # Return only the first 20 assets to keep response size manageable
 457 |                 limited_assets = {}
 458 |                 for i, (key, value) in enumerate(assets.items()):
 459 |                     if i >= 20:  # Limit to 20 assets
 460 |                         break
 461 |                     limited_assets[key] = value
 462 | 
 463 |                 return {"assets": limited_assets, "total_count": len(assets), "returned_count": len(limited_assets)}
 464 |             else:
 465 |                 return {"error": f"API request failed with status code {response.status_code}"}
 466 |         except Exception as e:
 467 |             return {"error": str(e)}
 468 | 
 469 |     def download_polyhaven_asset(self, asset_id, asset_type, resolution="1k", file_format=None):
 470 |         try:
 471 |             # First get the files information
 472 |             files_response = requests.get(f"https://api.polyhaven.com/files/{asset_id}", headers=REQ_HEADERS)
 473 |             if files_response.status_code != 200:
 474 |                 return {"error": f"Failed to get asset files: {files_response.status_code}"}
 475 | 
 476 |             files_data = files_response.json()
 477 | 
 478 |             # Handle different asset types
 479 |             if asset_type == "hdris":
 480 |                 # For HDRIs, download the .hdr or .exr file
 481 |                 if not file_format:
 482 |                     file_format = "hdr"  # Default format for HDRIs
 483 | 
 484 |                 if "hdri" in files_data and resolution in files_data["hdri"] and file_format in files_data["hdri"][resolution]:
 485 |                     file_info = files_data["hdri"][resolution][file_format]
 486 |                     file_url = file_info["url"]
 487 | 
 488 |                     # For HDRIs, we need to save to a temporary file first
 489 |                     # since Blender can't properly load HDR data directly from memory
 490 |                     with tempfile.NamedTemporaryFile(suffix=f".{file_format}", delete=False) as tmp_file:
 491 |                         # Download the file
 492 |                         response = requests.get(file_url, headers=REQ_HEADERS)
 493 |                         if response.status_code != 200:
 494 |                             return {"error": f"Failed to download HDRI: {response.status_code}"}
 495 | 
 496 |                         tmp_file.write(response.content)
 497 |                         tmp_path = tmp_file.name
 498 | 
 499 |                     try:
 500 |                         # Create a new world if none exists
 501 |                         if not bpy.data.worlds:
 502 |                             bpy.data.worlds.new("World")
 503 | 
 504 |                         world = bpy.data.worlds[0]
 505 |                         world.use_nodes = True
 506 |                         node_tree = world.node_tree
 507 | 
 508 |                         # Clear existing nodes
 509 |                         for node in node_tree.nodes:
 510 |                             node_tree.nodes.remove(node)
 511 | 
 512 |                         # Create nodes
 513 |                         tex_coord = node_tree.nodes.new(type='ShaderNodeTexCoord')
 514 |                         tex_coord.location = (-800, 0)
 515 | 
 516 |                         mapping = node_tree.nodes.new(type='ShaderNodeMapping')
 517 |                         mapping.location = (-600, 0)
 518 | 
 519 |                         # Load the image from the temporary file
 520 |                         env_tex = node_tree.nodes.new(type='ShaderNodeTexEnvironment')
 521 |                         env_tex.location = (-400, 0)
 522 |                         env_tex.image = bpy.data.images.load(tmp_path)
 523 | 
 524 |                         # Use a color space that exists in all Blender versions
 525 |                         if file_format.lower() == 'exr':
 526 |                             # Try to use Linear color space for EXR files
 527 |                             try:
 528 |                                 env_tex.image.colorspace_settings.name = 'Linear'
 529 |                             except:
 530 |                                 # Fallback to Non-Color if Linear isn't available
 531 |                                 env_tex.image.colorspace_settings.name = 'Non-Color'
 532 |                         else:  # hdr
 533 |                             # For HDR files, try these options in order
 534 |                             for color_space in ['Linear', 'Linear Rec.709', 'Non-Color']:
 535 |                                 try:
 536 |                                     env_tex.image.colorspace_settings.name = color_space
 537 |                                     break  # Stop if we successfully set a color space
 538 |                                 except:
 539 |                                     continue
 540 | 
 541 |                         background = node_tree.nodes.new(type='ShaderNodeBackground')
 542 |                         background.location = (-200, 0)
 543 | 
 544 |                         output = node_tree.nodes.new(type='ShaderNodeOutputWorld')
 545 |                         output.location = (0, 0)
 546 | 
 547 |                         # Connect nodes
 548 |                         node_tree.links.new(tex_coord.outputs['Generated'], mapping.inputs['Vector'])
 549 |                         node_tree.links.new(mapping.outputs['Vector'], env_tex.inputs['Vector'])
 550 |                         node_tree.links.new(env_tex.outputs['Color'], background.inputs['Color'])
 551 |                         node_tree.links.new(background.outputs['Background'], output.inputs['Surface'])
 552 | 
 553 |                         # Set as active world
 554 |                         bpy.context.scene.world = world
 555 | 
 556 |                         # Clean up temporary file
 557 |                         try:
 558 |                             tempfile._cleanup()  # This will clean up all temporary files
 559 |                         except:
 560 |                             pass
 561 | 
 562 |                         return {
 563 |                             "success": True,
 564 |                             "message": f"HDRI {asset_id} imported successfully",
 565 |                             "image_name": env_tex.image.name
 566 |                         }
 567 |                     except Exception as e:
 568 |                         return {"error": f"Failed to set up HDRI in Blender: {str(e)}"}
 569 |                 else:
 570 |                     return {"error": f"Requested resolution or format not available for this HDRI"}
 571 | 
 572 |             elif asset_type == "textures":
 573 |                 if not file_format:
 574 |                     file_format = "jpg"  # Default format for textures
 575 | 
 576 |                 downloaded_maps = {}
 577 | 
 578 |                 try:
 579 |                     for map_type in files_data:
 580 |                         if map_type not in ["blend", "gltf"]:  # Skip non-texture files
 581 |                             if resolution in files_data[map_type] and file_format in files_data[map_type][resolution]:
 582 |                                 file_info = files_data[map_type][resolution][file_format]
 583 |                                 file_url = file_info["url"]
 584 | 
 585 |                                 # Use NamedTemporaryFile like we do for HDRIs
 586 |                                 with tempfile.NamedTemporaryFile(suffix=f".{file_format}", delete=False) as tmp_file:
 587 |                                     # Download the file
 588 |                                     response = requests.get(file_url, headers=REQ_HEADERS)
 589 |                                     if response.status_code == 200:
 590 |                                         tmp_file.write(response.content)
 591 |                                         tmp_path = tmp_file.name
 592 | 
 593 |                                         # Load image from temporary file
 594 |                                         image = bpy.data.images.load(tmp_path)
 595 |                                         image.name = f"{asset_id}_{map_type}.{file_format}"
 596 | 
 597 |                                         # Pack the image into .blend file
 598 |                                         image.pack()
 599 | 
 600 |                                         # Set color space based on map type
 601 |                                         if map_type in ['color', 'diffuse', 'albedo']:
 602 |                                             try:
 603 |                                                 image.colorspace_settings.name = 'sRGB'
 604 |                                             except:
 605 |                                                 pass
 606 |                                         else:
 607 |                                             try:
 608 |                                                 image.colorspace_settings.name = 'Non-Color'
 609 |                                             except:
 610 |                                                 pass
 611 | 
 612 |                                         downloaded_maps[map_type] = image
 613 | 
 614 |                                         # Clean up temporary file
 615 |                                         try:
 616 |                                             os.unlink(tmp_path)
 617 |                                         except:
 618 |                                             pass
 619 | 
 620 |                     if not downloaded_maps:
 621 |                         return {"error": f"No texture maps found for the requested resolution and format"}
 622 | 
 623 |                     # Create a new material with the downloaded textures
 624 |                     mat = bpy.data.materials.new(name=asset_id)
 625 |                     mat.use_nodes = True
 626 |                     nodes = mat.node_tree.nodes
 627 |                     links = mat.node_tree.links
 628 | 
 629 |                     # Clear default nodes
 630 |                     for node in nodes:
 631 |                         nodes.remove(node)
 632 | 
 633 |                     # Create output node
 634 |                     output = nodes.new(type='ShaderNodeOutputMaterial')
 635 |                     output.location = (300, 0)
 636 | 
 637 |                     # Create principled BSDF node
 638 |                     principled = nodes.new(type='ShaderNodeBsdfPrincipled')
 639 |                     principled.location = (0, 0)
 640 |                     links.new(principled.outputs[0], output.inputs[0])
 641 | 
 642 |                     # Add texture nodes based on available maps
 643 |                     tex_coord = nodes.new(type='ShaderNodeTexCoord')
 644 |                     tex_coord.location = (-800, 0)
 645 | 
 646 |                     mapping = nodes.new(type='ShaderNodeMapping')
 647 |                     mapping.location = (-600, 0)
 648 |                     mapping.vector_type = 'TEXTURE'  # Changed from default 'POINT' to 'TEXTURE'
 649 |                     links.new(tex_coord.outputs['UV'], mapping.inputs['Vector'])
 650 | 
 651 |                     # Position offset for texture nodes
 652 |                     x_pos = -400
 653 |                     y_pos = 300
 654 | 
 655 |                     # Connect different texture maps
 656 |                     for map_type, image in downloaded_maps.items():
 657 |                         tex_node = nodes.new(type='ShaderNodeTexImage')
 658 |                         tex_node.location = (x_pos, y_pos)
 659 |                         tex_node.image = image
 660 | 
 661 |                         # Set color space based on map type
 662 |                         if map_type.lower() in ['color', 'diffuse', 'albedo']:
 663 |                             try:
 664 |                                 tex_node.image.colorspace_settings.name = 'sRGB'
 665 |                             except:
 666 |                                 pass  # Use default if sRGB not available
 667 |                         else:
 668 |                             try:
 669 |                                 tex_node.image.colorspace_settings.name = 'Non-Color'
 670 |                             except:
 671 |                                 pass  # Use default if Non-Color not available
 672 | 
 673 |                         links.new(mapping.outputs['Vector'], tex_node.inputs['Vector'])
 674 | 
 675 |                         # Connect to appropriate input on Principled BSDF
 676 |                         if map_type.lower() in ['color', 'diffuse', 'albedo']:
 677 |                             links.new(tex_node.outputs['Color'], principled.inputs['Base Color'])
 678 |                         elif map_type.lower() in ['roughness', 'rough']:
 679 |                             links.new(tex_node.outputs['Color'], principled.inputs['Roughness'])
 680 |                         elif map_type.lower() in ['metallic', 'metalness', 'metal']:
 681 |                             links.new(tex_node.outputs['Color'], principled.inputs['Metallic'])
 682 |                         elif map_type.lower() in ['normal', 'nor']:
 683 |                             # Add normal map node
 684 |                             normal_map = nodes.new(type='ShaderNodeNormalMap')
 685 |                             normal_map.location = (x_pos + 200, y_pos)
 686 |                             links.new(tex_node.outputs['Color'], normal_map.inputs['Color'])
 687 |                             links.new(normal_map.outputs['Normal'], principled.inputs['Normal'])
 688 |                         elif map_type in ['displacement', 'disp', 'height']:
 689 |                             # Add displacement node
 690 |                             disp_node = nodes.new(type='ShaderNodeDisplacement')
 691 |                             disp_node.location = (x_pos + 200, y_pos - 200)
 692 |                             links.new(tex_node.outputs['Color'], disp_node.inputs['Height'])
 693 |                             links.new(disp_node.outputs['Displacement'], output.inputs['Displacement'])
 694 | 
 695 |                         y_pos -= 250
 696 | 
 697 |                     return {
 698 |                         "success": True,
 699 |                         "message": f"Texture {asset_id} imported as material",
 700 |                         "material": mat.name,
 701 |                         "maps": list(downloaded_maps.keys())
 702 |                     }
 703 | 
 704 |                 except Exception as e:
 705 |                     return {"error": f"Failed to process textures: {str(e)}"}
 706 | 
 707 |             elif asset_type == "models":
 708 |                 # For models, prefer glTF format if available
 709 |                 if not file_format:
 710 |                     file_format = "gltf"  # Default format for models
 711 | 
 712 |                 if file_format in files_data and resolution in files_data[file_format]:
 713 |                     file_info = files_data[file_format][resolution][file_format]
 714 |                     file_url = file_info["url"]
 715 | 
 716 |                     # Create a temporary directory to store the model and its dependencies
 717 |                     temp_dir = tempfile.mkdtemp()
 718 |                     main_file_path = ""
 719 | 
 720 |                     try:
 721 |                         # Download the main model file
 722 |                         main_file_name = file_url.split("/")[-1]
 723 |                         main_file_path = os.path.join(temp_dir, main_file_name)
 724 | 
 725 |                         response = requests.get(file_url, headers=REQ_HEADERS)
 726 |                         if response.status_code != 200:
 727 |                             return {"error": f"Failed to download model: {response.status_code}"}
 728 | 
 729 |                         with open(main_file_path, "wb") as f:
 730 |                             f.write(response.content)
 731 | 
 732 |                         # Check for included files and download them
 733 |                         if "include" in file_info and file_info["include"]:
 734 |                             for include_path, include_info in file_info["include"].items():
 735 |                                 # Get the URL for the included file - this is the fix
 736 |                                 include_url = include_info["url"]
 737 | 
 738 |                                 # Create the directory structure for the included file
 739 |                                 include_file_path = os.path.join(temp_dir, include_path)
 740 |                                 os.makedirs(os.path.dirname(include_file_path), exist_ok=True)
 741 | 
 742 |                                 # Download the included file
 743 |                                 include_response = requests.get(include_url, headers=REQ_HEADERS)
 744 |                                 if include_response.status_code == 200:
 745 |                                     with open(include_file_path, "wb") as f:
 746 |                                         f.write(include_response.content)
 747 |                                 else:
 748 |                                     print(f"Failed to download included file: {include_path}")
 749 | 
 750 |                         # Import the model into Blender
 751 |                         if file_format == "gltf" or file_format == "glb":
 752 |                             bpy.ops.import_scene.gltf(filepath=main_file_path)
 753 |                         elif file_format == "fbx":
 754 |                             bpy.ops.import_scene.fbx(filepath=main_file_path)
 755 |                         elif file_format == "obj":
 756 |                             bpy.ops.import_scene.obj(filepath=main_file_path)
 757 |                         elif file_format == "blend":
 758 |                             # For blend files, we need to append or link
 759 |                             with bpy.data.libraries.load(main_file_path, link=False) as (data_from, data_to):
 760 |                                 data_to.objects = data_from.objects
 761 | 
 762 |                             # Link the objects to the scene
 763 |                             for obj in data_to.objects:
 764 |                                 if obj is not None:
 765 |                                     bpy.context.collection.objects.link(obj)
 766 |                         else:
 767 |                             return {"error": f"Unsupported model format: {file_format}"}
 768 | 
 769 |                         # Get the names of imported objects
 770 |                         imported_objects = [obj.name for obj in bpy.context.selected_objects]
 771 | 
 772 |                         return {
 773 |                             "success": True,
 774 |                             "message": f"Model {asset_id} imported successfully",
 775 |                             "imported_objects": imported_objects
 776 |                         }
 777 |                     except Exception as e:
 778 |                         return {"error": f"Failed to import model: {str(e)}"}
 779 |                     finally:
 780 |                         # Clean up temporary directory
 781 |                         with suppress(Exception):
 782 |                             shutil.rmtree(temp_dir)
 783 |                 else:
 784 |                     return {"error": f"Requested format or resolution not available for this model"}
 785 | 
 786 |             else:
 787 |                 return {"error": f"Unsupported asset type: {asset_type}"}
 788 | 
 789 |         except Exception as e:
 790 |             return {"error": f"Failed to download asset: {str(e)}"}
 791 | 
 792 |     def set_texture(self, object_name, texture_id):
 793 |         """Apply a previously downloaded Polyhaven texture to an object by creating a new material"""
 794 |         try:
 795 |             # Get the object
 796 |             obj = bpy.data.objects.get(object_name)
 797 |             if not obj:
 798 |                 return {"error": f"Object not found: {object_name}"}
 799 | 
 800 |             # Make sure object can accept materials
 801 |             if not hasattr(obj, 'data') or not hasattr(obj.data, 'materials'):
 802 |                 return {"error": f"Object {object_name} cannot accept materials"}
 803 | 
 804 |             # Find all images related to this texture and ensure they're properly loaded
 805 |             texture_images = {}
 806 |             for img in bpy.data.images:
 807 |                 if img.name.startswith(texture_id + "_"):
 808 |                     # Extract the map type from the image name
 809 |                     map_type = img.name.split('_')[-1].split('.')[0]
 810 | 
 811 |                     # Force a reload of the image
 812 |                     img.reload()
 813 | 
 814 |                     # Ensure proper color space
 815 |                     if map_type.lower() in ['color', 'diffuse', 'albedo']:
 816 |                         try:
 817 |                             img.colorspace_settings.name = 'sRGB'
 818 |                         except:
 819 |                             pass
 820 |                     else:
 821 |                         try:
 822 |                             img.colorspace_settings.name = 'Non-Color'
 823 |                         except:
 824 |                             pass
 825 | 
 826 |                     # Ensure the image is packed
 827 |                     if not img.packed_file:
 828 |                         img.pack()
 829 | 
 830 |                     texture_images[map_type] = img
 831 |                     print(f"Loaded texture map: {map_type} - {img.name}")
 832 | 
 833 |                     # Debug info
 834 |                     print(f"Image size: {img.size[0]}x{img.size[1]}")
 835 |                     print(f"Color space: {img.colorspace_settings.name}")
 836 |                     print(f"File format: {img.file_format}")
 837 |                     print(f"Is packed: {bool(img.packed_file)}")
 838 | 
 839 |             if not texture_images:
 840 |                 return {"error": f"No texture images found for: {texture_id}. Please download the texture first."}
 841 | 
 842 |             # Create a new material
 843 |             new_mat_name = f"{texture_id}_material_{object_name}"
 844 | 
 845 |             # Remove any existing material with this name to avoid conflicts
 846 |             existing_mat = bpy.data.materials.get(new_mat_name)
 847 |             if existing_mat:
 848 |                 bpy.data.materials.remove(existing_mat)
 849 | 
 850 |             new_mat = bpy.data.materials.new(name=new_mat_name)
 851 |             new_mat.use_nodes = True
 852 | 
 853 |             # Set up the material nodes
 854 |             nodes = new_mat.node_tree.nodes
 855 |             links = new_mat.node_tree.links
 856 | 
 857 |             # Clear default nodes
 858 |             nodes.clear()
 859 | 
 860 |             # Create output node
 861 |             output = nodes.new(type='ShaderNodeOutputMaterial')
 862 |             output.location = (600, 0)
 863 | 
 864 |             # Create principled BSDF node
 865 |             principled = nodes.new(type='ShaderNodeBsdfPrincipled')
 866 |             principled.location = (300, 0)
 867 |             links.new(principled.outputs[0], output.inputs[0])
 868 | 
 869 |             # Add texture nodes based on available maps
 870 |             tex_coord = nodes.new(type='ShaderNodeTexCoord')
 871 |             tex_coord.location = (-800, 0)
 872 | 
 873 |             mapping = nodes.new(type='ShaderNodeMapping')
 874 |             mapping.location = (-600, 0)
 875 |             mapping.vector_type = 'TEXTURE'  # Changed from default 'POINT' to 'TEXTURE'
 876 |             links.new(tex_coord.outputs['UV'], mapping.inputs['Vector'])
 877 | 
 878 |             # Position offset for texture nodes
 879 |             x_pos = -400
 880 |             y_pos = 300
 881 | 
 882 |             # Connect different texture maps
 883 |             for map_type, image in texture_images.items():
 884 |                 tex_node = nodes.new(type='ShaderNodeTexImage')
 885 |                 tex_node.location = (x_pos, y_pos)
 886 |                 tex_node.image = image
 887 | 
 888 |                 # Set color space based on map type
 889 |                 if map_type.lower() in ['color', 'diffuse', 'albedo']:
 890 |                     try:
 891 |                         tex_node.image.colorspace_settings.name = 'sRGB'
 892 |                     except:
 893 |                         pass  # Use default if sRGB not available
 894 |                 else:
 895 |                     try:
 896 |                         tex_node.image.colorspace_settings.name = 'Non-Color'
 897 |                     except:
 898 |                         pass  # Use default if Non-Color not available
 899 | 
 900 |                 links.new(mapping.outputs['Vector'], tex_node.inputs['Vector'])
 901 | 
 902 |                 # Connect to appropriate input on Principled BSDF
 903 |                 if map_type.lower() in ['color', 'diffuse', 'albedo']:
 904 |                     links.new(tex_node.outputs['Color'], principled.inputs['Base Color'])
 905 |                 elif map_type.lower() in ['roughness', 'rough']:
 906 |                     links.new(tex_node.outputs['Color'], principled.inputs['Roughness'])
 907 |                 elif map_type.lower() in ['metallic', 'metalness', 'metal']:
 908 |                     links.new(tex_node.outputs['Color'], principled.inputs['Metallic'])
 909 |                 elif map_type.lower() in ['normal', 'nor', 'dx', 'gl']:
 910 |                     # Add normal map node
 911 |                     normal_map = nodes.new(type='ShaderNodeNormalMap')
 912 |                     normal_map.location = (x_pos + 200, y_pos)
 913 |                     links.new(tex_node.outputs['Color'], normal_map.inputs['Color'])
 914 |                     links.new(normal_map.outputs['Normal'], principled.inputs['Normal'])
 915 |                 elif map_type.lower() in ['displacement', 'disp', 'height']:
 916 |                     # Add displacement node
 917 |                     disp_node = nodes.new(type='ShaderNodeDisplacement')
 918 |                     disp_node.location = (x_pos + 200, y_pos - 200)
 919 |                     disp_node.inputs['Scale'].default_value = 0.1  # Reduce displacement strength
 920 |                     links.new(tex_node.outputs['Color'], disp_node.inputs['Height'])
 921 |                     links.new(disp_node.outputs['Displacement'], output.inputs['Displacement'])
 922 | 
 923 |                 y_pos -= 250
 924 | 
 925 |             # Second pass: Connect nodes with proper handling for special cases
 926 |             texture_nodes = {}
 927 | 
 928 |             # First find all texture nodes and store them by map type
 929 |             for node in nodes:
 930 |                 if node.type == 'TEX_IMAGE' and node.image:
 931 |                     for map_type, image in texture_images.items():
 932 |                         if node.image == image:
 933 |                             texture_nodes[map_type] = node
 934 |                             break
 935 | 
 936 |             # Now connect everything using the nodes instead of images
 937 |             # Handle base color (diffuse)
 938 |             for map_name in ['color', 'diffuse', 'albedo']:
 939 |                 if map_name in texture_nodes:
 940 |                     links.new(texture_nodes[map_name].outputs['Color'], principled.inputs['Base Color'])
 941 |                     print(f"Connected {map_name} to Base Color")
 942 |                     break
 943 | 
 944 |             # Handle roughness
 945 |             for map_name in ['roughness', 'rough']:
 946 |                 if map_name in texture_nodes:
 947 |                     links.new(texture_nodes[map_name].outputs['Color'], principled.inputs['Roughness'])
 948 |                     print(f"Connected {map_name} to Roughness")
 949 |                     break
 950 | 
 951 |             # Handle metallic
 952 |             for map_name in ['metallic', 'metalness', 'metal']:
 953 |                 if map_name in texture_nodes:
 954 |                     links.new(texture_nodes[map_name].outputs['Color'], principled.inputs['Metallic'])
 955 |                     print(f"Connected {map_name} to Metallic")
 956 |                     break
 957 | 
 958 |             # Handle normal maps
 959 |             for map_name in ['gl', 'dx', 'nor']:
 960 |                 if map_name in texture_nodes:
 961 |                     normal_map_node = nodes.new(type='ShaderNodeNormalMap')
 962 |                     normal_map_node.location = (100, 100)
 963 |                     links.new(texture_nodes[map_name].outputs['Color'], normal_map_node.inputs['Color'])
 964 |                     links.new(normal_map_node.outputs['Normal'], principled.inputs['Normal'])
 965 |                     print(f"Connected {map_name} to Normal")
 966 |                     break
 967 | 
 968 |             # Handle displacement
 969 |             for map_name in ['displacement', 'disp', 'height']:
 970 |                 if map_name in texture_nodes:
 971 |                     disp_node = nodes.new(type='ShaderNodeDisplacement')
 972 |                     disp_node.location = (300, -200)
 973 |                     disp_node.inputs['Scale'].default_value = 0.1  # Reduce displacement strength
 974 |                     links.new(texture_nodes[map_name].outputs['Color'], disp_node.inputs['Height'])
 975 |                     links.new(disp_node.outputs['Displacement'], output.inputs['Displacement'])
 976 |                     print(f"Connected {map_name} to Displacement")
 977 |                     break
 978 | 
 979 |             # Handle ARM texture (Ambient Occlusion, Roughness, Metallic)
 980 |             if 'arm' in texture_nodes:
 981 |                 separate_rgb = nodes.new(type='ShaderNodeSeparateRGB')
 982 |                 separate_rgb.location = (-200, -100)
 983 |                 links.new(texture_nodes['arm'].outputs['Color'], separate_rgb.inputs['Image'])
 984 | 
 985 |                 # Connect Roughness (G) if no dedicated roughness map
 986 |                 if not any(map_name in texture_nodes for map_name in ['roughness', 'rough']):
 987 |                     links.new(separate_rgb.outputs['G'], principled.inputs['Roughness'])
 988 |                     print("Connected ARM.G to Roughness")
 989 | 
 990 |                 # Connect Metallic (B) if no dedicated metallic map
 991 |                 if not any(map_name in texture_nodes for map_name in ['metallic', 'metalness', 'metal']):
 992 |                     links.new(separate_rgb.outputs['B'], principled.inputs['Metallic'])
 993 |                     print("Connected ARM.B to Metallic")
 994 | 
 995 |                 # For AO (R channel), multiply with base color if we have one
 996 |                 base_color_node = None
 997 |                 for map_name in ['color', 'diffuse', 'albedo']:
 998 |                     if map_name in texture_nodes:
 999 |                         base_color_node = texture_nodes[map_name]
1000 |                         break
1001 | 
1002 |                 if base_color_node:
1003 |                     mix_node = nodes.new(type='ShaderNodeMixRGB')
1004 |                     mix_node.location = (100, 200)
1005 |                     mix_node.blend_type = 'MULTIPLY'
1006 |                     mix_node.inputs['Fac'].default_value = 0.8  # 80% influence
1007 | 
1008 |                     # Disconnect direct connection to base color
1009 |                     for link in base_color_node.outputs['Color'].links:
1010 |                         if link.to_socket == principled.inputs['Base Color']:
1011 |                             links.remove(link)
1012 | 
1013 |                     # Connect through the mix node
1014 |                     links.new(base_color_node.outputs['Color'], mix_node.inputs[1])
1015 |                     links.new(separate_rgb.outputs['R'], mix_node.inputs[2])
1016 |                     links.new(mix_node.outputs['Color'], principled.inputs['Base Color'])
1017 |                     print("Connected ARM.R to AO mix with Base Color")
1018 | 
1019 |             # Handle AO (Ambient Occlusion) if separate
1020 |             if 'ao' in texture_nodes:
1021 |                 base_color_node = None
1022 |                 for map_name in ['color', 'diffuse', 'albedo']:
1023 |                     if map_name in texture_nodes:
1024 |                         base_color_node = texture_nodes[map_name]
1025 |                         break
1026 | 
1027 |                 if base_color_node:
1028 |                     mix_node = nodes.new(type='ShaderNodeMixRGB')
1029 |                     mix_node.location = (100, 200)
1030 |                     mix_node.blend_type = 'MULTIPLY'
1031 |                     mix_node.inputs['Fac'].default_value = 0.8  # 80% influence
1032 | 
1033 |                     # Disconnect direct connection to base color
1034 |                     for link in base_color_node.outputs['Color'].links:
1035 |                         if link.to_socket == principled.inputs['Base Color']:
1036 |                             links.remove(link)
1037 | 
1038 |                     # Connect through the mix node
1039 |                     links.new(base_color_node.outputs['Color'], mix_node.inputs[1])
1040 |                     links.new(texture_nodes['ao'].outputs['Color'], mix_node.inputs[2])
1041 |                     links.new(mix_node.outputs['Color'], principled.inputs['Base Color'])
1042 |                     print("Connected AO to mix with Base Color")
1043 | 
1044 |             # CRITICAL: Make sure to clear all existing materials from the object
1045 |             while len(obj.data.materials) > 0:
1046 |                 obj.data.materials.pop(index=0)
1047 | 
1048 |             # Assign the new material to the object
1049 |             obj.data.materials.append(new_mat)
1050 | 
1051 |             # CRITICAL: Make the object active and select it
1052 |             bpy.context.view_layer.objects.active = obj
1053 |             obj.select_set(True)
1054 | 
1055 |             # CRITICAL: Force Blender to update the material
1056 |             bpy.context.view_layer.update()
1057 | 
1058 |             # Get the list of texture maps
1059 |             texture_maps = list(texture_images.keys())
1060 | 
1061 |             # Get info about texture nodes for debugging
1062 |             material_info = {
1063 |                 "name": new_mat.name,
1064 |                 "has_nodes": new_mat.use_nodes,
1065 |                 "node_count": len(new_mat.node_tree.nodes),
1066 |                 "texture_nodes": []
1067 |             }
1068 | 
1069 |             for node in new_mat.node_tree.nodes:
1070 |                 if node.type == 'TEX_IMAGE' and node.image:
1071 |                     connections = []
1072 |                     for output in node.outputs:
1073 |                         for link in output.links:
1074 |                             connections.append(f"{output.name} → {link.to_node.name}.{link.to_socket.name}")
1075 | 
1076 |                     material_info["texture_nodes"].append({
1077 |                         "name": node.name,
1078 |                         "image": node.image.name,
1079 |                         "colorspace": node.image.colorspace_settings.name,
1080 |                         "connections": connections
1081 |                     })
1082 | 
1083 |             return {
1084 |                 "success": True,
1085 |                 "message": f"Created new material and applied texture {texture_id} to {object_name}",
1086 |                 "material": new_mat.name,
1087 |                 "maps": texture_maps,
1088 |                 "material_info": material_info
1089 |             }
1090 | 
1091 |         except Exception as e:
1092 |             print(f"Error in set_texture: {str(e)}")
1093 |             traceback.print_exc()
1094 |             return {"error": f"Failed to apply texture: {str(e)}"}
1095 | 
1096 |     def get_polyhaven_status(self):
1097 |         """Get the current status of PolyHaven integration"""
1098 |         enabled = bpy.context.scene.blendermcp_use_polyhaven
1099 |         if enabled:
1100 |             return {"enabled": True, "message": "PolyHaven integration is enabled and ready to use."}
1101 |         else:
1102 |             return {
1103 |                 "enabled": False,
1104 |                 "message": """PolyHaven integration is currently disabled. To enable it:
1105 |                             1. In the 3D Viewport, find the BlenderMCP panel in the sidebar (press N if hidden)
1106 |                             2. Check the 'Use assets from Poly Haven' checkbox
1107 |                             3. Restart the connection to Claude"""
1108 |         }
1109 | 
1110 |     #region Hyper3D
1111 |     def get_hyper3d_status(self):
1112 |         """Get the current status of Hyper3D Rodin integration"""
1113 |         enabled = bpy.context.scene.blendermcp_use_hyper3d
1114 |         if enabled:
1115 |             if not bpy.context.scene.blendermcp_hyper3d_api_key:
1116 |                 return {
1117 |                     "enabled": False,
1118 |                     "message": """Hyper3D Rodin integration is currently enabled, but API key is not given. To enable it:
1119 |                                 1. In the 3D Viewport, find the BlenderMCP panel in the sidebar (press N if hidden)
1120 |                                 2. Keep the 'Use Hyper3D Rodin 3D model generation' checkbox checked
1121 |                                 3. Choose the right plaform and fill in the API Key
1122 |                                 4. Restart the connection to Claude"""
1123 |                 }
1124 |             mode = bpy.context.scene.blendermcp_hyper3d_mode
1125 |             message = f"Hyper3D Rodin integration is enabled and ready to use. Mode: {mode}. " + \
1126 |                 f"Key type: {'private' if bpy.context.scene.blendermcp_hyper3d_api_key != RODIN_FREE_TRIAL_KEY else 'free_trial'}"
1127 |             return {
1128 |                 "enabled": True,
1129 |                 "message": message
1130 |             }
1131 |         else:
1132 |             return {
1133 |                 "enabled": False,
1134 |                 "message": """Hyper3D Rodin integration is currently disabled. To enable it:
1135 |                             1. In the 3D Viewport, find the BlenderMCP panel in the sidebar (press N if hidden)
1136 |                             2. Check the 'Use Hyper3D Rodin 3D model generation' checkbox
1137 |                             3. Restart the connection to Claude"""
1138 |             }
1139 | 
1140 |     def create_rodin_job(self, *args, **kwargs):
1141 |         match bpy.context.scene.blendermcp_hyper3d_mode:
1142 |             case "MAIN_SITE":
1143 |                 return self.create_rodin_job_main_site(*args, **kwargs)
1144 |             case "FAL_AI":
1145 |                 return self.create_rodin_job_fal_ai(*args, **kwargs)
1146 |             case _:
1147 |                 return f"Error: Unknown Hyper3D Rodin mode!"
1148 | 
1149 |     def create_rodin_job_main_site(
1150 |             self,
1151 |             text_prompt: str=None,
1152 |             images: list[tuple[str, str]]=None,
1153 |             bbox_condition=None
1154 |         ):
1155 |         try:
1156 |             if images is None:
1157 |                 images = []
1158 |             """Call Rodin API, get the job uuid and subscription key"""
1159 |             files = [
1160 |                 *[("images", (f"{i:04d}{img_suffix}", img)) for i, (img_suffix, img) in enumerate(images)],
1161 |                 ("tier", (None, "Sketch")),
1162 |                 ("mesh_mode", (None, "Raw")),
1163 |             ]
1164 |             if text_prompt:
1165 |                 files.append(("prompt", (None, text_prompt)))
1166 |             if bbox_condition:
1167 |                 files.append(("bbox_condition", (None, json.dumps(bbox_condition))))
1168 |             response = requests.post(
1169 |                 "https://hyperhuman.deemos.com/api/v2/rodin",
1170 |                 headers={
1171 |                     "Authorization": f"Bearer {bpy.context.scene.blendermcp_hyper3d_api_key}",
1172 |                 },
1173 |                 files=files
1174 |             )
1175 |             data = response.json()
1176 |             return data
1177 |         except Exception as e:
1178 |             return {"error": str(e)}
1179 | 
1180 |     def create_rodin_job_fal_ai(
1181 |             self,
1182 |             text_prompt: str=None,
1183 |             images: list[tuple[str, str]]=None,
1184 |             bbox_condition=None
1185 |         ):
1186 |         try:
1187 |             req_data = {
1188 |                 "tier": "Sketch",
1189 |             }
1190 |             if images:
1191 |                 req_data["input_image_urls"] = images
1192 |             if text_prompt:
1193 |                 req_data["prompt"] = text_prompt
1194 |             if bbox_condition:
1195 |                 req_data["bbox_condition"] = bbox_condition
1196 |             response = requests.post(
1197 |                 "https://queue.fal.run/fal-ai/hyper3d/rodin",
1198 |                 headers={
1199 |                     "Authorization": f"Key {bpy.context.scene.blendermcp_hyper3d_api_key}",
1200 |                     "Content-Type": "application/json",
1201 |                 },
1202 |                 json=req_data
1203 |             )
1204 |             data = response.json()
1205 |             return data
1206 |         except Exception as e:
1207 |             return {"error": str(e)}
1208 | 
1209 |     def poll_rodin_job_status(self, *args, **kwargs):
1210 |         match bpy.context.scene.blendermcp_hyper3d_mode:
1211 |             case "MAIN_SITE":
1212 |                 return self.poll_rodin_job_status_main_site(*args, **kwargs)
1213 |             case "FAL_AI":
1214 |                 return self.poll_rodin_job_status_fal_ai(*args, **kwargs)
1215 |             case _:
1216 |                 return f"Error: Unknown Hyper3D Rodin mode!"
1217 | 
1218 |     def poll_rodin_job_status_main_site(self, subscription_key: str):
1219 |         """Call the job status API to get the job status"""
1220 |         response = requests.post(
1221 |             "https://hyperhuman.deemos.com/api/v2/status",
1222 |             headers={
1223 |                 "Authorization": f"Bearer {bpy.context.scene.blendermcp_hyper3d_api_key}",
1224 |             },
1225 |             json={
1226 |                 "subscription_key": subscription_key,
1227 |             },
1228 |         )
1229 |         data = response.json()
1230 |         return {
1231 |             "status_list": [i["status"] for i in data["jobs"]]
1232 |         }
1233 | 
1234 |     def poll_rodin_job_status_fal_ai(self, request_id: str):
1235 |         """Call the job status API to get the job status"""
1236 |         response = requests.get(
1237 |             f"https://queue.fal.run/fal-ai/hyper3d/requests/{request_id}/status",
1238 |             headers={
1239 |                 "Authorization": f"KEY {bpy.context.scene.blendermcp_hyper3d_api_key}",
1240 |             },
1241 |         )
1242 |         data = response.json()
1243 |         return data
1244 | 
1245 |     @staticmethod
1246 |     def _clean_imported_glb(filepath, mesh_name=None):
1247 |         # Get the set of existing objects before import
1248 |         existing_objects = set(bpy.data.objects)
1249 | 
1250 |         # Import the GLB file
1251 |         bpy.ops.import_scene.gltf(filepath=filepath)
1252 | 
1253 |         # Ensure the context is updated
1254 |         bpy.context.view_layer.update()
1255 | 
1256 |         # Get all imported objects
1257 |         imported_objects = list(set(bpy.data.objects) - existing_objects)
1258 |         # imported_objects = [obj for obj in bpy.context.view_layer.objects if obj.select_get()]
1259 | 
1260 |         if not imported_objects:
1261 |             print("Error: No objects were imported.")
1262 |             return
1263 | 
1264 |         # Identify the mesh object
1265 |         mesh_obj = None
1266 | 
1267 |         if len(imported_objects) == 1 and imported_objects[0].type == 'MESH':
1268 |             mesh_obj = imported_objects[0]
1269 |             print("Single mesh imported, no cleanup needed.")
1270 |         else:
1271 |             if len(imported_objects) == 2:
1272 |                 empty_objs = [i for i in imported_objects if i.type == "EMPTY"]
1273 |                 if len(empty_objs) != 1:
1274 |                     print("Error: Expected an empty node with one mesh child or a single mesh object.")
1275 |                     return
1276 |                 parent_obj = empty_objs.pop()
1277 |                 if len(parent_obj.children) == 1:
1278 |                     potential_mesh = parent_obj.children[0]
1279 |                     if potential_mesh.type == 'MESH':
1280 |                         print("GLB structure confirmed: Empty node with one mesh child.")
1281 | 
1282 |                         # Unparent the mesh from the empty node
1283 |                         potential_mesh.parent = None
1284 | 
1285 |                         # Remove the empty node
1286 |                         bpy.data.objects.remove(parent_obj)
1287 |                         print("Removed empty node, keeping only the mesh.")
1288 | 
1289 |                         mesh_obj = potential_mesh
1290 |                     else:
1291 |                         print("Error: Child is not a mesh object.")
1292 |                         return
1293 |                 else:
1294 |                     print("Error: Expected an empty node with one mesh child or a single mesh object.")
1295 |                     return
1296 |             else:
1297 |                 print("Error: Expected an empty node with one mesh child or a single mesh object.")
1298 |                 return
1299 | 
1300 |         # Rename the mesh if needed
1301 |         try:
1302 |             if mesh_obj and mesh_obj.name is not None and mesh_name:
1303 |                 mesh_obj.name = mesh_name
1304 |                 if mesh_obj.data.name is not None:
1305 |                     mesh_obj.data.name = mesh_name
1306 |                 print(f"Mesh renamed to: {mesh_name}")
1307 |         except Exception as e:
1308 |             print("Having issue with renaming, give up renaming.")
1309 | 
1310 |         return mesh_obj
1311 | 
1312 |     def import_generated_asset(self, *args, **kwargs):
1313 |         match bpy.context.scene.blendermcp_hyper3d_mode:
1314 |             case "MAIN_SITE":
1315 |                 return self.import_generated_asset_main_site(*args, **kwargs)
1316 |             case "FAL_AI":
1317 |                 return self.import_generated_asset_fal_ai(*args, **kwargs)
1318 |             case _:
1319 |                 return f"Error: Unknown Hyper3D Rodin mode!"
1320 | 
1321 |     def import_generated_asset_main_site(self, task_uuid: str, name: str):
1322 |         """Fetch the generated asset, import into blender"""
1323 |         response = requests.post(
1324 |             "https://hyperhuman.deemos.com/api/v2/download",
1325 |             headers={
1326 |                 "Authorization": f"Bearer {bpy.context.scene.blendermcp_hyper3d_api_key}",
1327 |             },
1328 |             json={
1329 |                 'task_uuid': task_uuid
1330 |             }
1331 |         )
1332 |         data_ = response.json()
1333 |         temp_file = None
1334 |         for i in data_["list"]:
1335 |             if i["name"].endswith(".glb"):
1336 |                 temp_file = tempfile.NamedTemporaryFile(
1337 |                     delete=False,
1338 |                     prefix=task_uuid,
1339 |                     suffix=".glb",
1340 |                 )
1341 | 
1342 |                 try:
1343 |                     # Download the content
1344 |                     response = requests.get(i["url"], stream=True)
1345 |                     response.raise_for_status()  # Raise an exception for HTTP errors
1346 | 
1347 |                     # Write the content to the temporary file
1348 |                     for chunk in response.iter_content(chunk_size=8192):
1349 |                         temp_file.write(chunk)
1350 | 
1351 |                     # Close the file
1352 |                     temp_file.close()
1353 | 
1354 |                 except Exception as e:
1355 |                     # Clean up the file if there's an error
1356 |                     temp_file.close()
1357 |                     os.unlink(temp_file.name)
1358 |                     return {"succeed": False, "error": str(e)}
1359 | 
1360 |                 break
1361 |         else:
1362 |             return {"succeed": False, "error": "Generation failed. Please first make sure that all jobs of the task are done and then try again later."}
1363 | 
1364 |         try:
1365 |             obj = self._clean_imported_glb(
1366 |                 filepath=temp_file.name,
1367 |                 mesh_name=name
1368 |             )
1369 |             result = {
1370 |                 "name": obj.name,
1371 |                 "type": obj.type,
1372 |                 "location": [obj.location.x, obj.location.y, obj.location.z],
1373 |                 "rotation": [obj.rotation_euler.x, obj.rotation_euler.y, obj.rotation_euler.z],
1374 |                 "scale": [obj.scale.x, obj.scale.y, obj.scale.z],
1375 |             }
1376 | 
1377 |             if obj.type == "MESH":
1378 |                 bounding_box = self._get_aabb(obj)
1379 |                 result["world_bounding_box"] = bounding_box
1380 | 
1381 |             return {
1382 |                 "succeed": True, **result
1383 |             }
1384 |         except Exception as e:
1385 |             return {"succeed": False, "error": str(e)}
1386 | 
1387 |     def import_generated_asset_fal_ai(self, request_id: str, name: str):
1388 |         """Fetch the generated asset, import into blender"""
1389 |         response = requests.get(
1390 |             f"https://queue.fal.run/fal-ai/hyper3d/requests/{request_id}",
1391 |             headers={
1392 |                 "Authorization": f"Key {bpy.context.scene.blendermcp_hyper3d_api_key}",
1393 |             }
1394 |         )
1395 |         data_ = response.json()
1396 |         temp_file = None
1397 | 
1398 |         temp_file = tempfile.NamedTemporaryFile(
1399 |             delete=False,
1400 |             prefix=request_id,
1401 |             suffix=".glb",
1402 |         )
1403 | 
1404 |         try:
1405 |             # Download the content
1406 |             response = requests.get(data_["model_mesh"]["url"], stream=True)
1407 |             response.raise_for_status()  # Raise an exception for HTTP errors
1408 | 
1409 |             # Write the content to the temporary file
1410 |             for chunk in response.iter_content(chunk_size=8192):
1411 |                 temp_file.write(chunk)
1412 | 
1413 |             # Close the file
1414 |             temp_file.close()
1415 | 
1416 |         except Exception as e:
1417 |             # Clean up the file if there's an error
1418 |             temp_file.close()
1419 |             os.unlink(temp_file.name)
1420 |             return {"succeed": False, "error": str(e)}
1421 | 
1422 |         try:
1423 |             obj = self._clean_imported_glb(
1424 |                 filepath=temp_file.name,
1425 |                 mesh_name=name
1426 |             )
1427 |             result = {
1428 |                 "name": obj.name,
1429 |                 "type": obj.type,
1430 |                 "location": [obj.location.x, obj.location.y, obj.location.z],
1431 |                 "rotation": [obj.rotation_euler.x, obj.rotation_euler.y, obj.rotation_euler.z],
1432 |                 "scale": [obj.scale.x, obj.scale.y, obj.scale.z],
1433 |             }
1434 | 
1435 |             if obj.type == "MESH":
1436 |                 bounding_box = self._get_aabb(obj)
1437 |                 result["world_bounding_box"] = bounding_box
1438 | 
1439 |             return {
1440 |                 "succeed": True, **result
1441 |             }
1442 |         except Exception as e:
1443 |             return {"succeed": False, "error": str(e)}
1444 |     #endregion
1445 | 
1446 |     #region Sketchfab API
1447 |     def get_sketchfab_status(self):
1448 |         """Get the current status of Sketchfab integration"""
1449 |         enabled = bpy.context.scene.blendermcp_use_sketchfab
1450 |         api_key = bpy.context.scene.blendermcp_sketchfab_api_key
1451 | 
1452 |         # Test the API key if present
1453 |         if api_key:
1454 |             try:
1455 |                 headers = {
1456 |                     "Authorization": f"Token {api_key}"
1457 |                 }
1458 | 
1459 |                 response = requests.get(
1460 |                     "https://api.sketchfab.com/v3/me",
1461 |                     headers=headers,
1462 |                     timeout=30  # Add timeout of 30 seconds
1463 |                 )
1464 | 
1465 |                 if response.status_code == 200:
1466 |                     user_data = response.json()
1467 |                     username = user_data.get("username", "Unknown user")
1468 |                     return {
1469 |                         "enabled": True,
1470 |                         "message": f"Sketchfab integration is enabled and ready to use. Logged in as: {username}"
1471 |                     }
1472 |                 else:
1473 |                     return {
1474 |                         "enabled": False,
1475 |                         "message": f"Sketchfab API key seems invalid. Status code: {response.status_code}"
1476 |                     }
1477 |             except requests.exceptions.Timeout:
1478 |                 return {
1479 |                     "enabled": False,
1480 |                     "message": "Timeout connecting to Sketchfab API. Check your internet connection."
1481 |                 }
1482 |             except Exception as e:
1483 |                 return {
1484 |                     "enabled": False,
1485 |                     "message": f"Error testing Sketchfab API key: {str(e)}"
1486 |                 }
1487 | 
1488 |         if enabled and api_key:
1489 |             return {"enabled": True, "message": "Sketchfab integration is enabled and ready to use."}
1490 |         elif enabled and not api_key:
1491 |             return {
1492 |                 "enabled": False,
1493 |                 "message": """Sketchfab integration is currently enabled, but API key is not given. To enable it:
1494 |                             1. In the 3D Viewport, find the BlenderMCP panel in the sidebar (press N if hidden)
1495 |                             2. Keep the 'Use Sketchfab' checkbox checked
1496 |                             3. Enter your Sketchfab API Key
1497 |                             4. Restart the connection to Claude"""
1498 |             }
1499 |         else:
1500 |             return {
1501 |                 "enabled": False,
1502 |                 "message": """Sketchfab integration is currently disabled. To enable it:
1503 |                             1. In the 3D Viewport, find the BlenderMCP panel in the sidebar (press N if hidden)
1504 |                             2. Check the 'Use assets from Sketchfab' checkbox
1505 |                             3. Enter your Sketchfab API Key
1506 |                             4. Restart the connection to Claude"""
1507 |             }
1508 | 
1509 |     def search_sketchfab_models(self, query, categories=None, count=20, downloadable=True):
1510 |         """Search for models on Sketchfab based on query and optional filters"""
1511 |         try:
1512 |             api_key = bpy.context.scene.blendermcp_sketchfab_api_key
1513 |             if not api_key:
1514 |                 return {"error": "Sketchfab API key is not configured"}
1515 | 
1516 |             # Build search parameters with exact fields from Sketchfab API docs
1517 |             params = {
1518 |                 "type": "models",
1519 |                 "q": query,
1520 |                 "count": count,
1521 |                 "downloadable": downloadable,
1522 |                 "archives_flavours": False
1523 |             }
1524 | 
1525 |             if categories:
1526 |                 params["categories"] = categories
1527 | 
1528 |             # Make API request to Sketchfab search endpoint
1529 |             # The proper format according to Sketchfab API docs for API key auth
1530 |             headers = {
1531 |                 "Authorization": f"Token {api_key}"
1532 |             }
1533 | 
1534 | 
1535 |             # Use the search endpoint as specified in the API documentation
1536 |             response = requests.get(
1537 |                 "https://api.sketchfab.com/v3/search",
1538 |                 headers=headers,
1539 |                 params=params,
1540 |                 timeout=30  # Add timeout of 30 seconds
1541 |             )
1542 | 
1543 |             if response.status_code == 401:
1544 |                 return {"error": "Authentication failed (401). Check your API key."}
1545 | 
1546 |             if response.status_code != 200:
1547 |                 return {"error": f"API request failed with status code {response.status_code}"}
1548 | 
1549 |             response_data = response.json()
1550 | 
1551 |             # Safety check on the response structure
1552 |             if response_data is None:
1553 |                 return {"error": "Received empty response from Sketchfab API"}
1554 | 
1555 |             # Handle 'results' potentially missing from response
1556 |             results = response_data.get("results", [])
1557 |             if not isinstance(results, list):
1558 |                 return {"error": f"Unexpected response format from Sketchfab API: {response_data}"}
1559 | 
1560 |             return response_data
1561 | 
1562 |         except requests.exceptions.Timeout:
1563 |             return {"error": "Request timed out. Check your internet connection."}
1564 |         except json.JSONDecodeError as e:
1565 |             return {"error": f"Invalid JSON response from Sketchfab API: {str(e)}"}
1566 |         except Exception as e:
1567 |             import traceback
1568 |             traceback.print_exc()
1569 |             return {"error": str(e)}
1570 | 
1571 |     def download_sketchfab_model(self, uid):
1572 |         """Download a model from Sketchfab by its UID"""
1573 |         try:
1574 |             api_key = bpy.context.scene.blendermcp_sketchfab_api_key
1575 |             if not api_key:
1576 |                 return {"error": "Sketchfab API key is not configured"}
1577 | 
1578 |             # Use proper authorization header for API key auth
1579 |             headers = {
1580 |                 "Authorization": f"Token {api_key}"
1581 |             }
1582 | 
1583 |             # Request download URL using the exact endpoint from the documentation
1584 |             download_endpoint = f"https://api.sketchfab.com/v3/models/{uid}/download"
1585 | 
1586 |             response = requests.get(
1587 |                 download_endpoint,
1588 |                 headers=headers,
1589 |                 timeout=30  # Add timeout of 30 seconds
1590 |             )
1591 | 
1592 |             if response.status_code == 401:
1593 |                 return {"error": "Authentication failed (401). Check your API key."}
1594 | 
1595 |             if response.status_code != 200:
1596 |                 return {"error": f"Download request failed with status code {response.status_code}"}
1597 | 
1598 |             data = response.json()
1599 | 
1600 |             # Safety check for None data
1601 |             if data is None:
1602 |                 return {"error": "Received empty response from Sketchfab API for download request"}
1603 | 
1604 |             # Extract download URL with safety checks
1605 |             gltf_data = data.get("gltf")
1606 |             if not gltf_data:
1607 |                 return {"error": "No gltf download URL available for this model. Response: " + str(data)}
1608 | 
1609 |             download_url = gltf_data.get("url")
1610 |             if not download_url:
1611 |                 return {"error": "No download URL available for this model. Make sure the model is downloadable and you have access."}
1612 | 
1613 |             # Download the model (already has timeout)
1614 |             model_response = requests.get(download_url, timeout=60)  # 60 second timeout
1615 | 
1616 |             if model_response.status_code != 200:
1617 |                 return {"error": f"Model download failed with status code {model_response.status_code}"}
1618 | 
1619 |             # Save to temporary file
1620 |             temp_dir = tempfile.mkdtemp()
1621 |             zip_file_path = os.path.join(temp_dir, f"{uid}.zip")
1622 | 
1623 |             with open(zip_file_path, "wb") as f:
1624 |                 f.write(model_response.content)
1625 | 
1626 |             # Extract the zip file with enhanced security
1627 |             with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
1628 |                 # More secure zip slip prevention
1629 |                 for file_info in zip_ref.infolist():
1630 |                     # Get the path of the file
1631 |                     file_path = file_info.filename
1632 | 
1633 |                     # Convert directory separators to the current OS style
1634 |                     # This handles both / and \ in zip entries
1635 |                     target_path = os.path.join(temp_dir, os.path.normpath(file_path))
1636 | 
1637 |                     # Get absolute paths for comparison
1638 |                     abs_temp_dir = os.path.abspath(temp_dir)
1639 |                     abs_target_path = os.path.abspath(target_path)
1640 | 
1641 |                     # Ensure the normalized path doesn't escape the target directory
1642 |                     if not abs_target_path.startswith(abs_temp_dir):
1643 |                         with suppress(Exception):
1644 |                             shutil.rmtree(temp_dir)
1645 |                         return {"error": "Security issue: Zip contains files with path traversal attempt"}
1646 | 
1647 |                     # Additional explicit check for directory traversal
1648 |                     if ".." in file_path:
1649 |                         with suppress(Exception):
1650 |                             shutil.rmtree(temp_dir)
1651 |                         return {"error": "Security issue: Zip contains files with directory traversal sequence"}
1652 | 
1653 |                 # If all files passed security checks, extract them
1654 |                 zip_ref.extractall(temp_dir)
1655 | 
1656 |             # Find the main glTF file
1657 |             gltf_files = [f for f in os.listdir(temp_dir) if f.endswith('.gltf') or f.endswith('.glb')]
1658 | 
1659 |             if not gltf_files:
1660 |                 with suppress(Exception):
1661 |                     shutil.rmtree(temp_dir)
1662 |                 return {"error": "No glTF file found in the downloaded model"}
1663 | 
1664 |             main_file = os.path.join(temp_dir, gltf_files[0])
1665 | 
1666 |             # Import the model
1667 |             bpy.ops.import_scene.gltf(filepath=main_file)
1668 | 
1669 |             # Get the names of imported objects
1670 |             imported_objects = [obj.name for obj in bpy.context.selected_objects]
1671 | 
1672 |             # Clean up temporary files
1673 |             with suppress(Exception):
1674 |                 shutil.rmtree(temp_dir)
1675 | 
1676 |             return {
1677 |                 "success": True,
1678 |                 "message": "Model imported successfully",
1679 |                 "imported_objects": imported_objects
1680 |             }
1681 | 
1682 |         except requests.exceptions.Timeout:
1683 |             return {"error": "Request timed out. Check your internet connection and try again with a simpler model."}
1684 |         except json.JSONDecodeError as e:
1685 |             return {"error": f"Invalid JSON response from Sketchfab API: {str(e)}"}
1686 |         except Exception as e:
1687 |             import traceback
1688 |             traceback.print_exc()
1689 |             return {"error": f"Failed to download model: {str(e)}"}
1690 |     #endregion
1691 | 
1692 | # Blender UI Panel
1693 | class BLENDERMCP_PT_Panel(bpy.types.Panel):
1694 |     bl_label = "Blender MCP"
1695 |     bl_idname = "BLENDERMCP_PT_Panel"
1696 |     bl_space_type = 'VIEW_3D'
1697 |     bl_region_type = 'UI'
1698 |     bl_category = 'BlenderMCP'
1699 | 
1700 |     def draw(self, context):
1701 |         layout = self.layout
1702 |         scene = context.scene
1703 | 
1704 |         layout.prop(scene, "blendermcp_port")
1705 |         layout.prop(scene, "blendermcp_use_polyhaven", text="Use assets from Poly Haven")
1706 | 
1707 |         layout.prop(scene, "blendermcp_use_hyper3d", text="Use Hyper3D Rodin 3D model generation")
1708 |         if scene.blendermcp_use_hyper3d:
1709 |             layout.prop(scene, "blendermcp_hyper3d_mode", text="Rodin Mode")
1710 |             layout.prop(scene, "blendermcp_hyper3d_api_key", text="API Key")
1711 |             layout.operator("blendermcp.set_hyper3d_free_trial_api_key", text="Set Free Trial API Key")
1712 | 
1713 |         layout.prop(scene, "blendermcp_use_sketchfab", text="Use assets from Sketchfab")
1714 |         if scene.blendermcp_use_sketchfab:
1715 |             layout.prop(scene, "blendermcp_sketchfab_api_key", text="API Key")
1716 | 
1717 |         if not scene.blendermcp_server_running:
1718 |             layout.operator("blendermcp.start_server", text="Connect to MCP server")
1719 |         else:
1720 |             layout.operator("blendermcp.stop_server", text="Disconnect from MCP server")
1721 |             layout.label(text=f"Running on port {scene.blendermcp_port}")
1722 | 
1723 | # Operator to set Hyper3D API Key
1724 | class BLENDERMCP_OT_SetFreeTrialHyper3DAPIKey(bpy.types.Operator):
1725 |     bl_idname = "blendermcp.set_hyper3d_free_trial_api_key"
1726 |     bl_label = "Set Free Trial API Key"
1727 | 
1728 |     def execute(self, context):
1729 |         context.scene.blendermcp_hyper3d_api_key = RODIN_FREE_TRIAL_KEY
1730 |         context.scene.blendermcp_hyper3d_mode = 'MAIN_SITE'
1731 |         self.report({'INFO'}, "API Key set successfully!")
1732 |         return {'FINISHED'}
1733 | 
1734 | # Operator to start the server
1735 | class BLENDERMCP_OT_StartServer(bpy.types.Operator):
1736 |     bl_idname = "blendermcp.start_server"
1737 |     bl_label = "Connect to Claude"
1738 |     bl_description = "Start the BlenderMCP server to connect with Claude"
1739 | 
1740 |     def execute(self, context):
1741 |         scene = context.scene
1742 | 
1743 |         # Create a new server instance
1744 |         if not hasattr(bpy.types, "blendermcp_server") or not bpy.types.blendermcp_server:
1745 |             bpy.types.blendermcp_server = BlenderMCPServer(port=scene.blendermcp_port)
1746 | 
1747 |         # Start the server
1748 |         bpy.types.blendermcp_server.start()
1749 |         scene.blendermcp_server_running = True
1750 | 
1751 |         return {'FINISHED'}
1752 | 
1753 | # Operator to stop the server
1754 | class BLENDERMCP_OT_StopServer(bpy.types.Operator):
1755 |     bl_idname = "blendermcp.stop_server"
1756 |     bl_label = "Stop the connection to Claude"
1757 |     bl_description = "Stop the connection to Claude"
1758 | 
1759 |     def execute(self, context):
1760 |         scene = context.scene
1761 | 
1762 |         # Stop the server if it exists
1763 |         if hasattr(bpy.types, "blendermcp_server") and bpy.types.blendermcp_server:
1764 |             bpy.types.blendermcp_server.stop()
1765 |             del bpy.types.blendermcp_server
1766 | 
1767 |         scene.blendermcp_server_running = False
1768 | 
1769 |         return {'FINISHED'}
1770 | 
1771 | # Registration functions
1772 | def register():
1773 |     bpy.types.Scene.blendermcp_port = IntProperty(
1774 |         name="Port",
1775 |         description="Port for the BlenderMCP server",
1776 |         default=9876,
1777 |         min=1024,
1778 |         max=65535
1779 |     )
1780 | 
1781 |     bpy.types.Scene.blendermcp_server_running = bpy.props.BoolProperty(
1782 |         name="Server Running",
1783 |         default=False
1784 |     )
1785 | 
1786 |     bpy.types.Scene.blendermcp_use_polyhaven = bpy.props.BoolProperty(
1787 |         name="Use Poly Haven",
1788 |         description="Enable Poly Haven asset integration",
1789 |         default=False
1790 |     )
1791 | 
1792 |     bpy.types.Scene.blendermcp_use_hyper3d = bpy.props.BoolProperty(
1793 |         name="Use Hyper3D Rodin",
1794 |         description="Enable Hyper3D Rodin generatino integration",
1795 |         default=False
1796 |     )
1797 | 
1798 |     bpy.types.Scene.blendermcp_hyper3d_mode = bpy.props.EnumProperty(
1799 |         name="Rodin Mode",
1800 |         description="Choose the platform used to call Rodin APIs",
1801 |         items=[
1802 |             ("MAIN_SITE", "hyper3d.ai", "hyper3d.ai"),
1803 |             ("FAL_AI", "fal.ai", "fal.ai"),
1804 |         ],
1805 |         default="MAIN_SITE"
1806 |     )
1807 | 
1808 |     bpy.types.Scene.blendermcp_hyper3d_api_key = bpy.props.StringProperty(
1809 |         name="Hyper3D API Key",
1810 |         subtype="PASSWORD",
1811 |         description="API Key provided by Hyper3D",
1812 |         default=""
1813 |     )
1814 | 
1815 |     bpy.types.Scene.blendermcp_use_sketchfab = bpy.props.BoolProperty(
1816 |         name="Use Sketchfab",
1817 |         description="Enable Sketchfab asset integration",
1818 |         default=False
1819 |     )
1820 | 
1821 |     bpy.types.Scene.blendermcp_sketchfab_api_key = bpy.props.StringProperty(
1822 |         name="Sketchfab API Key",
1823 |         subtype="PASSWORD",
1824 |         description="API Key provided by Sketchfab",
1825 |         default=""
1826 |     )
1827 | 
1828 |     bpy.utils.register_class(BLENDERMCP_PT_Panel)
1829 |     bpy.utils.register_class(BLENDERMCP_OT_SetFreeTrialHyper3DAPIKey)
1830 |     bpy.utils.register_class(BLENDERMCP_OT_StartServer)
1831 |     bpy.utils.register_class(BLENDERMCP_OT_StopServer)
1832 | 
1833 |     print("BlenderMCP addon registered")
1834 | 
1835 | def unregister():
1836 |     # Stop the server if it's running
1837 |     if hasattr(bpy.types, "blendermcp_server") and bpy.types.blendermcp_server:
1838 |         bpy.types.blendermcp_server.stop()
1839 |         del bpy.types.blendermcp_server
1840 | 
1841 |     bpy.utils.unregister_class(BLENDERMCP_PT_Panel)
1842 |     bpy.utils.unregister_class(BLENDERMCP_OT_SetFreeTrialHyper3DAPIKey)
1843 |     bpy.utils.unregister_class(BLENDERMCP_OT_StartServer)
1844 |     bpy.utils.unregister_class(BLENDERMCP_OT_StopServer)
1845 | 
1846 |     del bpy.types.Scene.blendermcp_port
1847 |     del bpy.types.Scene.blendermcp_server_running
1848 |     del bpy.types.Scene.blendermcp_use_polyhaven
1849 |     del bpy.types.Scene.blendermcp_use_hyper3d
1850 |     del bpy.types.Scene.blendermcp_hyper3d_mode
1851 |     del bpy.types.Scene.blendermcp_hyper3d_api_key
1852 |     del bpy.types.Scene.blendermcp_use_sketchfab
1853 |     del bpy.types.Scene.blendermcp_sketchfab_api_key
1854 | 
1855 |     print("BlenderMCP addon unregistered")
1856 | 
1857 | if __name__ == "__main__":
1858 |     register()
1859 | 
```