Compare commits

...

64 commits
v1.3.3 ... main

Author SHA1 Message Date
9786988690 Fix ComfyUI prompt queueing: always generate server-side UUID for prompt_id
ComfyUI's /prompt endpoint now validates prompt_id as a UUID. This app's
queueComfyPrompt() trusted a client-supplied identifiers.promptId (used as
a correlation id for progress polling), which is not guaranteed to be a
UUID, causing every queued workflow to fail with "prompt_id must be a
valid UUID" and no way to retry successfully. The correlation id used for
progress streaming (executionPromptId) is independent of what's actually
sent to ComfyUI in the request body, so this is safe to always regenerate.

Found and verified 2026-07-30 while getting 3DGenStudio's bundled mesh-gen
workflows working against a fresh ComfyUI instance.
2026-07-30 08:22:54 +03:00
Bruno Fargnoli
52862252f2 version 2.1.2
Some checks failed
Desktop build / build (macos-latest, dist:mac) (push) Has been cancelled
Desktop build / build (ubuntu-latest, dist:linux) (push) Has been cancelled
Desktop build / build (windows-latest, dist:win) (push) Has been cancelled
2026-07-28 11:13:57 +02:00
Bruno Fargnoli
e66c0c3fcd Added Wireframe mode in Mesh Previewer 2026-07-28 11:10:30 +02:00
Bruno Fargnoli
4558969b6c Updated Desktop App Splashscreen icon 2026-07-28 11:06:54 +02:00
Bruno Fargnoli
49f799058a ComfyUI: Added Enums 2026-07-28 10:55:46 +02:00
Bruno Fargnoli
e4715aa0c1 Fixed gitignore with skintokens 2026-07-28 10:07:29 +02:00
Bruno Fargnoli
64ed97fd3a Updated flash_attention_linux 2026-07-28 10:01:28 +02:00
Bruno Fargnoli
4d7ee2eff6 Trying to fix Rigging Service on Linux 2026-07-28 09:54:39 +02:00
Bruno Fargnoli
409158f056 version 2.1.1
Some checks failed
Desktop build / build (macos-latest, dist:mac) (push) Has been cancelled
Desktop build / build (ubuntu-latest, dist:linux) (push) Has been cancelled
Desktop build / build (windows-latest, dist:win) (push) Has been cancelled
2026-07-27 22:36:04 +02:00
Bruno Fargnoli
4c14f68cb6 Improved Graph page performances 2026-07-27 22:27:01 +02:00
Bruno Fargnoli
218f2ca468 Kanban: Can add more meshes and images from any column 2026-07-27 19:47:01 +02:00
Bruno Fargnoli
65d0b76c71 Updated Gen Image Workflows to support batch_size 2026-07-27 11:55:36 +02:00
Bruno Fargnoli
22c6badff1 Fixed assets linked to a project 2026-07-27 10:35:35 +02:00
Bruno Fargnoli
21312811e5 ComfyUI: Can set a custom models folder 2026-07-23 23:04:01 +02:00
Bruno Fargnoli
66eb43a9cf Mesh Export: AutoSave last output folder 2026-07-23 22:54:28 +02:00
Bruno Fargnoli
096c5e7851 version 2.1.0
Some checks failed
Desktop build / build (macos-latest, dist:mac) (push) Has been cancelled
Desktop build / build (ubuntu-latest, dist:linux) (push) Has been cancelled
Desktop build / build (windows-latest, dist:win) (push) Has been cancelled
2026-07-23 10:18:57 +02:00
Bruno Fargnoli
ae3472b4a8 Fixed bug in storage 2026-07-22 14:58:53 +02:00
Bruno Fargnoli
1389d9c443 Fixed Storage with images generated from a board 2026-07-20 16:43:25 +02:00
Bruno Fargnoli
be0318c1d8 Fixed Storge with Generated Image from a Board 2026-07-20 15:25:34 +02:00
Bruno Fargnoli
72455e8064 Added Brainstorming Boards 2026-07-20 13:41:58 +02:00
Bruno Fargnoli
5d1bb30044 version 2.0.0
Some checks failed
Desktop build / build (macos-latest, dist:mac) (push) Has been cancelled
Desktop build / build (ubuntu-latest, dist:linux) (push) Has been cancelled
Desktop build / build (windows-latest, dist:win) (push) Has been cancelled
2026-07-19 22:42:18 +02:00
Bruno Fargnoli
7875f01205 MCP: Added Wiki page 2026-07-19 22:31:12 +02:00
Bruno Fargnoli
044371d816 MCP: Visual Studio Code configuration 2026-07-19 20:28:20 +02:00
Bruno Fargnoli
3248db74a6 Fixed MCP with Kanban project 2026-07-19 19:35:27 +02:00
Bruno Fargnoli
d4ef8f8b1b Simplified Image Node Actions in Graph Page + Fixed MCP 2026-07-19 17:12:59 +02:00
Bruno Fargnoli
27645c4e0f Fixed number of meshes displayed in Assets page and Assets Selector Page + Fixed Refresh Assets page from Desktop App 2026-07-19 13:47:41 +02:00
Bruno Fargnoli
9c17e86a98 Mesh Thumnail is now generated with python-server -> MCP compatibility 2026-07-19 12:48:58 +02:00
Bruno Fargnoli
cb7ca5ff91 Use the image from external APIs for the thumbnail 2026-07-18 21:18:38 +02:00
Bruno Fargnoli
21a016dc72 Dekstop App: Fixed Wiki 2026-07-17 16:02:36 +02:00
Bruno Fargnoli
4868a97a32 MCP: Retrieve Mesh Generation job result for external APIs 2026-07-17 10:28:42 +02:00
Bruno Fargnoli
3dd664d95c MCP: Separated external APIs for Mesh Generation 2026-07-17 10:17:10 +02:00
Bruno Fargnoli
410aad6f2f MCP: Improved Auto UV and Auto Retopo 2026-07-17 10:05:27 +02:00
Bruno Fargnoli
fd2a362d59 GraphPage: Added Reorganize button 2026-07-16 22:02:40 +02:00
Bruno Fargnoli
8148a1d105 MCP: Can view/download assets 2026-07-16 21:32:06 +02:00
Bruno Fargnoli
83d1bd3248 Fixed MCP in Graph Page for Image Generation 2026-07-16 21:14:09 +02:00
Bruno Fargnoli
ba534b5b42 Start to implement MCP 2026-07-16 17:13:12 +02:00
Bruno Fargnoli
502829e50f Graph Page : save the last position and zoom level 2026-07-16 14:51:18 +02:00
Bruno Fargnoli
a3417f18bb Graph Page -> when multiple images are returned -> correctly connected and vertically aligned 2026-07-16 14:16:49 +02:00
Bruno Fargnoli
e27c46e44b version 1.5.0
Some checks failed
Desktop build / build (macos-latest, dist:mac) (push) Has been cancelled
Desktop build / build (ubuntu-latest, dist:linux) (push) Has been cancelled
Desktop build / build (windows-latest, dist:win) (push) Has been cancelled
2026-07-16 13:30:05 +02:00
Bruno Fargnoli
4afdb64f1d Can drag and drop 3d mesh in Kanban board from the computer 2026-07-16 13:10:24 +02:00
Bruno Fargnoli
9510618348 Removed Export to Blender -> use GLB instead 2026-07-15 21:03:57 +02:00
Bruno Fargnoli
6a1fd7cb5b Fixed FBX Exporter 2026-07-15 20:55:44 +02:00
Bruno Fargnoli
f02f436ee3 Can drag and drop a mesh directly in Graph page 2026-07-15 18:35:52 +02:00
Bruno Fargnoli
07fb113143 Graph Page: Can import a mesh from the computer 2026-07-15 18:29:25 +02:00
Bruno Fargnoli
2537913cba Added Rigging column in Kanban board 2026-07-15 18:20:47 +02:00
Bruno Fargnoli
e6a82adb94 Updated wiki about Auto UV and Auto Retopo 2026-07-15 17:53:55 +02:00
Bruno Fargnoli
670d8d59f8 Added missing documentation in the wiki 2026-07-15 17:44:56 +02:00
Bruno Fargnoli
3398851f8d Mesh Previewer: Can export to Blender, Unity, Unreal Engine in FBX 2026-07-15 17:28:08 +02:00
Bruno Fargnoli
8355e6b319 Updated upload-artifacts to v5 2026-07-15 12:08:44 +02:00
Bruno Fargnoli
aa88ea4e5f version 1.4.0
Some checks failed
Desktop build / build (macos-latest, dist:mac) (push) Has been cancelled
Desktop build / build (ubuntu-latest, dist:linux) (push) Has been cancelled
Desktop build / build (windows-latest, dist:win) (push) Has been cancelled
2026-07-15 12:01:57 +02:00
Bruno Fargnoli
ffd318738f Fixed Electron config 2026-07-15 11:46:42 +02:00
Bruno Fargnoli
cc90575717 Can search. select and save animations with the mesh 2026-07-15 11:38:55 +02:00
Bruno Fargnoli
12a6d81e2e Improved Bone Mapping modal 2026-07-15 11:11:04 +02:00
Bruno Fargnoli
e427092a4d Improved Bone Mapping modal 2026-07-15 10:55:42 +02:00
Bruno Fargnoli
22b8fce11e Improved Animation Retargeting for Human 2026-07-14 22:07:30 +02:00
Bruno Fargnoli
bfe4865a99 Added animations from mesh2motion 2026-07-14 18:12:36 +02:00
Bruno Fargnoli
7ab9752465 Added Skeleton panel 2026-07-14 17:16:40 +02:00
Bruno Fargnoli
8f556d9f11 Remove unused file 2026-07-14 17:00:41 +02:00
Bruno Fargnoli
22d41aca82 Can start/stop the python servers from the Settings 2026-07-14 17:00:04 +02:00
Bruno Fargnoli
f7b331834e Added "Keep model loaded in memory" for Auto Rig 2026-07-14 15:34:44 +02:00
Bruno Fargnoli
1934f7dbd9 Fixed python executable not closing 2026-07-14 14:23:00 +02:00
Bruno Fargnoli
1d7f3dee6d Fixed Desktop App Installer with Auto Rig 2026-07-14 12:24:41 +02:00
Bruno Fargnoli
0ffe63a410 Fixed Desktop App Setup + Added Auto Rig in Mesh Editor using Skintokens 2026-07-14 10:24:12 +02:00
Bruno Fargnoli
f1c5d12b15 Fixed Desktop App Builder config 2026-07-10 12:11:05 +02:00
421 changed files with 30278 additions and 859 deletions

11
.gitattributes vendored Normal file
View file

@ -0,0 +1,11 @@
# Default: let Git normalize text files, auto-detecting on commit.
* text=auto
# Shell scripts MUST use LF — CRLF breaks the shebang on Linux/macOS
# ("bad interpreter: /usr/bin/env bash^M"). core.autocrlf=true would otherwise
# convert them on checkout.
*.sh text eol=lf
# Windows batch files need CRLF.
*.bat text eol=crlf
*.cmd text eol=crlf

View file

@ -32,7 +32,7 @@ jobs:
- name: Set up Node
uses: actions/setup-node@v5
with:
node-version: 22
node-version: 24
cache: npm
- name: Install dependencies
@ -54,7 +54,7 @@ jobs:
# APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
- name: Upload installers
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: 3dgenstudio-${{ matrix.os }}
path: |

23
.gitignore vendored
View file

@ -7,8 +7,12 @@ dist/
# Electron packaged installers
release/
# Local database and assets (Portable Data)
data/
# Local database and assets (Portable Data).
# Leading slash ANCHORS this to the repo root. Unanchored, `data/` matches a
# directory named "data" at ANY depth — which silently excluded the whole
# thirdparty/skintokens/src/data package from the repo, so a fresh clone could
# not import rig.py at all ("No module named 'src.data'").
/data/
# Wiki author mode — presence of this file unlocks editing the Wiki.
# Kept local (never synced) so the published docs are read-only for end users.
@ -27,4 +31,17 @@ Thumbs.db
dev.log
python-server.log
.claude/
.claude/
# Python
__pycache__/
.venv/
# SkinTokens rigging service — generated / downloaded artifacts (never commit)
thirdparty/skintokens/.venv/
thirdparty/skintokens/rig-server.log
thirdparty/skintokens/experiments/
thirdparty/skintokens/models/
thirdparty/skintokens/tmp_ckpt/
thirdparty/skintokens/tmp_gradio/
thirdparty/skintokens/results/

View file

