Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: add opt-in first-use Blender MCP setup (#10443)

Wasim Yousef Said56b8a6e4a4fe
diff --git a/pyproject.toml b/pyproject.toml
index 71bbf2f1dfa..02a66b00116 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -65,8 +65,9 @@ studio = [
"frontend/*.yaml",
"frontend/.git*",
"backend/requirements/**/*",
- # Vendored truststore: not a package (no __init__.py), so it ships as data.
+ # Vendored truststore files.
"backend/vendor/**/*",
+ "backend/integrations/blender/*.py",
"backend/plugins/**/*",
"backend/assets/**/*.jinja",
"backend/assets/**/*.html",
diff --git a/studio/MCP.md b/studio/MCP.md
index 127a85a116b..d082b767588 100644
--- a/studio/MCP.md
+++ b/studio/MCP.md
@@ -1,4 +1,41 @@
-# Unsloth Studio MCP server
+# MCP in Unsloth Studio
+
+## Connect Blender MCP
+
+Blender MCP is **disabled by default**. Studio downloads a pinned, checksum-verified
+runtime on first enable/test and caches it on the backend machine. No commands,
+Git or pip installs are needed. Subsequent starts use the cache without internet.
+The Blender add-on is installed separately. No MCP archive or source is shipped
+in Studio's Python package or desktop build.
+
+1. Open **Manage MCP servers → Blender**, approve the execution warning and choose
+ **Enable Blender MCP**. Use a tool-capable model with MCP enabled for the chat.
+2. Open **Setup help → Download Blender add-on** for
+ [Blender's official page](https://www.blender.org/lab/mcp-server/).
+3. In Blender 5.1+, enable **Preferences → System → Network → Allow Online Access**.
+ Drag the website's install button into Blender twice: first to add the Blender
+ Lab repository, then to install MCP. Alternatively, search **MCP** in
+ **Get Extensions** after adding the repository.
+4. Enable and start the add-on bridge, keep Blender open, then **Test connection**.
+
+A green dot means Blender is connected; amber means only the MCP server is connected.
+Setup help stays in the same Blender entry. Advanced settings configure the bridge
+port (default `9876`) and optional Blender executable. This port is not an HTTP URL.
+
+The bridge uses loopback on the **Studio backend machine**, not a remote browser.
+Studio does not install or launch Blender during setup. Approved tools can run
+Python, write files and launch background Blender. Existing tool permissions apply;
+external model providers receive tool results. Keep the unauthenticated bridge local.
+
+The downloaded runtime excludes the large API/manual reference corpus and its three
+offline documentation tools. The official source is
+https://projects.blender.org/lab/blender_mcp (GPL-3.0-or-later).
+The pinned revision and SHA-256 are in `backend/integrations/blender/runtime.py`.
+Downloads are staged and verified before activation; failures leave the server
+disabled and can be retried with **Enable Blender MCP**. Merely opening the dialog
+or launching Studio does not download anything.
+
+## Studio's own MCP server
Unsloth can expose a local MCP server so an MCP client can inspect models and
GPU state, validate recipes, start or stop training, inspect recipe output, and
diff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.py
index 2022103409b..ce6f38c45c5 100644
--- a/studio/backend/core/inference/tool_loop_controller.py
+++ b/studio/backend/core/inference/tool_loop_controller.py
@@ -723,7 +723,7 @@ def mcp_display_parts(tool_name: str) -> "tuple[str, str] | None":
return None
try:
from storage import mcp_servers_db
- server = mcp_servers_db.get_server(parts[1])
+ server = mcp_servers_db.get_server_for_tool(parts[1])
except Exception: # noqa: BLE001
return None
display = (server or {}).get("display_name")
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index efc0efe5bf5..c92799c2342 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -2036,6 +2036,18 @@ _AUTO_SAFE_WRAPPERS = frozenset(
}
)
+# These read-named tools launch unsandboxed Blender on a caller-selected file.
+_BLENDER_CLI_SUMMARY_TOOLS = frozenset(
+ {
+ "get_blendfile_summary_datablocks_for_cli",
+ "get_blendfile_summary_missing_files_for_cli",
+ "get_blendfile_summary_of_linked_libraries_for_cli",
+ "get_blendfile_summary_path_info_for_cli",
+ "get_blendfile_summary_usage_guess_for_cli",
+ }
+)
+
+
# MCP tools whose names look read-only auto-run; anything else asks.
_AUTO_SAFE_MCP_TOOL_RE = re.compile(
r"^(get|list|search|read|fetch|query|find|describe|show|view|lookup|"
@@ -4623,6 +4635,8 @@ def is_potentially_unsafe_tool_call(name: str, arguments: dict) -> bool:
return _render_html_reaches_network(arguments)
if name.startswith(MCP_TOOL_PREFIX):
tool_name = name.split("__", 2)[-1]
+ if tool_name in _BLENDER_CLI_SUMMARY_TOOLS:
+ return True
# A mutating verb anywhere (get_or_create_issue, read_and_delete)
# overrides a read-only prefix.
if _AUTO_UNSAFE_MCP_VERB_RE.search(tool_name):
@@ -6611,6 +6625,8 @@ def is_high_risk_tool_call(name: str, arguments: dict) -> bool:
return _render_html_reaches_network(arguments)
if name.startswith(MCP_TOOL_PREFIX):
tool_name = name.split("__", 2)[-1]
+ if tool_name in _BLENDER_CLI_SUMMARY_TOOLS:
+ return True
# Split camelCase into `_`-delimited terms so the term-boundary regexes
# below match camelCase names too.
tool_name = _CAMEL_CASE_RE.sub("_", tool_name)
@@ -10239,7 +10255,8 @@ def _mcp_specs_for_server(server: dict, mcp_tools: list[dict]) -> list[dict]:
if not _mcp_tool_model_visible(tool):
logger.debug("Skipping app-only MCP tool '%s' on '%s'.", raw_name, display)
continue
- name = f"{MCP_TOOL_PREFIX}{server['id']}__{raw_name}"
+ server_key = "blender" if server.get("builtin_id") == "blender" else server["id"]
+ name = f"{MCP_TOOL_PREFIX}{server_key}__{raw_name}"
# Bad chars or oversized names would 400 the whole request; skip + warn
# so the rest of the tools still ship.
if not _OPENAI_FN_NAME_RE.fullmatch(name):
@@ -10482,9 +10499,10 @@ def execute_tool(
_, server_id, tool_name = name.split("__", 2)
except ValueError:
return f"Error: malformed MCP tool name '{name}'"
- server = mcp_servers_db.get_server(server_id)
+ server = mcp_servers_db.get_server_for_tool(server_id)
if not server:
return f"Error: MCP server for tool '{tool_name}' not found"
+ server_id = server["id"]
display = server.get("display_name") or server_id
if not server.get("is_enabled"):
return f"Error: MCP server '{display}' is disabled"
diff --git a/studio/backend/integrations/blender/__init__.py b/studio/backend/integrations/blender/__init__.py
new file mode 100644
index 00000000000..764b8b541a3
--- /dev/null
+++ b/studio/backend/integrations/blender/__init__.py
@@ -0,0 +1,21 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+
+"""Studio-managed Blender MCP integration."""
+
+import sys
+from pathlib import Path
+
+from .runtime import runtime_path
+
+MIN_PYTHON_VERSION = (3, 10)
+MIN_BLENDER_VERSION = "5.1.0"
+
+
+def launch_command() -> list[str]:
+ return [
+ sys.executable,
+ str(Path(__file__).resolve().with_name("launcher.py")),
+ str(runtime_path()),
+ ]
diff --git a/studio/backend/integrations/blender/launcher.py b/studio/backend/integrations/blender/launcher.py
new file mode 100644
index 00000000000..e14ade066c7
--- /dev/null
+++ b/studio/backend/integrations/blender/launcher.py
@@ -0,0 +1,30 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+
+"""Launch the cached Blender MCP runtime over stdio without downloading."""
+
+import sys
+from pathlib import Path
+
+
+def main() -> int:
+ if sys.version_info < (3, 10):
+ print("Blender MCP requires Python 3.10 or newer.", file = sys.stderr)
+ return 1
+ if len(sys.argv) != 2:
+ print("Expected the Blender MCP runtime path.", file = sys.stderr)
+ return 2
+ runtime = Path(sys.argv[1])
+ if not (runtime / ".ready").is_file():
+ print("Open Blender MCP in Studio and enable it to download the runtime.", file = sys.stderr)
+ return 1
+ sys.path.insert(0, str(runtime))
+ from blmcp import main as upstream_main
+
+ sys.argv = [str(Path(__file__).resolve()), "--transport", "stdio"]
+ return upstream_main()
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/studio/backend/integrations/blender/runtime.py b/studio/backend/integrations/blender/runtime.py
new file mode 100644
index 00000000000..4bb934f8ec2
--- /dev/null
+++ b/studio/backend/integrations/blender/runtime.py
@@ -0,0 +1,94 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import hashlib
+import io
+import tarfile
+import tempfile
+from pathlib import Path, PurePosixPath
+
+import httpx
+from utils.paths.storage_roots import cache_root
+
+REVISION = "4309a39646e644261624bfcd2bca669b343b7621"
+ARCHIVE_SHA256 = "acb68eb4beff27a84ba751931745e62f03ad51b7be50b3a924624153b6c38197"
+ARCHIVE_URL = f"https://projects.blender.org/api/v1/repos/lab/blender_mcp/archive/{REVISION}.tar.gz"
+_EXCLUDED = {
+ "get_python_api_docs.py",
+ "search_api_docs.py",
+ "search_manual_docs.py",
+ "rst_doc_search.py",
+ "rst_parse_docs.py",
+}
+
+
+def runtime_path() -> Path:
+ return cache_root() / "blender-mcp" / (REVISION + "-runtime-v1")
+
+
+def _download() -> bytes:
+ data = bytearray()
+ with httpx.stream("GET", ARCHIVE_URL, follow_redirects = True, timeout = 30) as response:
+ response.raise_for_status()
+ for chunk in response.iter_bytes():
+ data.extend(chunk)
+ if len(data) > 32 * 1024 * 1024:
+ raise ValueError("Blender MCP download exceeds the size limit")
+ return bytes(data)
+
+
+def _extract(data: bytes, target: Path) -> None:
+ if hashlib.sha256(data).hexdigest() != ARCHIVE_SHA256:
+ raise ValueError("Blender MCP download checksum mismatch")
+ with tarfile.open(fileobj = io.BytesIO(data), mode = "r:gz") as archive:
+ for member in archive:
+ parts = PurePosixPath(member.name).parts
+ if len(parts) < 4 or parts[1:3] != ("mcp", "blmcp"):
+ continue
+ if member.isdir():
+ continue
+ relative = PurePosixPath(*parts[2:])
+ if ".." in parts or "\\" in member.name or ":" in member.name or not member.isfile():
+ raise ValueError("Unsafe Blender MCP archive entry")
+ if relative.name in _EXCLUDED:
+ continue
+ if relative.suffix != ".py" and str(relative) != "blmcp/data/prompts.yml":
+ continue
+ if member.size > 1024 * 1024:
+ raise ValueError("Blender MCP archive entry exceeds the size limit")
+ source = archive.extractfile(member)
+ if source is None:
+ raise ValueError("Missing Blender MCP archive entry")
+ destination = target / str(relative)
+ destination.parent.mkdir(parents = True, exist_ok = True)
+ destination.write_bytes(source.read())
+ prompt = target / "blmcp/data/prompts.yml"
+ text = prompt.read_text(encoding = "utf-8")
+ start, end = text.index(" # Bundled Manuals"), text.index(" # Executing Code")
+ prompt.write_text(
+ text[:start]
+ + " # Documentation\n\n Offline documentation tools are not installed.\n\n"
+ + text[end:],
+ encoding = "utf-8",
+ )
+ if not (target / "blmcp/__init__.py").is_file():
+ raise ValueError("Incomplete Blender MCP runtime")
+
+
+def ensure_runtime() -> Path:
+ from filelock import FileLock
+
+ target = runtime_path()
+ target.parent.mkdir(parents = True, exist_ok = True)
+ with FileLock(str(target) + ".lock", timeout = 120):
+ if (target / ".ready").is_file():
+ return target
+ if target.exists():
+ raise ValueError("Incomplete Blender MCP cache; remove this runtime cache and retry")
+ with tempfile.TemporaryDirectory(prefix = ".install-", dir = target.parent) as temporary:
+ staged = Path(temporary) / "runtime"
+ staged.mkdir()
+ _extract(_download(), staged)
+ (staged / ".ready").write_text(ARCHIVE_SHA256, encoding = "ascii")
+ staged.rename(target)
+ return target
diff --git a/studio/backend/integrations/blender/service.py b/studio/backend/integrations/blender/service.py
new file mode 100644
index 00000000000..b60aa856d70
--- /dev/null
+++ b/studio/backend/integrations/blender/service.py
@@ -0,0 +1,126 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import asyncio
+import json
+import sys
+
+from core.inference.mcp_client import (
+ join_stdio_command,
+ list_tools_async,
+ stdio_mcp_disabled_reason,
+ stdio_mcp_enabled,
+)
+from integrations.blender import MIN_BLENDER_VERSION, MIN_PYTHON_VERSION, launch_command
+from integrations.blender.runtime import ensure_runtime
+from models.mcp_servers import BlenderSettings, McpBuiltinResponse, McpServerProbeResult
+
+
+def unavailable_reason():
+ if sys.version_info < MIN_PYTHON_VERSION:
+ return "Blender MCP requires Python 3.10 or newer."
+ if not stdio_mcp_enabled():
+ return stdio_mcp_disabled_reason()
+ return None
+
+
+def settings_for(row):
+ config = json.loads(row.get("builtin_config_json") or "{}") if row else {}
+ return BlenderSettings(
+ port = config.get("port", 9876), blender_path = config.get("blender_path", "")
+ )
+
+
+def resolve_server(row: dict) -> dict:
+ if row.get("builtin_id") != "blender":
+ raise ValueError("Unknown managed MCP integration")
+ settings = settings_for(row)
+ env = {
+ "BLENDER_MCP_HOST": "127.0.0.1",
+ "BLENDER_MCP_PORT": str(settings.port),
+ "BLENDER_PATH": settings.blender_path or "blender",
+ }
+ return {
+ **row,
+ "url": join_stdio_command(launch_command()),
+ "headers_json": json.dumps(env),
+ "use_oauth": False,
+ }
+
+
+def catalog_item(row = None):
+ reason = unavailable_reason()
+ return McpBuiltinResponse(
+ **settings_for(row).model_dump(),
+ server_id = row["id"] if row else None,
+ is_enabled = bool(row and row["is_enabled"]),
+ available = reason is None,
+ unavailable_reason = reason,
+ min_blender_version = MIN_BLENDER_VERSION,
+ )
+
+
+async def _bridge_version(port):
+ reader, writer = await asyncio.open_connection("127.0.0.1", port, limit = 16384)
+ try:
+ request = {
+ "type": "execute",
+ "code": "import bpy\nresult = {'version': list(bpy.app.version)}",
+ "strict_json": True,
+ }
+ writer.write((json.dumps(request) + "\0").encode())
+ await writer.drain()
+ response = json.loads((await reader.readuntil(b"\0"))[:-1])
+ version = response.get("result", {}).get("version")
+ if (
+ response.get("status") != "ok"
+ or not isinstance(version, list)
+ or len(version) != 3
+ or any(type(v) is not int for v in version)
+ ):
+ raise ValueError("Invalid Blender bridge version response")
+ if tuple(version) < tuple(map(int, MIN_BLENDER_VERSION.split("."))):
+ raise ValueError(f"Blender {MIN_BLENDER_VERSION} or newer is required")
+ finally:
+ writer.close()
+ await writer.wait_closed()
+
+
+async def probe(
+ settings: BlenderSettings,
+ *,
+ check_bridge: bool = True,
+ on_tools = None,
+) -> McpServerProbeResult:
+ reason = unavailable_reason()
+ if reason:
+ return McpServerProbeResult(ok = False, error = reason)
+ try:
+ await asyncio.to_thread(ensure_runtime)
+ except Exception:
+ return McpServerProbeResult(
+ ok = False,
+ error = "Could not set up Blender MCP. Check the backend's internet connection and cache permissions, then retry. Downloads must match the pinned checksum.",
+ )
+ row = resolve_server(
+ {"builtin_id": "blender", "builtin_config_json": settings.model_dump_json()}
+ )
+ env = json.loads(row["headers_json"])
+ try:
+ tools = await list_tools_async(row["url"], headers = env, timeout = 15)
+ except Exception:
+ return McpServerProbeResult(
+ ok = False,
+ error = "Could not connect to Blender MCP. Check the Studio backend installation and retry.",
+ )
+ result = McpServerProbeResult(ok = True, tool_count = len(tools))
+ if check_bridge:
+ try:
+ await asyncio.wait_for(_bridge_version(settings.port), timeout = 5)
+ result.blender_ready = True
+ except Exception:
+ result.blender_ready = False
+ result.blender_error = f"Blender is not connected on port {settings.port}. Enable its MCP add-on, then retry."
+ if on_tools is not None:
+ on_tools(tools)
+ return result
diff --git a/studio/backend/models/mcp_servers.py b/studio/backend/models/mcp_servers.py
index 6beb116823c..cee6a2da7a3 100644
--- a/studio/backend/models/mcp_servers.py
+++ b/studio/backend/models/mcp_servers.py
@@ -25,6 +25,7 @@ class McpServerUpdate(BaseModel):
class McpServerResponse(BaseModel):
id: str
+ builtin_id: Optional[str] = None
display_name: str
url: str
headers: dict[str, str] = Field(default_factory = dict)
@@ -40,6 +41,32 @@ class McpServerTestRequest(BaseModel):
use_oauth: bool = False
+class BlenderSettings(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ port: int = Field(default = 9876, ge = 1, le = 65535, strict = True)
+ blender_path: StrictStr = Field(default = "", pattern = r"^[^\x00]*$")
+
+
+class BlenderTest(BlenderSettings):
+ consent: bool = Field(default = False, strict = True)
+
+
+class BlenderSetup(BlenderSettings):
+ is_enabled: bool
+ consent: bool = False
+
+
+class McpBuiltinResponse(BlenderSettings):
+ builtin_id: str = "blender"
+ display_name: str = "Blender"
+ server_id: Optional[str] = None
+ is_enabled: bool = False
+ available: bool
+ unavailable_reason: Optional[str] = None
+ min_blender_version: str
+
+
class McpStdioDecodeRequest(BaseModel):
url: StrictStr
@@ -57,6 +84,8 @@ class McpServerProbeResult(BaseModel):
ok: bool
tool_count: int = 0
error: Optional[str] = None
+ blender_ready: Optional[bool] = None
+ blender_error: Optional[str] = None
class McpServerImportRequest(BaseModel):
diff --git a/studio/backend/routes/mcp_servers.py b/studio/backend/routes/mcp_servers.py
index 9fc92348e3d..10e3eebfbdc 100644
--- a/studio/backend/routes/mcp_servers.py
+++ b/studio/backend/routes/mcp_servers.py
@@ -10,6 +10,8 @@ from urllib.parse import urlparse
import structlog
from fastapi import APIRouter, Depends, HTTPException
+from integrations.blender import service as blender
+from models.mcp_servers import BlenderSettings, BlenderSetup, McpBuiltinResponse
from auth.authentication import (
authenticated_via_api_key,
@@ -36,6 +38,7 @@ from core.inference.mcp_client import (
)
from core.inference.mcp_config_import import parse_mcp_config
from models.mcp_servers import (
+ BlenderTest,
McpServerCreate,
McpServerImportRequest,
McpServerImportResult,
@@ -152,6 +155,7 @@ def _normalize_headers(headers: dict[str, str] | None) -> dict[str, str] | None:
def _row_to_response(row: dict, *, include_headers: bool = True) -> McpServerResponse:
return McpServerResponse(
id = row["id"],
+ builtin_id = row.get("builtin_id"),
display_name = row["display_name"],
url = row["url"],
headers = (parse_server_headers(row) or {}) if include_headers else {},
@@ -162,6 +166,103 @@ def _row_to_response(row: dict, *, include_headers: bool = True) -> McpServerRes
)
+def _blender_row():
+ return next(
+ (row for row in mcp_servers_db.list_servers() if row.get("builtin_id") == "blender"), None
+ )
+
+
+def _require_managed_access(
+ via_api_key,
+ no_credential,
+ *,
+ executes = False,
+):
+ require_ui_session_for_local_commands(via_api_key or no_credential)
+ if executes and not stdio_mcp_enabled():
+ raise HTTPException(status_code = 400, detail = stdio_mcp_disabled_reason())
+
+
[email protected]("/builtins", response_model = list[McpBuiltinResponse])
+def list_builtins(
+ current_subject: str = Depends(get_current_subject),
+ via_api_key: ViaApiKey = False,
+ no_credential: WithoutCredential = False,
+):
+ if via_api_key or no_credential:
+ item = blender.catalog_item()
+ item.available = False
+ item.unavailable_reason = "An authenticated Studio UI session is required for Blender MCP."
+ return [item]
+ return [blender.catalog_item(_blender_row())]
+
+
[email protected]("/builtins/blender/test", response_model = McpServerProbeResult)
+@serialize_mcp_server_mutation
+async def test_blender(
+ payload: BlenderTest,
+ current_subject: str = Depends(get_current_subject),
+ via_api_key: ViaApiKey = False,
+ no_credential: WithoutCredential = False,
+):
+ _require_managed_access(via_api_key, no_credential, executes = True)
+ row = _blender_row()
+ config = json.loads(row.get("builtin_config_json") or "{}") if row else {}
+ if not (config.get("consent") or payload.consent):
+ raise HTTPException(
+ status_code = 400, detail = "Explicit consent is required before testing Blender MCP."
+ )
+ settings = BlenderSettings(port = payload.port, blender_path = payload.blender_path)
+ on_tools = None
+ if row and blender.settings_for(row) == settings:
+ on_tools = lambda tools: cache_tools(row["id"], tools)
+ return await blender.probe(settings, on_tools = on_tools)
+
+
[email protected]("/builtins/blender", response_model = McpBuiltinResponse)
+@serialize_mcp_server_mutation
+async def setup_blender(
+ payload: BlenderSetup,
+ current_subject: str = Depends(get_current_subject),
+ via_api_key: ViaApiKey = False,
+ no_credential: WithoutCredential = False,
+):
+ _require_managed_access(via_api_key, no_credential, executes = payload.is_enabled)
+ old = _blender_row()
+ config = json.loads(old.get("builtin_config_json") or "{}") if old else {}
+ if payload.is_enabled and not (config.get("consent") or payload.consent):
+ raise HTTPException(
+ status_code = 400, detail = "Explicit consent is required before enabling Blender MCP."
+ )
+ settings = BlenderSettings(port = payload.port, blender_path = payload.blender_path)
+ config = {**settings.model_dump(), "consent": bool(config.get("consent") or payload.consent)}
+ server_id = old["id"] if old else uuid.uuid4().hex[:16]
+ if old:
+ mcp_servers_db.update_server(
+ server_id, {"builtin_config_json": json.dumps(config), "is_enabled": False}
+ )
+ else:
+ mcp_servers_db.create_server(
+ server_id,
+ "Blender",
+ "",
+ is_enabled = False,
+ builtin_id = "blender",
+ builtin_config_json = json.dumps(config),
+ )
+ invalidate_tool_cache(server_id)
+ if old:
+ await asyncio.to_thread(close_mcp_sessions, old["url"], parse_server_headers(old))
+ if payload.is_enabled:
+ result = await blender.probe(
+ settings, check_bridge = False, on_tools = lambda tools: cache_tools(server_id, tools)
+ )
+ if not result.ok:
+ raise HTTPException(status_code = 400, detail = result.error)
+ mcp_servers_db.update_server(server_id, {"is_enabled": True})
+ return blender.catalog_item(mcp_servers_db.get_server(server_id))
+
+
@router.post("/stdio/decode", response_model = McpStdioCommand)
def decode_stdio_command(
payload: McpStdioDecodeRequest,
@@ -282,6 +383,13 @@ async def update_mcp_server(
if not old:
raise HTTPException(status_code = 404, detail = "MCP server not found")
changes = _changes_from_payload(payload)
+ if old.get("builtin_id"):
+ _require_managed_access(via_api_key, no_credential)
+ if payload.model_fields_set != {"is_enabled"} or payload.is_enabled is not False:
+ raise HTTPException(
+ status_code = 400,
+ detail = "Use the managed integration setup to configure or enable this server.",
+ )
if not changes:
raise HTTPException(status_code = 400, detail = "No fields to update")
# Both directions, so an API key can neither repoint an http row at a command
@@ -329,6 +437,10 @@ async def delete_mcp_server(server_id: str, current_subject: str = Depends(get_c
old = mcp_servers_db.get_server(server_id)
if not old:
raise HTTPException(status_code = 404, detail = "MCP server not found")
+ if old.get("builtin_id"):
+ raise HTTPException(
+ status_code = 400, detail = "Managed integrations cannot be deleted; disable them instead."
+ )
if old.get("use_oauth"):
await clear_oauth_tokens_async(old["url"])
mcp_servers_db.delete_server(server_id)
@@ -345,6 +457,11 @@ async def refresh_mcp_server_tools(
server = mcp_servers_db.get_server(server_id)
if not server:
raise HTTPException(status_code = 404, detail = "MCP server not found")
+ if server.get("builtin_id"):
+ raise HTTPException(
+ status_code = 400,
+ detail = "Use the managed integration Test action to check Blender readiness.",
+ )
# Refresh uses the stored address.
if is_stdio(server["url"]):
require_ui_session_for_local_commands(via_api_key)
diff --git a/studio/backend/storage/mcp_servers_db.py b/studio/backend/storage/mcp_servers_db.py
index 6482bae1406..d5f7190e2b5 100644
--- a/studio/backend/storage/mcp_servers_db.py
+++ b/studio/backend/storage/mcp_servers_db.py
@@ -32,6 +32,12 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
cols = {r["name"] for r in conn.execute("PRAGMA table_info(mcp_servers)").fetchall()}
if "use_oauth" not in cols:
conn.execute("ALTER TABLE mcp_servers ADD COLUMN use_oauth INTEGER NOT NULL DEFAULT 0")
+ for column in ("builtin_id", "builtin_config_json"):
+ if column not in cols:
+ conn.execute(f"ALTER TABLE mcp_servers ADD COLUMN {column} TEXT")
+ conn.execute(
+ "CREATE UNIQUE INDEX IF NOT EXISTS mcp_servers_builtin_id ON mcp_servers(builtin_id)"
+ )
def get_connection() -> sqlite3.Connection:
@@ -59,6 +65,8 @@ def create_server(
headers_json: Optional[str] = None,
is_enabled: bool = True,
use_oauth: bool = False,
+ builtin_id: Optional[str] = None,
+ builtin_config_json: Optional[str] = None,
) -> None:
now = datetime.now(timezone.utc).isoformat()
conn = get_connection()
@@ -67,8 +75,8 @@ def create_server(
"""
INSERT INTO mcp_servers
(id, display_name, url, headers_json,
- is_enabled, use_oauth, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ is_enabled, use_oauth, created_at, updated_at, builtin_id, builtin_config_json)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
id,
@@ -79,6 +87,8 @@ def create_server(
int(use_oauth),
now,
now,
+ builtin_id,
+ builtin_config_json,
),
)
conn.commit()
@@ -124,7 +134,7 @@ def get_server(id: str) -> Optional[dict]:
conn = get_connection()
try:
row = conn.execute("SELECT * FROM mcp_servers WHERE id = ?", (id,)).fetchone()
- return dict(row) if row else None
+ return _effective_row(dict(row)) if row else None
finally:
conn.close()
@@ -133,6 +143,19 @@ def list_servers() -> list[dict]:
conn = get_connection()
try:
rows = conn.execute("SELECT * FROM mcp_servers ORDER BY created_at").fetchall()
- return [dict(row) for row in rows]
+ return [_effective_row(dict(row)) for row in rows]
finally:
conn.close()
+
+
+def get_server_for_tool(key: str) -> Optional[dict]:
+ if key == "blender":
+ return next((row for row in list_servers() if row.get("builtin_id") == key), None)
+ return get_server(key)
+
+
+def _effective_row(row: dict) -> dict:
+ if row.get("builtin_id"):
+ from integrations.blender.service import resolve_server
+ return resolve_server(row)
+ return row
diff --git a/studio/backend/tests/test_blender_managed.py b/studio/backend/tests/test_blender_managed.py
new file mode 100644
index 00000000000..d66702160de
--- /dev/null
+++ b/studio/backend/tests/test_blender_managed.py
@@ -0,0 +1,163 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+
+import json
+import sqlite3
+from unittest.mock import AsyncMock
+
+import pytest
+from fastapi import HTTPException
+from pydantic import ValidationError
+
+from integrations.blender import service
+from models.mcp_servers import BlenderTest
+from models.mcp_servers import BlenderSettings, BlenderSetup, McpServerProbeResult, McpServerUpdate
+from routes import mcp_servers as routes
+from storage import mcp_servers_db as db
+
+
[email protected](autouse = True)
+def managed_policy(monkeypatch):
+ monkeypatch.setattr(routes, "stdio_mcp_enabled", lambda: True)
+ monkeypatch.setattr(service, "stdio_mcp_enabled", lambda: True)
+ from core.inference.mcp_client import invalidate_tool_cache
+
+ invalidate_tool_cache()
+
+
+def test_catalog_is_opt_in_and_settings_are_typed(monkeypatch):
+ probe = AsyncMock()
+ monkeypatch.setattr(service, "probe", probe)
+ item = routes.list_builtins()[0]
+ assert item.server_id is None and not item.is_enabled and item.port == 9876
+ assert db.list_servers() == []
+ probe.assert_not_called()
+ for fields in (
+ {"port": True},
+ {"port": "9876"},
+ {"port": 0},
+ {"port": 65536},
+ {"blender_path": "x\0y"},
+ {"command": "sh"},
+ ):
+ with pytest.raises(ValidationError):
+ BlenderSettings(**fields)
+
+
+async def test_managed_enable_failure_retry_disable_and_portability(monkeypatch):
+ probe = AsyncMock(return_value = McpServerProbeResult(ok = False, error = "Blender unavailable"))
+ monkeypatch.setattr(service, "probe", probe)
+ with pytest.raises(HTTPException):
+ await routes.setup_blender(BlenderSetup(is_enabled = True))
+ assert db.list_servers() == []
+ with pytest.raises(HTTPException):
+ await routes.setup_blender(BlenderSetup(is_enabled = True, consent = True, port = 9877))
+ row = db.list_servers()[0]
+ assert not row["is_enabled"]
+ assert json.loads(row["headers_json"])["BLENDER_MCP_HOST"] == "127.0.0.1"
+ with db.get_connection() as conn:
+ raw = dict(conn.execute("SELECT * FROM mcp_servers").fetchone())
+ assert raw["url"] == "" and raw["headers_json"] is None
+ assert json.loads(raw["builtin_config_json"])["port"] == 9877
+ with pytest.raises(sqlite3.IntegrityError):
+ db.create_server("other", "Blender", "", builtin_id = "blender")
+ probe.return_value = McpServerProbeResult(ok = True, tool_count = 3)
+ enabled = await routes.setup_blender(BlenderSetup(is_enabled = True, port = 9877))
+ assert enabled.server_id == row["id"] and enabled.is_enabled
+ for update in (
+ McpServerUpdate(is_enabled = True),
+ McpServerUpdate(url = "python"),
+ McpServerUpdate(headers = {"X": "y"}),
+ ):
+ with pytest.raises(HTTPException):
+ await routes.update_mcp_server(row["id"], update)
+ with pytest.raises(HTTPException):
+ await routes.delete_mcp_server(row["id"])
+ monkeypatch.setattr(routes, "stdio_mcp_enabled", lambda: False)
+ await routes.update_mcp_server(row["id"], McpServerUpdate(is_enabled = False))
+ assert not db.get_server(row["id"])["is_enabled"]
+
+
+async def test_managed_authorization_precedes_side_effects(monkeypatch):
+ probe = AsyncMock()
+ monkeypatch.setattr(service, "probe", probe)
+ for auth in ({"via_api_key": True}, {"no_credential": True}):
+ with pytest.raises(HTTPException):
+ await routes.setup_blender(BlenderSetup(is_enabled = False), **auth)
+ with pytest.raises(HTTPException):
+ await routes.test_blender(BlenderSettings(), **auth)
+ monkeypatch.setattr(routes, "stdio_mcp_enabled", lambda: False)
+ with pytest.raises(HTTPException):
+ await routes.test_blender(BlenderSettings())
+ assert db.list_servers() == []
+ probe.assert_not_called()
+ saved = await routes.setup_blender(BlenderSetup(is_enabled = False, port = 9878))
+ assert not saved.is_enabled and saved.port == 9878
+ for auth in ({"via_api_key": True}, {"no_credential": True}):
+ item = routes.list_builtins(**auth)[0]
+ assert not item.available and item.server_id is None and item.port == 9876
+ probe.assert_not_called()
+
+
+async def test_first_probe_requires_consent_before_setup(monkeypatch):
+ probe = AsyncMock(return_value = McpServerProbeResult(ok = True))
+ monkeypatch.setattr(service, "probe", probe)
+ with pytest.raises(HTTPException, match = "consent"):
+ await routes.test_blender(BlenderTest())
+ probe.assert_not_called()
+ await routes.test_blender(BlenderTest(consent = True))
+ probe.assert_awaited_once()
+
+
+async def test_probe_separates_mcp_and_blender_readiness(monkeypatch):
+ monkeypatch.setattr(service, "ensure_runtime", lambda: None)
+ bridge = AsyncMock(side_effect = ConnectionError())
+ tools = AsyncMock(return_value = [{"name": "execute_blender_code"}])
+ monkeypatch.setattr(service, "_bridge_version", bridge)
+ monkeypatch.setattr(service, "list_tools_async", tools)
+ from core.inference import mcp_client
+
+ result = await service.probe(BlenderSettings())
+ assert result.ok and result.tool_count == 1 and result.blender_ready is False
+ assert result.blender_error
+ bridge.assert_awaited_with(9876)
+ bridge.reset_mock()
+ assert (await service.probe(BlenderSettings(), check_bridge = False)).ok
+ bridge.assert_not_called()
+ bridge.side_effect = None
+ assert (await service.probe(BlenderSettings())).blender_ready is True
+ enabled = await routes.setup_blender(BlenderSetup(is_enabled = True, consent = True))
+ assert mcp_client.get_cached_tools(enabled.server_id) == tools.return_value
+ mcp_client.invalidate_tool_cache(enabled.server_id)
+ await routes.test_blender(BlenderSettings(port = 9877))
+ assert mcp_client.get_cached_tools(enabled.server_id) is None
+ await routes.test_blender(BlenderSettings())
+ assert mcp_client.get_cached_tools(enabled.server_id) == tools.return_value
+
+
+def test_long_blender_names_dispatch_with_approval(monkeypatch):
+ from core.inference import tools
+ from unittest.mock import Mock
+
+ db.create_server("0123456789abcdef", "Blender", "", builtin_id = "blender")
+ monkeypatch.setattr(tools, "stdio_mcp_enabled", lambda: True)
+ call = Mock(return_value = "ok")
+ monkeypatch.setattr(tools, "call_tool_sync", call)
+ names = sorted(tools._BLENDER_CLI_SUMMARY_TOOLS)
+ specs = tools._mcp_specs_for_server(db.list_servers()[0], [{"name": n} for n in names])
+ assert len(specs) == len(names)
+ for raw, spec in zip(names, specs):
+ name = spec["function"]["name"]
+ assert len(name) <= 64
+ assert tools.is_potentially_unsafe_tool_call(name, {})
+ assert tools.is_high_risk_tool_call(name, {})
+ tools.execute_tool(name, {})
+ assert call.call_args.kwargs["name"] == raw
+ assert call.call_args.kwargs["config_check"]()
+ db.update_server("0123456789abcdef", {"is_enabled": False})
+ call.reset_mock()
+ assert "disabled" in tools.execute_tool(specs[0]["function"]["name"], {})
+ call.assert_not_called()
diff --git a/studio/backend/tests/test_blender_runtime.py b/studio/backend/tests/test_blender_runtime.py
new file mode 100644
index 00000000000..d586cda84a2
--- /dev/null
+++ b/studio/backend/tests/test_blender_runtime.py
@@ -0,0 +1,59 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import hashlib
+import io
+import tarfile
+from concurrent.futures import ThreadPoolExecutor
+from unittest.mock import Mock
+
+import pytest
+from integrations.blender import runtime
+
+
+def archive_bytes(extra = None):
+ buffer = io.BytesIO()
+ entries = {
+ "root/mcp/blmcp/__init__.py": b"",
+ "root/mcp/blmcp/data/prompts.yml": b"initial_instructions: |\n # Bundled Manuals\n old\n # Executing Code\n",
+ "root/mcp/blmcp/data/api/ignored.rst": b"not installed",
+ "root/mcp/blmcp/tools/search_api_docs.py": b"not installed",
+ }
+ if extra:
+ entries[extra] = b"unsafe"
+ with tarfile.open(fileobj = buffer, mode = "w:gz") as archive:
+ directory = tarfile.TarInfo("root/mcp/blmcp/data")
+ directory.type = tarfile.DIRTYPE
+ archive.addfile(directory)
+ for name, data in entries.items():
+ member = tarfile.TarInfo(name)
+ member.size = len(data)
+ archive.addfile(member, io.BytesIO(data))
+ return buffer.getvalue()
+
+
+def test_failed_download_retry_and_concurrent_offline_cache(tmp_path, monkeypatch):
+ data = archive_bytes()
+ monkeypatch.setattr(runtime, "cache_root", lambda: tmp_path)
+ monkeypatch.setattr(runtime, "ARCHIVE_SHA256", hashlib.sha256(data).hexdigest())
+ download = Mock(side_effect = [b"corrupt", data])
+ monkeypatch.setattr(runtime, "_download", download)
+ with pytest.raises(ValueError, match = "checksum"):
+ runtime.ensure_runtime()
+ assert not runtime.runtime_path().exists()
+ assert not list(runtime.runtime_path().parent.glob(".install-*"))
+ with ThreadPoolExecutor(max_workers = 2) as pool:
+ paths = list(pool.map(lambda _: runtime.ensure_runtime(), range(2)))
+ assert paths[0] == paths[1] and download.call_count == 2
+ assert (paths[0] / ".ready").is_file()
+ assert not (paths[0] / "blmcp/data/api").exists()
+ assert not (paths[0] / "blmcp/tools/search_api_docs.py").exists()
+ assert "Bundled Manuals" not in (paths[0] / "blmcp/data/prompts.yml").read_text()
+
+
+def test_verified_archive_still_rejects_traversal(tmp_path, monkeypatch):
+ data = archive_bytes("root/mcp/blmcp/../../escape.py")
+ monkeypatch.setattr(runtime, "ARCHIVE_SHA256", hashlib.sha256(data).hexdigest())
+ with pytest.raises(ValueError, match = "Unsafe"):
+ runtime._extract(data, tmp_path / "runtime")
+ assert not (tmp_path / "escape.py").exists()
diff --git a/studio/backend/tests/test_permission_mode.py b/studio/backend/tests/test_permission_mode.py
index 74f5a195f9a..4ba895841a4 100644
--- a/studio/backend/tests/test_permission_mode.py
+++ b/studio/backend/tests/test_permission_mode.py
@@ -2452,6 +2452,27 @@ def test_mcp_classifier(tool, unsafe):
assert is_potentially_unsafe_tool_call(name, {}) is unsafe
+ "tool, approval",
+ [
+ ("get_blendfile_summary_datablocks_for_cli", True),
+ ("get_blendfile_summary_missing_files_for_cli", True),
+ ("get_blendfile_summary_of_linked_libraries_for_cli", True),
+ ("get_blendfile_summary_path_info_for_cli", True),
+ ("get_blendfile_summary_usage_guess_for_cli", True),
+ ("get_python_api_docs", False),
+ ("search_api_docs", False),
+ ("search_manual_docs", False),
+ ],
+)
+def test_blender_cli_summaries_require_approval(tool, approval):
+ from core.inference.tools import is_high_risk_tool_call
+
+ name = f"{MCP_TOOL_PREFIX}srv1__{tool}"
+ assert is_potentially_unsafe_tool_call(name, {}) is approval
+ assert is_high_risk_tool_call(name, {}) is approval
+
+
@pytest.mark.parametrize(
("args", "unsafe"),
[
diff --git a/studio/backend/tests/test_tool_result_fits_window.py b/studio/backend/tests/test_tool_result_fits_window.py
index a1daef8aa9d..0ce4dcae64c 100644
--- a/studio/backend/tests/test_tool_result_fits_window.py
+++ b/studio/backend/tests/test_tool_result_fits_window.py
@@ -481,7 +481,7 @@ class TestEveryToolIsHeldToTheRoom:
monkeypatch.setattr(
tools.mcp_servers_db,
"get_server",
- lambda _id: {"url": "https://example.invalid/mcp", "is_enabled": True},
+ lambda _id: {"id": "srv", "url": "https://example.invalid/mcp", "is_enabled": True},
)
monkeypatch.setattr(tools, "parse_server_headers", lambda _s: {})
monkeypatch.setattr(tools, "is_stdio", lambda _u: False)
@@ -616,7 +616,7 @@ class TestTheFrontendEnvelopeSurvivesTheCap:
monkeypatch.setattr(
tools.mcp_servers_db,
"get_server",
- lambda _id: {"url": "https://example.invalid/mcp", "is_enabled": True},
+ lambda _id: {"id": "srv", "url": "https://example.invalid/mcp", "is_enabled": True},
)
monkeypatch.setattr(tools, "parse_server_headers", lambda _s: {})
monkeypatch.setattr(tools, "is_stdio", lambda _u: False)
diff --git a/studio/frontend/src/features/chat/api/mcp-servers-api.ts b/studio/frontend/src/features/chat/api/mcp-servers-api.ts
index 23ca91dd46e..33f62e8b24c 100644
--- a/studio/frontend/src/features/chat/api/mcp-servers-api.ts
+++ b/studio/frontend/src/features/chat/api/mcp-servers-api.ts
@@ -13,6 +13,7 @@ import {
export interface McpServerConfig {
id: string;
+ builtin_id: string | null;
display_name: string;
url: string;
headers: Record<string, string>;
@@ -28,6 +29,45 @@ export interface McpServerProbeResult {
error: string | null;
}
+export interface McpBuiltinConfig {
+ builtin_id: "blender";
+ display_name: string;
+ server_id: string | null;
+ is_enabled: boolean;
+ available: boolean;
+ unavailable_reason: string | null;
+ port: number;
+ blender_path: string;
+ min_blender_version: string;
+}
+
+export interface BlenderMcpSettings {
+ port: number;
+ blender_path: string;
+}
+
+export function listMcpBuiltins(waitForPendingMutations = true): Promise<McpBuiltinConfig[]> {
+ const read = () => mcpRequest<McpBuiltinConfig[]>("/builtins");
+ return waitForPendingMutations
+ ? readAfterPendingMcpServerMutations(read)
+ : readMcpServerMutationSnapshot(read);
+}
+
+export function updateBlenderMcp(
+ payload: BlenderMcpSettings & { is_enabled: boolean; consent: boolean },
+): Promise<McpBuiltinConfig> {
+ return trackMcpServerMutation(
+ mcpRequest("/builtins/blender", { method: "PUT", body: payload }),
+ );
+}
+
+export function testBlenderMcp(payload: BlenderMcpSettings & { consent: boolean }): Promise<McpServerProbeResult & {
+ blender_ready?: boolean;
+ blender_error?: string | null;
+}> {
+ return mcpRequest("/builtins/blender/test", { method: "POST", body: payload });
+}
+
export interface McpServerImportResult {
created: McpServerConfig[];
skipped: string[];
diff --git a/studio/frontend/src/features/chat/blender-mcp-setup.tsx b/studio/frontend/src/features/chat/blender-mcp-setup.tsx
new file mode 100644
index 00000000000..f9acd354056
--- /dev/null
+++ b/studio/frontend/src/features/chat/blender-mcp-setup.tsx
@@ -0,0 +1,211 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
+import { ChevronDown } from "lucide-react";
+import { openLink } from "@/lib/open-link";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Spinner } from "@/components/ui/spinner";
+import { subscribeToMcpServerMutationSettlements } from "./api/mcp-server-mutation-tracker";
+import {
+ type McpBuiltinConfig,
+ type McpServerConfig,
+ listMcpBuiltins,
+ testBlenderMcp,
+ updateBlenderMcp,
+ updateMcpServer,
+} from "./api/mcp-servers-api";
+import { useChatRuntimeStore } from "./stores/chat-runtime-store";
+
+export function BlenderMcpSetup({ servers, disabled, onBusyChange }: {
+ servers: McpServerConfig[];
+ disabled: boolean;
+ onBusyChange: (busy: boolean) => void;
+}) {
+ const [config, setConfig] = useState<McpBuiltinConfig | null>(null);
+ const [port, setPort] = useState("9876");
+ const [blenderPath, setBlenderPath] = useState("");
+ const [consent, setConsent] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [connection, setConnection] = useState<"checking" | "ready" | "partial" | "failed" | null>(null);
+ const [message, setMessage] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const generation = useRef(0);
+ const busyRef = useRef(false);
+ const initialized = useRef(false);
+ const mounted = useRef(false);
+
+ const refresh = useCallback(async (wait = true) => {
+ const current = ++generation.current;
+ try {
+ const rows = await listMcpBuiltins(wait);
+ if (generation.current !== current) return;
+ const blender = rows.find((row) => row.builtin_id === "blender");
+ if (!blender) throw new Error("Blender MCP is not available from this Studio backend.");
+ setConfig(blender);
+ setLoadError(null);
+ if (!initialized.current) {
+ initialized.current = true;
+ setPort(String(blender.port));
+ setBlenderPath(blender.blender_path);
+ }
+ } catch (err) {
+ if (generation.current === current) setLoadError(err instanceof Error ? err.message : String(err));
+ }
+ }, []);
+
+ useEffect(() => {
+ mounted.current = true;
+ let cancelled = false;
+ queueMicrotask(() => { if (!cancelled) void refresh(); });
+ const unsubscribe = subscribeToMcpServerMutationSettlements(() => void refresh(false));
+ return () => {
+ cancelled = true;
+ mounted.current = false;
+ unsubscribe();
+ generation.current += 1;
+ onBusyChange(false);
+ };
+ }, [refresh, onBusyChange]);
+
+ const validPort = /^\d+$/.test(port) && Number(port) >= 1 && Number(port) <= 65535;
+ const locked = disabled || busy;
+ const duplicate = servers.some((server) => !server.builtin_id && /blender|blmcp/i.test(`${server.display_name} ${server.url}`));
+
+ async function act(action: "test" | "save" | "enable" | "disable") {
+ if (busyRef.current || disabled) return;
+ busyRef.current = true;
+ setBusy(true);
+ onBusyChange(true);
+ setError(null);
+ setMessage(null);
+ setConnection(action === "test" ? "checking" : null);
+ try {
+ const settings = { port: Number(port), blender_path: blenderPath.trim() };
+ if (action === "test") {
+ const result = await testBlenderMcp({ ...settings, consent });
+ if (!mounted.current) return;
+ if (!result.ok) throw new Error(result.error ?? "MCP connection failed. Retry or check the Studio backend.");
+ setConnection(result.blender_ready ? "ready" : "partial");
+ setMessage(`MCP connected (${result.tool_count} tools). ${result.blender_ready
+ ? "Blender ready."
+ : result.blender_error ?? "Blender is not connected. Open Setup help below."}`);
+ } else if (action === "disable" && config?.server_id) {
+ await updateMcpServer(config.server_id, { isEnabled: false });
+ if (!mounted.current) return;
+ setMessage("Blender tools disabled. Your Blender window remains open.");
+ } else {
+ const updated = await updateBlenderMcp({ ...settings, is_enabled: action === "enable", consent });
+ if (!mounted.current) return;
+ if (updated.is_enabled) useChatRuntimeStore.getState().setMcpEnabledForChat(true);
+ setConfig(updated);
+ setMessage(updated.is_enabled
+ ? "Blender MCP enabled for this chat. Scene tools require a connected Blender add-on."
+ : "Settings saved; Blender is disabled.");
+ }
+ } catch (err) {
+ if (mounted.current && action === "test") setConnection("failed");
+ if (mounted.current) setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ busyRef.current = false;
+ if (mounted.current) {
+ setBusy(false);
+ onBusyChange(false);
+ }
+ }
+ }
+
+ return (
+ <section className="space-y-4 rounded-xl border p-4" aria-label="Blender MCP">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <h3 className="text-sm font-medium">Blender</h3>
+ {connection && (
+ <span role="status" className={`inline-flex items-center gap-1.5 text-xs ${
+ connection === "ready" ? "text-emerald-600 dark:text-emerald-400"
+ : connection === "partial" ? "text-amber-600 dark:text-amber-400"
+ : connection === "failed" ? "text-destructive" : "text-muted-foreground"
+ }`}>
+ <span aria-hidden="true" className={`size-2 shrink-0 rounded-full bg-current ${connection === "checking" ? "motion-safe:animate-pulse" : ""}`} />
+ {connection === "ready" ? "Connected"
+ : connection === "partial" ? "MCP only"
+ : connection === "failed" ? "Connection failed" : "Testing…"}
+ </span>
+ )}
+ </div>
+ <span className="text-xs text-muted-foreground">
+ {!config ? "Loading…" : config.is_enabled ? "Enabled" : !config.available ? "Unavailable" : "Disabled"}
+ </span>
+ </div>
+ {!config?.is_enabled && <p className="text-sm leading-relaxed text-muted-foreground">
+ Studio downloads and sets up MCP on first use. Internet is needed once; the Blender add-on is installed separately.
+ </p>}
+ {duplicate && <p className="text-xs leading-relaxed text-amber-600">A custom Blender server also exists. Disable it below if you prefer Studio’s managed setup.</p>}
+ {config && !config.is_enabled && (
+ <div className="flex items-start gap-3">
+ <Checkbox id="blender-mcp-consent" className="mt-0.5" checked={consent} disabled={locked} onCheckedChange={(checked) => setConsent(checked === true)} />
+ <Label htmlFor="blender-mcp-consent" className="text-xs font-normal leading-relaxed">
+ Allow unsandboxed Python, scene changes and background Blender tool processes. Results may be sent to your model provider. Cancelling may not undo changes.
+ </Label>
+ </div>
+ )}
+ <div className="flex flex-wrap items-center gap-2">
+ {config && !config.is_enabled && (
+ <Button size="sm" disabled={locked || !config.available || !validPort || !consent} onClick={() => void act("enable")}>Enable Blender MCP</Button>
+ )}
+ <Button size="sm" variant="outline" disabled={locked || !config?.available || !validPort || (!config.is_enabled && !consent)} onClick={() => void act("test")}>Test connection</Button>
+ {config?.is_enabled && <Button size="sm" variant="outline" disabled={locked} onClick={() => void act("disable")}>Disable</Button>}
+ {busy && <span role="status" className="inline-flex items-center gap-2 text-xs text-muted-foreground"><Spinner />Setting up / checking MCP…</span>}
+ </div>
+ <Collapsible className="border-t pt-3">
+ <CollapsibleTrigger className="group flex items-center gap-1 rounded-md py-1 text-xs text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ {config?.server_id ? "Setup help" : "Set up Blender"}
+ <ChevronDown aria-hidden="true" className="size-4 text-muted-foreground transition-transform duration-200 group-data-[state=open]:rotate-180 motion-reduce:transition-none" />
+ </CollapsibleTrigger>
+ <CollapsibleContent className="[--duration:200ms] motion-reduce:animate-none">
+ <div className="space-y-4 pt-4 text-sm leading-relaxed text-muted-foreground">
+ <p>Use Blender {config?.min_blender_version ?? "5.1.0"}+ on the Studio backend machine.</p>
+ <Button size="sm" variant="outline" onClick={() => openLink("https://www.blender.org/lab/mcp-server/")}>Download Blender add-on</Button>
+ <ol className="list-decimal space-y-3 pl-5">
+ <li>In Blender, enable <strong className="font-medium text-foreground">Online Access</strong> in Preferences → System.</li>
+ <li>Drag the website’s install button into Blender to add the <strong className="font-medium text-foreground">Blender Lab</strong> repository.</li>
+ <li>Drag it in again and confirm the add-on installation. Or, after adding the repository, search <strong className="font-medium text-foreground">MCP</strong> in Preferences → Get Extensions.</li>
+ </ol>
+ <p>Enable the add-on, keep Blender open, then test the connection above.</p>
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+
+ <Collapsible className="border-t pt-3">
+ <CollapsibleTrigger className="group flex w-full items-center justify-between rounded-md py-1 text-sm font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ Advanced settings
+ <ChevronDown aria-hidden="true" className="size-4 text-muted-foreground transition-transform duration-200 group-data-[state=open]:rotate-180 motion-reduce:transition-none" />
+ </CollapsibleTrigger>
+ <CollapsibleContent className="[--duration:200ms] motion-reduce:animate-none">
+ <div className="space-y-4 pt-4">
+ <p className="text-xs leading-relaxed text-muted-foreground">Loopback only (127.0.0.1). Match the add-on’s port. Studio needs Python 3.10+.</p>
+ <div className="grid gap-3 sm:grid-cols-[100px_1fr]">
+ <div className="space-y-1">
+ <Label htmlFor="blender-mcp-port">Port</Label>
+ <Input id="blender-mcp-port" inputMode="numeric" value={port} disabled={locked || !config} onChange={(event) => { setPort(event.target.value); setMessage(null); setConnection(null); }} />
+ </div>
+ <div className="space-y-1">
+ <Label htmlFor="blender-mcp-path">Blender executable (optional)</Label>
+ <Input id="blender-mcp-path" value={blenderPath} disabled={locked || !config} placeholder="Auto-detect Blender" onChange={(event) => { setBlenderPath(event.target.value); setMessage(null); setConnection(null); }} />
+ </div>
+ </div>
+ <Button size="sm" variant="outline" disabled={locked || !config || !validPort} onClick={() => void act("save")}>Save &amp; disable</Button>
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+ {config?.unavailable_reason && <p className="text-xs text-muted-foreground">{config.unavailable_reason}</p>}
+ {message && <p role="status" className="text-xs">{message}</p>}
+ {(error || loadError) && <div role="alert" className="text-xs text-destructive">{error || loadError}{loadError && <Button size="sm" variant="ghost" onClick={() => void refresh()}>Retry</Button>}</div>}
+ </section>
+ );
+}
diff --git a/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx b/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx
index 636acbaa5b1..14f572c5c99 100644
--- a/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx
+++ b/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx
@@ -57,6 +57,8 @@ import {
createMcpStdioSnapshot,
resolveMcpStdioUrl,
} from "./mcp-server-form";
+import { BlenderMcpSetup } from "./blender-mcp-setup";
+
type HeaderRow = { id: string; key: string; value: string };
type ArgumentRow = { id: string; value: string };
type FormTransport = "unknown" | "http" | "stdio";
@@ -356,6 +358,7 @@ export function ChatMcpServersDialog({
}: ChatMcpServersDialogProps) {
const [servers, setServers] = useState<McpServerConfig[]>([]);
const [loading, setLoading] = useState(false);
+ const [blenderBusy, setBlenderBusy] = useState(false);
const [view, setView] = useState<View>({ kind: "list" });
const [form, setForm] = useState<FormState>(EMPTY_FORM);
const [saving, setSaving] = useState(false);
@@ -487,6 +490,7 @@ export function ChatMcpServersDialog({
}
async function startEdit(server: McpServerConfig) {
+ if (blenderBusy) return;
const generation = formGenerationRef.current + 1;
formGenerationRef.current = generation;
activeEditIdRef.current = server.id;
@@ -569,7 +573,7 @@ export function ChatMcpServersDialog({
function handleOpenChange(next: boolean) {
// once crud starts, dismissal must wait for the authoritative refresh
- if (!next && ((saving && !codecPending) || busyIdsRef.current.size > 0))
+ if (!next && (blenderBusy || (saving && !codecPending) || busyIdsRef.current.size > 0))
return;
if (!next) {
formGenerationRef.current += 1;
@@ -880,8 +884,8 @@ export function ChatMcpServersDialog({
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent
- className="max-w-2xl"
- showCloseButton={!(saving && !codecPending) && busyIds.size === 0}
+ className="max-w-2xl max-h-[85dvh] overflow-y-auto"
+ showCloseButton={!blenderBusy && !(saving && !codecPending) && busyIds.size === 0}
aria-busy={decodingCommand}
>
<DialogHeader>
@@ -1095,18 +1099,19 @@ export function ChatMcpServersDialog({
</div>
) : (
<div className="flex min-w-0 flex-col gap-3">
+ {open && <BlenderMcpSetup servers={servers} disabled={importing} onBusyChange={setBlenderBusy} />}
<div className="flex justify-end gap-2">
<Button
size="sm"
variant="outline"
onClick={() => fileInputRef.current?.click()}
- disabled={importing}
+ disabled={importing || blenderBusy}
title="Import servers from a mcpServers JSON config (Claude Desktop, Cursor, VS Code…)"
>
{importing ? <Spinner /> : <UploadIcon size={14} />}
Import config
</Button>
- <Button size="sm" onClick={startCreate} disabled={importing}>
+ <Button size="sm" onClick={startCreate} disabled={importing || blenderBusy}>
<HugeiconsIcon icon={PlusSignIcon} size={14} />
Add server
</Button>
@@ -1115,13 +1120,13 @@ export function ChatMcpServersDialog({
<div className="flex justify-center py-6">
<Spinner />
</div>
- ) : servers.length === 0 ? (
+ ) : servers.filter((server) => !server.builtin_id).length === 0 ? (
<div className="rounded-md border border-dashed py-6 text-center text-sm text-muted-foreground">
- No MCP servers configured yet.
+ No custom MCP servers configured yet.
</div>
) : (
<ul className="flex flex-col divide-y rounded-md border">
- {servers.map((server) => (
+ {servers.filter((server) => !server.builtin_id).map((server) => (
<li
key={server.id}
className="flex items-center justify-between gap-3 px-3 py-2"
@@ -1162,7 +1167,7 @@ export function ChatMcpServersDialog({
size="icon"
onClick={() => void startEdit(server)}
aria-label="Edit server"
- disabled={importing || busyIds.has(server.id)}
+ disabled={importing || blenderBusy || busyIds.has(server.id)}
>
<HugeiconsIcon icon={Edit03Icon} size={14} />
</Button>
diff --git a/studio/frontend/src/features/chat/mcp-composer-button.tsx b/studio/frontend/src/features/chat/mcp-composer-button.tsx
index f4c8fe3cccf..dd5aec5c59f 100644
--- a/studio/frontend/src/features/chat/mcp-composer-button.tsx
+++ b/studio/frontend/src/features/chat/mcp-composer-button.tsx
@@ -175,7 +175,10 @@ export function McpComposerButton({
);
// Non-preset servers, shown below the presets so they stay toggleable.
const customServers = servers.filter(
- (s) => !PRESET_URLS.has(normalizeMcpUrl(s.url)),
+ (s) => !s.builtin_id && !PRESET_URLS.has(normalizeMcpUrl(s.url)),
+ );
+ const blenderEnabled = servers.some(
+ (server) => server.builtin_id === "blender" && server.is_enabled,
);
const enabledCount = servers.filter((s) => s.is_enabled).length;
const active = usable && mcpEnabledForChat && enabledCount > 0;
@@ -356,6 +359,18 @@ export function McpComposerButton({
disablesWebSearch: preset.disablesWebSearch,
});
})}
+ <DropdownMenuItem
+ onSelect={() => {
+ setMenuOpen(false);
+ setDialogOpen(true);
+ }}
+ className={blenderEnabled ? "relative text-primary font-medium" : "relative"}
+ >
+ <span className="truncate">Blender</span>
+ {blenderEnabled ? (
+ <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="ml-auto" />
+ ) : null}
+ </DropdownMenuItem>
{customServers.length > 0 ? <DropdownMenuSeparator /> : null}
{customServers.map((server) =>
renderRow({
diff --git a/studio/frontend/tests/mcp-server-arguments.test.ts b/studio/frontend/tests/mcp-server-arguments.test.ts
index 23e3f451be5..81b49559ac8 100644
--- a/studio/frontend/tests/mcp-server-arguments.test.ts
+++ b/studio/frontend/tests/mcp-server-arguments.test.ts
@@ -281,7 +281,7 @@ test("dialog actions and reconciliation stop when the dialog closes", () => {
assert.match(dialog, /open=\{open && confirmingDelete !== null\}/);
assert.match(
dialog,
- /<Button size="sm" onClick=\{startCreate\} disabled=\{importing\}>/,
+ /<Button size="sm" onClick=\{startCreate\} disabled=\{importing \|\| blenderBusy\}>/,
);
});
@@ -327,12 +327,12 @@ test("dialog closure is blocked while a CRUD mutation is in flight", () => {
assert.match(
closeHandler,
- /if \(!next && \(\(saving && !codecPending\) \|\| busyIdsRef\.current\.size > 0\)\)[\s\S]*return;[\s\S]*if \(!next\) \{[\s\S]*formGenerationRef\.current \+= 1;/,
+ /if \(!next && \(blenderBusy \|\| \(saving && !codecPending\) \|\| busyIdsRef\.current\.size > 0\)\)[\s\S]*return;[\s\S]*if \(!next\) \{[\s\S]*formGenerationRef\.current \+= 1;/,
"the in-flight mutation guard must run before close invalidates the form generation",
);
assert.match(
dialog,
- /<DialogContent[\s\S]*?showCloseButton=\{!\(saving && !codecPending\) && busyIds\.size === 0\}[\s\S]*?>/,
+ /<DialogContent[\s\S]*?showCloseButton=\{!blenderBusy && !\(saving && !codecPending\) && busyIds\.size === 0\}[\s\S]*?>/,
"the built-in close control must disappear during the same mutation window",
);
assert.match(
@@ -786,8 +786,8 @@ test("every list consumer uses the shared pending-mutation read barrier", () =>
assert.equal(
api.match(/return trackMcpServerMutation\(/g)?.length,
- 4,
- "create, update, delete, and import must register at the API boundary",
+ 5,
+ "create, update, delete, import, and managed Blender updates must register at the API boundary",
);
assert.match(
listApi,