@ -19,6 +19,12 @@
| Date | Description |
| --- | --- |
| **2026-07-28** | Fixed Desktop App on Linux<br>ComfyUI: Added Enums<br>Wireframe mode in Mesh Previewer |
| **2026-07-27** | ComfyUI: Custom models folder<br>Mesh Export: Save last output folder<br>DB: Fixed assets linked to a project<br>Kanban: Can add more meshes and images from any column<br>Desktop App: Fixed Graph page slowness |
| **2026-07-23** | Added Brainstorming Boards |
| **2026-07-20** | MCP Server<br>Graph Page: Added Reorganize button<br>Graph Page: Save the last position and zoom level<br>Graph Page: Simplified Image Node Actions<br>Desktop App: Fixed Wiki<br>Desktop App: Auto-start python services in Settings<br>3D Mesh: Thumbnail is now generated by mesh-tools (python) |
| **2026-07-16** | Mesh Preview: FBX Export (Unity, Unreal Engine)<br>Graph Page: Can import a mesh directly from the computer<br>Kanban board: Added Rigging column |
| **2026-07-15** | MeshEditor: Auto Rig with Skintokens<br>Fixed Desktop App Setup |
| **2026-07-10** | Desktop App Installer<br>Speed up Auto Retopo<br>Added Clean Non-Manifold Edges in Auto Retopo |
| **2026-07-08** | Added Hitem3D API v1 |
| **2026-07-07** | Fixed slowness when queuing multiple ComfyUI workflows<br>SetupWizard: Added Gen Mesh with Hy2.0<br>MeshEditor - Projection: Fixed Blend overlap seams with original texture |
@ -112,6 +118,9 @@ Each stage feeds the next. Use **ComfyUI** workflows or external APIs at any ste
4. **Painting:** Paint directly on your mesh using brushes/images.
5. **Displace:** Use a brush to displace the vertices with tessellation.
6. **Projection:** With ComfyUI, project views on the mesh to get higher texture quality.
7. **Auto UV:** Automatically unwrap your mesh to generate clean UV coordinates.
8. **Auto Retopo:** Automatically retopologize your mesh for a cleaner, optimized topology (with non-manifold edge cleanup).
9. **Auto Rig:** Automatically generate a skeleton and skin weights for your mesh using AI.
---
@ -203,7 +212,17 @@ Open the application and configure your services in the settings area:
## Documentation
You will find some documentation here: https://github.com/visualbruno/3DGenStudio/tree/main/docs
A complete Wiki is included with the application.
---
## 🙏 Acknowledgments
3D Gen Studio builds on the great work of the open-source community. Special thanks to:
- [**SkinTokens**](https://github.com/VAST-AI-Research/SkinTokens) — used in **Auto Rig** for AI-powered skeleton generation and skinning.
- [**mesh2motion-app**](https://github.com/Mesh2Motion/mesh2motion-app) — used in **Auto Rig** for skeleton/animation reference.
- [**excalidraw**](https://github.com/excalidraw/excalidraw) — used for Brainstorming Boards.
---

159
docs/mcp.md Normal file
View file

@ -0,0 +1,159 @@
# 3D Gen Studio — MCP Server
3D Gen Studio ships an [MCP](https://modelcontextprotocol.io) (Model Context Protocol) server so any AI — Claude Desktop/Code, ChatGPT, local LLM stacks — can automate the app: create projects, build node graphs, run ComfyUI workflows, generate images and meshes, run mesh tools (auto UV, retopo, repair, rig, optimize), and export/import projects.
## Endpoint
The MCP server is part of the app backend. Start the app (dev: `npm run dev`, or launch the desktop app) and the endpoint is live at:
```
http://localhost:3001/mcp (Streamable HTTP, stateless)
```
No extra process is needed — it ships with the backend in both dev and the packaged desktop app.
### Security
- **Local by default** — without a token, only clients on the same machine may connect.
- **Remote access** — set a bearer token in settings (`mcp.token`); remote clients must send `Authorization: Bearer <token>`.
- **Disable** — set `mcp.enabled` to `false` in settings; the endpoint then returns 404.
Settings live in the app database and can be changed via `POST /api/settings` with `{"mcp": {"enabled": true, "token": "..."}}` (or the Settings UI once exposed there).
## Client setup
### Claude Code
```sh
claude mcp add --transport http 3d-gen-studio http://localhost:3001/mcp
```
### Claude Desktop
Add a custom connector (Settings → Connectors) with URL `http://localhost:3001/mcp`, or use the stdio bridge in `claude_desktop_config.json`:
```json
{
"mcpServers": {
"3d-gen-studio": {
"command": "node",
"args": ["C:/Git/3DGenStudio/mcp/stdio.js"]
}
}
}
```
The stdio bridge requires the app to be running; it talks to `http://127.0.0.1:3001` (override with the `GENSTUDIO_URL` env var).
Alternatively, without a checkout: `npx mcp-remote http://localhost:3001/mcp` as the command.
### VS Code (GitHub Copilot)
Requires VS Code 1.102+ with the GitHub Copilot and GitHub Copilot Chat extensions; MCP tools are used from Copilot **Agent mode**. Fastest path: Command Palette → **MCP: Add Server…** → **HTTP** → `http://localhost:3001/mcp` → name it `3d-gen-studio`.
Or add a workspace `.vscode/mcp.json` (VS Code uses the `servers` key, not `mcpServers`):
```json
{
"servers": {
"3d-gen-studio": {
"type": "http",
"url": "http://localhost:3001/mcp"
}
}
}
```
Start it via the CodeLens in that file (or the MCP view), then open Copilot Chat, switch to **Agent** mode, and select the 3D Gen Studio tools in the tools (🔧) picker. For a token-protected/remote endpoint, add a header and prompt for the token:
```json
{
"servers": {
"3d-gen-studio": {
"type": "http",
"url": "http://localhost:3001/mcp",
"headers": { "Authorization": "Bearer ${input:genstudio-token}" }
}
},
"inputs": [
{ "id": "genstudio-token", "type": "promptString", "description": "3D Gen Studio MCP token", "password": true }
]
}
```
A `stdio` server (`"type": "stdio"`, `"command": "node"`, `"args": ["C:/Git/3DGenStudio/mcp/stdio.js"]`) also works and requires the app to be running.
### ChatGPT (developer mode) / other clients
Any client that supports Streamable HTTP MCP servers can connect to `http://localhost:3001/mcp` (remote clients need the bearer token, see Security).
### MCP Inspector (debugging)
```sh
npx @modelcontextprotocol/inspector
```
Connect with transport "Streamable HTTP" to `http://localhost:3001/mcp`.
## Tools
| Group | Tools |
|---|---|
| Projects | `list_projects`, `get_project`, `create_project`, `update_project`, `delete_project`, `export_project`, `import_project` |
| Kanban cards | `list_cards`, `move_card`, `delete_card`, `list_card_attributes`, `create_card_attribute`, `update_card_attribute`, `delete_card_attribute` |
| Graph | `get_graph`, `create_node`, `update_node`, `move_node`, `delete_node`, `connect_nodes`, `disconnect_nodes` |
| ComfyUI workflows | `list_workflows`, `inspect_workflow`, `import_workflow`, `update_workflow`, `run_workflow`, `get_run_status` |
| AI actions | `generate_image`, `edit_image`, `generate_mesh`, `generate_mesh_tencent`, `generate_mesh_tripo`, `generate_mesh_hitem`, `get_mesh_result`, `edit_mesh`, `texture_mesh`, `rig_mesh_api` |
| Mesh tools | `auto_uv_mesh`, `auto_retopo_mesh` (fully-typed parameters), `run_mesh_tool` (auto_uv / auto_retopo / repair / auto_rig / optimize / convert_fbx), `export_mesh` |
| Assets | `list_assets`, `list_library_assets`, `view_asset`, `download_asset`, `upload_asset`, `link_asset`, `delete_asset` |
| System | `get_settings` (secrets redacted), `get_system_stats` |
### Displaying results on graph nodes
In graph projects, pass `nodeId` to `run_workflow`, `generate_image`, `edit_image`, or `generate_mesh` to display the results on that node — the first result becomes the node's asset, and additional results become new nodes stacked below it (wired to the same inputs). Without `nodeId` the generated assets are saved to the project but no node displays them.
`run_workflow` saves its output **under the source it was derived from, automatically** — you normally never set `parentAssetId`. The server matches each output to a resolved image/mesh input of the same type (whether that input was wired from the target node in a graph project or passed in `inputs` — so this works the same in **kanban** projects, which have no node wiring): an image output becomes an edit of that source image, a mesh output a version of that source mesh (matching the graph UI). So a re-texture (image + mesh in → mesh out) becomes a version of the input mesh, and a background-removal (image in → image out) an edit of the input image, with nothing extra to pass. Because the server knows the true output type (from the produced file), this holds even when the workflow's declared output type is missing or wrong. Set `parentAssetId` only to override the inferred parent; a parent whose type doesn't match the output type is ignored and a new root asset is created. (`edit_image` likewise saves an edit of its `imageSource`, and `run_mesh_tool` a version of its `assetId`.)
The target node's connected input assets also **auto-fill the workflow's image/mesh parameters**, matched by type (each connected asset used once). A node wired to an image and a mesh feeds a workflow that needs a Source Image + a mesh input without any manual mapping — so for a wired node you should **not** pass `inputs` for file (image/mesh/video) parameters and never need to guess their parameter ids. Set an `inputs` entry for a file parameter only to override a wired input or when nothing is connected; use `inputs` otherwise just for string/number/boolean parameters. Explicit `inputs`/`fileInputs` always take precedence over an auto-filled value.
When you *do* pass an image/mesh parameter in `inputs` (e.g. in a kanban project, which has no wiring), the value is simply the asset's **numeric id** — nothing else. The same plain id works for a root asset, an **edit**, or a **version**: a background-removed image is an edit, so pass that edit's own `id` (from the `children`/`edits` tree in `list_assets`). Do **not** pass a file path or filename, and do **not** pass a `{assetId, editId}` object — a bare id is always correct.
**Connect the input nodes _before_ you run.** `run_workflow`, `edit_image`, and `generate_mesh` read a node's connected input at the moment they execute — the input feeds the workflow/API and determines whether the result is saved as an edit/version. So the correct order is always: (1) `create_node` for the target, (2) `connect_nodes` to wire its input asset(s), then (3) run the workflow or API on that node. Running first and connecting afterwards is wrong: the run sees no input, so it can't use the source image/mesh and saves a stray new root asset instead of an edit/version — and the late connection does **not** re-run or re-parent it. If you ran in the wrong order, delete the stray result, connect the inputs, and run again.
### Parameter-heavy mesh tools
Auto UV and Auto Retopo have many tuning parameters (14 and 20 respectively) that materially change the output. Use the dedicated `auto_uv_mesh` and `auto_retopo_mesh` tools rather than `run_mesh_tool` for these: each declares every parameter in its schema with type, range, default, and description (mirroring the Python service's models), so a client can set exactly what it needs and see the valid bounds. Any subset of options may be set; unset keys fall back to the documented default. For Auto Retopo, the `shell_*` options apply only when `watertight` is `true`. `run_mesh_tool` still accepts `auto_uv`/`auto_retopo` (options ride along as a free-form object) for backward compatibility.
### External mesh-generation providers
Tencent Hunyuan3D, Tripo AI, and Hitem3D each take a different, parameter-heavy option set. Use the dedicated `generate_mesh_tencent`, `generate_mesh_tripo`, and `generate_mesh_hitem` tools: each hardwires its provider and declares every parameter in its `options` schema with type, enum/range, and default (mirroring the backend 1:1), so a client can set exactly what it needs. Provider notes: Tencent `region` is required and `LowPoly` needs model `3.0`; Tripo's `P1` model ignores several options and `generateParts` is incompatible with `texture`/`pbr`/`quad`; Hitem3D requires an `imageSource`. Tencent and Tripo accept either a `prompt` (text-to-3D) or an `imageSource` (image-to-3D). The generic `generate_mesh` still accepts these providers with a free-form `options` object for backward compatibility.
These provider jobs are asynchronous. Unlike the app UI (where you click **Get Result** to poll), the MCP tools poll for you automatically: `generate_mesh*` submits the job and then polls the provider until the mesh is ready, streaming progress, and returns the saved assets — the AI just awaits the call and gets `{status:"completed", assets}`. The mesh is only saved once a poll sees completion, so if a job outlives `timeoutSeconds` (default 1200s) the tool returns `{status:"running", provider, taskId/jobId, region}`; pass those ids to **`get_mesh_result`** to finish and save the job (safe to call repeatedly). Do not re-run generation on timeout — that starts a new job.
Image generation (`generate_image`) is prompt-only by design: OpenAI/Google image parameters (size, quality, aspect ratio) are fixed in each provider's payload template in Settings, not passed per request, so there is nothing extra to set over MCP.
### Long-running operations
`run_workflow`, `generate_mesh`, and `run_mesh_tool` block until the result is ready and stream MCP progress notifications. If a run outlives the tool's `timeoutSeconds`, it keeps running in the background and the tool returns a `promptId`/job info to poll (`get_run_status` for ComfyUI runs; `list_assets`/`list_cards` otherwise).
### Files and assets
- `view_asset` returns the **actual image** as MCP image content, so the AI can visually inspect generated images (for meshes it returns the thumbnail preview when one exists). Inline viewing is capped at ~3.5 MB per image.
- `download_asset` writes any asset file (image/mesh/workflow) to an absolute folder on the machine running the app.
- Asset listings and results otherwise carry direct download URLs (`http://localhost:3001/assets/...`); local files are passed into tools by absolute path (`upload_asset`, `import_workflow filePath`, `run_workflow fileInputs`), and exports write to absolute folders.
## Requirements per capability
| Capability | Needs |
|---|---|
| Projects / cards / graph / assets / export / import | just the app running |
| `run_workflow`, ComfyUI-based edits | ComfyUI running (URL in Settings, default `127.0.0.1:8188`) |
| `generate_image`, `edit_image`, `generate_mesh`, `generate_mesh_tencent`, `generate_mesh_tripo`, `generate_mesh_hitem`, `edit_mesh`, `texture_mesh`, `rig_mesh_api` | provider API keys in Settings |
| `auto_uv_mesh`, `auto_retopo_mesh`, `run_mesh_tool` auto_uv / auto_retopo / repair / convert_fbx | Python mesh-tools service (`:8200`) running — the desktop app can start it from Settings |
| `run_mesh_tool` auto_rig | rigging service (`:8300`) running |
| `run_mesh_tool` optimize | nothing extra (bundled gltfpack) |
## Limitations
- The interactive **Mesh Editor** operations (sculpt, modeling, boolean, painting, projection, texture bake) and **Image Editor** pixel operations (crop, filters, shadow remover) run in the browser (WebGL/canvas) and are not exposed over MCP. AI-driven alternatives: ComfyUI workflows (`run_workflow`), prompt-based edits (`edit_image`), and the mesh-tool services.
- If the app UI is open in a browser while an MCP client mutates data, open Graph/Kanban pages refresh automatically via the app event stream; other pages may need a manual refresh.

View file

@ -13,6 +13,13 @@ appId: com.3dgenstudio.app
productName: 3D Gen Studio
copyright: Copyright © 2026 3D Gen Studio
# Consistent, predictable output filenames across every platform and target.
# ${os} = mac | linux | windows, ${arch} = x64 | arm64, ${ext} = the target's
# file extension. This overrides electron-builder's per-target defaults (which
# were producing version-less .exe names and an "app_…_amd64.deb"). Windows'
# two .exe targets get their own names below so they don't collide.
artifactName: 3DGenStudio-${version}-${os}-${arch}.${ext}
directories:
output: release
buildResources: build
@ -28,18 +35,39 @@ files:
- server.js
- storage.js
- wikiStorage.js
# MCP automation server (POST /mcp on the backend + stdio bridge).
- mcp/**/*
- version.json
- package.json
- dist/**/*
- electron/**/*
# App icon shown on the splash/setup windows (electron/splash.html loads it
# from disk, so it must ship even though dist/ has its own copy).
- public/favicon.png
- comfyui_workflows/**/*
- setup/**/*
- tools/**/*
- wiki/**/*
# Bundled reference animation library (mesh2motion, MIT) served at /resources:
# skinned animation GLBs, mp4 clip previews, and the clean skeleton-only rig
# GLBs used by the Auto Rig → Animations bone-mapping 3D views.
- resources/animations/**/*
- resources/animpreviews/**/*
- resources/rigs/**/*
- python-server/**/*
- "!python-server/.venv/**"
- "!python-server/**/__pycache__/**"
- "!python-server/*.log"
# Rigging service (opt-in). Ship the source; the venv + multi-GB model
# checkpoints are provisioned into the per-user data dir on opt-in, never shipped.
- thirdparty/skintokens/**/*
- "!thirdparty/skintokens/.venv/**"
- "!thirdparty/skintokens/**/__pycache__/**"
- "!thirdparty/skintokens/experiments/**"
- "!thirdparty/skintokens/models/**"
- "!thirdparty/skintokens/tmp_ckpt/**"
- "!thirdparty/skintokens/tmp_gradio/**"
- "!thirdparty/skintokens/*.log"
- "!**/*.map"
win:
@ -51,12 +79,17 @@ win:
arch: [x64]
nsis:
# Distinct from the portable .exe so the two Windows outputs don't collide.
artifactName: 3DGenStudio-Setup-${version}-${arch}.${ext}
oneClick: false
perMachine: false
allowToChangeInstallationDirectory: true
createDesktopShortcut: true
createStartMenuShortcut: true
portable:
artifactName: 3DGenStudio-Portable-${version}-${arch}.${ext}
mac:
# TODO: add build/icon.icns for a branded icon (falls back to default now).
category: public.app-category.graphics-design

View file

@ -4,58 +4,72 @@
// 1. Resolve the app root + a writable data directory.
// 2. Spawn the Node/Express backend (server.js) using Electron's own Node
// runtime (ELECTRON_RUN_AS_NODE) so users don't need Node installed.
// 3. Spawn the Python mesh-tools service (optional; Auto UV / Auto Retopo).
// On first launch it creates a venv and installs requirements — this is
// the "require Python on the machine" model (fastest to ship).
// 4. Wait for the backend to answer, then open the window pointing at it.
// 5. Kill both child processes on quit.
//
// The window loads http://localhost:<PORT>, where the backend serves the Vite
// production build (dist/) and the API from the same origin — see server.js.
// 3. FIRST RUN: show a setup window that provisions the Python services with
// uv (Mesh Tools always; Rigging opt-in) and streams live progress. Later
// runs skip straight to the splash — the venvs already exist.
// 4. Launch the Python services (Mesh Tools always; Rigging if it was set up).
// 5. Wait for the backend to answer, then open the app window.
// 6. Kill child processes on quit.
const { app, BrowserWindow, shell, dialog } = require('electron');
const { app, BrowserWindow, shell, dialog, ipcMain } = require('electron');
const path = require('node:path');
const http = require('node:http');
const fs = require('node:fs');
const { spawn } = require('node:child_process');
const { startPythonService } = require('./python.cjs');
const {
isReady,
MESHTOOLS_REQS_TAG,
ensureUv,
setupPythonServer,
setupSkintokens,
startPythonServer,
startSkintokens,
} = require('./pysetup.cjs');
// Force a stable, brandable name BEFORE any getPath('userData') call so the
// per-user data folder is ".../3DGenStudio" instead of ".../app" (which came
// from package.json "name"). Applies to both dev and packaged builds.
// Force a stable, brandable name BEFORE any getPath('userData') call.
app.setName('3DGenStudio');
const BACKEND_PORT = Number(process.env.PORT) || 3001;
const BACKEND_ORIGIN = `http://localhost:${BACKEND_PORT}`;
const PYTHON_PORT = Number(process.env.MESHTOOLS_PORT) || 8200;
const RIG_PORT = Number(process.env.RIGTOOLS_PORT) || 8300;
// app.getAppPath() is the project root in dev and resources/app in a packaged
// build (we ship unpacked — asar:false — so relative requires + dist/ resolve
// normally and the backend can serve static files without asar path shims).
const APP_ROOT = app.getAppPath();
const SERVER_JS = path.join(APP_ROOT, 'server.js');
const PYTHON_DIR = path.join(APP_ROOT, 'python-server');
const SKINTOKENS_DIR = path.join(APP_ROOT, 'thirdparty', 'skintokens');
// The backend keys its data/ folder off process.cwd() (see storage.js), so we
// point it at a per-user writable location. The installed app directory is
// read-only on macOS/Linux, so we must not write there.
// Backend keys data/ off process.cwd() (storage.js); point it at a per-user
// writable dir. The venvs also live here — the installed app dir is read-only.
const DATA_ROOT = process.env.GENSTUDIO_DATA_ROOT || app.getPath('userData');
const LOG_DIR = path.join(DATA_ROOT, 'logs');
const PY_VENV = path.join(DATA_ROOT, 'python-venv');
const RIG_VENV = path.join(DATA_ROOT, 'rig-venv');
// Rigging model weights (experiments/, models/) — the installed app dir is
// read-only, so download them here and point rig_server.py at it.
const RIG_DATA = path.join(DATA_ROOT, 'rig-data');
let backendProc = null;
let pythonHandle = null;
let mainWindow = null;
let setupWindow = null;
let shuttingDown = false;
// The two Python services are started ON DEMAND (not at boot) and can be
// stopped from Settings — stopping the rigging service fully releases its GPU
// memory (the CUDA context an in-process unload can't free). `handles[name]`
// holds a running service's { stop() }; `starting[name]` dedupes concurrent
// ensure() calls. The registry is populated after the launchers are defined.
const handles = { meshtools: null, rigging: null };
const starting = { meshtools: null, rigging: null };
let SERVICES = null;
function log(line) {
const stamped = `[main] ${line}`;
console.log(stamped);
try {
fs.mkdirSync(LOG_DIR, { recursive: true });
fs.appendFileSync(path.join(LOG_DIR, 'desktop.log'), stamped + '\n');
} catch {
/* logging must never crash startup */
}
} catch { /* logging must never crash startup */ }
}
function openLogStream(name) {
@ -72,14 +86,32 @@ function startBackend() {
cwd: DATA_ROOT,
env: {
...process.env,
ELECTRON_RUN_AS_NODE: '1', // run server.js as plain Node, not an Electron window
ELECTRON_RUN_AS_NODE: '1',
PORT: String(BACKEND_PORT),
NODE_ENV: 'production',
},
stdio: ['ignore', 'pipe', 'pipe'],
// 4th fd = IPC channel: lets the headless backend ask the main process to
// start a Python service on demand (e.g. to render a mesh thumbnail) —
// something it otherwise can't do (ensureService lives here, not there).
stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
});
proc.stdout.pipe(out);
proc.stderr.pipe(out);
// Backend → main service requests. Reuses the same ensureService the Start
// buttons and on-demand UI path use (start + health wait + dedupe).
proc.on('message', async (msg) => {
if (!msg || msg.type !== 'services:ensure') return;
const { name, requestId } = msg;
let reply = { type: 'services:ensure:result', requestId };
try {
await ensureService(name);
reply.ok = true;
} catch (err) {
reply = { ...reply, ok: false, error: err?.message || String(err) };
}
try { proc.send(reply); } catch { /* backend gone */ }
});
proc.on('exit', (code, signal) => {
log(`Backend exited (code=${code} signal=${signal})`);
if (!shuttingDown) {
@ -93,15 +125,11 @@ function startBackend() {
return proc;
}
// Poll the backend until it answers or we time out.
function waitForBackend(timeoutMs = 60000, intervalMs = 400) {
const deadline = Date.now() + timeoutMs;
return new Promise((resolve, reject) => {
const tick = () => {
const req = http.get(`${BACKEND_ORIGIN}/`, (res) => {
res.resume();
resolve();
});
const req = http.get(`${BACKEND_ORIGIN}/`, (res) => { res.resume(); resolve(); });
req.on('error', () => {
if (Date.now() > deadline) reject(new Error('Backend did not start in time'));
else setTimeout(tick, intervalMs);
@ -112,74 +140,269 @@ function waitForBackend(timeoutMs = 60000, intervalMs = 400) {
});
}
// Fetch the app settings from the backend over HTTP (the backend owns the DB).
// Resolves null on any error — callers treat that as "no auto-start".
function fetchSettings(timeoutMs = 4000) {
return new Promise((resolve) => {
const req = http.get(`${BACKEND_ORIGIN}/api/settings`, (res) => {
if (res.statusCode !== 200) { res.resume(); return resolve(null); }
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => { body += chunk; });
res.on('end', () => { try { resolve(JSON.parse(body)); } catch { resolve(null); } });
});
req.on('error', () => resolve(null));
req.setTimeout(timeoutMs, () => req.destroy());
});
}
// Start the services the user opted into auto-starting (Settings → Mesh Tools /
// Auto Rig). Non-blocking and best-effort: failures are logged, never fatal, and
// never delay the window. Setting key `rigtools` maps to service `rigging`.
async function autoStartServices() {
const settings = await fetchSettings();
const apis = settings?.apis || {};
const wanted = [
apis.meshtools?.autoStart ? 'meshtools' : null,
apis.rigtools?.autoStart ? 'rigging' : null,
].filter(Boolean);
for (const name of wanted) {
log(`Auto-starting ${name} service (enabled in Settings)`);
ensureService(name).catch((err) => log(`Auto-start of ${name} failed: ${err?.message || err}`));
}
}
// --- On-demand Python service management ------------------------------------
function serviceRegistry() {
return {
meshtools: {
// reqsTag: a requirements.txt bump flips this service back to
// "not installed" until setup re-runs (incrementally) and re-tags it.
label: 'Mesh Tools', venv: PY_VENV, port: PYTHON_PORT, reqsTag: MESHTOOLS_REQS_TAG,
start: () => startPythonServer({
serviceDir: PYTHON_DIR, venvDir: PY_VENV, port: PYTHON_PORT,
logStream: openLogStream('python.log'), log,
}),
},
rigging: {
label: 'Rigging', venv: RIG_VENV, port: RIG_PORT,
start: () => startSkintokens({
serviceDir: SKINTOKENS_DIR, venvDir: RIG_VENV, dataDir: RIG_DATA, port: RIG_PORT,
logStream: openLogStream('rig.log'), log,
}),
},
};
}
// One /health probe → boolean.
function isHealthy(port) {
return new Promise((resolve) => {
const req = http.get({ host: '127.0.0.1', port, path: '/health', timeout: 2000 }, (res) => {
res.resume();
resolve(res.statusCode === 200);
});
req.on('error', () => resolve(false));
req.on('timeout', () => { req.destroy(); resolve(false); });
});
}
// Poll /health until healthy or timeout. Rigging can take a while (heavy imports
// + model), hence the generous default.
function waitForHealth(port, timeoutMs = 180000, intervalMs = 600) {
const deadline = Date.now() + timeoutMs;
return new Promise((resolve, reject) => {
const tick = async () => {
if (await isHealthy(port)) return resolve();
if (Date.now() > deadline) return reject(new Error('service did not become ready in time'));
setTimeout(tick, intervalMs);
};
tick();
});
}
function stopService(name) {
const h = handles[name];
handles[name] = null;
starting[name] = null;
if (h && typeof h.stop === 'function') {
log(`Stopping ${name} service`);
try { h.stop(); } catch { /* ignore */ }
}
}
// Start the service if needed and wait until it answers /health. Concurrent
// callers share one in-flight start. Recovers a crashed service (handle present
// but not answering) by restarting it.
function ensureService(name) {
const svc = SERVICES[name];
if (!svc) return Promise.reject(new Error(`Unknown service: ${name}`));
if (!isReady(svc.venv, svc.reqsTag)) {
return Promise.reject(new Error(`${svc.label} is not installed yet. Install it in Settings.`));
}
if (starting[name]) return starting[name];
const p = (async () => {
if (handles[name]) {
if (await isHealthy(svc.port)) return;
stopService(name); // crashed → restart
}
log(`Starting ${name} service on demand`);
handles[name] = svc.start();
await waitForHealth(svc.port);
})();
starting[name] = p;
p.catch(() => {}).finally(() => { if (starting[name] === p) starting[name] = null; });
return p;
}
function serviceStatus() {
const out = {};
for (const [name, svc] of Object.entries(SERVICES)) {
out[name] = {
label: svc.label,
installed: isReady(svc.venv, svc.reqsTag),
running: !!handles[name],
starting: !!starting[name],
};
}
return out;
}
function registerServicesIpc() {
ipcMain.handle('services:status', () => serviceStatus());
ipcMain.handle('services:ensure', async (_e, { name } = {}) => {
try { await ensureService(name); return { ok: true, status: serviceStatus() }; }
catch (err) { return { ok: false, error: err.message, status: serviceStatus() }; }
});
ipcMain.handle('services:start', async (_e, { name } = {}) => {
try { await ensureService(name); return { ok: true, status: serviceStatus() }; }
catch (err) { return { ok: false, error: err.message, status: serviceStatus() }; }
});
ipcMain.handle('services:stop', (_e, { name } = {}) => {
stopService(name);
return { ok: true, status: serviceStatus() };
});
}
// Provision the Python services with uv, forwarding progress to `send`. Skips a
// service that is already set up (so the in-app "install rigging" path doesn't
// needlessly reinstall Mesh Tools).
async function doSetup(rigging, send) {
const uv = await ensureUv({ appRoot: APP_ROOT, onLine: (t) => send({ service: 'meshtools', kind: 'log', text: t }) });
if (!uv) throw new Error('Could not find or install uv (the Python toolchain manager).');
if (!isReady(PY_VENV, MESHTOOLS_REQS_TAG)) {
await setupPythonServer({
uv, serviceDir: PYTHON_DIR, venvDir: PY_VENV,
onProgress: (e) => send({ service: 'meshtools', ...e }),
});
} else {
send({ service: 'meshtools', kind: 'done' });
}
if (rigging && !isReady(RIG_VENV)) {
await setupSkintokens({
uv, serviceDir: SKINTOKENS_DIR, venvDir: RIG_VENV, dataDir: RIG_DATA,
onProgress: (e) => send({ service: 'rigging', ...e }),
});
}
}
// Global setup IPC — used by BOTH the first-run window and the running app
// (Settings → Rigging "install" action). Progress streams back to whichever
// window invoked it; on success the newly-provisioned services are launched.
function registerSetupIpc() {
ipcMain.handle('setup:status', () => ({
desktop: true,
meshtools: isReady(PY_VENV, MESHTOOLS_REQS_TAG),
rigging: isReady(RIG_VENV),
}));
ipcMain.handle('setup:run', async (event, opts = {}) => {
const send = (evt) => { try { event.sender.send('setup:progress', evt); } catch { /* window gone */ } };
try {
await doSetup(!!opts.rigging, send);
// Provisioned only — services are started on demand (or from Settings),
// not here, so installing doesn't spin up a process the user isn't using.
log('Setup run complete.');
return { ok: true, status: { meshtools: isReady(PY_VENV, MESHTOOLS_REQS_TAG), rigging: isReady(RIG_VENV) } };
} catch (err) {
log(`Setup run failed: ${err.message}`);
send({ kind: 'error', text: err.message });
return { ok: false, error: err.message };
}
});
}
// First-run setup window. Resolves when the user launches (or closes) it.
function runFirstRunSetup() {
return new Promise((resolve) => {
const win = new BrowserWindow({
width: 640, height: 560, resizable: false, backgroundColor: '#0d0f14',
title: '3D Gen Studio — Setup', show: true, center: true,
webPreferences: {
preload: path.join(__dirname, 'preload.cjs'),
contextIsolation: true, nodeIntegration: false,
},
});
setupWindow = win;
win.setMenuBarVisibility(false);
win.loadFile(path.join(__dirname, 'setup.html'));
let resolved = false;
const done = () => { if (!resolved) { resolved = true; resolve(); } };
ipcMain.once('setup:finish', done);
win.on('closed', done);
});
}
function createWindow() {
mainWindow = new BrowserWindow({
width: 1600,
height: 1000,
minWidth: 1024,
minHeight: 700,
backgroundColor: '#111318',
show: false,
title: '3D Gen Studio',
width: 1600, height: 1000, minWidth: 1024, minHeight: 700,
backgroundColor: '#111318', show: false, title: '3D Gen Studio',
webPreferences: {
preload: path.join(__dirname, 'preload.cjs'),
contextIsolation: true,
nodeIntegration: false,
contextIsolation: true, nodeIntegration: false,
},
});
mainWindow.once('ready-to-show', () => mainWindow.show());
mainWindow.loadURL(BACKEND_ORIGIN);
// Open external links (docs, Discord, cloud API dashboards) in the OS browser.
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
if (!url.startsWith(BACKEND_ORIGIN)) {
shell.openExternal(url);
return { action: 'deny' };
}
if (!url.startsWith(BACKEND_ORIGIN)) { shell.openExternal(url); return { action: 'deny' }; }
return { action: 'allow' };
});
mainWindow.on('closed', () => {
mainWindow = null;
});
mainWindow.on('closed', () => { mainWindow = null; });
}
function loadingWindow() {
const win = new BrowserWindow({
width: 520,
height: 320,
frame: false,
resizable: false,
transparent: true,
backgroundColor: '#00000000',
show: true,
center: true,
title: '3D Gen Studio',
// Edit electron/splash.html to change the splash design.
width: 520, height: 320, frame: false, resizable: false, transparent: true,
backgroundColor: '#00000000', show: true, center: true, title: '3D Gen Studio',
});
win.loadFile(path.join(__dirname, 'splash.html'));
return win;
}
async function boot() {
const splash = loadingWindow();
fs.mkdirSync(DATA_ROOT, { recursive: true });
SERVICES = serviceRegistry();
registerSetupIpc();
registerServicesIpc();
backendProc = startBackend();
// Python is optional — Auto UV/Retopo only. Never block or fail the app on it.
try {
pythonHandle = startPythonService({
pythonDir: PYTHON_DIR,
dataRoot: DATA_ROOT,
port: PYTHON_PORT,
logStream: openLogStream('python.log'),
log,
});
} catch (err) {
log(`Python service failed to start (non-fatal): ${err.message}`);
// First run OR a broken/absent Mesh Tools venv → guided setup window with
// progress (isReady probes the venv, so a legacy venv whose system Python was
// removed is detected and rebuilt). Otherwise → fast path (splash).
let splash = null;
if (!isReady(PY_VENV, MESHTOOLS_REQS_TAG)) {
await runFirstRunSetup();
} else {
splash = loadingWindow();
}
// Python services are NOT started here — they start on demand when the user
// runs Auto UV/Retopo (Mesh Tools) or Auto Rig (Rigging), or from Settings.
try {
await waitForBackend();
log('Backend is up.');
@ -194,29 +417,35 @@ async function boot() {
}
createWindow();
if (!splash.isDestroyed()) splash.close();
if (splash && !splash.isDestroyed()) splash.close();
if (setupWindow && !setupWindow.isDestroyed()) setupWindow.close();
// Fire the opt-in service auto-starts AFTER the window is up so they never
// delay launch (fire-and-forget — each service reports its own readiness).
autoStartServices();
}
let didShutdown = false;
function shutdown() {
if (didShutdown) return;
didShutdown = true;
shuttingDown = true;
if (pythonHandle && typeof pythonHandle.stop === 'function') {
try { pythonHandle.stop(); } catch { /* ignore */ }
}
if (backendProc && !backendProc.killed) {
try { backendProc.kill(); } catch { /* ignore */ }
// Kill each running service's whole process tree (the rigging service spawns
// a bpy_server child + cold worker that a plain kill would orphan).
for (const name of Object.keys(handles)) {
const h = handles[name];
if (h && typeof h.stop === 'function') { try { h.stop(); } catch { /* ignore */ } }
}
// Backend is a lone Node process (no long-lived children) → a plain kill is fine.
if (backendProc && !backendProc.killed) { try { backendProc.kill(); } catch { /* ignore */ } }
}
// Single-instance: focus the existing window instead of launching a 2nd copy
// (which would fight over ports 3001/8200).
if (!app.requestSingleInstanceLock()) {
app.quit();
} else {
app.on('second-instance', () => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
const win = mainWindow || setupWindow;
if (win) { if (win.isMinimized()) win.restore(); win.focus(); }
});
app.whenReady().then(boot);

View file

@ -1,11 +1,41 @@
// Minimal preload. The UI is a normal same-origin web app served by the
// backend, so it needs no privileged bridge today. We expose only a tiny,
// read-only marker so the frontend can detect it's running inside the desktop
// shell (e.g. to hide "open in browser" hints) without granting Node access.
const { contextBridge } = require('electron');
// Preload bridges.
// - genStudioDesktop: read-only marker so the web UI can tell it runs in the
// desktop shell.
// - genStudioSetup: used ONLY by the first-run setup window (setup.html) to
// drive the Python provisioning and stream progress. Harmless elsewhere.
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('genStudioDesktop', {
isDesktop: true,
platform: process.platform,
version: process.env.npm_package_version || null,
});
// Start/stop the on-demand Python services (Mesh Tools, Rigging). Used by the
// mesh-editor tool handlers (ensure the right service is up before a request)
// and by Settings (manual Start/Stop). No-op semantics outside the desktop app,
// where the services are launched externally.
contextBridge.exposeInMainWorld('genStudioServices', {
isDesktop: true,
// Ensure a service is running + healthy before use. name: 'meshtools' | 'rigging'.
ensure: (name) => ipcRenderer.invoke('services:ensure', { name }),
start: (name) => ipcRenderer.invoke('services:start', { name }),
stop: (name) => ipcRenderer.invoke('services:stop', { name }),
status: () => ipcRenderer.invoke('services:status'),
});
contextBridge.exposeInMainWorld('genStudioSetup', {
// Kick off provisioning. opts: { rigging: boolean }. Resolves to { ok, error }.
run: (opts) => ipcRenderer.invoke('setup:run', opts),
// Which services are provisioned: { desktop, meshtools, rigging }.
status: () => ipcRenderer.invoke('setup:status'),
// Subscribe to progress events: { service, kind, phase, pct, text }.
// Returns an unsubscribe function.
onProgress: (cb) => {
const handler = (_e, evt) => cb(evt);
ipcRenderer.on('setup:progress', handler);
return () => ipcRenderer.removeListener('setup:progress', handler);
},
// Tell the main process the user is done and the app can launch (first-run window).
finish: () => ipcRenderer.send('setup:finish'),
});

366
electron/pysetup.cjs Normal file
View file

@ -0,0 +1,366 @@
// uv-based provisioning + launch for the bundled Python services, with progress
// callbacks so the first-run setup window can show live status. Supersedes the
// older python.cjs (system-Python model).
//
// Model: uv provisions a pinned standalone Python (3.13 — see each service's
// .python-version) and a venv in a WRITABLE per-user dir (the installed app
// folder is read-only on macOS/Linux). This mirrors the CLI run.bat/run.sh and
// makes the flash-attn wheel selection for rigging deterministic.
//
// - Mesh Tools (python-server): always provisioned. CPU only.
// - Rigging (skintokens): opt-in. Heavy (torch + flash-attn + model) and needs
// an NVIDIA GPU; the setup reuses the service's own Python helpers
// (select_flash_attn.py / download_wheel.py / download.py). Windows and Linux
// only — flash-attn comes from a prebuilt wheel curated PER PLATFORM
// (flash_attention_windows.txt / flash_attention_linux.txt) because building
// it from source takes ~an hour either way. macOS has no CUDA and is refused.
//
// Everything is async and streams output to an onProgress callback; nothing
// blocks the Electron main-process event loop.
const path = require('node:path');
const fs = require('node:fs');
const os = require('node:os');
const { spawn, spawnSync } = require('node:child_process');
const IS_WIN = process.platform === 'win32';
const IS_MAC = process.platform === 'darwin';
const PYVER = '3.13';
const UV_EXE = IS_WIN ? 'uv.exe' : 'uv';
// Bump whenever python-server/requirements.txt changes so EXISTING installs
// re-run the (incremental) mesh-tools setup and pick up the new deps — the
// marker alone only proves that SOME requirements set was installed once.
// History: 2 = added bpy (GLB->FBX engine export, v1.5.0).
const MESHTOOLS_REQS_TAG = 'meshtools-reqs-2';
function venvPython(venvDir) {
return IS_WIN
? path.join(venvDir, 'Scripts', 'python.exe')
: path.join(venvDir, 'bin', 'python');
}
// Written only after a service's deps fully install, so an interrupted first run
// is detected and re-completed next time instead of launching a broken service.
function depsMarker(venvDir) {
return path.join(venvDir, '.deps-installed');
}
// A venv's python.exe existing on disk is NOT enough: a venv made by
// `python -m venv` depends on its base interpreter, so if that system Python was
// uninstalled/moved the venv python fails to launch ("did not find executable at
// C:\PythonXXX\python.exe", exit 103). Actually PROBE it so a broken venv is
// detected and rebuilt (uv venvs are self-contained and don't have this issue).
function venvUsable(venvDir) {
const vp = venvPython(venvDir);
if (!fs.existsSync(vp)) return false;
try {
const r = spawnSync(vp, ['-c', 'import sys'], { timeout: 20000, stdio: 'ignore' });
return r.status === 0;
} catch {
return false;
}
}
// `requiredTag` (optional) additionally requires the marker to start with that
// tag — pass MESHTOOLS_REQS_TAG for the mesh-tools venv so a requirements bump
// re-triggers its setup. Rigging keeps the tag-less check (its marker must not
// be invalidated by mesh-tools changes: re-setup means multi-GB torch/model
// downloads).
function isReady(venvDir, requiredTag) {
if (!fs.existsSync(depsMarker(venvDir)) || !venvUsable(venvDir)) return false;
if (!requiredTag) return true;
try {
return fs.readFileSync(depsMarker(venvDir), 'utf8').startsWith(requiredTag);
} catch {
return false;
}
}
// Create the venv with uv, rebuilding from scratch if the existing one is broken
// (e.g. a legacy python -m venv whose base interpreter is gone). A healthy venv
// is left untouched. Returns an exit code (0 = ok).
async function ensureVenv({ uv, serviceDir, venvDir, onLine }) {
if (venvUsable(venvDir)) return 0;
if (fs.existsSync(venvDir)) {
if (onLine) onLine(`Existing virtual environment is unusable — rebuilding it.\n`);
try { fs.rmSync(venvDir, { recursive: true, force: true }); } catch { /* ignore */ }
}
const r = await runStream(uv, ['venv', venvDir, '--python', PYVER], { cwd: serviceDir, env: process.env, onLine });
return r.code;
}
// Spawn a command, stream stdout+stderr line-ish chunks to onLine, resolve the
// exit code. Never rejects. `capture` also accumulates stdout for the caller.
function runStream(cmd, args, { cwd, env, onLine } = {}) {
return new Promise((resolve) => {
const emit = (s) => { if (onLine) try { onLine(s); } catch { /* ignore */ } };
emit(`$ ${path.basename(cmd)} ${args.join(' ')}\n`);
let p;
try {
p = spawn(cmd, args, { cwd, env: env || process.env });
} catch (err) {
emit(`spawn error: ${err.message}\n`);
return resolve({ code: -1, stdout: '' });
}
let stdout = '';
p.stdout.on('data', (d) => { const s = d.toString(); stdout += s; emit(s); });
p.stderr.on('data', (d) => emit(d.toString()));
p.on('error', (err) => { emit(`error: ${err.message}\n`); resolve({ code: -1, stdout }); });
p.on('exit', (code) => resolve({ code: code ?? -1, stdout }));
});
}
// Locate uv, or install it. Order: env override -> bundled resource ->
// PATH -> ~/.local/bin -> official installer (into ~/.local/bin). Returns the
// uv path, or null on failure.
async function ensureUv({ appRoot, onLine }) {
const emit = (s) => { if (onLine) try { onLine(s); } catch { /* ignore */ } };
const candidates = [
process.env.GENSTUDIO_UV,
// Bundled via electron-builder extraResources (resources/uv/uv[.exe]).
appRoot && path.join(appRoot, 'resources', 'uv', UV_EXE),
path.join(os.homedir(), '.local', 'bin', UV_EXE),
].filter(Boolean);
for (const c of candidates) {
if (fs.existsSync(c)) return c;
}
// On PATH?
try {
const probe = spawnSync('uv', ['--version'], { encoding: 'utf8' });
if (probe.status === 0) return 'uv';
} catch { /* not on PATH */ }
emit('Installing uv (Python toolchain manager)…\n');
if (IS_WIN) {
await runStream('powershell', [
'-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
'irm https://astral.sh/uv/install.ps1 | iex',
], { onLine });
} else {
await runStream('sh', ['-c', 'curl -LsSf https://astral.sh/uv/install.sh | sh'], { onLine });
}
const installed = path.join(os.homedir(), '.local', 'bin', UV_EXE);
if (fs.existsSync(installed)) return installed;
try {
const probe = spawnSync('uv', ['--version'], { encoding: 'utf8' });
if (probe.status === 0) return 'uv';
} catch { /* still not found */ }
return null;
}
// Run a weighted list of steps, mapping progress to 0..1 and forwarding phase +
// log events via onProgress({ kind, phase, pct, text }). A step returns an exit
// code (0 = ok); a non-zero code from a `required` step aborts with an error.
async function runSteps(steps, onProgress) {
const total = steps.reduce((s, st) => s + (st.weight || 1), 0);
let done = 0;
const emitLog = (text) => onProgress({ kind: 'log', text });
for (const step of steps) {
onProgress({ kind: 'phase', phase: step.label, pct: done / total });
const code = await step.run(emitLog);
if (code !== 0 && step.required !== false) {
throw new Error(`${step.label} failed (exit ${code}).`);
}
done += step.weight || 1;
onProgress({ kind: 'phase', phase: step.label, pct: done / total });
}
}
// ---- Mesh Tools (python-server) -------------------------------------------
async function setupPythonServer({ uv, serviceDir, venvDir, onProgress }) {
const vp = venvPython(venvDir);
const env = process.env;
await runSteps([
{
label: 'Provisioning Python', weight: 2,
run: (log) => runStream(uv, ['python', 'install', PYVER], { cwd: serviceDir, env, onLine: log }).then((r) => r.code),
},
{
label: 'Creating virtual environment', weight: 1,
run: (log) => ensureVenv({ uv, serviceDir, venvDir, onLine: log }),
},
{
label: 'Installing mesh-tools dependencies', weight: 6,
run: (log) => runStream(uv, ['pip', 'install', '--python', vp, '-r', 'requirements.txt'], { cwd: serviceDir, env, onLine: log }).then((r) => r.code),
},
], onProgress);
fs.writeFileSync(depsMarker(venvDir), `${MESHTOOLS_REQS_TAG} ${new Date().toISOString()}`);
onProgress({ kind: 'done' });
}
// ---- Rigging (skintokens) --------------------------------------------------
// `dataDir` is a WRITABLE folder for the downloaded weights (experiments/,
// models/). The packaged app's code dir is read-only, so the model MUST NOT be
// downloaded there; rig_server.py chdirs to this same dir at launch (via
// RIGTOOLS_DATA_DIR) so its relative weight lookups resolve here.
async function setupSkintokens({ uv, serviceDir, venvDir, dataDir, onProgress }) {
// Rigging needs an NVIDIA GPU. Say so up front rather than failing several GB
// into a torch install that has no macOS CUDA build to find.
if (IS_MAC) {
throw new Error('Rigging (Auto Rig) needs an NVIDIA GPU (CUDA), which macOS does not provide. The rest of the app works normally.');
}
const vp = venvPython(venvDir);
const env = process.env;
const modelDir = dataDir || serviceDir;
try { fs.mkdirSync(modelDir, { recursive: true }); } catch { /* ignore */ }
// Provision + base deps first.
await runSteps([
{
label: 'Provisioning Python', weight: 2,
run: (log) => runStream(uv, ['python', 'install', PYVER], { cwd: serviceDir, env, onLine: log }).then((r) => r.code),
},
{
label: 'Creating virtual environment', weight: 1,
run: (log) => ensureVenv({ uv, serviceDir, venvDir, onLine: log }),
},
{
label: 'Installing rigging dependencies', weight: 5,
run: (log) => runStream(uv, ['pip', 'install', '--python', vp, '-r', 'requirements.txt'], { cwd: serviceDir, env, onLine: log }).then((r) => r.code),
},
], (e) => onProgress(scaled(e, 0, 0.4)));
// Select the flash-attn wheel + matching torch for this machine's CUDA.
// select_flash_attn.py picks the table for THIS platform (win_amd64 wheels from
// flash_attention_windows.txt, linux_x86_64 from flash_attention_linux.txt) —
// a wheel from the wrong table is rejected outright by uv at install time.
onProgress({ kind: 'phase', phase: 'Selecting CUDA build', pct: 0.4 });
const sel = await runStream(vp, ['select_flash_attn.py'], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
let wheel = null, torchArgs = null;
for (const line of sel.stdout.split(/\r?\n/)) {
if (line.startsWith('WHEEL=')) wheel = line.slice(6).trim();
else if (line.startsWith('TORCHARGS=')) torchArgs = line.slice(10).trim();
}
// No match -> no rigging. Bail BEFORE the torch download: flash-attn is a hard
// requirement (src/model/tokenrig.py imports it unguarded, so the service cannot
// even load without it), and building it from source takes ~an hour on every
// platform. Pulling multi-GB of torch on the way to a certain failure is waste.
if (!wheel || !torchArgs) {
throw new Error('No prebuilt flash-attn wheel matched this GPU/CUDA (see details). Rigging is unavailable on this machine.');
}
// Install torch with the curated per-wheel command, ABI-matched to the wheel.
onProgress({ kind: 'phase', phase: 'Installing PyTorch', pct: 0.45 });
{
const r = await runStream(uv, ['pip', 'install', '--python', vp, ...torchArgs.split(/\s+/)], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
if (r.code !== 0) throw new Error(`PyTorch install failed (exit ${r.code}).`);
}
// flash-attn — download the prebuilt wheel first (Hugging Face Xet URLs 403 for
// pip and need the HF client; GitHub release assets are plain URLs), install it,
// then PROVE it loads: a wheel built against a different torch ABI installs
// cleanly and only dies at `import flash_attn` with `undefined symbol: _ZN3c10…`.
// Catching that here beats surfacing it after the multi-GB checkpoint download.
onProgress({ kind: 'phase', phase: 'Installing flash-attn', pct: 0.6 });
{
const dl = await runStream(vp, ['download_wheel.py', wheel], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
const localWheel = dl.stdout.split(/\r?\n/).map((s) => s.trim()).filter(Boolean).pop();
if (dl.code !== 0 || !localWheel) throw new Error('flash-attn download failed. Rigging cannot start without it.');
const r = await runStream(uv, ['pip', 'install', '--python', vp, localWheel], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
if (r.code !== 0) throw new Error('flash-attn install failed. Rigging cannot start without it.');
}
onProgress({ kind: 'phase', phase: 'Verifying flash-attn', pct: 0.72 });
{
const probe = 'import torch, flash_attn; print("flash_attn", flash_attn.__version__, "/ torch", torch.__version__)';
const r = await runStream(vp, ['-c', probe], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
if (r.code !== 0) throw new Error('flash-attn installed but will not import — most likely a torch ABI mismatch with the selected wheel (see details). Rigging cannot start.');
}
// Model checkpoints (large; downloaded into the WRITABLE data dir).
onProgress({ kind: 'phase', phase: 'Downloading model checkpoints', pct: 0.8 });
{
const r = await runStream(vp, ['download.py', '--model', '--dir', modelDir], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
if (r.code !== 0) throw new Error(`Model download failed (exit ${r.code}).`);
}
fs.writeFileSync(depsMarker(venvDir), new Date().toISOString());
onProgress({ kind: 'phase', phase: 'Rigging ready', pct: 1 });
onProgress({ kind: 'done' });
}
// Remap a child onProgress event's pct into a [lo, hi] slice of the parent bar.
function scaled(evt, lo, hi) {
if (evt.kind === 'phase' && typeof evt.pct === 'number') {
return { ...evt, pct: lo + (hi - lo) * evt.pct };
}
return evt;
}
// Kill a process AND its descendants. The rigging service is a tree —
// rig_server.py spawns bpy_server.py as a child — and a plain proc.kill() only
// terminates the direct child, orphaning bpy_server (which then keeps holding
// the rig venv). On Windows `taskkill /T` walks the whole PID tree; on POSIX we
// signal the process group.
function killTree(pid) {
if (!pid) return;
try {
if (IS_WIN) {
spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' });
} else {
try { process.kill(-pid, 'SIGTERM'); } catch { process.kill(pid, 'SIGTERM'); }
}
} catch { /* already gone */ }
}
// ---- Launchers -------------------------------------------------------------
function startPythonServer({ serviceDir, venvDir, port, logStream, log }) {
return startService({
name: 'mesh-tools', serviceDir, venvDir, script: 'main.py', logStream, log,
env: { MESHTOOLS_HOST: '127.0.0.1', MESHTOOLS_PORT: String(port) },
});
}
function startSkintokens({ serviceDir, venvDir, dataDir, port, logStream, log }) {
// RIGTOOLS_DATA_DIR makes rig_server.py chdir to the same writable folder the
// weights were downloaded into, so its relative model lookups resolve.
const env = { RIGTOOLS_HOST: '127.0.0.1', RIGTOOLS_PORT: String(port) };
if (dataDir) env.RIGTOOLS_DATA_DIR = dataDir;
return startService({ name: 'rigging', serviceDir, venvDir, script: 'rig_server.py', logStream, log, env });
}
function startService({ name, serviceDir, venvDir, script, env, logStream, log }) {
const write = (s) => { try { logStream && logStream.write(s); } catch { /* ignore */ } };
const vp = venvPython(venvDir);
if (!isReady(venvDir)) {
log && log(`${name} not set up yet — skipping launch.`);
return { stop() {} };
}
let proc = null;
try {
log && log(`Starting ${name} service…`);
proc = spawn(vp, [script], {
cwd: serviceDir,
env: { ...process.env, ...env },
stdio: ['ignore', 'pipe', 'pipe'],
});
proc.stdout.on('data', (d) => write(d.toString()));
proc.stderr.on('data', (d) => write(d.toString()));
proc.on('exit', (code, signal) => { log && log(`${name} service exited (code=${code} signal=${signal})`); });
} catch (err) {
log && log(`${name} service failed to start: ${err.message}`);
}
let stopped = false;
return {
stop() {
if (stopped) return;
stopped = true;
if (proc && proc.pid) killTree(proc.pid);
},
};
}
module.exports = {
PYVER,
MESHTOOLS_REQS_TAG,
venvPython,
isReady,
ensureUv,
setupPythonServer,
setupSkintokens,
startPythonServer,
startSkintokens,
killTree,
};

View file

@ -1,168 +0,0 @@
// Cross-platform launcher for the Python mesh-tools service (Auto UV / Auto
// Retopo). This is the Node/Electron equivalent of python-server/run.bat, made
// to work on Windows, macOS and Linux.
//
// Model: "require Python on the machine" (fastest to ship). On first launch we
// 1. locate a system Python interpreter,
// 2. create a virtualenv in a WRITABLE location (the per-user data dir — the
// installed app folder is read-only on macOS/Linux),
// 3. install requirements.txt (CPU-only base install),
// then run main.py against that venv. Subsequent launches reuse the venv.
//
// IMPORTANT: every step here is ASYNCHRONOUS. venv creation + pip install take
// minutes on first run; doing them synchronously (spawnSync) would block
// Electron's main-process event loop and starve the backend health-poll,
// causing a bogus "backend did not start" error on first launch.
//
// GPU acceleration (CuPy/Warp) is intentionally NOT installed here to keep the
// first-run install portable and fast; it can be layered in later per the
// python-server README (requirements-nvidia.txt + detect_cuda.py).
const path = require('node:path');
const fs = require('node:fs');
const { spawn, spawnSync } = require('node:child_process');
const IS_WIN = process.platform === 'win32';
function venvPython(venvDir) {
return IS_WIN
? path.join(venvDir, 'Scripts', 'python.exe')
: path.join(venvDir, 'bin', 'python');
}
// Written only after requirements install fully succeeds. Gating on this (not
// just python.exe's existence) means a venv left half-built by a crashed or
// interrupted first run is detected and completed on the next launch, instead
// of launching a broken service that fails on missing imports.
function depsMarker(venvDir) {
return path.join(venvDir, '.deps-installed');
}
// Find a usable system Python (3.x). A one-shot `--version` probe is instant,
// so spawnSync is fine here (it does not block for any meaningful time).
function findSystemPython() {
const candidates = IS_WIN ? ['python', 'python3', 'py'] : ['python3', 'python'];
for (const c of candidates) {
try {
const r = spawnSync(c, ['--version'], { encoding: 'utf8' });
if (r.status === 0 && /Python 3\./.test((r.stdout || '') + (r.stderr || ''))) {
return c;
}
} catch {
/* try next */
}
}
return null;
}
// Public entry point. Fully non-blocking: kicks off setup + launch and returns
// immediately with a handle exposing stop().
function startPythonService({ pythonDir, dataRoot, port, logStream, log }) {
const venvDir = path.join(dataRoot, 'python-venv');
let proc = null;
let stopped = false;
const write = (s) => { try { logStream.write(s); } catch { /* ignore */ } };
// Run a command asynchronously, streaming output to the log. Resolves to the
// exit code (0 = success). Never rejects.
const run = (cmd, args) =>
new Promise((resolve) => {
write(`\n$ ${cmd} ${args.join(' ')}\n`);
let p;
try {
p = spawn(cmd, args, { cwd: pythonDir });
} catch (err) {
write(`spawn error: ${err.message}\n`);
return resolve(-1);
}
// {end:false} so a finished child doesn't close the shared log stream.
p.stdout.on('data', (d) => write(d.toString()));
p.stderr.on('data', (d) => write(d.toString()));
p.on('error', (err) => { write(`error: ${err.message}\n`); resolve(-1); });
p.on('exit', (code) => resolve(code));
});
async function ensureVenv() {
// Fully set up already (venv + deps marker) → nothing to do.
if (fs.existsSync(venvPython(venvDir)) && fs.existsSync(depsMarker(venvDir))) {
return true;
}
const py = venvPython(venvDir);
// Create the venv only if it isn't there yet. If a previous run created it
// but crashed before finishing pip install, reuse it and just (re)install.
if (!fs.existsSync(py)) {
const sysPython = findSystemPython();
if (!sysPython) {
log(
'Python 3 not found on PATH — the mesh-tools service (Auto UV/Retopo) ' +
'will be unavailable. Install Python 3.10+ and restart to enable it.'
);
return false;
}
log(`First run: creating Python venv with "${sysPython}" (this can take a few minutes)…`);
fs.mkdirSync(path.dirname(venvDir), { recursive: true });
if ((await run(sysPython, ['-m', 'venv', venvDir])) !== 0) {
log('Failed to create Python venv — see python.log.');
return false;
}
} else {
log('Completing Python setup (installing dependencies)…');
}
await run(py, ['-m', 'pip', 'install', '--upgrade', 'pip']);
const reqs = path.join(pythonDir, 'requirements.txt');
if ((await run(py, ['-m', 'pip', 'install', '-r', reqs])) !== 0) {
log('Failed to install Python requirements — see python.log.');
return false;
}
try { fs.writeFileSync(depsMarker(venvDir), new Date().toISOString()); } catch { /* ignore */ }
log('Python environment ready.');
return true;
}
async function launch() {
try {
if (stopped) return;
const ok = await ensureVenv();
if (stopped || !ok) return;
const py = venvPython(venvDir);
log(`Starting Python mesh-tools service on port ${port}…`);
proc = spawn(py, ['main.py'], {
cwd: pythonDir,
env: {
...process.env,
MESHTOOLS_HOST: '127.0.0.1',
MESHTOOLS_PORT: String(port),
},
stdio: ['ignore', 'pipe', 'pipe'],
});
proc.stdout.on('data', (d) => write(d.toString()));
proc.stderr.on('data', (d) => write(d.toString()));
proc.on('exit', (code, signal) => {
log(`Python service exited (code=${code} signal=${signal})`);
});
} catch (err) {
log(`Python service failed: ${err.message}`);
}
}
// Fire and forget — runs on the microtask queue, never blocks the caller.
launch();
return {
stop() {
stopped = true;
if (proc && !proc.killed) {
try { proc.kill(); } catch { /* ignore */ }
}
},
};
}
module.exports = { startPythonService };

178
electron/setup.html Normal file
View file

@ -0,0 +1,178 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<style>
:root {
--bg: #0d0f14; --card: #141821; --text: #e8eaf0; --muted: #8b91a3;
--accent1: #7c5cff; --accent2: #22d3ee; --ok: #4ade80; --err: #f87171;
--line: rgba(255,255,255,0.08);
}
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { width: 100%; height: 100%; background: var(--bg); color: var(--text); overflow: hidden; }
body {
font-family: "Space Grotesk", "Inter", system-ui, -apple-system, "Segoe UI", sans-serif;
-webkit-user-select: none; user-select: none;
display: flex; flex-direction: column; padding: 26px 30px; gap: 16px;
}
h1 {
font-size: 20px; font-weight: 700;
background: linear-gradient(90deg, #fff, #c9c2ff 60%, #9be9ff);
-webkit-background-clip: text; background-clip: text; color: transparent;
}
.sub { font-size: 12.5px; color: var(--muted); margin-top: -8px; }
.services { display: flex; flex-direction: column; gap: 10px; }
.svc {
border: 1px solid var(--line); border-radius: 12px; padding: 12px 14px;
background: var(--card); display: flex; flex-direction: column; gap: 8px;
}
.svc__head { display: flex; align-items: center; gap: 10px; }
.dot { width: 10px; height: 10px; border-radius: 50%; background: #3a3f4b; flex: none; transition: background .3s; }
.dot.running { background: var(--accent2); box-shadow: 0 0 10px var(--accent2); animation: pulse 1.2s infinite; }
.dot.done { background: var(--ok); box-shadow: 0 0 8px var(--ok); }
.dot.error { background: var(--err); box-shadow: 0 0 8px var(--err); }
@keyframes pulse { 0%,100%{opacity:.5} 50%{opacity:1} }
.svc__name { font-size: 14px; font-weight: 600; }
.svc__tag { font-size: 11px; color: var(--muted); margin-left: auto; }
.svc__phase { font-size: 12px; color: var(--muted); min-height: 15px; }
.bar { height: 6px; border-radius: 4px; background: rgba(255,255,255,0.06); overflow: hidden; }
.bar > i { display: block; height: 100%; width: 0; border-radius: 4px;
background: linear-gradient(90deg, var(--accent1), var(--accent2)); transition: width .3s; }
label.opt { display: flex; align-items: center; gap: 8px; font-size: 12.5px; color: var(--muted); cursor: pointer; }
label.opt input { accent-color: var(--accent1); width: 15px; height: 15px; }
.log {
flex: 1; min-height: 90px; border: 1px solid var(--line); border-radius: 10px;
background: #0a0c11; color: #9aa3b2; font-family: ui-monospace, "Cascadia Code", Consolas, monospace;
font-size: 11px; line-height: 1.45; padding: 10px 12px; overflow-y: auto; white-space: pre-wrap;
display: none;
}
.row { display: flex; align-items: center; gap: 12px; }
.spacer { flex: 1; }
button {
font-family: inherit; font-size: 13px; font-weight: 600; cursor: pointer;
border: 1px solid var(--line); border-radius: 10px; padding: 9px 18px;
background: #1b2130; color: var(--text); transition: filter .2s, opacity .2s;
}
button.primary { border: none; background: linear-gradient(90deg, var(--accent1), var(--accent2)); color: #0b0e14; }
button:hover { filter: brightness(1.12); }
button:disabled { opacity: .45; cursor: default; filter: none; }
.err { color: var(--err); font-size: 12px; min-height: 15px; }
.link { color: var(--accent2); cursor: pointer; font-size: 11.5px; }
</style>
</head>
<body>
<div>
<h1>Set up 3D Gen Studio</h1>
<div class="sub">First launch installs the local Python services. This runs once; later launches are instant.</div>
</div>
<div class="services">
<div class="svc" id="svc-meshtools">
<div class="svc__head">
<span class="dot"></span>
<span class="svc__name">Mesh Tools</span>
<span class="svc__tag">required · Auto UV / Retopo / FBX export (~1 GB)</span>
</div>
<div class="svc__phase">Waiting to start…</div>
<div class="bar"><i></i></div>
</div>
<div class="svc" id="svc-rigging">
<div class="svc__head">
<span class="dot"></span>
<span class="svc__name">Rigging (Auto Rig)</span>
<span class="svc__tag">optional · NVIDIA GPU, large download</span>
</div>
<label class="opt"><input type="checkbox" id="opt-rigging" /> Install the AI rigging service (needs an NVIDIA GPU ≥14 GB with a recent driver — CUDA 12.8+; downloads several GB)</label>
<div class="svc__phase" style="display:none"></div>
<div class="bar" style="display:none"><i></i></div>
</div>
</div>
<div class="err" id="err"></div>
<div class="log" id="log"></div>
<div class="row">
<span class="link" id="toggle-log">Show details</span>
<div class="spacer"></div>
<button id="btn-install" class="primary">Install &amp; continue</button>
<button id="btn-launch" class="primary" style="display:none">Launch 3D Gen Studio</button>
</div>
<script>
const $ = (s) => document.querySelector(s);
const rows = {
meshtools: $('#svc-meshtools'),
rigging: $('#svc-rigging'),
uv: $('#svc-meshtools'), // uv provisioning shows under the first row
};
const logEl = $('#log');
const errEl = $('#err');
// Rigging needs CUDA, so it exists on Windows and Linux only. Hide the option on
// macOS rather than offering an install that cannot succeed. (An unchecked box
// reads as false in runInstall, so nothing else needs to know.)
if ((window.genStudioDesktop && window.genStudioDesktop.platform) === 'darwin') {
$('#svc-rigging').style.display = 'none';
}
function setRow(service, { state, phase, pct }) {
const row = rows[service];
if (!row) return;
const dot = row.querySelector('.dot');
const phaseEl = row.querySelector('.svc__phase');
const bar = row.querySelector('.bar > i');
if (service === 'rigging') { // reveal rigging progress once it starts
row.querySelector('.svc__phase').style.display = '';
row.querySelector('.bar').style.display = '';
}
if (state) { dot.className = 'dot ' + state; }
if (phase != null && phaseEl) phaseEl.textContent = phase;
if (pct != null && bar) bar.style.width = Math.round(pct * 100) + '%';
}
window.genStudioSetup.onProgress((evt) => {
if (evt.kind === 'log') {
logEl.textContent += evt.text;
logEl.scrollTop = logEl.scrollHeight;
return;
}
if (evt.kind === 'phase') {
setRow(evt.service, { state: 'running', phase: evt.phase, pct: evt.pct });
} else if (evt.kind === 'done') {
setRow(evt.service, { state: 'done', phase: 'Done', pct: 1 });
} else if (evt.kind === 'error') {
setRow(evt.service, { state: 'error' });
errEl.textContent = evt.text || 'Setup failed.';
}
});
$('#toggle-log').addEventListener('click', () => {
const show = logEl.style.display === 'none' || !logEl.style.display;
logEl.style.display = show ? 'block' : 'none';
$('#toggle-log').textContent = show ? 'Hide details' : 'Show details';
});
async function runInstall() {
errEl.textContent = '';
const rigging = $('#opt-rigging').checked;
$('#btn-install').disabled = true;
$('#opt-rigging').disabled = true;
setRow('meshtools', { state: 'running', phase: 'Starting…', pct: 0 });
const res = await window.genStudioSetup.run({ rigging });
if (res && res.ok) {
$('#btn-install').style.display = 'none';
$('#btn-launch').style.display = '';
} else {
errEl.textContent = (res && res.error) || 'Setup failed. See details.';
$('#btn-install').disabled = false;
$('#opt-rigging').disabled = false;
$('#btn-install').textContent = 'Retry';
}
}
$('#btn-install').addEventListener('click', runInstall);
$('#btn-launch').addEventListener('click', () => window.genStudioSetup.finish());
</script>
</body>
</html>

View file

@ -52,6 +52,13 @@
box-shadow: 0 0 22px rgba(124,92,255,0.55);
display: flex; align-items: center; justify-content: center;
font-size: 22px;
overflow: hidden;
}
/* App icon fills the orb; if the file is missing the emoji underneath shows. */
.orb img {
position: absolute; inset: 0; width: 100%; height: 100%;
object-fit: cover; border-radius: 50%;
-webkit-user-drag: none;
}
.title {
font-size: 26px; font-weight: 700; letter-spacing: .3px;
@ -68,7 +75,7 @@
<div class="glow"></div>
<div class="mark">
<div class="ring"></div>
<div class="orb">🌌</div>
<div class="orb">🌌<img src="../public/favicon.png" alt="" onerror="this.remove()" /></div>
</div>
<div class="title">3D Gen Studio</div>
<div class="status">Starting local services<span class="dots"></span></div>

204
mcp/client.js Normal file
View file

@ -0,0 +1,204 @@
// Loopback HTTP client for the MCP layer.
//
// Every MCP tool talks to the running 3D Gen Studio backend through its own
// REST API (the exact contract the React frontend uses) instead of importing
// storage.js directly. This keeps SQLite behind a single process and reuses
// the existing route handlers unchanged, so the MCP layer stays a thin shell.
import { Buffer } from 'node:buffer';
export function createApiClient(baseUrl) {
const base = String(baseUrl || 'http://127.0.0.1:3001').replace(/\/+$/, '');
async function parseJsonResponse(res, fallbackMessage) {
if (res.status === 204) return { ok: true };
const data = await res.json().catch(() => ({}));
if (!res.ok) {
throw new Error(data?.error || `${fallbackMessage} (HTTP ${res.status})`);
}
return data;
}
async function apiJson(method, apiPath, { body, query } = {}) {
const url = new URL(`${base}/api${apiPath}`);
for (const [key, value] of Object.entries(query || {})) {
if (value !== undefined && value !== null) url.searchParams.set(key, String(value));
}
const res = await fetch(url, {
method,
headers: body !== undefined ? { 'Content-Type': 'application/json' } : undefined,
body: body !== undefined ? JSON.stringify(body) : undefined
});
return parseJsonResponse(res, `${method} /api${apiPath} failed`);
}
async function apiForm(method, apiPath, formData) {
const res = await fetch(`${base}/api${apiPath}`, { method, body: formData });
return parseJsonResponse(res, `${method} /api${apiPath} failed`);
}
// Parse an SSE byte stream, invoking onData for each `data:` JSON payload.
// Heartbeat comments (`: keep-alive`) and malformed frames are skipped.
async function readSseStream(stream, onData) {
const reader = stream.getReader();
const decoder = new TextDecoder();
let buffer = '';
const handleEvent = raw => {
for (const line of raw.split('\n')) {
if (!line.startsWith('data:')) continue;
try {
onData(JSON.parse(line.slice(5).trim()));
} catch {
// Non-JSON data frame — ignore.
}
}
};
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let sep;
while ((sep = buffer.indexOf('\n\n')) >= 0) {
handleEvent(buffer.slice(0, sep));
buffer = buffer.slice(sep + 2);
}
}
if (buffer.trim()) handleEvent(buffer);
}
// POST multipart to an endpoint that answers with an SSE stream (the mesh
// tool proxies). onProgress receives every `progress` event; resolves with
// the terminal `done` event; throws on an `error` event.
async function apiFormSse(apiPath, formData, onProgress) {
const res = await fetch(`${base}/api${apiPath}`, { method: 'POST', body: formData });
if (!res.ok) {
const data = await res.json().catch(() => ({}));
const detail = data?.detail ? `: ${JSON.stringify(data.detail)}` : '';
throw new Error((data?.error || `POST /api${apiPath} failed (HTTP ${res.status})`) + detail);
}
let doneEvent = null;
let errorEvent = null;
await readSseStream(res.body, evt => {
if (evt?.type === 'progress') onProgress?.(evt);
else if (evt?.type === 'done') doneEvent = evt;
else if (evt?.type === 'error') errorEvent = evt;
});
if (errorEvent) throw new Error(errorEvent.detail || 'The mesh tool reported an error.');
if (!doneEvent) throw new Error('The mesh tool finished without returning a result.');
return doneEvent;
}
// Subscribe to a long-lived SSE endpoint. Events are delivered to onData
// until close() is called or the stream ends (onEnd fires on unexpected end).
function subscribeSse(apiPath, onData, { onEnd } = {}) {
const controller = new AbortController();
(async () => {
const res = await fetch(`${base}/api${apiPath}`, {
headers: { Accept: 'text/event-stream' },
signal: controller.signal
});
if (!res.ok) throw new Error(`SSE /api${apiPath} failed (HTTP ${res.status})`);
await readSseStream(res.body, onData);
throw new Error(`SSE /api${apiPath} ended unexpectedly`);
})().catch(err => {
if (!controller.signal.aborted) onEnd?.(err);
});
return { close: () => controller.abort() };
}
// Public URL for a stored asset file. Asset records carry both `filePath`
// ("data/assets/meshes/x.glb", storage-prefixed) and `filename`
// ("meshes/x.glb", relative to the served assets dir) — accept either.
function assetUrl(filePath) {
const relative = String(filePath || '').replace(/^\/+/, '').replace(/^data\/assets\//, '');
return `${base}/assets/${relative}`;
}
// Download a stored asset file as a Buffer.
async function fetchAssetBuffer(filePath) {
const res = await fetch(assetUrl(filePath));
if (!res.ok) throw new Error(`Failed to read asset file "${filePath}" (HTTP ${res.status})`);
return Buffer.from(await res.arrayBuffer());
}
return { base, apiJson, apiForm, apiFormSse, subscribeSse, assetUrl, fetchAssetBuffer };
}
// ---------------------------------------------------------------------------
// Tool plumbing shared by every tools/*.js module.
export function jsonResult(value) {
return { content: [{ type: 'text', text: JSON.stringify(value ?? null, null, 2) }] };
}
// Wrap a tool implementation: resolve to a JSON text result, surface thrown
// errors as MCP tool errors (isError) instead of protocol-level failures.
export function toolHandler(fn) {
return async (args, extra) => {
try {
return jsonResult(await fn(args ?? {}, extra));
} catch (err) {
return { isError: true, content: [{ type: 'text', text: String(err?.message || err) }] };
}
};
}
// Progress reporter bound to the caller's progressToken (no-op when the client
// didn't request progress). progress/total follow MCP semantics.
export function createProgressReporter(extra) {
const token = extra?._meta?.progressToken;
if (token === undefined || token === null) {
return async () => {};
}
return async (progress, total, message) => {
try {
await extra.sendNotification({
method: 'notifications/progress',
params: {
progressToken: token,
progress,
...(total !== undefined && total !== null ? { total } : {}),
...(message ? { message } : {})
}
});
} catch {
// Client disconnected or transport closed — progress is best-effort.
}
};
}
// Locate an asset anywhere in a project's asset tree (top-level assets plus
// nested edits/versions/children). Throws with a hint when the id is unknown.
export async function findProjectAsset(api, projectId, assetId) {
const assets = await api.apiJson('GET', '/assets', { query: { projectId } });
const flat = [];
const visit = asset => {
if (!asset) return;
flat.push(asset);
for (const key of ['edits', 'versions', 'children']) {
if (Array.isArray(asset[key])) asset[key].forEach(visit);
}
};
(Array.isArray(assets) ? assets : []).forEach(visit);
const asset = flat.find(a => Number(a?.id) === Number(assetId));
if (!asset) throw new Error(`Asset ${assetId} not found in project ${projectId} (use list_assets to find valid ids).`);
if (!asset.filename && !asset.filePath) throw new Error(`Asset ${assetId} has no stored file.`);
return asset;
}
// Attach a public URL to an asset record (and its nested edits/versions when
// present) so MCP clients can download files without base64 round-trips.
export function withAssetUrls(api, asset) {
if (!asset || typeof asset !== 'object') return asset;
const out = { ...asset };
const file = out.filename || out.filePath;
if (file) out.url = api.assetUrl(file);
if (out.thumbnail) out.thumbnailUrl = api.assetUrl(out.thumbnail);
for (const key of ['edits', 'versions', 'children']) {
if (Array.isArray(out[key])) out[key] = out[key].map(item => withAssetUrls(api, item));
}
return out;
}

75
mcp/http.js Normal file
View file

@ -0,0 +1,75 @@
// Streamable-HTTP mount for the MCP server (stateless mode).
//
// Each POST /mcp request gets a fresh McpServer + transport — all real state
// lives in the app's database, so no session bookkeeping is needed, and
// progress notifications still stream on the POST response's SSE leg.
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { buildMcpServer } from './index.js';
const LOOPBACK_ADDRESSES = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1']);
export function mountMcp(app, { baseUrl, getSettings, notifyMutation }) {
const handler = async (req, res) => {
try {
const settings = await getSettings().catch(() => null);
const mcpSettings = settings?.mcp || {};
if (mcpSettings.enabled === false) {
return res.status(404).json({ error: 'MCP server is disabled in Settings' });
}
const token = String(mcpSettings.token || '');
if (token) {
if (req.headers.authorization !== `Bearer ${token}`) {
return res.status(401).json({
jsonrpc: '2.0',
error: { code: -32001, message: 'Unauthorized: invalid or missing bearer token' },
id: null
});
}
} else if (!LOOPBACK_ADDRESSES.has(req.socket.remoteAddress)) {
// Without a token, only local clients may connect (the server binds
// all interfaces). Set settings.mcp.token to allow remote access.
return res.status(403).json({
jsonrpc: '2.0',
error: { code: -32002, message: 'Forbidden: remote access requires a bearer token (settings.mcp.token)' },
id: null
});
}
if (req.method !== 'POST') {
// Stateless mode: no server-initiated GET stream, no DELETE sessions.
res.setHeader('Allow', 'POST');
return res.status(405).json({
jsonrpc: '2.0',
error: { code: -32000, message: 'Method not allowed (stateless MCP endpoint — use POST)' },
id: null
});
}
const server = buildMcpServer({ baseUrl, notifyMutation });
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
res.on('close', () => {
transport.close();
server.close();
});
await server.connect(transport);
// The app's global express.json() already parsed the body — pass it in.
await transport.handleRequest(req, res, req.body);
} catch (err) {
console.error('MCP request failed:', err);
if (!res.headersSent) {
res.status(500).json({
jsonrpc: '2.0',
error: { code: -32603, message: 'Internal server error' },
id: null
});
}
}
};
app.post('/mcp', handler);
app.get('/mcp', handler);
app.delete('/mcp', handler);
}

70
mcp/index.js Normal file
View file

@ -0,0 +1,70 @@
// MCP server for 3D Gen Studio.
//
// Exposes the app's headless capabilities (projects, kanban cards, node graph,
// ComfyUI workflows, AI actions, mesh tools, assets) as MCP tools so any MCP
// client — Claude Desktop/Code, ChatGPT, local LLM stacks — can automate the
// app. Tools call the running backend over loopback HTTP (see client.js).
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createApiClient } from './client.js';
import { registerProjectTools } from './tools/projects.js';
import { registerCardTools } from './tools/cards.js';
import { registerGraphTools } from './tools/graph.js';
import { registerWorkflowTools } from './tools/workflows.js';
import { registerActionTools } from './tools/actions.js';
import { registerMeshToolTools } from './tools/meshTools.js';
import { registerAssetTools } from './tools/assets.js';
import { registerSettingsTools } from './tools/settings.js';
function readAppVersion() {
try {
const packagePath = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
return JSON.parse(fs.readFileSync(packagePath, 'utf8'))?.version || '0.0.0';
} catch {
return '0.0.0';
}
}
const APP_VERSION = readAppVersion();
const SERVER_INSTRUCTIONS = `3D Gen Studio automation server.
Typical flows:
- New pipeline: create_project (preset "graph") -> create_node / connect_nodes to lay out the pipeline -> run_workflow or generate_image / generate_mesh to produce assets.
- IMPORTANT (graph projects): always pass nodeId to run_workflow / generate_image / edit_image / generate_mesh so the results are DISPLAYED on that node. Without nodeId the assets are saved but no node shows them. The first result becomes the node's image/mesh; extra results become new nodes stacked below it.
- IMPORTANT ordering: connect_nodes to wire a node's input asset(s) BEFORE you run_workflow / edit_image / generate_mesh on it. The run reads the node's connected input at execution time — it feeds the workflow/API and decides whether the result is saved as an edit of the connected image / a version of the connected mesh. Running first and connecting afterwards is wrong: the run sees no input, so it uses none and saves a stray new root asset, and the late connection does not re-run or re-parent it. If you got the order wrong, delete the stray result, connect the inputs, then run again.
- ComfyUI: list_workflows for saved workflows and their parameters; import_workflow to add new ones (inspect_workflow first to discover inputs/outputs). run_workflow blocks with progress until the assets are ready. ComfyUI itself must be running (URL in get_settings).
- ComfyUI image/mesh (file) parameters are filled AUTOMATICALLY from the target node's wired inputs (matched by type) — so for a node whose inputs are connected, do NOT pass inputs for file parameters (no need to guess their ids); just connect_nodes then run_workflow with nodeId. Only set a file-parameter input to override a wired input or when nothing is connected. Set inputs only for non-file parameters (string/number/boolean) you want to change.
- When you DO pass an image/mesh (file) parameter in inputs (e.g. in a kanban project with no wiring), the value is just the asset's numeric id — nothing else. The SAME plain id works for a root asset, an edit, or a version (a background-removed image is an edit → pass that edit's own id, found in the children/edits tree from list_assets). Do NOT pass a file path/filename or a {assetId, editId} object; a bare id is correct.
- Parent linkage is AUTOMATIC — do NOT manage parentAssetId yourself. run_workflow saves its output under the source it was derived from (the image/mesh input matching the output type, wired or passed in inputs): an image output becomes an edit of that image, a mesh output a version of that mesh. edit_image already saves an edit of its imageSource, and run_mesh_tool saves a version of its assetId. So a re-texture (image+mesh in, mesh out) versions the input mesh, and a background-removal (image in, image out) edits the input image, with no parentAssetId needed. Only pass parentAssetId to override the inferred parent.
- Mesh processing: run_mesh_tool (auto_uv / auto_retopo / repair / auto_rig / optimize / convert_fbx) works on mesh assets; results save as asset versions.
- Seeing results: use view_asset to LOOK at a generated image (returns the actual image; for meshes it returns the thumbnail when available). Use download_asset to save any asset file to a local folder. Assets also carry direct download URLs in every response.
Note: interactive Mesh Editor sculpting/painting and Image Editor pixel edits are browser-only and not exposed here. If the app UI is open in a browser, it may need a refresh to show changes made through these tools.`;
// Build a fully-registered MCP server instance.
// baseUrl: origin of the running backend (defaults to loopback :3001).
// notifyMutation(projectId): optional hook fired after any mutation so the
// host process can push a refresh signal to open browser UIs.
export function buildMcpServer({ baseUrl, notifyMutation } = {}) {
const api = createApiClient(baseUrl);
const server = new McpServer(
{ name: '3d-gen-studio', version: APP_VERSION },
{ instructions: SERVER_INSTRUCTIONS }
);
const ctx = { api, notifyMutation: typeof notifyMutation === 'function' ? notifyMutation : () => {} };
registerProjectTools(server, ctx);
registerCardTools(server, ctx);
registerGraphTools(server, ctx);
registerWorkflowTools(server, ctx);
registerActionTools(server, ctx);
registerMeshToolTools(server, ctx);
registerAssetTools(server, ctx);
registerSettingsTools(server, ctx);
return server;
}

145
mcp/nodeResults.js Normal file
View file

@ -0,0 +1,145 @@
// Attach generated assets to a graph node, mirroring what GraphPage does after
// a run completes (applyNodeResult + spawnAdditionalResultNodes): the first
// result becomes the node's asset (that's what the node card displays); every
// additional result becomes a new node stacked below, wired to the same
// incoming reference edges so it can be used the same way.
const VERTICAL_STEP = 580; // collapsed node card height (~480px) + gap
const NODE_TYPE_BY_ASSET_TYPE = { image: 'Image', mesh: 'Mesh' };
// Decide where a generated result should land. Graph nodes are filled via
// `nodeId` (→ attachResultsToNode → the node's own asset); kanban cards via
// `cardId`. Clients sometimes pass a graph node id as `cardId`, which the kanban
// path can't attach to a node (and worse, silently creates an orphaned card), so
// promote such an id to a node target here. Returns the resolved target; a node
// target never also carries a kanban cardId.
//
// Safe because graph nodes and kanban cards are unique rows in one `Cards` table:
// an id that matches a graph node IS that node, not a card.
export async function resolveNodeTarget(api, projectId, { nodeId, cardId } = {}) {
if (nodeId !== undefined && nodeId !== null && nodeId !== '') {
return { nodeId: Number(nodeId), cardId: undefined };
}
if (cardId !== undefined && cardId !== null && cardId !== '' && projectId) {
const numeric = Number(cardId);
if (Number.isInteger(numeric)) {
const nodes = await api.apiJson('GET', '/graph/nodes', { query: { projectId } }).catch(() => []);
const isGraphNode = (Array.isArray(nodes) ? nodes : []).some(node => Number(node?.id) === numeric);
if (isGraphNode) {
return { nodeId: numeric, cardId: undefined };
}
}
}
return { nodeId: undefined, cardId };
}
// List the assets feeding a node's inputs: for each incoming edge whose source
// node holds an asset, the asset id + type (ordered by input connector so the
// result is deterministic). Lets a workflow run fill its image/mesh parameters
// from what the node is wired to — mirroring the GraphPage, which binds each
// file parameter to the connected input of the matching type — and pick the
// parent asset (image edit / mesh version) by matching the output type.
export async function resolveNodeInputAssets(api, projectId, nodeId) {
if (!nodeId || projectId === undefined || projectId === null) {
return [];
}
const [nodes, connections] = await Promise.all([
api.apiJson('GET', '/graph/nodes', { query: { projectId } }).catch(() => []),
api.apiJson('GET', '/graph/connections', { query: { projectId } }).catch(() => [])
]);
const nodeList = Array.isArray(nodes) ? nodes : [];
const incomingEdges = (Array.isArray(connections) ? connections : [])
.filter(connection => Number(connection?.targetNodeId) === Number(nodeId))
.sort((a, b) => String(a?.inputId || '').localeCompare(String(b?.inputId || '')));
const inputs = [];
for (const edge of incomingEdges) {
const sourceNode = nodeList.find(node => Number(node?.id) === Number(edge.sourceNodeId));
const assetId = sourceNode?.assetId ?? sourceNode?.asset?.id ?? null;
if (assetId) {
inputs.push({
assetId: Number(assetId),
type: String(sourceNode?.asset?.type || '').toLowerCase() || null,
connectorId: edge.inputId || null
});
}
}
return inputs;
}
export async function attachResultsToNode(api, { projectId, nodeId, assets, metadata = {} }) {
const usable = (Array.isArray(assets) ? assets : [assets]).filter(asset =>
asset?.id && NODE_TYPE_BY_ASSET_TYPE[String(asset.type || '').toLowerCase()]
);
if (!nodeId || usable.length === 0) {
return { attached: false };
}
const [nodes, connections] = await Promise.all([
api.apiJson('GET', '/graph/nodes', { query: { projectId } }),
api.apiJson('GET', '/graph/connections', { query: { projectId } })
]);
const targetNode = (Array.isArray(nodes) ? nodes : []).find(node => Number(node?.id) === Number(nodeId));
if (!targetNode) {
throw new Error(`nodeId ${nodeId} not found in project ${projectId} — the generated assets are saved, use get_graph to find valid node ids.`);
}
const [firstAsset, ...extraAssets] = usable;
const updatedNode = await api.apiJson('PUT', `/graph/nodes/${nodeId}`, {
body: {
projectId,
assetId: firstAsset.id,
name: firstAsset.name || targetNode.name,
status: null,
progress: null,
metadata
}
});
// Additional results: new nodes below the target, re-wired to the target's
// incoming edges (same handles) so they carry the same references.
const incomingEdges = (Array.isArray(connections) ? connections : [])
.filter(connection => Number(connection?.targetNodeId) === Number(nodeId));
const baseX = Number(targetNode.xPos) || 0;
const baseY = Number(targetNode.yPos) || 0;
const additionalNodes = [];
for (let index = 0; index < extraAssets.length; index += 1) {
const asset = extraAssets[index];
const nodeTypeName = NODE_TYPE_BY_ASSET_TYPE[String(asset.type).toLowerCase()];
const createdNode = await api.apiJson('POST', '/graph/nodes', {
body: {
projectId,
nodeTypeName,
name: asset.name || nodeTypeName,
xPos: baseX,
yPos: baseY + ((index + 1) * VERTICAL_STEP),
assetId: asset.id,
metadata: { createdFromNodeId: Number(nodeId) }
}
});
additionalNodes.push(createdNode);
for (const edge of incomingEdges) {
await api.apiJson('POST', '/graph/connections', {
body: {
projectId,
sourceNodeId: edge.sourceNodeId,
targetNodeId: createdNode.id,
inputId: edge.inputId || 'input-0',
outputId: edge.outputId || 'output-0'
}
}).catch(() => null); // an unwirable edge shouldn't lose the result node
}
}
return {
attached: true,
node: updatedNode,
additionalNodeIds: additionalNodes.map(node => node.id)
};
}

24
mcp/stdio.js Normal file
View file

@ -0,0 +1,24 @@
#!/usr/bin/env node
// stdio entry point for MCP clients that spawn a process (e.g. Claude Desktop
// local servers). It is a thin bridge: tools still call the RUNNING 3D Gen
// Studio backend over loopback HTTP — this process never opens the database.
//
// Usage: node mcp/stdio.js (app must be running, default :3001)
// GENSTUDIO_URL=http://localhost:3001 node mcp/stdio.js
import process from 'node:process';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { buildMcpServer } from './index.js';
const baseUrl = (process.env.GENSTUDIO_URL || `http://127.0.0.1:${process.env.PORT || 3001}`).replace(/\/+$/, '');
try {
const res = await fetch(`${baseUrl}/api/projects`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
} catch (err) {
console.error(`3D Gen Studio is not reachable at ${baseUrl} (${err?.message || err}).`);
console.error('Start the app first (npm run dev, or launch the desktop app), then retry.');
process.exit(1);
}
const server = buildMcpServer({ baseUrl });
await server.connect(new StdioServerTransport());

439
mcp/tools/actions.js Normal file
View file

@ -0,0 +1,439 @@
import { z } from 'zod';
import { toolHandler, createProgressReporter } from '../client.js';
import { attachResultsToNode, resolveNodeTarget } from '../nodeResults.js';
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
// Map the submit response of POST /api/meshes/generate to the matching
// provider poll endpoint and its request body.
function buildMeshPollRequest(submit, base) {
const provider = String(submit?.provider || '').toLowerCase();
if (provider.includes('tencent')) {
return {
path: '/meshes/generate/tencent/result',
body: { ...base, jobId: submit.jobId, region: submit.region }
};
}
if (provider.includes('tripo')) {
return { path: '/meshes/generate/tripo/result', body: { ...base, taskId: submit.taskId } };
}
if (provider.includes('hitem')) {
return { path: '/meshes/generate/hitem/result', body: { ...base, taskId: submit.taskId, jobId: submit.jobId } };
}
return null;
}
// Fixed mesh-generation provider ids the backend dispatches on
// (see src/utils/kanbanHelpers.js). Each typed tool below hardwires one, so a
// client only supplies parameters — no need to know the id.
const TENCENT_MESH_API_ID = 'tencent_meshgeneration';
const TRIPO_MESH_API_ID = 'tripo_meshgeneration';
const HITEM_MESH_API_ID = 'hitem_meshgeneration';
// Typed provider option shapes. These mirror the request-body keys and defaults
// that server.js reads for each provider (normalize{Tencent,Tripo,Hitem}
// MeshGenerationInput) 1:1, so a client sees every knob with its enum/range and
// default instead of an opaque options blob. Keep in sync with server.js and
// src/utils/kanbanHelpers.js.
const TENCENT_MESH_OPTIONS = {
region: z.enum(['ap-singapore', 'eu-frankfurt', 'na-siliconvalley']).describe('Tencent Cloud region — REQUIRED (no default).'),
modelVersion: z.enum(['3.0', '3.1']).default('3.0').describe('Hunyuan3D model version. LowPoly generation requires 3.0.'),
generationType: z.enum(['Normal', 'LowPoly', 'Geometry']).default('Normal').describe('Generation mode. LowPoly requires modelVersion 3.0.'),
polygonType: z.enum(['triangle', 'quadrilaterial']).default('triangle').describe('Polygon type — only applied when generationType is LowPoly.'),
faceCount: z.number().int().min(3000).max(1500000).default(500000).describe('Target face count (3000–1,500,000).'),
enablePBR: z.boolean().default(false).describe('Generate a PBR-ready mesh.')
};
const TRIPO_MESH_OPTIONS = {
modelVersion: z.enum(['v2.0-20240919', 'v2.5-20250123', 'v3.0-20250812', 'v3.1-20260211', 'Turbo-v1.0-20250506', 'P1-20260311']).default('v2.5-20250123').describe('Tripo model version. The P1 model ignores enableImageAutofix/textureAlignment/orientation/quad/smartLowPoly/generateParts/geometryQuality.'),
modelSeed: z.number().int().optional().describe('Geometry RNG seed (optional; omit for random).'),
enableImageAutofix: z.boolean().default(false).describe('Fix the input image before generation (ignored by P1).'),
faceLimit: z.number().int().min(1000).optional().describe('Max face count (>=1000; optional).'),
texture: z.boolean().default(true).describe('Generate texture maps. Incompatible with generateParts=true.'),
pbr: z.boolean().default(true).describe('Export a PBR model. Incompatible with generateParts=true.'),
textureSeed: z.number().int().optional().describe('Texture RNG seed (optional).'),
textureAlignment: z.enum(['original_image', 'geometry']).default('original_image').describe('Texture alignment (ignored by P1).'),
textureQuality: z.enum(['standard', 'detailed']).default('standard').describe('Texture quality.'),
autoSize: z.boolean().default(false).describe('Auto-fit scale to real-world size.'),
orientation: z.enum(['default', 'align_image']).default('default').describe('Output orientation (ignored by P1).'),
quad: z.boolean().default(false).describe('Generate a quad mesh (ignored by P1). Incompatible with generateParts=true.'),
smartLowPoly: z.boolean().default(false).describe('Optimize for low poly (ignored by P1).'),
generateParts: z.boolean().default(false).describe('Split into semantic parts (ignored by P1). Incompatible with texture/pbr/quad=true.'),
exportUv: z.boolean().default(true).describe('Include UVs in the output.'),
geometryQuality: z.enum(['standard', 'detailed']).default('standard').describe('Geometry quality — only applied for v3.0/v3.1 models.')
};
const HITEM_MESH_OPTIONS = {
hitemModel: z.enum(['hitem3dv1.5', 'hitem3dv2.0', 'hitem3dv2.1']).default('hitem3dv2.1').describe('Hitem3D model version.'),
hitemResolution: z.enum(['512', '1024', '1536', '1536pro', '1536fast']).optional().describe('Resolution. Valid per model: v1.5/v2.0 = 512/1024/1536/1536pro; v2.1 = 1536fast/1536pro. Invalid/omitted falls back to the model default.'),
hitemRequestType: z.union([z.literal(1), z.literal(3)]).default(3).describe('1 = mesh only, 3 = textured mesh.'),
hitemFace: z.number().int().min(100000).max(2000000).default(300000).describe('Target face count (100,000–2,000,000).'),
hitemPbr: z.boolean().default(false).describe('Generate a PBR-ready mesh.')
};
// Poll a provider's mesh-result endpoint until the job completes, errors, or the
// timeout elapses — streaming MCP progress and attaching results to a graph node
// on completion. The mesh is only persisted server-side once a poll sees the job
// complete, so this loop IS what finishes an async job. Returns the completed
// result, throws on provider error, or returns {status:'running'} on timeout.
async function pollMeshResult(api, notifyMutation, {
pollRequest, providerLabel, projectId, nodeId, selectedApi, timeoutSeconds, pollIntervalSeconds, pollFirst = false
}, reportProgress) {
const deadline = Date.now() + timeoutSeconds * 1000;
let lastStatus = null;
let first = true;
while (Date.now() < deadline) {
if (!(first && pollFirst)) await sleep(pollIntervalSeconds * 1000);
first = false;
lastStatus = await api.apiJson('POST', pollRequest.path, { body: pollRequest.body });
if (lastStatus?.status === 'completed') {
await reportProgress(100, 100, 'Mesh generation completed');
let nodeAttachment = null;
if (nodeId && Array.isArray(lastStatus.assets) && lastStatus.assets.length > 0) {
nodeAttachment = await attachResultsToNode(api, {
projectId,
nodeId,
assets: lastStatus.assets.map(asset => ({ ...asset, type: asset?.type || 'mesh' })),
metadata: { lastAction: 'mesh-generation', selectedApi }
});
}
notifyMutation(projectId);
return nodeAttachment ? { ...lastStatus, nodeAttachment } : lastStatus;
}
if (lastStatus?.status === 'error') {
throw new Error(lastStatus.error || 'Mesh generation failed');
}
const percent = Number(lastStatus?.progressPercent ?? lastStatus?.progress);
await reportProgress(
Number.isFinite(percent) ? percent : 50,
100,
`${providerLabel} status: ${lastStatus?.jobStatus || lastStatus?.taskStatus || lastStatus?.status || 'processing'}`
);
}
return { status: 'running', lastStatus };
}
// Core submit-and-poll runner shared by generate_mesh and the typed
// generate_mesh_{tencent,tripo,hitem} tools: submit the provider job, poll to
// completion (streaming MCP progress), attach results to a graph node when
// asked, and return the saved assets (or job info on timeout).
async function runMeshGeneration(api, notifyMutation, args, extra) {
const {
projectId, selectedApi, name, prompt, imageSource, nodeId, cardId, parentAssetId,
options = {}, timeoutSeconds = 1200, pollIntervalSeconds = 10
} = args;
const reportProgress = createProgressReporter(extra);
// Route a graph-node target to the node; never send a node id as a kanban
// cardId. targetNodeId gets the final mesh attached (via pollMeshResult).
const { nodeId: targetNodeId, cardId: kanbanCardId } = await resolveNodeTarget(api, projectId, { nodeId, cardId });
const submit = await api.apiJson('POST', '/meshes/generate', {
body: {
projectId, selectedApi, name,
...(prompt ? { prompt } : {}),
...(imageSource !== undefined ? { imageSource } : {}),
...(kanbanCardId !== undefined && kanbanCardId !== null ? { cardId: kanbanCardId } : {}),
...(parentAssetId !== undefined ? { parentAssetId } : {}),
...options
}
});
notifyMutation(projectId);
const pollRequest = buildMeshPollRequest(submit, {
projectId,
name,
prompt: prompt || '',
cardId: submit?.cardId ?? kanbanCardId ?? null,
selectedApi,
parentAssetId: parentAssetId ?? null
});
// Custom APIs respond synchronously — nothing to poll.
if (!pollRequest) return submit;
await reportProgress(0, 100, `${submit.provider} job submitted (${submit.jobId || submit.taskId})`);
const outcome = await pollMeshResult(api, notifyMutation, {
pollRequest,
providerLabel: submit.provider,
projectId,
nodeId: targetNodeId,
selectedApi,
timeoutSeconds,
pollIntervalSeconds
}, reportProgress);
if (outcome.status === 'running') {
// Timed out with the job still on the provider. The mesh is NOT saved until a
// result poll sees completion, so hand back the job ids for get_mesh_result.
// Surface the resolved node target so a follow-up get_mesh_result can pass
// nodeId and still land the mesh on the intended node.
return {
status: 'running',
note: `Still processing after ${timeoutSeconds}s. The provider keeps working, but the mesh is only saved once a result poll sees it finish — call get_mesh_result with the ids below to retrieve it when ready${targetNodeId ? ' (pass nodeId to attach it to the graph node)' : ''}. Do NOT re-run generation (that starts a new job).`,
provider: submit.provider,
selectedApi,
projectId,
name,
...(targetNodeId ? { nodeId: targetNodeId } : {}),
...(submit.jobId ? { jobId: submit.jobId } : {}),
...(submit.taskId ? { taskId: submit.taskId } : {}),
...(submit.region ? { region: submit.region } : {}),
...(submit.cardId ? { cardId: submit.cardId } : {}),
lastStatus: outcome.lastStatus
};
}
return outcome;
}
export function registerActionTools(server, { api, notifyMutation }) {
server.registerTool('generate_image', {
title: 'Generate image',
description: 'Generate an image with an external AI provider and save it as a project asset. selectedApi identifies the provider/model configured in Settings (e.g. Google/OpenAI image APIs or a custom_* API) — check get_settings for what is configured. In graph projects pass nodeId so the result is displayed on that node (cardId is for kanban cards; a graph node id passed as cardId is auto-routed to that node).',
inputSchema: {
projectId: z.number().int(),
selectedApi: z.string().min(1).describe('Provider/model id from Settings (e.g. "google_gemini", "openai_gpt_image", or a custom_* id)'),
prompt: z.string().min(1),
name: z.string().min(1).describe('Name for the generated asset/card'),
nodeId: z.number().int().optional().describe('Graph node to attach the result to'),
cardId: z.union([z.number().int(), z.string()]).optional().describe('Existing kanban card to attach the result to')
}
}, toolHandler(async ({ projectId, nodeId, ...body }) => {
// A graph node id may arrive as nodeId or (mistakenly) as cardId — route it
// to the node and keep only a real kanban cardId in the request body.
const { nodeId: targetNodeId, cardId: kanbanCardId } = await resolveNodeTarget(api, projectId, { nodeId, cardId: body.cardId });
const result = await api.apiJson('POST', '/images/generate', { body: { projectId, ...body, cardId: kanbanCardId } });
let nodeAttachment = null;
if (targetNodeId) {
nodeAttachment = await attachResultsToNode(api, {
projectId,
nodeId: targetNodeId,
assets: [{ ...result, type: result?.type || 'image' }],
metadata: { lastAction: 'image-api' }
});
}
notifyMutation(projectId);
return nodeAttachment ? { ...result, nodeAttachment } : result;
}));
server.registerTool('edit_image', {
title: 'Edit image (AI)',
description: 'Edit an existing project image with an external AI provider (prompt-based edit). The result is saved as an edit of the source asset. In graph projects pass nodeId so the result is displayed on that node (cardId is for kanban cards; a graph node id passed as cardId is auto-routed to that node). For ComfyUI-based edits use run_workflow instead.',
inputSchema: {
projectId: z.number().int(),
selectedApi: z.string().min(1),
prompt: z.string().min(1),
name: z.string().min(1),
imageSource: z.union([z.number().int(), z.string()]).describe('Source image: asset id or stored filePath'),
nodeId: z.number().int().optional().describe('Graph node to attach the result to'),
cardId: z.union([z.number().int(), z.string()]).optional()
}
}, toolHandler(async ({ projectId, nodeId, ...body }) => {
const { nodeId: targetNodeId, cardId: kanbanCardId } = await resolveNodeTarget(api, projectId, { nodeId, cardId: body.cardId });
const result = await api.apiJson('POST', '/image-edits/api', { body: { projectId, ...body, cardId: kanbanCardId } });
let nodeAttachment = null;
const savedEdits = Array.isArray(result?.savedEdits) ? result.savedEdits : [];
if (targetNodeId && savedEdits.length > 0) {
nodeAttachment = await attachResultsToNode(api, {
projectId,
nodeId: targetNodeId,
assets: savedEdits.map(edit => ({ id: edit.id, name: edit.name || body.name, type: 'image' })),
metadata: { lastAction: 'image-edit-api' }
});
}
notifyMutation(projectId);
return nodeAttachment ? { ...result, nodeAttachment } : result;
}));
server.registerTool('generate_mesh', {
title: 'Generate 3D mesh',
description: 'Generate a 3D mesh from an image and/or prompt using Tencent Hunyuan, Tripo AI, or Hitem3D (selectedApi from Settings). Submits the job and polls the provider until the mesh is ready (streams MCP progress), then returns the saved mesh assets. In graph projects pass nodeId so the mesh is displayed on that node (cardId is for kanban cards; a graph node id passed as cardId is auto-routed to that node). Takes minutes — on timeout returns the job info so it can be re-polled by calling this tool\'s sibling get-result flow or checking list_assets later.',
inputSchema: {
projectId: z.number().int(),
selectedApi: z.string().min(1).describe('Mesh provider id from Settings (Tencent / Tripo / Hitem3D / custom_*)'),
name: z.string().min(1),
prompt: z.string().optional().describe('Text prompt (Tencent/Tripo support text-to-3D)'),
imageSource: z.union([z.number().int(), z.string()]).optional().describe('Source image: asset id or stored filePath (required for Hitem3D)'),
nodeId: z.number().int().optional().describe('Graph node to attach the generated mesh to (graph projects). The correct way to fill a node; a graph node id passed as cardId is auto-routed here.'),
cardId: z.union([z.number().int(), z.string()]).optional(),
parentAssetId: z.number().int().optional(),
options: z.record(z.string(), z.any()).default({}).describe('Provider options, e.g. Tencent: region, modelVersion, enablePBR, faceCount, generationType, polygonType; Tripo: modelVersion, texture, pbr, quad, faceLimit, …. Prefer the dedicated generate_mesh_tencent / generate_mesh_tripo / generate_mesh_hitem tools, which document and validate every option.'),
timeoutSeconds: z.number().int().min(30).max(3600).default(1200),
pollIntervalSeconds: z.number().int().min(3).max(120).default(10)
}
}, toolHandler((args, extra) => runMeshGeneration(api, notifyMutation, args, extra)));
server.registerTool('generate_mesh_tencent', {
title: 'Generate 3D mesh (Tencent Hunyuan3D)',
description: 'Generate a 3D mesh with Tencent Cloud Hunyuan3D and save it as a project asset. Provide EITHER prompt (text-to-3D) OR imageSource (image-to-3D), not both. Every Tencent parameter is exposed under `options` with its enum/range and default; region is required. Submits and polls until ready (streams progress), returning the saved mesh assets (or job info on timeout). Requires Tencent Cloud credentials configured in Settings.',
inputSchema: {
projectId: z.number().int(),
name: z.string().min(1),
prompt: z.string().optional().describe('Text prompt (text-to-3D). Provide this OR imageSource.'),
imageSource: z.union([z.number().int(), z.string()]).optional().describe('Source image: asset id or stored filePath (image-to-3D). Provide this OR prompt.'),
options: z.object(TENCENT_MESH_OPTIONS).describe('Tencent Hunyuan3D parameters (region is required).'),
nodeId: z.number().int().optional().describe('Graph node to attach the generated mesh to (graph projects). The correct way to fill a node; a graph node id passed as cardId is auto-routed here.'),
cardId: z.union([z.number().int(), z.string()]).optional(),
parentAssetId: z.number().int().optional(),
timeoutSeconds: z.number().int().min(30).max(3600).default(1200),
pollIntervalSeconds: z.number().int().min(3).max(120).default(10)
}
}, toolHandler((args, extra) => runMeshGeneration(api, notifyMutation, { ...args, selectedApi: TENCENT_MESH_API_ID }, extra)));
server.registerTool('generate_mesh_tripo', {
title: 'Generate 3D mesh (Tripo AI)',
description: 'Generate a 3D mesh with Tripo AI and save it as a project asset. Provide EITHER prompt (text-to-3D) OR imageSource (image-to-3D), not both. Every Tripo parameter is exposed under `options` with its enum/range and default. Note: the P1 model ignores several options, and generateParts is incompatible with texture/pbr/quad. Submits and polls until ready (streams progress), returning the saved mesh assets (or job info on timeout). Requires a Tripo AI API key configured in Settings.',
inputSchema: {
projectId: z.number().int(),
name: z.string().min(1),
prompt: z.string().optional().describe('Text prompt (text-to-3D). Provide this OR imageSource.'),
imageSource: z.union([z.number().int(), z.string()]).optional().describe('Source image: asset id or stored filePath (image-to-3D). Provide this OR prompt.'),
options: z.object(TRIPO_MESH_OPTIONS).default({}).describe('Tripo AI parameters (all optional; unset keys use their default).'),
nodeId: z.number().int().optional().describe('Graph node to attach the generated mesh to (graph projects). The correct way to fill a node; a graph node id passed as cardId is auto-routed here.'),
cardId: z.union([z.number().int(), z.string()]).optional(),
parentAssetId: z.number().int().optional(),
timeoutSeconds: z.number().int().min(30).max(3600).default(1200),
pollIntervalSeconds: z.number().int().min(3).max(120).default(10)
}
}, toolHandler((args, extra) => runMeshGeneration(api, notifyMutation, { ...args, selectedApi: TRIPO_MESH_API_ID }, extra)));
server.registerTool('generate_mesh_hitem', {
title: 'Generate 3D mesh (Hitem3D)',
description: 'Generate a 3D mesh with Hitem3D from an image and save it as a project asset. imageSource is REQUIRED (Hitem3D is image-to-3D only). Every Hitem3D parameter is exposed under `options` with its enum/range and default. Submits and polls until ready (streams progress), returning the saved mesh assets (or job info on timeout). Requires Hitem3D access/secret keys configured in Settings.',
inputSchema: {
projectId: z.number().int(),
name: z.string().min(1),
imageSource: z.union([z.number().int(), z.string()]).describe('Source image: asset id or stored filePath — REQUIRED.'),
options: z.object(HITEM_MESH_OPTIONS).default({}).describe('Hitem3D parameters (all optional; unset keys use their default).'),
nodeId: z.number().int().optional().describe('Graph node to attach the generated mesh to (graph projects). The correct way to fill a node; a graph node id passed as cardId is auto-routed here.'),
cardId: z.union([z.number().int(), z.string()]).optional(),
parentAssetId: z.number().int().optional(),
timeoutSeconds: z.number().int().min(30).max(3600).default(1200),
pollIntervalSeconds: z.number().int().min(3).max(120).default(10)
}
}, toolHandler((args, extra) => runMeshGeneration(api, notifyMutation, { ...args, selectedApi: HITEM_MESH_API_ID }, extra)));
server.registerTool('get_mesh_result', {
title: 'Get mesh generation result',
description: 'Retrieve and finish an async mesh-generation job (Tencent / Tripo / Hitem3D) — use this when the original generate_mesh* call returned {status:"running"} after timing out. The generated mesh is NOT saved to the project until a result poll sees the job complete, so this tool is required to recover a timed-out job (list_assets will not show it before then). It polls the provider until the mesh is ready, saves it, and returns the assets. Pass the ids from the timeout payload: Tripo/Hitem3D use taskId; Tencent uses jobId + region. It is safe to call repeatedly.',
inputSchema: {
projectId: z.number().int(),
name: z.string().min(1).describe('The same name the job was submitted with (used to save the asset)'),
provider: z.enum(['tencent', 'tripo', 'hitem']).describe('Provider the job was submitted to'),
taskId: z.string().optional().describe('Tripo AI / Hitem3D job id (from the timeout payload)'),
jobId: z.string().optional().describe('Tencent Cloud job id (from the timeout payload)'),
region: z.enum(['ap-singapore', 'eu-frankfurt', 'na-siliconvalley']).optional().describe('Tencent Cloud region the job was submitted in (required for Tencent)'),
selectedApi: z.string().optional().describe('Provider id override (defaults to the standard id for the provider)'),
prompt: z.string().optional().describe('Original prompt (stored in asset metadata; optional)'),
cardId: z.union([z.number().int(), z.string()]).optional().describe('Kanban card the job is attached to (from the timeout payload)'),
parentAssetId: z.number().int().optional().describe('Save the result as a version of this asset'),
nodeId: z.number().int().optional().describe('Graph node to attach the result to (graph projects)'),
timeoutSeconds: z.number().int().min(5).max(3600).default(600),
pollIntervalSeconds: z.number().int().min(3).max(120).default(10)
}
}, toolHandler(async (args, extra) => {
const {
projectId, name, provider, taskId, jobId, region, selectedApi, prompt,
cardId, parentAssetId, nodeId, timeoutSeconds = 600, pollIntervalSeconds = 10
} = args;
const reportProgress = createProgressReporter(extra);
const providerIds = { tencent: TENCENT_MESH_API_ID, tripo: TRIPO_MESH_API_ID, hitem: HITEM_MESH_API_ID };
const providerLabels = { tencent: 'Tencent Cloud', tripo: 'Tripo AI', hitem: 'Hitem3D' };
const effectiveSelectedApi = selectedApi || providerIds[provider];
const providerLabel = providerLabels[provider];
if (provider === 'tencent' && (!jobId || !region)) {
throw new Error('Tencent result lookup requires both jobId and region (from the timeout payload).');
}
if ((provider === 'tripo' || provider === 'hitem') && !taskId) {
throw new Error(`${providerLabel} result lookup requires taskId (from the timeout payload).`);
}
// buildMeshPollRequest keys off the provider label substring and the ids.
const pollRequest = buildMeshPollRequest(
{ provider: providerLabel, jobId, taskId, region },
{ projectId, name, prompt: prompt || '', cardId: cardId ?? null, selectedApi: effectiveSelectedApi, parentAssetId: parentAssetId ?? null }
);
if (!pollRequest) throw new Error(`Unknown mesh provider: ${provider}`);
const outcome = await pollMeshResult(api, notifyMutation, {
pollRequest,
providerLabel,
projectId,
nodeId,
selectedApi: effectiveSelectedApi,
timeoutSeconds,
pollIntervalSeconds,
pollFirst: true
}, reportProgress);
if (outcome.status === 'running') {
return {
status: 'running',
note: `Still processing after ${timeoutSeconds}s. Call get_mesh_result again with the same ids to keep waiting.`,
provider: providerLabel,
projectId,
name,
...(jobId ? { jobId } : {}),
...(taskId ? { taskId } : {}),
...(region ? { region } : {}),
lastStatus: outcome.lastStatus
};
}
return outcome;
}));
server.registerTool('edit_mesh', {
title: 'Edit mesh (AI)',
description: 'Edit an existing project mesh through a configured custom mesh-edit API (selectedApi must be a custom_* id from Settings).',
inputSchema: {
projectId: z.number().int(),
selectedApi: z.string().min(1),
prompt: z.string().min(1),
name: z.string().min(1),
meshSource: z.union([z.number().int(), z.string()]).describe('Source mesh: asset id or stored filePath'),
cardId: z.union([z.number().int(), z.string()]).optional()
}
}, toolHandler(async ({ projectId, ...body }) => {
const result = await api.apiJson('POST', '/meshes/edit', { body: { projectId, ...body } });
notifyMutation(projectId);
return result;
}));
server.registerTool('texture_mesh', {
title: 'Texture mesh (AI)',
description: 'Texture an existing project mesh through a configured custom texturing API (selectedApi must be a custom_* id from Settings). For ComfyUI-based texturing use run_workflow.',
inputSchema: {
projectId: z.number().int(),
selectedApi: z.string().min(1),
prompt: z.string().min(1),
name: z.string().min(1),
meshSource: z.union([z.number().int(), z.string()]),
cardId: z.union([z.number().int(), z.string()]).optional()
}
}, toolHandler(async ({ projectId, ...body }) => {
const result = await api.apiJson('POST', '/meshes/texture', { body: { projectId, ...body } });
notifyMutation(projectId);
return result;
}));
server.registerTool('rig_mesh_api', {
title: 'Rig mesh (external API)',
description: 'Rig an existing project mesh through a configured custom rigging API (selectedApi must be a custom_* id from Settings). For the built-in local Auto Rig service use run_mesh_tool with operation "auto_rig".',
inputSchema: {
projectId: z.number().int(),
selectedApi: z.string().min(1),
prompt: z.string().min(1),
name: z.string().min(1),
meshSource: z.union([z.number().int(), z.string()]),
cardId: z.union([z.number().int(), z.string()]).optional()
}
}, toolHandler(async ({ projectId, ...body }) => {
const result = await api.apiJson('POST', '/meshes/rigging', { body: { projectId, ...body } });
notifyMutation(projectId);
return result;
}));
}

240
mcp/tools/assets.js Normal file
View file

@ -0,0 +1,240 @@
import { z } from 'zod';
import { Buffer } from 'node:buffer';
import fs from 'node:fs/promises';
import path from 'node:path';
import { toolHandler, withAssetUrls, findProjectAsset } from '../client.js';
const MIME_BY_EXT = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.webp': 'image/webp',
'.gif': 'image/gif',
'.glb': 'model/gltf-binary',
'.gltf': 'model/gltf+json',
'.fbx': 'application/octet-stream',
'.obj': 'text/plain',
'.json': 'application/json'
};
// MCP image blocks Claude can actually see. Cap the raw size so the base64
// payload stays under typical model/image limits (~5 MB base64).
const VIEWABLE_IMAGE_MIME = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif']);
const MAX_VIEW_BYTES = 3.5 * 1024 * 1024;
function imageMimeOf(filePath) {
return MIME_BY_EXT[path.extname(String(filePath || '')).toLowerCase()] || null;
}
// Resolve what file a view/download request points at: an image asset's own
// file, or — for meshes — its thumbnail when viewing.
function resolveViewTarget(asset) {
const file = asset.filename || asset.filePath;
const mime = imageMimeOf(file);
if (mime && VIEWABLE_IMAGE_MIME.has(mime)) {
return { file, mime, note: null };
}
if (asset.thumbnail) {
const thumbMime = imageMimeOf(asset.thumbnail) || 'image/png';
return {
file: asset.thumbnail,
mime: thumbMime,
note: `This is the thumbnail preview of "${asset.name}" (${String(asset.type || 'asset')}), not the file itself. Use download_asset for the full file.`
};
}
return null;
}
export function registerAssetTools(server, { api, notifyMutation }) {
server.registerTool('list_assets', {
title: 'List project assets',
description: 'List a project\'s assets (images, meshes, workflows) with their version/edit trees and direct download URLs.',
inputSchema: {
projectId: z.number().int(),
includeChildren: z.boolean().optional().describe('Also return every project-linked edit/version as a top-level entry, not only nested under its root.')
},
annotations: { readOnlyHint: true }
}, toolHandler(async ({ projectId, includeChildren }) => {
const assets = await api.apiJson('GET', '/assets', {
query: { projectId, ...(includeChildren ? { includeChildren: 'true' } : {}) }
});
return (Array.isArray(assets) ? assets : []).map(asset => withAssetUrls(api, asset));
}));
server.registerTool('list_library_assets', {
title: 'List asset library',
description: 'List the global (project-independent) asset library: images, meshes, brushes, and saved workflows.',
annotations: { readOnlyHint: true }
}, toolHandler(async () => {
const assets = await api.apiJson('GET', '/assets/library');
if (Array.isArray(assets)) return assets.map(asset => withAssetUrls(api, asset));
if (assets && typeof assets === 'object') {
return Object.fromEntries(Object.entries(assets).map(([key, value]) => [
key,
Array.isArray(value) ? value.map(asset => withAssetUrls(api, asset)) : value
]));
}
return assets;
}));
server.registerTool('upload_asset', {
title: 'Upload asset',
description: 'Upload a local file (image or mesh) into a project as a new asset. The file is read from an absolute path on this machine.',
inputSchema: {
projectId: z.number().int(),
filePath: z.string().min(1).describe('Absolute local path of the file to upload'),
name: z.string().optional().describe('Asset name (defaults to the file name)'),
type: z.enum(['image', 'mesh']).optional().describe('Asset type (inferred from the file extension when omitted)'),
metadata: z.record(z.string(), z.any()).optional()
}
}, toolHandler(async ({ projectId, filePath, name, type, metadata }) => {
const buffer = await fs.readFile(filePath);
const fileName = path.basename(filePath);
const mime = MIME_BY_EXT[path.extname(fileName).toLowerCase()] || 'application/octet-stream';
const form = new FormData();
form.append('file', new Blob([buffer], { type: mime }), fileName);
form.append('projectId', String(projectId));
if (type) form.append('type', type);
if (name) form.append('name', name);
form.append('metadata', JSON.stringify(metadata || {}));
const asset = await api.apiForm('POST', '/assets/upload', form);
notifyMutation(projectId);
return withAssetUrls(api, asset);
}));
server.registerTool('link_asset', {
title: 'Link existing asset',
description: 'Attach an existing asset to a project. Pass assetId to link an asset that is already in the database — this works for a root asset AND for an image edit or mesh version (use the child id from list_assets). Pass filename instead to link a stored file from the asset library.',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int().optional().describe('Asset id to link — root, image edit or mesh version. Preferred over filename.'),
filename: z.string().min(1).optional().describe('Stored asset filename (from list_library_assets). Used when assetId is not given.'),
type: z.enum(['image', 'mesh']).default('image'),
name: z.string().optional(),
metadata: z.record(z.string(), z.any()).optional(),
cascadeChildren: z.boolean().optional().describe('With assetId: also link every edit/version of that asset.')
}
}, toolHandler(async ({ projectId, assetId, filename, type, name, metadata, cascadeChildren }) => {
if (assetId === undefined && !filename) {
throw new Error('Pass either assetId or filename.');
}
const asset = assetId !== undefined
? await api.apiJson('POST', `/projects/${projectId}/assets`, {
body: { assetId, ...(cascadeChildren ? { cascadeChildren: true } : {}) }
})
: await api.apiJson('POST', '/assets/link', {
body: { projectId, filename, type, ...(name ? { name } : {}), ...(metadata ? { metadata } : {}) }
});
notifyMutation(projectId);
return withAssetUrls(api, asset);
}));
server.registerTool('unlink_asset', {
title: 'Unlink asset from project',
description: 'Remove an asset from a project without deleting the file or the library record. Also removes it from any card/node it sits on in that project.',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int().describe('Asset id — root, image edit or mesh version'),
cascadeChildren: z.boolean().default(true).describe('Also unlink every edit/version of that asset.')
}
}, toolHandler(async ({ projectId, assetId, cascadeChildren }) => {
const query = cascadeChildren === false ? { cascadeChildren: 'false' } : {};
const result = await api.apiJson('DELETE', `/projects/${projectId}/assets/${assetId}`, { query });
notifyMutation(projectId);
return result;
}));
server.registerTool('view_asset', {
title: 'View asset (image)',
description: 'SEE a project asset: returns the actual image so it can be visually inspected. For image assets returns the image itself; for meshes returns the thumbnail preview when one exists. Use this after generating images to check the results. For raw file access use download_asset.',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int().describe('Asset id (from list_assets or a generation result)')
},
annotations: { readOnlyHint: true }
}, async ({ projectId, assetId } = {}) => {
try {
const asset = await findProjectAsset(api, projectId, assetId);
const target = resolveViewTarget(asset);
if (!target) {
return {
isError: true,
content: [{
type: 'text',
text: `Asset ${assetId} ("${asset.name}", type ${asset.type}) has no viewable image or thumbnail. Use download_asset to save the file locally instead.`
}]
};
}
const buffer = await api.fetchAssetBuffer(target.file);
if (buffer.length > MAX_VIEW_BYTES) {
return {
isError: true,
content: [{
type: 'text',
text: `Asset file is too large to view inline (${(buffer.length / 1024 / 1024).toFixed(1)} MB). Use download_asset to save it locally, or open its URL: ${api.assetUrl(target.file)}`
}]
};
}
const info = {
id: asset.id,
name: asset.name,
type: asset.type,
width: asset.width || undefined,
height: asset.height || undefined,
url: api.assetUrl(asset.filename || asset.filePath)
};
return {
content: [
{ type: 'image', data: buffer.toString('base64'), mimeType: target.mime },
{ type: 'text', text: (target.note ? `${target.note}\n` : '') + JSON.stringify(info) }
]
};
} catch (err) {
return { isError: true, content: [{ type: 'text', text: String(err?.message || err) }] };
}
});
server.registerTool('download_asset', {
title: 'Download asset to disk',
description: 'Save a project asset\'s file (image, mesh, or workflow) into an absolute folder on the machine running 3D Gen Studio, so it can be opened or inspected from the filesystem.',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int(),
folder: z.string().min(1).describe('Absolute output folder'),
fileName: z.string().optional().describe('Output file name (defaults to the asset\'s stored file name)')
},
annotations: { readOnlyHint: true }
}, toolHandler(async ({ projectId, assetId, folder, fileName }) => {
const asset = await findProjectAsset(api, projectId, assetId);
const assetFile = asset.filename || asset.filePath;
const buffer = await api.fetchAssetBuffer(assetFile);
// Reuse the server's export endpoint — it writes arbitrary files under an
// absolute folder with basename sanitization.
const form = new FormData();
form.append('folder', folder);
form.append('files', new Blob([buffer]), fileName || path.basename(String(assetFile)) || `asset-${assetId}`);
const written = await api.apiForm('POST', '/export/mesh', form);
return { ...written, sizeBytes: buffer.length, asset: { id: asset.id, name: asset.name, type: asset.type } };
}));
server.registerTool('delete_asset', {
title: 'Delete asset',
description: 'PERMANENTLY delete an asset from a project. Set confirm=true to proceed.',
inputSchema: {
assetId: z.number().int(),
confirm: z.boolean().describe('Must be true — confirms the permanent deletion')
},
annotations: { destructiveHint: true }
}, toolHandler(async ({ assetId, confirm }) => {
if (confirm !== true) throw new Error('Refusing to delete: pass confirm=true to permanently delete this asset.');
await api.apiJson('DELETE', `/assets/${assetId}`);
notifyMutation(null);
return { deleted: true, assetId };
}));
}

125
mcp/tools/cards.js Normal file
View file

@ -0,0 +1,125 @@
import { z } from 'zod';
import { toolHandler } from '../client.js';
// Kanban columns are fixed (seeded in storage.js). Accept names, map to ids.
const KANBAN_COLUMNS = {
'images': 1,
'image edit': 2,
'mesh gen': 3,
'mesh edit': 4,
'texturing': 5,
'rigging': 6
};
function resolveColumnId(column) {
if (typeof column === 'number') return column;
const id = KANBAN_COLUMNS[String(column || '').trim().toLowerCase()];
if (!id) {
throw new Error(`Unknown kanban column "${column}". Valid columns: Images, Image Edit, Mesh Gen, Mesh Edit, Texturing, Rigging.`);
}
return id;
}
export function registerCardTools(server, { api, notifyMutation }) {
server.registerTool('list_cards', {
title: 'List cards',
description: 'List every card of a project. Kanban cards carry kanbanColumnId (1=Images, 2=Image Edit, 3=Mesh Gen, 4=Mesh Edit, 5=Texturing, 6=Rigging) and position; graph nodes appear here too with a non-null nodeTypeId (use get_graph for the graph view).',
inputSchema: { projectId: z.number().int() },
annotations: { readOnlyHint: true }
}, toolHandler(async ({ projectId }) => api.apiJson('GET', '/cards', { query: { projectId } })));
server.registerTool('move_card', {
title: 'Move kanban card',
description: 'Move a kanban card to a column ("Images", "Image Edit", "Mesh Gen", "Mesh Edit", "Texturing", "Rigging") at the given position (0-based).',
inputSchema: {
projectId: z.number().int(),
cardId: z.number().int().describe('Card id (from list_cards)'),
column: z.string().describe('Target column name'),
position: z.number().int().min(0).describe('0-based position inside the column')
}
}, toolHandler(async ({ projectId, cardId, column, position }) => {
const result = await api.apiJson('PUT', '/cards/move', {
body: { projectId, cardId, kanbanColumnId: resolveColumnId(column), position }
});
notifyMutation(projectId);
return result;
}));
server.registerTool('delete_card', {
title: 'Delete card',
description: 'PERMANENTLY delete a card from a project (its linked assets remain).',
inputSchema: { projectId: z.number().int(), cardId: z.number().int() },
annotations: { destructiveHint: true }
}, toolHandler(async ({ projectId, cardId }) => {
await api.apiJson('DELETE', `/cards/${cardId}`, { query: { projectId } });
notifyMutation(projectId);
return { deleted: true, cardId };
}));
server.registerTool('list_card_attributes', {
title: 'List card attributes',
description: 'List custom attributes attached to a project\'s cards, plus the available attribute types (1=Text, 2=Number).',
inputSchema: { projectId: z.number().int() },
annotations: { readOnlyHint: true }
}, toolHandler(async ({ projectId }) => {
const [attributes, types] = await Promise.all([
api.apiJson('GET', '/card-attributes', { query: { projectId } }),
api.apiJson('GET', '/card-attributes/types')
]);
return { attributes, types };
}));
server.registerTool('create_card_attribute', {
title: 'Create card attribute',
description: 'Add a custom attribute to a card. attributeTypeId: 1=Text, 2=Number.',
inputSchema: {
projectId: z.number().int(),
cardId: z.number().int(),
attributeTypeId: z.number().int().describe('1=Text, 2=Number'),
value: z.string().default('').describe('Attribute value (string; numbers as text)')
}
}, toolHandler(async ({ projectId, cardId, attributeTypeId, value }) => {
const attribute = await api.apiJson('POST', '/card-attributes', {
body: { projectId, cardId, attributeTypeId, attributeValue: value }
});
notifyMutation(projectId);
return attribute;
}));
server.registerTool('update_card_attribute', {
title: 'Update card attribute',
description: 'Update a card attribute (identified by cardId + position from list_card_attributes).',
inputSchema: {
projectId: z.number().int(),
cardId: z.number().int(),
position: z.number().int(),
attributeTypeId: z.number().int().optional(),
value: z.string().optional()
}
}, toolHandler(async ({ projectId, cardId, position, attributeTypeId, value }) => {
const attribute = await api.apiJson('PUT', `/card-attributes/${cardId}/${position}`, {
body: {
projectId,
...(attributeTypeId !== undefined ? { attributeTypeId } : {}),
...(value !== undefined ? { attributeValue: value } : {})
}
});
notifyMutation(projectId);
return attribute;
}));
server.registerTool('delete_card_attribute', {
title: 'Delete card attribute',
description: 'Delete a card attribute (identified by cardId + position).',
inputSchema: {
projectId: z.number().int(),
cardId: z.number().int(),
position: z.number().int()
},
annotations: { destructiveHint: true }
}, toolHandler(async ({ projectId, cardId, position }) => {
await api.apiJson('DELETE', `/card-attributes/${cardId}/${position}`, { query: { projectId } });
notifyMutation(projectId);
return { deleted: true, cardId, position };
}));
}

140
mcp/tools/graph.js Normal file
View file

@ -0,0 +1,140 @@
import { z } from 'zod';
import { toolHandler } from '../client.js';
// Node types seeded in storage.js (NODE_TYPES). The friendly enum maps to the
// exact nodeTypeName the backend expects.
const NODE_KINDS = {
image: 'Image',
mesh: 'Mesh',
number: 'Number',
text: 'Text',
boolean: 'Boolean',
image_compare: 'Image Compare'
};
export function registerGraphTools(server, { api, notifyMutation }) {
server.registerTool('get_graph', {
title: 'Get graph',
description: 'Get a graph project\'s full node graph: nodes (with xPos/yPos, nodeTypeName, linked assetId, status, metadata) and connections (sourceNodeId/targetNodeId with React Flow handle ids like "output-0"/"input-0").',
inputSchema: { projectId: z.number().int() },
annotations: { readOnlyHint: true }
}, toolHandler(async ({ projectId }) => {
const [nodes, connections] = await Promise.all([
api.apiJson('GET', '/graph/nodes', { query: { projectId } }),
api.apiJson('GET', '/graph/connections', { query: { projectId } })
]);
return { nodes, connections };
}));
server.registerTool('create_node', {
title: 'Create graph node',
description: 'Add a node to a graph project. Kinds: image (holds/generates images and runs ComfyUI/API actions), mesh (mesh generation/editing), number/text/boolean (value nodes feeding workflow parameters), image_compare. Value nodes store their value in metadata as {"outputType":"number|text|boolean","outputValue":<value>}.',
inputSchema: {
projectId: z.number().int(),
kind: z.enum(['image', 'mesh', 'number', 'text', 'boolean', 'image_compare']),
name: z.string().optional().describe('Node display name'),
x: z.number().default(0).describe('Canvas X position'),
y: z.number().default(0).describe('Canvas Y position'),
assetId: z.number().int().optional().describe('Existing asset to attach to the node'),
metadata: z.record(z.string(), z.any()).optional().describe('Node metadata JSON (e.g. outputType/outputValue for value nodes)')
}
}, toolHandler(async ({ projectId, kind, name, x, y, assetId, metadata }) => {
const node = await api.apiJson('POST', '/graph/nodes', {
body: {
projectId,
nodeTypeName: NODE_KINDS[kind],
name: name || NODE_KINDS[kind],
xPos: x,
yPos: y,
...(assetId !== undefined ? { assetId } : {}),
...(metadata !== undefined ? { metadata } : {})
}
});
notifyMutation(projectId);
return node;
}));
server.registerTool('update_node', {
title: 'Update graph node',
description: 'Update a graph node\'s name, linked asset, status, progress, or metadata.',
inputSchema: {
projectId: z.number().int(),
nodeId: z.number().int(),
name: z.string().optional(),
assetId: z.number().int().nullable().optional(),
status: z.string().optional(),
progress: z.number().optional(),
metadata: z.record(z.string(), z.any()).optional()
}
}, toolHandler(async ({ projectId, nodeId, ...updates }) => {
const body = Object.fromEntries(Object.entries(updates).filter(([, v]) => v !== undefined));
if (Object.keys(body).length === 0) throw new Error('Provide at least one field to update.');
const node = await api.apiJson('PUT', `/graph/nodes/${nodeId}`, { body: { projectId, ...body } });
notifyMutation(projectId);
return node;
}));
server.registerTool('move_node', {
title: 'Move graph node',
description: 'Move a graph node to a new canvas position.',
inputSchema: {
projectId: z.number().int(),
nodeId: z.number().int(),
x: z.number(),
y: z.number()
}
}, toolHandler(async ({ projectId, nodeId, x, y }) => {
const node = await api.apiJson('PUT', `/graph/nodes/${nodeId}/position`, {
body: { projectId, xPos: x, yPos: y }
});
notifyMutation(projectId);
return node;
}));
server.registerTool('delete_node', {
title: 'Delete graph node',
description: 'PERMANENTLY delete a graph node (its connections are removed with it; linked assets remain).',
inputSchema: { projectId: z.number().int(), nodeId: z.number().int() },
annotations: { destructiveHint: true }
}, toolHandler(async ({ projectId, nodeId }) => {
await api.apiJson('DELETE', `/graph/nodes/${nodeId}`, { query: { projectId } });
notifyMutation(projectId);
return { deleted: true, nodeId };
}));
server.registerTool('connect_nodes', {
title: 'Connect graph nodes',
description: 'Create an edge from a source node\'s output handle to a target node\'s input handle. Handles default to "output-0"/"input-0"; connector types must be compatible (an image output feeds an image input, a number output feeds a number parameter, etc.).',
inputSchema: {
projectId: z.number().int(),
sourceNodeId: z.number().int(),
targetNodeId: z.number().int(),
outputId: z.string().default('output-0').describe('Source handle id'),
inputId: z.string().default('input-0').describe('Target handle id')
}
}, toolHandler(async ({ projectId, sourceNodeId, targetNodeId, outputId, inputId }) => {
const connection = await api.apiJson('POST', '/graph/connections', {
body: { projectId, sourceNodeId, targetNodeId, outputId, inputId }
});
notifyMutation(projectId);
return connection;
}));
server.registerTool('disconnect_nodes', {
title: 'Disconnect graph nodes',
description: 'Remove an edge between two graph nodes (all four identifiers must match the existing connection).',
inputSchema: {
projectId: z.number().int(),
sourceNodeId: z.number().int(),
targetNodeId: z.number().int(),
outputId: z.string().default('output-0'),
inputId: z.string().default('input-0')
}
}, toolHandler(async ({ projectId, sourceNodeId, targetNodeId, outputId, inputId }) => {
await api.apiJson('DELETE', '/graph/connections', {
query: { projectId, sourceNodeId, targetNodeId, outputId, inputId }
});
notifyMutation(projectId);
return { deleted: true };
}));
}

201
mcp/tools/meshTools.js Normal file
View file

@ -0,0 +1,201 @@
import { z } from 'zod';
import { Buffer } from 'node:buffer';
import path from 'node:path';
import { toolHandler, createProgressReporter, withAssetUrls, findProjectAsset } from '../client.js';
// Local mesh services behind the Node proxy. auto_uv/auto_retopo/repair/
// convert_fbx run on the Python mesh-tools service (:8200), auto_rig on the
// rigging service (:8300), optimize on the bundled gltfpack binary.
const OPERATIONS = {
auto_uv: { path: '/meshes/auto-uv', sse: true },
auto_retopo: { path: '/meshes/auto-retopo', sse: true },
repair: { path: '/meshes/repair', sse: true },
convert_fbx: { path: '/meshes/convert', sse: true, format: 'fbx' },
auto_rig: { path: '/meshes/rig', sse: true },
optimize: { path: '/meshes/optimize', sse: false }
};
// Typed option shapes for the parameter-heavy tools. These mirror the Python
// service's Pydantic models 1:1 (python-server/app/schemas.py) — same keys,
// ranges, and defaults — so an MCP client sees every knob with its bounds and
// default instead of an opaque options blob. Keep them in sync with schemas.py
// and the panel defaults in src/pages/MeshEditorPage.jsx.
const AUTO_UV_OPTIONS = {
// segmentation
max_cone_deg: z.number().min(1).max(180).default(50).describe('Normal-cone cap (deg). Higher = fewer, more distorted charts.'),
sharp_weight: z.number().min(0).max(1).default(0.35).describe('How strongly sharp edges attract seams.'),
min_faces: z.number().int().min(1).max(100000).default(20).describe('Charts smaller than this are dissolved into neighbours.'),
min_area_frac: z.number().min(0).max(1).default(0.004).describe('Min chart area as a fraction of total surface area.'),
fold_cap_deg: z.number().min(1).max(180).default(88).describe('Dihedral fold cap that forces a seam.'),
// refinement (LSCM-validated chart merge)
refine: z.boolean().default(true).describe('Run the LSCM-validated chart-merge pass (off = faster, more charts).'),
refine_target_faces: z.number().int().min(1).max(100000).default(80).describe('Charts below this face count are merge candidates.'),
refine_ad_thresh: z.number().min(1).max(10).default(1.32).describe('Max angle-distortion ratio a merge may introduce.'),
// parameterization
method: z.enum(['auto', 'lscm', 'arap', 'planar']).default('auto').describe('Per-chart flattening method.'),
arap_iters: z.number().int().min(0).max(100).default(4).describe('As-rigid-as-possible iterations (0 = LSCM/planar only).'),
// packing
resolution: z.number().int().min(64).max(8192).default(1024).describe('Atlas resolution used to size padding (px). Typical values: 256/512/1024/2048/4096/8192.'),
padding_texels: z.number().int().min(0).max(64).default(4).describe('Inter-island padding in texels.'),
// topology repair
weld: z.boolean().default(true).describe('Proximity-weld coincident verts before unwrapping (stitches shattered shells).'),
weld_tol_frac: z.number().min(0).max(1).default(0.1).describe('Weld tolerance as a fraction of median edge length.')
};
const AUTO_RETOPO_OPTIONS = {
// target
target_faces: z.number().int().min(50).max(5_000_000).default(6000).describe('Approximate face budget of the output.'),
quads: z.boolean().default(false).describe('Convert the final mesh to quad-dominant (reported in metrics; GLB stays triangulated).'),
// base generation (watertight shell)
watertight: z.boolean().default(true).describe('Build a unified voxel shell (robust to messy input) vs. remesh the surface directly (keeps open boundaries).'),
shell_resolution: z.number().int().min(16).max(1024).default(256).describe('Voxel grid cells along the longest bbox axis (watertight only).'),
shell_close_iter: z.number().int().min(0).max(20).default(1).describe('Morphological closing iterations to bridge cracks (watertight only).'),
shell_smooth: z.number().min(0).max(5).default(1.4).describe('Gaussian sigma (voxels) on the SDF; kills voxel ripple, lower = crisper (watertight only).'),
shell_taubin: z.number().int().min(0).max(100).default(10).describe('Taubin polish steps on the dense shell, 0 disables (watertight only).'),
shell_samples_per_pitch: z.number().min(1).max(8).default(2).describe('Surface sampling density; >=2 guarantees gap-free voxel coverage (watertight only).'),
max_memory_gb: z.number().min(0).max(128).default(4).describe('Auto-lower shell resolution to fit this budget, 0 disables (watertight only).'),
// clean topology (field-adaptive isotropic remeshing)
adaptive: z.boolean().default(true).describe('Curvature-adaptive density (more faces where the surface bends).'),
remesh_iters: z.number().int().min(1).max(100).default(10).describe('Isotropic remesh iterations.'),
feature_deg: z.number().min(0).max(180).default(30).describe('Crease angle preserved as a feature.'),
calibrate_passes: z.number().int().min(0).max(10).default(1).describe('Rough edge-length correction passes.'),
// hard-surface / detail preservation
preserve_features: z.boolean().default(false).describe('Hard-surface mode: keep sharp creases crisp, skip smoothing/projection.'),
feature_angle: z.number().min(0).max(180).default(25).describe('Crease angle (deg) treated as a hard edge when preserve_features is on.'),
// silhouette projection
project: z.boolean().default(true).describe('Project the remesh back onto the original surface.'),
project_iters: z.number().int().min(0).max(100).default(10).describe('Projection iterations.'),
project_clamp: z.number().min(0).max(10).default(1.5).describe('Max per-vertex move as a multiple of local edge length.'),
relax_strength: z.number().min(0).max(1).default(0.4).describe('Tangential relaxation factor per iteration.'),
// compute backend (shell stage only)
device: z.enum(['auto', 'cpu', 'cuda']).default('auto').describe("Shell-stage compute backend: 'auto' uses an NVIDIA GPU (CuPy) when available and falls back to CPU; 'cpu' forces CPU; 'cuda' forces GPU (errors if unavailable). Other stages always run on CPU."),
// misc
seed: z.number().int().min(0).default(0).describe('RNG seed for reproducibility.')
};
// Core runner shared by run_mesh_tool and the typed auto_uv_mesh/auto_retopo_mesh
// tools: load the asset, run the operation (SSE-streamed or synchronous), and
// save the result as a new version (or replace / write FBX to disk).
async function runMeshOperation(api, notifyMutation, args, extra) {
const { projectId, assetId, operation, options = {}, saveMode = 'version', name, targetFolder } = args;
const op = OPERATIONS[operation];
const reportProgress = createProgressReporter(extra);
const asset = await findProjectAsset(api, projectId, assetId);
await reportProgress(5, 100, `Loaded ${asset.name || 'mesh'} — running ${operation}`);
const assetFile = asset.filename || asset.filePath;
const meshBuffer = await api.fetchAssetBuffer(assetFile);
const form = new FormData();
const fileName = path.basename(String(assetFile)) || 'mesh.glb';
form.append('meshFile', new Blob([meshBuffer], { type: 'model/gltf-binary' }), fileName);
form.append('options', JSON.stringify(options));
let resultBuffer;
let stats;
let outFormat = 'glb';
if (op.sse) {
form.append('format', op.format || 'glb');
const done = await api.apiFormSse(op.path, form, evt => {
const frac = Number(evt?.frac);
reportProgress(
Number.isFinite(frac) ? Math.round(5 + frac * 85) : 50,
100,
evt?.message || evt?.stage || `Running ${operation}`
);
});
resultBuffer = Buffer.from(done.mesh_b64, 'base64');
stats = done.stats || null;
outFormat = done.format || op.format || 'glb';
} else {
const done = await api.apiForm('POST', op.path, form);
resultBuffer = Buffer.from(done.mesh_b64, 'base64');
stats = done.stats || null;
}
await reportProgress(92, 100, 'Saving result');
// FBX conversion is an export, not an editable asset — write it to disk.
if (operation === 'convert_fbx') {
if (!targetFolder) throw new Error('convert_fbx requires targetFolder (absolute folder to write the .fbx into).');
const exportForm = new FormData();
const fbxName = `${(name || asset.name || 'mesh').replace(/\.[^.]*$/, '')}.fbx`;
exportForm.append('folder', targetFolder);
exportForm.append('files', new Blob([resultBuffer]), fbxName);
const written = await api.apiForm('POST', '/export/mesh', exportForm);
await reportProgress(100, 100, 'FBX written');
return { operation, stats, ...written };
}
const saveForm = new FormData();
saveForm.append('assetId', String(asset.id));
saveForm.append('filePath', '');
saveForm.append('name', name || `${asset.name || 'Mesh'} (${operation.replace(/_/g, ' ')})`);
saveForm.append('saveMode', saveMode);
saveForm.append('meshFile', new Blob([resultBuffer], { type: 'model/gltf-binary' }), `mesh.${outFormat}`);
const savedAsset = await api.apiForm('POST', '/meshes/editor/save', saveForm);
notifyMutation(projectId);
await reportProgress(100, 100, 'Done');
return { operation, stats, savedAsset: withAssetUrls(api, savedAsset) };
}
export function registerMeshToolTools(server, { api, notifyMutation }) {
server.registerTool('run_mesh_tool', {
title: 'Run mesh tool',
description: 'Run a local mesh-processing tool on a project mesh asset and save the result. Operations: auto_uv (UV unwrap), auto_retopo (retopology), repair (fix non-manifold geometry), auto_rig (skeleton + skin weights via the rigging service), optimize (gltfpack simplification; options.simplify_ratio 0..1), convert_fbx (GLB→FBX via headless Blender; requires targetFolder, options.preset unity|unreal|generic). NOTE: auto_uv and auto_retopo have many parameters — prefer the dedicated auto_uv_mesh and auto_retopo_mesh tools, which document and validate every option; here their options ride along as a free-form object and unset keys fall back to service defaults. Requires the Python mesh-tools service (auto_uv/auto_retopo/repair/convert_fbx) or rigging service (auto_rig) to be running — in the desktop app start them from Settings. Results save as a new version of the asset by default.',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int().describe('Mesh asset id (from list_assets)'),
operation: z.enum(['auto_uv', 'auto_retopo', 'repair', 'auto_rig', 'optimize', 'convert_fbx']),
options: z.record(z.string(), z.any()).default({}).describe('Operation options (e.g. {simplify_ratio: 0.5} for optimize, {preset: "unity"} for convert_fbx). For auto_uv/auto_retopo see the dedicated tools for the full option list.'),
saveMode: z.enum(['version', 'replace']).default('version').describe('Save the processed mesh as a new version (default) or replace the asset file'),
name: z.string().optional().describe('Name for the saved result'),
targetFolder: z.string().optional().describe('convert_fbx only: absolute folder to write the .fbx file into')
}
}, toolHandler((args, extra) => runMeshOperation(api, notifyMutation, args, extra)));
server.registerTool('auto_uv_mesh', {
title: 'Auto UV unwrap',
description: 'UV-unwrap a project mesh asset with the Python mesh-tools service (:8200) and save the result as a new version. Every autouv.unwrap() parameter is exposed under `options` with its range and default — set the ones you need; omitted keys use the documented default. Streams progress. Requires the Python mesh-tools service running (start it from Settings in the desktop app).',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int().describe('Mesh asset id (from list_assets)'),
options: z.object(AUTO_UV_OPTIONS).default({}).describe('Auto UV unwrap parameters. Any subset may be set; unset keys use their default.'),
saveMode: z.enum(['version', 'replace']).default('version').describe('Save as a new version (default) or replace the asset file'),
name: z.string().optional().describe('Name for the saved result')
}
}, toolHandler((args, extra) => runMeshOperation(api, notifyMutation, { ...args, operation: 'auto_uv' }, extra)));
server.registerTool('auto_retopo_mesh', {
title: 'Auto retopology',
description: 'Rebuild clean topology on a project mesh asset with the Python mesh-tools service (:8200) and save the result as a new version. Every autoretopo.RetopoConfig field is exposed under `options` with its range and default — set the ones you need; omitted keys use the documented default. The shell_* options apply only when watertight=true. Streams progress. Requires the Python mesh-tools service running (start it from Settings in the desktop app).',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int().describe('Mesh asset id (from list_assets)'),
options: z.object(AUTO_RETOPO_OPTIONS).default({}).describe('Auto retopology parameters. Any subset may be set; unset keys use their default.'),
saveMode: z.enum(['version', 'replace']).default('version').describe('Save as a new version (default) or replace the asset file'),
name: z.string().optional().describe('Name for the saved result')
}
}, toolHandler((args, extra) => runMeshOperation(api, notifyMutation, { ...args, operation: 'auto_retopo' }, extra)));
server.registerTool('export_mesh', {
title: 'Export mesh file',
description: 'Copy a project mesh asset\'s file (GLB passthrough) into an absolute folder on this machine. For engine FBX exports (Unity/Unreal) use run_mesh_tool with operation "convert_fbx" instead.',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int(),
folder: z.string().min(1).describe('Absolute output folder'),
fileName: z.string().optional().describe('Output file name (defaults to the asset\'s stored file name)')
}
}, toolHandler(async ({ projectId, assetId, folder, fileName }) => {
const asset = await findProjectAsset(api, projectId, assetId);
const assetFile = asset.filename || asset.filePath;
const buffer = await api.fetchAssetBuffer(assetFile);
const form = new FormData();
form.append('folder', folder);
form.append('files', new Blob([buffer]), fileName || path.basename(String(assetFile)) || 'mesh.glb');
return api.apiForm('POST', '/export/mesh', form);
}));
}

93
mcp/tools/projects.js Normal file
View file

@ -0,0 +1,93 @@
import { z } from 'zod';
import { toolHandler } from '../client.js';
export function registerProjectTools(server, { api, notifyMutation }) {
server.registerTool('list_projects', {
title: 'List projects',
description: 'List every 3D Gen Studio project (id, name, description, preset "graph" or kanban, creation date, status).',
annotations: { readOnlyHint: true }
}, toolHandler(async () => api.apiJson('GET', '/projects')));
server.registerTool('get_project', {
title: 'Get project',
description: 'Get one project by id, including its preset (graph vs kanban board) and saved graph viewport.',
inputSchema: { projectId: z.number().int().describe('Project id') },
annotations: { readOnlyHint: true }
}, toolHandler(async ({ projectId }) => api.apiJson('GET', `/projects/${projectId}`)));
server.registerTool('create_project', {
title: 'Create project',
description: 'Create a new project. preset "graph" creates a node-graph project (Graph page); "kanban" creates a pipeline board with the fixed columns Images, Image Edit, Mesh Gen, Mesh Edit, Texturing, Rigging.',
inputSchema: {
name: z.string().min(1).describe('Project name'),
description: z.string().optional().describe('Optional project description'),
preset: z.enum(['graph', 'kanban']).default('graph').describe('Project type: node graph or kanban board')
}
}, toolHandler(async ({ name, description, preset }) => {
// The UI stores presets in title case ('Graph' / 'Kanban') and keys its
// preview images by that exact string — match it.
const project = await api.apiJson('POST', '/projects', {
body: { name, description: description || '', preset: preset === 'kanban' ? 'Kanban' : 'Graph' }
});
notifyMutation(project?.id);
return project;
}));
server.registerTool('update_project', {
title: 'Update project',
description: 'Update a project\'s name, description, or status.',
inputSchema: {
projectId: z.number().int(),
name: z.string().optional(),
description: z.string().optional(),
status: z.string().optional()
}
}, toolHandler(async ({ projectId, ...updates }) => {
const body = Object.fromEntries(Object.entries(updates).filter(([, v]) => v !== undefined));
if (Object.keys(body).length === 0) throw new Error('Provide at least one field to update (name, description, status).');
const project = await api.apiJson('PUT', `/projects/${projectId}`, { body });
notifyMutation(projectId);
return project;
}));
server.registerTool('delete_project', {
title: 'Delete project',
description: 'PERMANENTLY delete a project. Set confirm=true to proceed. With deleteAssets=true the project\'s asset files are removed from disk as well.',
inputSchema: {
projectId: z.number().int(),
confirm: z.boolean().describe('Must be true — confirms the permanent deletion'),
deleteAssets: z.boolean().default(false).describe('Also delete the project\'s asset files from disk')
},
annotations: { destructiveHint: true }
}, toolHandler(async ({ projectId, confirm, deleteAssets }) => {
if (confirm !== true) throw new Error('Refusing to delete: pass confirm=true to permanently delete this project.');
await api.apiJson('DELETE', `/projects/${projectId}`, { query: deleteAssets ? { deleteAssets: 'true' } : {} });
notifyMutation(projectId);
return { deleted: true, projectId };
}));
server.registerTool('export_project', {
title: 'Export project',
description: 'Export a project as a portable .3dgp bundle folder (manifest + all asset files) under the given absolute destination folder. Returns the created bundle path.',
inputSchema: {
projectId: z.number().int(),
folder: z.string().min(1).describe('Absolute destination folder on this machine (a subfolder named after the project is created inside it)'),
name: z.string().optional().describe('Optional bundle name override')
}
}, toolHandler(async ({ projectId, folder, name }) =>
api.apiJson('POST', `/projects/${projectId}/export`, { body: { folder, name: name || '' } })
));
server.registerTool('import_project', {
title: 'Import project',
description: 'Import a project from a previously exported bundle folder (must contain exactly one .3dgp manifest). Returns the created project.',
inputSchema: {
folder: z.string().min(1).describe('Absolute path of the exported bundle folder'),
name: z.string().optional().describe('Optional name for the imported project')
}
}, toolHandler(async ({ folder, name }) => {
const project = await api.apiJson('POST', '/projects/import', { body: { folder, name: name || '' } });
notifyMutation(project?.id);
return project;
}));
}

33
mcp/tools/settings.js Normal file
View file

@ -0,0 +1,33 @@
import { toolHandler } from '../client.js';
const SECRET_KEY_PATTERN = /(api[-_]?key|secret|token|password|credential|authorization)/i;
// Recursively replace secret-looking string values so API keys configured in
// Settings never leave the machine through an MCP client.
function redactSecrets(value) {
if (Array.isArray(value)) return value.map(redactSecrets);
if (value && typeof value === 'object') {
const out = {};
for (const [key, item] of Object.entries(value)) {
out[key] = SECRET_KEY_PATTERN.test(key) && typeof item === 'string' && item.length > 0
? '***redacted***'
: redactSecrets(item);
}
return out;
}
return value;
}
export function registerSettingsTools(server, { api }) {
server.registerTool('get_settings', {
title: 'Get settings (redacted)',
description: 'Read the app settings — which AI providers and custom APIs are configured (their ids for selectedApi), service URLs (ComfyUI, mesh tools, rigging), and preferences. All API keys and secrets are redacted.',
annotations: { readOnlyHint: true }
}, toolHandler(async () => redactSecrets(await api.apiJson('GET', '/settings'))));
server.registerTool('get_system_stats', {
title: 'Get system stats',
description: 'Live CPU, RAM, and GPU usage of the machine running 3D Gen Studio.',
annotations: { readOnlyHint: true }
}, toolHandler(async () => api.apiJson('GET', '/system/stats')));
}

305
mcp/tools/workflows.js Normal file
View file

@ -0,0 +1,305 @@
import { z } from 'zod';
import { randomUUID } from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import { toolHandler, createProgressReporter } from '../client.js';
import { attachResultsToNode, resolveNodeTarget, resolveNodeInputAssets } from '../nodeResults.js';
const FILE_PARAM_TYPES = ['image', 'mesh', 'video'];
// Strip the raw graph JSON from workflow records so list responses stay small.
function summarizeWorkflow(workflow) {
if (!workflow || typeof workflow !== 'object') return workflow;
const { workflowJson: _workflowJson, ...rest } = workflow;
return rest;
}
async function resolveWorkflowJson({ workflowJson, filePath }) {
if (workflowJson !== undefined && workflowJson !== null) {
return typeof workflowJson === 'string' ? JSON.parse(workflowJson) : workflowJson;
}
if (filePath) {
const raw = await fs.readFile(filePath, 'utf8');
const parsed = JSON.parse(raw);
// Accept both raw ComfyUI API graphs and .3dgw share bundles.
if (parsed?.type === '3dgenstudio-workflow' && parsed.workflowJson) return parsed;
return parsed;
}
throw new Error('Provide either workflowJson (the ComfyUI API-format graph) or filePath (a local .json/.3dgw file).');
}
export function registerWorkflowTools(server, { api, notifyMutation }) {
server.registerTool('list_workflows', {
title: 'List ComfyUI workflows',
description: 'List the ComfyUI workflows saved in the library, with their configured parameters (inputs the caller can set, each with id/name/valueType/defaultValue, plus enums when the parameter only accepts a fixed list of values) and output nodes.',
annotations: { readOnlyHint: true }
}, toolHandler(async () => {
const workflows = await api.apiJson('GET', '/library/comfy-workflows');
return (Array.isArray(workflows) ? workflows : []).map(summarizeWorkflow);
}));
server.registerTool('inspect_workflow', {
title: 'Inspect ComfyUI workflow JSON',
description: 'Parse a ComfyUI workflow graph (API format) without saving it. Returns candidate inputs (every literal node input, id "{nodeId}.{inputKey}") and terminal output nodes — use these to choose parameters/outputs for import_workflow. Accepts inline JSON or a local file path (.json or .3dgw share bundle).',
inputSchema: {
workflowJson: z.any().optional().describe('ComfyUI API-format graph JSON (object or string)'),
filePath: z.string().optional().describe('Absolute path to a local workflow .json or .3dgw file')
},
annotations: { readOnlyHint: true }
}, toolHandler(async (args) => {
const resolved = await resolveWorkflowJson(args);
const graph = resolved?.type === '3dgenstudio-workflow' ? resolved.workflowJson : resolved;
const parsed = await api.apiJson('POST', '/library/comfy-workflows/inspect', { body: { workflowJson: graph } });
if (resolved?.type === '3dgenstudio-workflow') {
parsed.bundledConfiguration = { parameters: resolved.parameters || [], outputs: resolved.outputs || [] };
}
return parsed;
}));
server.registerTool('import_workflow', {
title: 'Import ComfyUI workflow',
description: 'Save a ComfyUI workflow into the library. parameters selects which inspected inputs become runtime parameters ({id, name?, valueType?: image|mesh|video|string|number|boolean, enums?: allowed values for a string/number parameter}); outputs selects which terminal nodes\' results are saved ({nodeId, name?}). At least one output is required. When importing a .3dgw share bundle via filePath, the bundled parameter/output configuration is used automatically unless overridden.',
inputSchema: {
name: z.string().min(1).describe('Workflow name in the library'),
workflowJson: z.any().optional().describe('ComfyUI API-format graph JSON (object or string)'),
filePath: z.string().optional().describe('Absolute path to a local workflow .json or .3dgw file'),
parameters: z.array(z.object({
id: z.string(),
name: z.string().optional(),
valueType: z.string().optional(),
enums: z.array(z.union([z.string(), z.number()])).optional()
.describe('Allowed values for a string/number parameter — the app renders it as a dropdown limited to this list. Ignored for other value types.')
})).optional().describe('Inputs to expose as parameters (ids from inspect_workflow)'),
outputs: z.array(z.object({
nodeId: z.string(),
name: z.string().optional(),
valueType: z.string().optional()
})).optional().describe('Output nodes to save results from (nodeIds from inspect_workflow)')
}
}, toolHandler(async ({ name, parameters, outputs, ...source }) => {
const resolved = await resolveWorkflowJson(source);
const isBundle = resolved?.type === '3dgenstudio-workflow';
const graph = isBundle ? resolved.workflowJson : resolved;
const effectiveParameters = parameters ?? (isBundle ? resolved.parameters : undefined) ?? [];
const effectiveOutputs = outputs ?? (isBundle ? resolved.outputs : undefined) ?? [];
const workflow = await api.apiJson('POST', '/library/comfy-workflows', {
body: { name, workflowJson: graph, parameters: effectiveParameters, outputs: effectiveOutputs }
});
notifyMutation(null);
return summarizeWorkflow(workflow);
}));
server.registerTool('update_workflow', {
title: 'Update ComfyUI workflow',
description: 'Update a saved workflow: rename it, change its parameter/output selection (including parameter default values), or replace the graph JSON.',
inputSchema: {
workflowId: z.number().int(),
name: z.string().optional(),
parameters: z.array(z.record(z.string(), z.any())).optional(),
outputs: z.array(z.record(z.string(), z.any())).optional(),
workflowJson: z.any().optional()
}
}, toolHandler(async ({ workflowId, ...updates }) => {
const body = Object.fromEntries(Object.entries(updates).filter(([, v]) => v !== undefined));
const workflow = await api.apiJson('PUT', `/library/comfy-workflows/${workflowId}`, { body });
notifyMutation(null);
return summarizeWorkflow(workflow);
}));
server.registerTool('run_workflow', {
title: 'Run ComfyUI workflow',
description: 'Execute a saved ComfyUI workflow and wait for the generated assets (streams MCP progress notifications). inputs maps parameter id -> value; for image/mesh parameters pass a project asset id (number) as the value, or use fileInputs to upload a local file. IMPORTANT for graph projects: pass nodeId (a graph node from get_graph/create_node) so the results are displayed on that node — the first result becomes the node\'s asset, additional results become new nodes stacked below it. nodeId is the ONLY way to fill a graph node; cardId is for kanban cards. (If you pass a graph node id as cardId it is auto-attached to that node, not turned into a card.) Wiring: the target node\'s connected input assets automatically fill the workflow\'s image/mesh parameters (matched by type), so you normally do NOT set inputs for file parameters — just connect_nodes to wire the source image/mesh, then run with nodeId. Only pass inputs for file parameters to override a wired input or when the node has no connection. Requires ComfyUI to be running (configured in Settings). On timeout returns {status:"running", promptId} — poll with get_run_status.',
inputSchema: {
workflowId: z.number().int().describe('Saved workflow id (from list_workflows)'),
projectId: z.number().int().optional().describe('Project to attach results to (required unless persistGeneratedAssets=false)'),
inputs: z.record(z.string(), z.any()).default({}).describe('Parameter id -> value. For an image/mesh parameter pass the asset\'s numeric id (from list_assets / a generation result) — this is ALL you need. The SAME plain id works for a root asset, an edit, or a version (e.g. a background-removed image is an edit — pass that edit\'s own id). Do NOT pass a file path/filename, and do NOT pass a {assetId, editId} object — a bare number is correct. Non-file parameters take their literal value (string/number/boolean).'),
fileInputs: z.record(z.string(), z.string()).optional().describe('Parameter id -> absolute local file path to upload for image/mesh/video parameters'),
nodeId: z.number().int().optional().describe('Graph node to attach the results to (graph projects) — the correct way to fill a node; without it the generated assets are saved but no node displays them'),
cardId: z.union([z.number().int(), z.string()]).optional().describe('Existing KANBAN card to attach the run to (kanban projects). For graph nodes use nodeId — a graph node id passed here is auto-routed to that node'),
name: z.string().optional().describe('Name for the generated asset(s)'),
parentAssetId: z.number().int().optional().describe('Save results under this asset: a mesh output becomes a version of it, an image output an edit of it (the parent must match the output type, else a new root asset is created). USUALLY LEAVE UNSET — it is inferred automatically from the source the output was derived from: the workflow file (image/mesh) input matching the output type, whether that input came from the target node\'s wiring or was passed in `inputs`. Set this only to override that inference (e.g. attach to a different asset).'),
persistProcessingCard: z.boolean().optional(),
persistGeneratedAssets: z.boolean().optional(),
timeoutSeconds: z.number().int().min(5).max(3600).default(600)
}
}, toolHandler(async (args, extra) => {
const {
workflowId, projectId, inputs = {}, fileInputs, nodeId, cardId, name,
parentAssetId, persistProcessingCard, persistGeneratedAssets, timeoutSeconds = 600
} = args;
const reportProgress = createProgressReporter(extra);
const promptId = randomUUID();
// Route a graph-node target to the node (via nodeId), even if the caller
// passed the node id as cardId. targetNodeId gets the result attached;
// kanbanCardId is only forwarded to the server when it's a real kanban card.
const { nodeId: targetNodeId, cardId: kanbanCardId } = await resolveNodeTarget(api, projectId, { nodeId, cardId });
// Mirror the GraphPage: use what the target node is wired to. Its connected
// input assets fill the workflow's image/mesh parameters (by matching type) so
// the caller doesn't have to hand-map parameter ids, and — when the caller
// didn't pin one — set the parent so the output is saved as an edit of a
// connected image / a version of a connected mesh (parent matches output type).
const nodeInputAssets = (targetNodeId && projectId)
? await resolveNodeInputAssets(api, projectId, targetNodeId)
: [];
// Fetch the workflow definition to know its file parameters and output type.
const workflowDef = (await api.apiJson('GET', '/library/comfy-workflows').catch(() => []))
.find?.(item => Number(item?.id) === Number(workflowId)) || null;
const fileParams = (workflowDef?.parameters || [])
.map(parameter => ({ id: parameter.id, type: String(parameter.valueType || '').toLowerCase() }))
.filter(parameter => FILE_PARAM_TYPES.includes(parameter.type));
// Auto-fill each unset image/mesh/video parameter from a connected input of
// the matching type (each connected asset used at most once). Explicit `inputs`
// and `fileInputs` always win over an auto-filled value.
const autoInputs = {};
if (nodeInputAssets.length > 0 && fileParams.length > 0) {
const available = nodeInputAssets.map(asset => ({ ...asset, used: false }));
for (const parameter of fileParams) {
const explicitlySet = (inputs[parameter.id] !== undefined && inputs[parameter.id] !== null)
|| (fileInputs && fileInputs[parameter.id]);
if (explicitlySet) continue;
const match = available.find(asset => !asset.used && asset.type === parameter.type);
if (match) {
autoInputs[parameter.id] = `asset:${match.assetId}`;
match.used = true;
}
}
}
// Unless the caller pinned a parent, let the server save the output under the
// source it was derived from: it matches each output to a resolved image/mesh
// input of the same type (from wiring or `inputs`) — an image output becomes an
// edit of its source image, a mesh output a version of its source mesh. This
// means a caller that reuses a source asset as an input doesn't have to remember
// parentAssetId (works for kanban too, where there is no node wiring). The server
// knows the true output type, so this is robust even when the workflow's declared
// output type is missing/wrong. Pass parentAssetId to override.
const autoParentFromInputs = (parentAssetId === undefined || parentAssetId === null);
// Subscribe to the single-job progress stream BEFORE submitting so the
// terminal event can't be missed (the endpoint also replays the latest
// snapshot on connect).
let resolveTerminal;
const terminalPromise = new Promise(resolve => { resolveTerminal = resolve; });
const subscription = api.subscribeSse(`/comfyui/workflows/progress/${promptId}`, payload => {
if (String(payload?.promptId || '') !== promptId) return;
if (payload?.status === 'error' || payload?.done) {
resolveTerminal(payload);
return;
}
const percent = Number(payload?.progressPercent);
reportProgress(
Number.isFinite(percent) ? percent : 0,
100,
[payload?.detail, payload?.currentNodeLabel].filter(Boolean).join(' — ') || 'Running ComfyUI workflow'
);
}, {
onEnd: err => resolveTerminal({ status: 'error', detail: `Progress stream ended unexpectedly: ${err?.message || err}` })
});
let timer = null;
try {
const form = new FormData();
if (projectId !== undefined && projectId !== null) form.append('projectId', String(projectId));
form.append('workflowId', String(workflowId));
form.append('promptId', promptId);
if (kanbanCardId !== undefined && kanbanCardId !== null) form.append('cardId', String(kanbanCardId));
if (name) form.append('name', name);
if (parentAssetId !== undefined && parentAssetId !== null) {
form.append('parentAssetId', String(parentAssetId));
} else if (autoParentFromInputs) {
form.append('autoParentFromInputs', 'true');
}
if (persistProcessingCard === false) form.append('persistProcessingCard', 'false');
if (persistGeneratedAssets === false) form.append('persistGeneratedAssets', 'false');
const inputValues = { ...autoInputs, ...inputs };
for (const [key, localPath] of Object.entries(fileInputs || {})) {
const fieldName = `comfyFile:${key}`;
const buffer = await fs.readFile(localPath);
form.append(fieldName, new Blob([buffer]), path.basename(localPath));
inputValues[key] = { __fileField: fieldName };
}
form.append('inputValues', JSON.stringify(inputValues));
await api.apiForm('POST', '/comfyui/workflows/run', form);
await reportProgress(0, 100, 'Workflow queued in ComfyUI');
const outcome = await Promise.race([
terminalPromise,
new Promise(resolve => { timer = setTimeout(() => resolve({ __timeout: true }), timeoutSeconds * 1000); })
]);
if (outcome.__timeout) {
return {
status: 'running',
promptId,
note: `Still running after ${timeoutSeconds}s. The workflow continues in the background — call get_run_status with this promptId to check on it; results are attached to the project when it finishes.`
};
}
if (outcome.status === 'error') {
throw new Error(outcome.detail || outcome.error || 'ComfyUI workflow failed');
}
await reportProgress(100, 100, 'Workflow completed');
const result = outcome.result;
const assets = Array.isArray(result) ? result : (result ? [result] : []);
// Graph projects: display the results on the target node (mirrors what
// the GraphPage does after a run — without this the assets exist but no
// node shows them).
let nodeAttachment = null;
if (targetNodeId && projectId) {
nodeAttachment = await attachResultsToNode(api, {
projectId,
nodeId: targetNodeId,
assets,
metadata: { lastAction: 'comfy-workflow', promptId }
});
notifyMutation(projectId);
}
return {
status: 'completed',
promptId,
assets,
...(nodeAttachment ? { nodeAttachment } : {})
};
} finally {
if (timer) clearTimeout(timer);
subscription.close();
}
}));
server.registerTool('get_run_status', {
title: 'Get workflow run status',
description: 'Check on a ComfyUI workflow run by promptId (returned by run_workflow). Returns the latest progress snapshot: status (processing/completed/error), progressPercent, detail, and the generated assets once done.',
inputSchema: {
promptId: z.string().min(1)
},
annotations: { readOnlyHint: true }
}, toolHandler(async ({ promptId }) => {
// The single-job stream replays the latest snapshot immediately on
// connect; grab it and close. No snapshot within 3s means the server no
// longer tracks this prompt (finished >60s ago, or never existed).
const snapshot = await new Promise(resolve => {
const timer = setTimeout(() => { subscription.close(); resolve(null); }, 3000);
const subscription = api.subscribeSse(`/comfyui/workflows/progress/${encodeURIComponent(promptId)}`, payload => {
clearTimeout(timer);
subscription.close();
resolve(payload);
}, { onEnd: () => { clearTimeout(timer); resolve(null); } });
});
if (!snapshot) {
return {
status: 'unknown',
promptId,
note: 'No progress snapshot for this promptId. The run either finished more than a minute ago (check the project\'s assets with list_assets) or was never started.'
};
}
return snapshot;
}));
}

2702
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,7 @@
{
"name": "app",
"private": true,
"version": "1.3.3",
"version": "2.1.2",
"type": "module",
"main": "electron/main.cjs",
"description": "AI-powered 3D mesh production studio — image generation, mesh generation, UV unwrapping, and texturing pipelines.",
@ -18,6 +18,7 @@
"serve": "vite build && node server.js",
"lint": "eslint .",
"preview": "vite preview",
"mcp:stdio": "node mcp/stdio.js",
"electron:dev": "npm run build && electron .",
"dist": "npm run build && electron-builder",
"dist:win": "npm run build && electron-builder --win",
@ -26,6 +27,8 @@
"dist:dir": "npm run build && electron-builder --dir"
},
"dependencies": {
"@excalidraw/excalidraw": "^0.18.1",
"@modelcontextprotocol/sdk": "^1.29.0",
"@react-three/drei": "^10.7.7",
"@react-three/fiber": "^9.5.0",
"@types/three": "^0.183.1",
@ -49,19 +52,21 @@
"tencentcloud-sdk-nodejs-intl-en": "^3.0.1352",
"three": "^0.183.2",
"three-bvh-csg": "^0.0.18",
"three-mesh-bvh": "^0.9.9"
"three-mesh-bvh": "^0.9.9",
"ws": "^8.21.0",
"zod": "^4.4.3"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"electron": "^33.2.0",
"electron-builder": "^25.1.8",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.4.0",
"vite": "^8.0.4",
"electron": "^33.2.0",
"electron-builder": "^25.1.8"
"vite": "^8.0.4"
}
}

View file

@ -0,0 +1 @@
3.13

View file

@ -39,6 +39,14 @@ ALLOWED_ORIGINS: list[str] = [
# Upload guard rails.
MAX_UPLOAD_BYTES: int = _env_int("MESHTOOLS_MAX_UPLOAD_BYTES", 512 * 1024 * 1024)
# GLB -> FBX conversion (headless Blender subprocess). Generous default: bpy
# import alone takes seconds and heavy scenes bake many animation takes.
CONVERT_TIMEOUT_S: int = _env_int("MESHTOOLS_CONVERT_TIMEOUT", 600)
# Thumbnail render (headless Blender subprocess). Shorter than convert: a single
# low-sample Cycles-CPU render of one frame after the bpy import (~seconds).
THUMBNAIL_TIMEOUT_S: int = _env_int("MESHTOOLS_THUMBNAIL_TIMEOUT", 180)
# Scratch space for temp files when a tool needs real paths on disk
# (many mesh CLIs/libraries only accept file paths, not in-memory buffers).
WORK_DIR: Path = Path(

View file

@ -1,6 +1,6 @@
"""Mesh-processing endpoints: Auto UV and Auto Retopo.
"""Mesh-processing endpoints: Auto UV, Auto Retopo, Repair and FBX Convert.
Contract (shared by both routes):
Contract (shared by all routes):
Request : multipart/form-data
- meshFile : the mesh to process (GLB/OBJ/PLY/STL)
- options : JSON string of the operation options (optional)
@ -24,14 +24,17 @@ import queue
import threading
from fastapi import APIRouter, File, Form, HTTPException, UploadFile
from fastapi.concurrency import run_in_threadpool
from fastapi.responses import StreamingResponse
from pydantic import ValidationError
from ..config import MAX_UPLOAD_BYTES
from ..meshio import export_mesh, load_mesh, mesh_stats
from ..schemas import AutoRetopoOptions, AutoUvOptions, RepairOptions
from ..schemas import AutoRetopoOptions, AutoUvOptions, ConvertOptions, RepairOptions
from ..services.auto_retopo import run_auto_retopo
from ..services.auto_uv import run_auto_uv
from ..services.convert_fbx import run_convert_fbx
from ..services.mesh_thumbnail import render_mesh_thumbnail
from ..services.repair import run_repair
router = APIRouter(prefix="/meshes", tags=["meshes"])
@ -86,11 +89,13 @@ def _sse(obj: dict) -> str:
return f"data: {json.dumps(obj, separators=(',', ':'))}\n\n"
def _stream_tool(run_callable, fmt: str, label: str) -> StreamingResponse:
def _stream_payload(run_callable, label: str) -> StreamingResponse:
"""Run `run_callable(emit)` in a worker thread and stream SSE progress events.
`run_callable(emit)` must return (mesh, tool_stats, preview_png) and may call
emit(stage, frac, message) to report progress.
`run_callable(emit)` must return the terminal `done` payload dict and may
call emit(stage, frac, message) to report progress. Use this directly for
tools that build their own envelope (e.g. FBX conversion, which must never
round-trip through trimesh); use `_stream_tool` for trimesh-based tools.
"""
events: "queue.Queue" = queue.Queue()
holder: dict = {}
@ -100,8 +105,7 @@ def _stream_tool(run_callable, fmt: str, label: str) -> StreamingResponse:
def worker():
try:
mesh, tool_stats, preview = run_callable(emit)
holder["payload"] = _envelope(mesh, fmt, tool_stats, preview)
holder["payload"] = run_callable(emit)
except Exception as exc: # noqa: BLE001 — surfaced to the client as an error event
holder["error"] = f"{label} failed: {exc}"
finally:
@ -132,6 +136,17 @@ def _stream_tool(run_callable, fmt: str, label: str) -> StreamingResponse:
return StreamingResponse(generate(), media_type="text/event-stream", headers=_SSE_HEADERS)
def _stream_tool(run_callable, fmt: str, label: str) -> StreamingResponse:
"""`_stream_payload` for trimesh-based tools: `run_callable(emit)` returns
(mesh, tool_stats, preview_png) and the envelope is built here.
"""
def run(emit):
mesh, tool_stats, preview = run_callable(emit)
return _envelope(mesh, fmt, tool_stats, preview)
return _stream_payload(run, label)
@router.post("/auto-uv")
async def auto_uv(
meshFile: UploadFile = File(...),
@ -166,3 +181,56 @@ async def repair(
data = await _read_upload(meshFile)
mesh = load_mesh(data, meshFile.filename or "mesh.glb")
return _stream_tool(lambda emit: run_repair(mesh, opts, progress=emit), format, "Repair")
@router.post("/convert")
async def convert(
meshFile: UploadFile = File(...),
options: str | None = Form(None),
format: str = Form("fbx"),
) -> StreamingResponse:
"""GLB -> FBX engine export (headless Blender subprocess).
Deliberately bypasses trimesh (`load_mesh`/`_envelope`): trimesh cannot
write FBX and flattens skinned meshes, and this endpoint's whole point is
preserving the skeleton + animation takes. The GLB bytes go to the worker
untouched.
"""
opts = _parse_options(options, ConvertOptions)
data = await _read_upload(meshFile)
if (format or "fbx").lstrip(".").lower() != "fbx":
raise HTTPException(status_code=400, detail="Only 'fbx' output is supported by /meshes/convert.")
def run(emit):
fbx_bytes, tool_stats = run_convert_fbx(data, opts, progress=emit)
return {
"format": "fbx",
"mesh_b64": base64.b64encode(fbx_bytes).decode("ascii"),
"stats": {
"vertex_count": tool_stats.get("vertices"),
"face_count": None,
"has_uv": bool(tool_stats.get("has_uv")),
"tool": tool_stats,
},
"preview_b64": None,
}
return _stream_payload(run, "Convert to FBX")
@router.post("/thumbnail")
async def thumbnail(meshFile: UploadFile = File(...)) -> dict:
"""Render a GLB to a 512x512 PNG thumbnail (headless Blender subprocess).
Single-artifact endpoint (no SSE): returns plain JSON with the PNG base64 in
`preview_b64`. Used by the Node backend to give server-side-generated meshes
(ComfyUI / external-API, driven over MCP) a thumbnail — those never get the
browser's WebGL render. The render runs in a threadpool so the bpy subprocess
does not block the event loop.
"""
data = await _read_upload(meshFile)
try:
png = await run_in_threadpool(render_mesh_thumbnail, data)
except Exception as exc: # noqa: BLE001 — surface as a clean HTTP error
raise HTTPException(status_code=500, detail=f"Thumbnail render failed: {exc}") from exc
return {"preview_b64": base64.b64encode(png).decode("ascii")}

View file

@ -132,6 +132,28 @@ class RepairOptions(BaseModel):
description="Weld coincident vertices by position before repairing (matches the editor's check).")
class ConvertOptions(BaseModel):
"""Options for the GLB -> FBX engine-export endpoint (headless Blender).
Presets tune the FBX for the target engine's import pipeline; see
app/tools/fbx_worker.py for the exact exporter settings each one maps to.
"""
preset: Literal["unity", "unreal", "generic"] = Field(
default="generic",
description="Target engine. 'unity'/'generic' write a meters file with "
"scale-1 transforms; 'unreal' bakes the scene to centimeters.")
unreal_scale_mode: Literal["bake", "units"] = Field(
default="bake",
description="Unreal only. 'bake' rescales mesh/armature/animation data "
"x100 to native centimeters; 'units' keeps meters and relies "
"on UE's 'Convert Scene Unit' import option.")
bake_fps: int = Field(default=30, ge=1, le=120,
description="Frame rate animation takes are baked at.")
anim_simplify: float = Field(default=1.0, ge=0.0, le=10.0,
description="Baked curve simplification (0 = lossless, larger = smaller files).")
class MeshStats(BaseModel):
"""Reported back to the caller (also surfaced via response headers)."""

View file

@ -0,0 +1,116 @@
"""GLB -> FBX conversion — subprocess driver for app/tools/fbx_worker.py.
The worker owns the actual Blender (bpy) work; this module only provisions a
job directory, spawns the worker with the venv's own interpreter, relays its
sentinel-prefixed progress lines, and returns the FBX bytes + stats.
bpy stays OUT of this process on purpose: it is not thread-safe, keeps ~1GB RSS
once imported, and a Blender crash must not take the API down. Conversions are
serialized with a semaphore for the same reason (each subprocess peaks 1-2GB).
"""
from __future__ import annotations
import json
import os
import shutil
import subprocess
import sys
import threading
from pathlib import Path
from uuid import uuid4
from ..config import CONVERT_TIMEOUT_S, WORK_DIR
from ..schemas import ConvertOptions
SENTINEL = "GENSTUDIO_EVT " # keep in sync with app/tools/fbx_worker.py
_WORKER = Path(__file__).resolve().parents[1] / "tools" / "fbx_worker.py"
_convert_lock = threading.Semaphore(1)
def run_convert_fbx(glb_bytes: bytes, opts: ConvertOptions, progress) -> tuple[bytes, dict]:
"""Convert a GLB to FBX. Returns (fbx_bytes, worker_stats); raises on failure.
`progress(stage, frac, message)` is called for each worker progress event.
"""
job_dir = WORK_DIR / f"convert-{uuid4().hex}"
job_dir.mkdir(parents=True)
try:
in_path = job_dir / "input.glb"
in_path.write_bytes(glb_bytes)
out_path = job_dir / "output.fbx"
opt_path = job_dir / "options.json"
opt_path.write_text(opts.model_dump_json(), encoding="utf-8")
with _convert_lock:
result = _run_worker(in_path, out_path, opt_path, progress)
if not result.get("ok"):
raise RuntimeError(result.get("error") or "FBX conversion failed.")
if not out_path.exists():
raise RuntimeError("FBX worker reported success but produced no output file.")
return out_path.read_bytes(), result.get("stats") or {}
finally:
shutil.rmtree(job_dir, ignore_errors=True)
def _run_worker(in_path: Path, out_path: Path, opt_path: Path, progress) -> dict:
proc = subprocess.Popen(
[
sys.executable,
str(_WORKER),
"--input", str(in_path),
"--output", str(out_path),
"--options", str(opt_path),
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
env={**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"},
)
# Watchdog instead of a read timeout: the stdout iteration below ends when
# the process dies, so killing it on expiry unblocks the loop too.
timed_out = threading.Event()
def _expire():
timed_out.set()
proc.kill()
watchdog = threading.Timer(CONVERT_TIMEOUT_S, _expire)
watchdog.daemon = True
watchdog.start()
result: dict | None = None
tail: list[str] = [] # last non-protocol lines, for error context
try:
for line in proc.stdout:
if not line.startswith(SENTINEL):
stripped = line.strip()
if stripped:
tail.append(stripped)
del tail[:-8]
continue
try:
event = json.loads(line[len(SENTINEL):])
except json.JSONDecodeError:
continue
if event.get("type") == "progress":
progress(event.get("stage", "convert"), event.get("frac", 0.0), event.get("message", ""))
elif event.get("type") == "result":
result = event
code = proc.wait()
finally:
watchdog.cancel()
if proc.poll() is None:
proc.kill()
if timed_out.is_set():
raise RuntimeError(f"FBX conversion timed out after {CONVERT_TIMEOUT_S}s.")
if result is None:
detail = f" Last output: {' | '.join(tail)}" if tail else ""
raise RuntimeError(f"FBX worker exited (code {code}) without a result.{detail}")
return result

View file

@ -0,0 +1,108 @@
"""GLB -> PNG thumbnail — subprocess driver for app/tools/thumbnail_worker.py.
The worker owns the actual Blender (bpy) render; this module only provisions a
job directory, spawns the worker with the venv's own interpreter, and returns
the PNG bytes.
bpy stays OUT of this process on purpose: it is not thread-safe, keeps ~1GB RSS
once imported, and a Blender crash must not take the API down. Renders are
serialized with a semaphore for the same reason (each subprocess peaks ~1-2GB).
"""
from __future__ import annotations
import json
import os
import shutil
import subprocess
import sys
import threading
from pathlib import Path
from uuid import uuid4
from ..config import THUMBNAIL_TIMEOUT_S, WORK_DIR
SENTINEL = "GENSTUDIO_EVT " # keep in sync with app/tools/thumbnail_worker.py
_WORKER = Path(__file__).resolve().parents[1] / "tools" / "thumbnail_worker.py"
_render_lock = threading.Semaphore(1)
def render_mesh_thumbnail(glb_bytes: bytes) -> bytes:
"""Render a GLB to a 512x512 PNG thumbnail. Returns the PNG bytes; raises on
failure."""
job_dir = WORK_DIR / f"thumb-{uuid4().hex}"
job_dir.mkdir(parents=True)
try:
in_path = job_dir / "input.glb"
in_path.write_bytes(glb_bytes)
out_path = job_dir / "output.png"
with _render_lock:
result = _run_worker(in_path, out_path)
if not result.get("ok"):
raise RuntimeError(result.get("error") or "Thumbnail render failed.")
if not out_path.exists():
raise RuntimeError("Thumbnail worker reported success but produced no output file.")
return out_path.read_bytes()
finally:
shutil.rmtree(job_dir, ignore_errors=True)
def _run_worker(in_path: Path, out_path: Path) -> dict:
proc = subprocess.Popen(
[
sys.executable,
str(_WORKER),
"--input", str(in_path),
"--output", str(out_path),
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
env={**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"},
)
# Watchdog instead of a read timeout: the stdout iteration below ends when
# the process dies, so killing it on expiry unblocks the loop too.
timed_out = threading.Event()
def _expire():
timed_out.set()
proc.kill()
watchdog = threading.Timer(THUMBNAIL_TIMEOUT_S, _expire)
watchdog.daemon = True
watchdog.start()
result: dict | None = None
tail: list[str] = [] # last non-protocol lines, for error context
try:
for line in proc.stdout:
if not line.startswith(SENTINEL):
stripped = line.strip()
if stripped:
tail.append(stripped)
del tail[:-8]
continue
try:
event = json.loads(line[len(SENTINEL):])
except json.JSONDecodeError:
continue
if event.get("type") == "result":
result = event
code = proc.wait()
finally:
watchdog.cancel()
if proc.poll() is None:
proc.kill()
if timed_out.is_set():
raise RuntimeError(f"Thumbnail render timed out after {THUMBNAIL_TIMEOUT_S}s.")
if result is None:
detail = f" Last output: {' | '.join(tail)}" if tail else ""
raise RuntimeError(f"Thumbnail worker exited (code {code}) without a result.{detail}")
return result

View file

@ -0,0 +1,5 @@
"""Standalone worker scripts run as subprocesses by app/services wrappers.
Nothing in here should be imported by the FastAPI process — workers may pull in
heavy/unsafe-in-process dependencies (bpy is not thread-safe and never unloads).
"""

View file

@ -0,0 +1,318 @@
"""GLB -> FBX conversion worker (headless Blender).
Runs `bpy` in ISOLATION: invoked as a subprocess by app/services/convert_fbx.py
(`python fbx_worker.py --input in.glb --output out.fbx --options opts.json`).
Never import this module from the service — bpy is not thread-safe, holds ~1GB
RSS once imported, and a crash inside Blender must not take the API down.
Presets tailor the FBX for the target engine:
- unity : file declared in meters with clean scale-1 transforms
(FBX_SCALE_UNITS -> Unity "File Scale" = 1).
- unreal : the scene is baked to centimeters (x100 on mesh/armature data and
every location F-curve) and written with FBX_SCALE_NONE, so UE
imports at the right size with unit bone scales — no reliance on
the "Convert Scene Unit" import option.
- generic : same neutral meters export as unity (most interoperable).
Every glTF animation arrives as an NLA track (that is how Blender's importer
stashes clips); the exporter turns each NLA strip into a separate FBX take, so
engines see one clip per animation.
Protocol: progress/result JSON lines on stdout prefixed with GENSTUDIO_EVT
(bpy prints its own "Info:" noise, the parent ignores non-matching lines).
Exit codes: 0 ok, 2 conversion error, 3 validation failed, 4 bpy missing.
"""
from __future__ import annotations
import argparse
import json
import sys
SENTINEL = "GENSTUDIO_EVT " # keep in sync with app/services/convert_fbx.py
# Shared exporter settings. Axis conversion stays on the export matrix
# (use_space_transform) instead of being baked into vertices:
# bake_space_transform=True is unsafe with skinned meshes — it transforms mesh
# data but not armature/bone animation consistently. The compensating root
# rotation it avoids is absorbed by Unity/Unreal importers anyway.
COMMON_FBX = dict(
check_existing=False,
use_selection=False,
object_types={"ARMATURE", "MESH"},
use_mesh_modifiers=True,
mesh_smooth_type="FACE",
use_tspace=False, # tangent export fails on generated/disconnected UVs
add_leaf_bones=False, # leaf bones pollute Unity/UE skeletons
primary_bone_axis="Y",
secondary_bone_axis="X",
use_armature_deform_only=True,
armature_nodetype="NULL",
bake_anim=True,
bake_anim_use_all_bones=True,
bake_anim_use_nla_strips=True, # one take per clip (NLA-stashed by the importer)
bake_anim_use_all_actions=False, # True would cross-product junk takes
bake_anim_force_startend_keying=True,
bake_anim_step=1.0,
path_mode="COPY",
embed_textures=True,
axis_forward="-Z",
axis_up="Y",
use_space_transform=True,
bake_space_transform=False,
)
METER_SCALE_FBX = dict( # unity + generic
apply_unit_scale=True,
apply_scale_options="FBX_SCALE_UNITS",
global_scale=1.0,
)
CM_BAKED_FBX = dict( # unreal, after the x100 bake
apply_unit_scale=False,
apply_scale_options="FBX_SCALE_NONE",
global_scale=1.0,
)
def emit(obj: dict) -> None:
sys.stdout.write(SENTINEL + json.dumps(obj, separators=(",", ":")) + "\n")
sys.stdout.flush()
def progress(stage: str, frac: float, message: str = "") -> None:
emit({"type": "progress", "stage": stage, "frac": round(float(frac), 4), "message": message})
def fail(error: str, code: int) -> None:
emit({"type": "result", "ok": False, "error": error})
sys.exit(code)
def normalize_nla(objects) -> list[str]:
"""Make the exporter's take collection deterministic.
The FBX exporter only bakes UNMUTED NLA strips, and depending on the
Blender version the glTF importer may leave the last clip as a dangling
active action instead of a stashed track. Unmute everything, stash any
dangling active action as its own track, and clear active actions so no
clip layers on top of the strip bakes. Returns the clip (strip) names.
"""
clip_names: list[str] = []
for obj in objects:
ad = obj.animation_data
if not ad:
continue
for track in ad.nla_tracks:
track.mute = False
clip_names.extend(strip.name for strip in track.strips)
action = ad.action
if action is not None:
in_nla = any(
strip.action == action
for track in ad.nla_tracks
for strip in track.strips
)
if not in_nla:
track = ad.nla_tracks.new()
track.name = action.name
track.strips.new(action.name, int(action.frame_range[0]), action)
clip_names.append(action.name)
ad.action = None
# A clip animating several objects appears once per object — dedupe, keep order.
return list(dict.fromkeys(clip_names))
def collect_stats(objects, clip_names) -> dict:
import bpy
armatures = [o for o in objects if o.type == "ARMATURE"]
meshes = [o for o in objects if o.type == "MESH"]
seen_mesh_data = {m.data for m in meshes}
return {
"armature_count": len(armatures),
"bones": sum(len(a.data.bones) for a in armatures),
"meshes": len(meshes),
"vertices": sum(len(d.vertices) for d in seen_mesh_data),
"materials": len([m for m in bpy.data.materials if m.users]),
"has_uv": any(d.uv_layers for d in seen_mesh_data),
"clips": clip_names,
}
def bake_unreal_scale(objects, factor: float = 100.0) -> None:
"""Bake the scene from meters to centimeters at the DATA level.
Data-level transforms (Mesh.transform / Armature.transform) avoid the
operator selection/context dance that transform_apply needs headless, and
sidestep its child parent-inverse compensation (which would leave mesh data
small behind a scale-100 node — exactly the transform FBX must not carry).
Skinning stays consistent because in Blender the armature rest pose IS the
bind pose: scaling mesh and rest bones by the same factor preserves it.
"""
import bpy
from mathutils import Matrix
scale = Matrix.Scale(factor, 4)
seen_data = set()
for obj in objects:
if obj.type in {"MESH", "ARMATURE"} and obj.data not in seen_data:
seen_data.add(obj.data)
obj.data.transform(scale)
obj.location = [component * factor for component in obj.location]
parent_inverse = obj.matrix_parent_inverse.copy()
parent_inverse.translation *= factor
obj.matrix_parent_inverse = parent_inverse
# Object/data transforms do not touch animation: location F-curves (object
# and pose-bone hip/root-motion translation) are in now-x100 local units.
for action in bpy.data.actions:
for fcurve in _action_fcurves(action):
if fcurve.data_path == "location" or fcurve.data_path.endswith(".location"):
for key in fcurve.keyframe_points:
key.co.y *= factor
key.handle_left.y *= factor
key.handle_right.y *= factor
def _action_fcurves(action):
"""All F-curves of an action across bpy versions: Blender 5.x replaced the
flat Action.fcurves with slotted actions (layers > strips > channelbags)."""
fcurves = getattr(action, "fcurves", None)
if fcurves is not None:
return list(fcurves)
return [
fcurve
for layer in action.layers
for strip in layer.strips
if strip.type == "KEYFRAME"
for channelbag in strip.channelbags
for fcurve in channelbag.fcurves
]
def _remove_bone_widget_objects() -> None:
"""Delete bone display-widget objects (pose bones' custom shapes).
Belt and braces on top of bone_heuristic='TEMPERANCE': should any import
path still attach widget meshes to pose bones, they must never reach the
FBX (they are viewport dressing, not scene content).
"""
import bpy
widgets = set()
for obj in bpy.context.scene.objects:
if obj.type != "ARMATURE":
continue
for pose_bone in obj.pose.bones:
if pose_bone.custom_shape is not None:
widgets.add(pose_bone.custom_shape)
pose_bone.custom_shape = None
for widget in widgets:
bpy.data.objects.remove(widget, do_unlink=True)
def validate_reimport(path: str, in_stats: dict, clip_names: list[str]) -> dict:
"""Re-import the exported FBX into a fresh scene and assert nothing was lost."""
import bpy
bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.ops.import_scene.fbx(filepath=path, ignore_leaf_bones=True)
objects = list(bpy.context.scene.objects)
armatures = [o for o in objects if o.type == "ARMATURE"]
meshes = [o for o in objects if o.type == "MESH"]
actions = list(bpy.data.actions) # FBX importer: one action per take
if in_stats["armature_count"] and not armatures:
raise ValidationError("exported FBX contains no armature")
if clip_names and len(actions) < len(clip_names):
raise ValidationError(
f"expected {len(clip_names)} animation take(s), re-import found {len(actions)}"
)
if in_stats["meshes"] and not meshes:
raise ValidationError("exported FBX contains no mesh")
return {
"armatures": len(armatures),
"meshes": len(meshes),
"actions": sorted(action.name for action in actions),
}
class ValidationError(RuntimeError):
pass
def convert(input_path: str, output_path: str, opts: dict) -> dict:
import bpy
bpy.ops.wm.read_factory_settings(use_empty=True)
scene = bpy.context.scene
# Set fps BEFORE import: the glTF importer converts clip times to frames
# with the scene fps, and the exporter bakes one key per frame.
scene.render.fps = int(opts.get("bake_fps", 30))
scene.render.fps_base = 1.0
progress("import", 0.1, "Importing GLB…")
# bone_heuristic: the default 'BLENDER' creates an "Icosphere" mesh object
# as the bones' display widget — a real scene object the FBX exporter would
# happily ship to the engine. 'TEMPERANCE' only orients bones, no widgets.
bpy.ops.import_scene.gltf(filepath=input_path, bone_heuristic="TEMPERANCE")
_remove_bone_widget_objects()
objects = list(scene.objects)
clip_names = normalize_nla(objects)
stats = collect_stats(objects, clip_names)
progress(
"import", 0.3,
f"Imported {stats['armature_count']} armature(s) ({stats['bones']} bones), "
f"{stats['meshes']} mesh(es), {len(clip_names)} clip(s)",
)
preset = opts.get("preset", "generic")
kwargs = dict(COMMON_FBX)
kwargs["bake_anim_simplify_factor"] = float(opts.get("anim_simplify", 1.0))
if preset == "unreal" and opts.get("unreal_scale_mode", "bake") == "bake":
progress("transform", 0.45, "Baking centimeter scale for Unreal…")
bake_unreal_scale(objects)
kwargs.update(CM_BAKED_FBX)
else:
kwargs.update(METER_SCALE_FBX)
progress("export", 0.55, f"Baking {len(clip_names)} animation take(s) to FBX…")
bpy.ops.export_scene.fbx(filepath=output_path, **kwargs)
progress("validate", 0.8, "Re-importing FBX to validate…")
stats["validation"] = validate_reimport(output_path, stats, clip_names)
stats["preset"] = preset
return stats
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input", required=True, help="Source .glb path")
parser.add_argument("--output", required=True, help="Destination .fbx path")
parser.add_argument("--options", required=True, help="Path to an options JSON file")
args = parser.parse_args()
with open(args.options, encoding="utf-8") as handle:
opts = json.load(handle)
try:
import bpy # noqa: F401 — probe only; used inside convert()
except ImportError as exc:
fail(f"bpy is not installed in this environment: {exc}", 4)
try:
stats = convert(args.input, args.output, opts)
except ValidationError as exc:
fail(f"Validation failed: {exc}", 3)
except Exception as exc: # noqa: BLE001 — everything must surface to the parent
import traceback
traceback.print_exc()
fail(f"{type(exc).__name__}: {exc}", 2)
else:
emit({"type": "result", "ok": True, "stats": stats})
if __name__ == "__main__":
main()

View file

@ -0,0 +1,185 @@
"""GLB -> PNG thumbnail worker (headless Blender).
Runs `bpy` in ISOLATION: invoked as a subprocess by app/services/mesh_thumbnail.py
(`python thumbnail_worker.py --input in.glb --output out.png`). Never import this
module from the service — bpy is not thread-safe, holds ~1GB RSS once imported,
and a crash inside Blender must not take the API down.
Why a server-side render at all: mesh thumbnails are normally rendered in the
browser (src/utils/meshThumbnail.js, WebGL). Meshes created without a browser
(ComfyUI workflows / external-API generation driven over MCP) never get one, so
the app shows an empty image. This renders one headlessly instead.
Engine choice: Cycles on the CPU. Cycles needs no GL/display context, so it
renders reliably headless on every platform (EEVEE/Workbench depend on an
OpenGL context that is often absent on servers). Low samples keep a 512px frame
to ~1-3s. The framing/lighting mirrors the client renderer so thumbnails look
consistent: dark background, a 3/4 camera, key + fill + rim lights.
Protocol: progress/result JSON lines on stdout prefixed with GENSTUDIO_EVT (bpy
prints its own "Info:" noise, the parent ignores non-matching lines).
Exit codes: 0 ok, 2 render error, 4 bpy missing.
"""
from __future__ import annotations
import argparse
import json
import math
import sys
SENTINEL = "GENSTUDIO_EVT " # keep in sync with app/services/mesh_thumbnail.py
RESOLUTION = 512
SAMPLES = 24
CAMERA_FOV_DEG = 35.0
# Camera direction (Blender is Z-up; the glTF importer puts model front toward
# -Y). A 3/4 view from front-right-above, matching the client's angle.
CAMERA_DIR = (0.9, -1.0, 0.7)
# Neutral world colour used only for soft ambient fill (never shown — the film
# is transparent). Blender colour inputs are linear.
AMBIENT_COLOR = (0.09, 0.095, 0.11)
def emit(obj: dict) -> None:
sys.stdout.write(SENTINEL + json.dumps(obj, separators=(",", ":")) + "\n")
sys.stdout.flush()
def progress(stage: str, frac: float, message: str = "") -> None:
emit({"type": "progress", "stage": stage, "frac": round(float(frac), 4), "message": message})
def fail(error: str, code: int) -> None:
emit({"type": "result", "ok": False, "error": error})
sys.exit(code)
def _scene_bounds(objects):
"""World-space (min, max) corners over every mesh object's bounding box."""
from mathutils import Vector
lo = Vector((math.inf, math.inf, math.inf))
hi = Vector((-math.inf, -math.inf, -math.inf))
found = False
for obj in objects:
if obj.type != "MESH":
continue
found = True
for corner in obj.bound_box:
world = obj.matrix_world @ Vector(corner)
lo = Vector((min(lo.x, world.x), min(lo.y, world.y), min(lo.z, world.z)))
hi = Vector((max(hi.x, world.x), max(hi.y, world.y), max(hi.z, world.z)))
if not found:
return None
return lo, hi
def _add_sun(name, direction, energy):
import bpy
from mathutils import Vector
data = bpy.data.lights.new(name=name, type="SUN")
data.energy = energy
obj = bpy.data.objects.new(name=name, object_data=data)
bpy.context.scene.collection.objects.link(obj)
# A sun's rays travel along its local -Z; aim that at `direction`.
obj.rotation_euler = Vector(direction).normalized().to_track_quat("-Z", "Y").to_euler()
return obj
def render(input_path: str, output_path: str) -> None:
import bpy
from mathutils import Vector
bpy.ops.wm.read_factory_settings(use_empty=True)
scene = bpy.context.scene
progress("import", 0.2, "Importing GLB…")
# TEMPERANCE: the default bone heuristic spawns an Icosphere widget mesh for
# rigged meshes that would pollute the framing; TEMPERANCE only orients bones.
bpy.ops.import_scene.gltf(filepath=input_path, bone_heuristic="TEMPERANCE")
objects = list(scene.objects)
bounds = _scene_bounds(objects)
if bounds is None:
raise RuntimeError("The GLB contains no mesh geometry to render.")
lo, hi = bounds
center = (lo + hi) * 0.5
size = hi - lo
max_dim = max(size.x, size.y, size.z, 1e-4)
progress("camera", 0.4, "Framing camera…")
cam_data = bpy.data.cameras.new("thumb_cam")
cam_data.angle = math.radians(CAMERA_FOV_DEG)
cam_obj = bpy.data.objects.new("thumb_cam", cam_data)
scene.collection.objects.link(cam_obj)
scene.camera = cam_obj
direction = Vector(CAMERA_DIR).normalized()
distance = max_dim * 2.2
cam_obj.location = center + direction * distance
# Camera looks down its local -Z with +Y up.
cam_obj.rotation_euler = (-direction).to_track_quat("-Z", "Y").to_euler()
# Lights: a soft ambient world plus key/fill/rim suns (mirrors the client's
# ambient + key + rim setup).
world = bpy.data.worlds.new("thumb_world")
scene.world = world
world.use_nodes = True
bg = world.node_tree.nodes.get("Background")
if bg is not None:
bg.inputs[0].default_value = (*AMBIENT_COLOR, 1.0)
bg.inputs[1].default_value = 1.1 # ambient strength
_add_sun("key", (-0.5, 0.8, -1.0), 4.0)
_add_sun("fill", (0.9, 0.4, -0.6), 1.6)
_add_sun("rim", (0.4, -0.9, 0.5), 2.2)
progress("render", 0.6, "Rendering thumbnail…")
scene.render.engine = "CYCLES"
scene.cycles.device = "CPU"
scene.cycles.samples = SAMPLES
scene.cycles.use_denoising = True
scene.render.resolution_x = RESOLUTION
scene.render.resolution_y = RESOLUTION
scene.render.resolution_percentage = 100
# Transparent background (RGBA): the model composites cleanly over the app's
# dark cards, and it avoids the version-specific Blender compositor API. The
# world stays bright for ambient fill but is not shown.
scene.render.film_transparent = True
scene.render.image_settings.file_format = "PNG"
scene.render.image_settings.color_mode = "RGBA"
scene.render.filepath = output_path
# Match the client's plain-sRGB output: Blender's default AgX/Filmic view
# transform lifts darks and shifts colours. "Standard" keeps colours
# as-authored so thumbnails look like the in-app WebGL renders.
try:
scene.view_settings.view_transform = "Standard"
except TypeError: # build may name it differently — non-fatal
pass
bpy.ops.render.render(write_still=True)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input", required=True, help="Source .glb path")
parser.add_argument("--output", required=True, help="Destination .png path")
args = parser.parse_args()
try:
import bpy # noqa: F401 — probe only; used inside render()
except ImportError as exc:
fail(f"bpy is not installed in this environment: {exc}", 4)
try:
render(args.input, args.output)
except Exception as exc: # noqa: BLE001 — everything must surface to the parent
import traceback
traceback.print_exc()
fail(f"{type(exc).__name__}: {exc}", 2)
else:
emit({"type": "result", "ok": True})
if __name__ == "__main__":
main()

View file

@ -16,6 +16,12 @@ pymeshlab>=2023.12 # isotropic remesh / decimation / quad conversion
matplotlib>=3.8 # only needed for the CLI's UV-layout / compare PNGs
rtree
# Engine export (GLB -> FBX via headless Blender). cp313 wheel (~340MB download,
# ~1GB installed); each bpy release supports exactly one Python version — keep in
# sync with .python-version (3.13). Imported ONLY by app/tools/fbx_worker.py,
# which runs as a subprocess (never import bpy in the FastAPI process).
bpy>=5.0,<6
# --- Optional GPU acceleration (Auto Retopo) ---------------------------------
# GPU packages live in requirements-nvidia.txt and are NOT installed from this
# file. run.bat auto-detects an NVIDIA GPU on first setup and installs them

View file

@ -1,10 +1,17 @@
@echo off
:: Start the 3D Gen Studio Python mesh-processing service.
:: On first run: creates a local virtual environment, installs the base (CPU)
:: requirements, then auto-detects an NVIDIA GPU and installs matching GPU
:: On first run: uses `uv` to provision a pinned standalone Python (see
:: .python-version), create a local virtual environment, install the base (CPU)
:: requirements, then auto-detect an NVIDIA GPU and install matching GPU
:: acceleration (Warp + the correct cupy-cudaXXx wheel for your CUDA version).
::
:: uv gives every machine the SAME Python without depending on a system install
:: (mirrors thirdparty/skintokens). It is auto-downloaded if not already present.
setlocal enabledelayedexpansion
cd /d "%~dp0"
set "PYVER=3.13"
call :ensure_uv || goto :error
if not exist ".venv\Scripts\python.exe" (
call :setup || goto :error
@ -17,15 +24,29 @@ python main.py
goto :eof
:ensure_uv
set "UV="
where uv >nul 2>nul && set "UV=uv"
if not defined UV if exist "%USERPROFILE%\.local\bin\uv.exe" set "UV=%USERPROFILE%\.local\bin\uv.exe"
if not defined UV (
echo Installing uv ^(Python toolchain manager^)...
powershell -NoProfile -ExecutionPolicy Bypass -Command "irm https://astral.sh/uv/install.ps1 | iex" || exit /b 1
set "UV=%USERPROFILE%\.local\bin\uv.exe"
)
exit /b 0
:setup
echo Creating virtual environment...
python -m venv .venv || exit /b 1
echo Provisioning Python %PYVER% via uv...
"%UV%" python install %PYVER% || exit /b 1
echo Creating virtual environment ^(Python %PYVER%^)...
"%UV%" venv .venv --python %PYVER% || exit /b 1
call ".venv\Scripts\activate.bat"
python -m pip install --upgrade pip
echo.
echo Installing base (CPU) requirements...
pip install -r requirements.txt || exit /b 1
"%UV%" pip install -r requirements.txt || exit /b 1
:: --- Optional NVIDIA GPU acceleration -------------------------------------
:: detect_cuda.py prints the matching CuPy wheel (e.g. cupy-cuda13x) when an
@ -43,8 +64,8 @@ for /f "usebackq delims=" %%p in (`python detect_cuda.py`) do set "CUPY_PKG=%%p"
if defined CUPY_PKG (
echo NVIDIA GPU detected -- installing GPU acceleration: !CUPY_PKG! + Warp
pip install -r requirements-nvidia.txt || exit /b 1
pip install "!CUPY_PKG!" || exit /b 1
"%UV%" pip install -r requirements-nvidia.txt || exit /b 1
"%UV%" pip install "!CUPY_PKG!" || exit /b 1
echo GPU acceleration installed.
) else (
echo No NVIDIA GPU detected -- CPU-only install. Auto Retopo will run on the CPU.

60
python-server/run.sh Normal file
View file

@ -0,0 +1,60 @@
#!/usr/bin/env bash
# Start the 3D Gen Studio Python mesh-processing service (Linux / macOS).
#
# On first run: uses `uv` to provision a pinned standalone Python (see
# .python-version), create a local virtual environment, install the base (CPU)
# requirements, then auto-detect an NVIDIA GPU and install matching GPU
# acceleration (Warp + the correct cupy-cudaXXx wheel). macOS has no NVIDIA GPU,
# so it always does a CPU-only install.
#
# uv is auto-downloaded if not already present. Override host/port via env
# (e.g. MESHTOOLS_PORT=8200).
set -euo pipefail
cd "$(dirname "$0")"
PYVER=3.13
# --- Ensure uv is available -------------------------------------------------
if command -v uv >/dev/null 2>&1; then
UV="uv"
elif [ -x "$HOME/.local/bin/uv" ]; then
UV="$HOME/.local/bin/uv"
else
echo "Installing uv (Python toolchain manager)..."
curl -LsSf https://astral.sh/uv/install.sh | sh
UV="$HOME/.local/bin/uv"
fi
if [ ! -x ".venv/bin/python" ]; then
echo "Provisioning Python $PYVER via uv..."
"$UV" python install "$PYVER"
echo "Creating virtual environment (Python $PYVER)..."
"$UV" venv .venv --python "$PYVER"
# shellcheck disable=SC1091
source .venv/bin/activate
echo
echo "Installing base (CPU) requirements..."
"$UV" pip install -r requirements.txt
# --- Optional NVIDIA GPU acceleration -------------------------------------
echo
if [ -n "${MESHTOOLS_SKIP_GPU:-}" ]; then
echo "MESHTOOLS_SKIP_GPU set -- skipping GPU acceleration (CPU-only install)."
else
echo "Detecting NVIDIA GPU / CUDA version..."
CUPY_PKG="$(python detect_cuda.py || true)"
if [ -n "$CUPY_PKG" ]; then
echo "NVIDIA GPU detected -- installing GPU acceleration: $CUPY_PKG + Warp"
"$UV" pip install -r requirements-nvidia.txt
"$UV" pip install "$CUPY_PKG"
echo "GPU acceleration installed."
else
echo "No NVIDIA GPU detected -- CPU-only install. Auto Retopo will run on the CPU."
fi
fi
else
# shellcheck disable=SC1091
source .venv/bin/activate
fi
python main.py

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show more