Start to implement MCP

This commit is contained in:
Bruno Fargnoli 2026-07-16 17:13:12 +02:00
parent 502829e50f
commit ba534b5b42
21 changed files with 1822 additions and 12 deletions

97
docs/mcp.md Normal file
View file

@ -0,0 +1,97 @@
# 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 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": {
"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.
### 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`, `edit_mesh`, `texture_mesh`, `rig_mesh_api` |
| Mesh tools | `run_mesh_tool` (auto_uv / auto_retopo / repair / auto_rig / optimize / convert_fbx), `export_mesh` |
| Assets | `list_assets`, `list_library_assets`, `upload_asset`, `link_asset`, `delete_asset` |
| System | `get_settings` (secrets redacted), `get_system_stats` |
### 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
Tools never return file bytes. Assets 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 on the machine running the app.
## 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`, `edit_mesh`, `texture_mesh`, `rig_mesh_api` | provider API keys in Settings |
| `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

@ -35,6 +35,8 @@ files:
- server.js
- storage.js
- wikiStorage.js
# MCP automation server (POST /mcp on the backend + stdio bridge).
- mcp/**/*
- version.json
- package.json
- dist/**/*

185
mcp/client.js Normal file
View file

@ -0,0 +1,185 @@
// 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.
}
};
}
// 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);
}

65
mcp/index.js Normal file
View file

@ -0,0 +1,65 @@
// 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.
- 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).
- Mesh processing: run_mesh_tool (auto_uv / auto_retopo / repair / auto_rig / optimize / convert_fbx) works on mesh assets; results save as asset versions.
- Assets 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;
}

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());

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

@ -0,0 +1,187 @@
import { z } from 'zod';
import { toolHandler, createProgressReporter } from '../client.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;
}
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.',
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'),
cardId: z.union([z.number().int(), z.string()]).optional().describe('Existing card/node to attach the result to')
}
}, toolHandler(async ({ projectId, ...body }) => {
const result = await api.apiJson('POST', '/images/generate', { body: { projectId, ...body } });
notifyMutation(projectId);
return 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. 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'),
cardId: z.union([z.number().int(), z.string()]).optional()
}
}, toolHandler(async ({ projectId, ...body }) => {
const result = await api.apiJson('POST', '/image-edits/api', { body: { projectId, ...body } });
notifyMutation(projectId);
return 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. 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)'),
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, …'),
timeoutSeconds: z.number().int().min(30).max(3600).default(1200),
pollIntervalSeconds: z.number().int().min(3).max(120).default(10)
}
}, toolHandler(async (args, extra) => {
const {
projectId, selectedApi, name, prompt, imageSource, cardId, parentAssetId,
options = {}, timeoutSeconds = 1200, pollIntervalSeconds = 10
} = args;
const reportProgress = createProgressReporter(extra);
const submit = await api.apiJson('POST', '/meshes/generate', {
body: {
projectId, selectedApi, name,
...(prompt ? { prompt } : {}),
...(imageSource !== undefined ? { imageSource } : {}),
...(cardId !== undefined ? { cardId } : {}),
...(parentAssetId !== undefined ? { parentAssetId } : {}),
...options
}
});
notifyMutation(projectId);
const pollRequest = buildMeshPollRequest(submit, {
projectId,
name,
prompt: prompt || '',
cardId: submit?.cardId ?? cardId ?? 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 deadline = Date.now() + timeoutSeconds * 1000;
let lastStatus = submit;
while (Date.now() < deadline) {
await sleep(pollIntervalSeconds * 1000);
lastStatus = await api.apiJson('POST', pollRequest.path, { body: pollRequest.body });
if (lastStatus?.status === 'completed') {
await reportProgress(100, 100, 'Mesh generation completed');
notifyMutation(projectId);
return lastStatus;
}
if (lastStatus?.status === 'error') {
throw new Error(lastStatus.error || 'Mesh generation failed');
}
const percent = Number(lastStatus?.progressPercent);
await reportProgress(
Number.isFinite(percent) ? percent : 50,
100,
`${submit.provider} status: ${lastStatus?.jobStatus || lastStatus?.taskStatus || lastStatus?.status || 'processing'}`
);
}
return {
status: 'running',
note: `Still processing after ${timeoutSeconds}s. The provider keeps working — re-run generate_mesh later is NOT needed; check the project with list_assets, or the card status with list_cards.`,
submit,
lastStatus
};
}));
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;
}));
}

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

@ -0,0 +1,105 @@
import { z } from 'zod';
import fs from 'node:fs/promises';
import path from 'node:path';
import { toolHandler, withAssetUrls } 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'
};
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() },
annotations: { readOnlyHint: true }
}, toolHandler(async ({ projectId }) => {
const assets = await api.apiJson('GET', '/assets', { query: { projectId } });
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 already-stored asset file (by its stored filename) to a project — creates the card/link without re-uploading.',
inputSchema: {
projectId: z.number().int(),
filename: z.string().min(1).describe('Stored asset filename (from list_library_assets)'),
type: z.enum(['image', 'mesh']).default('image'),
name: z.string().optional(),
metadata: z.record(z.string(), z.any()).optional()
}
}, toolHandler(async ({ projectId, filename, type, name, metadata }) => {
const asset = await api.apiJson('POST', '/assets/link', {
body: { projectId, filename, type, ...(name ? { name } : {}), ...(metadata ? { metadata } : {}) }
});
notifyMutation(projectId);
return withAssetUrls(api, asset);
}));
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 };
}));
}

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

@ -0,0 +1,131 @@
import { z } from 'zod';
import { Buffer } from 'node:buffer';
import path from 'node:path';
import { toolHandler, createProgressReporter, withAssetUrls } 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 }
};
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;
}
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). 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)'),
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(async (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) };
}));
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')));
}

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

@ -0,0 +1,229 @@
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';
// 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) 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}); 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()
})).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. 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. Image/mesh parameters accept a project assetId (number) or stored filePath (string).'),
fileInputs: z.record(z.string(), z.string()).optional().describe('Parameter id -> absolute local file path to upload for image/mesh/video parameters'),
cardId: z.union([z.number().int(), z.string()]).optional().describe('Existing card/node to attach the run to (its status updates live in the UI)'),
name: z.string().optional().describe('Name for the generated asset(s)'),
parentAssetId: z.number().int().optional().describe('Save results as versions of this 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, cardId, name,
parentAssetId, persistProcessingCard, persistGeneratedAssets, timeoutSeconds = 600
} = args;
const reportProgress = createProgressReporter(extra);
const promptId = randomUUID();
// 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 (cardId !== undefined && cardId !== null) form.append('cardId', String(cardId));
if (name) form.append('name', name);
if (parentAssetId !== undefined && parentAssetId !== null) form.append('parentAssetId', String(parentAssetId));
if (persistProcessingCard === false) form.append('persistProcessingCard', 'false');
if (persistGeneratedAssets === false) form.append('persistGeneratedAssets', 'false');
const inputValues = { ...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;
return {
status: 'completed',
promptId,
assets: Array.isArray(result) ? result : (result ? [result] : [])
};
} 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;
}));
}

227
package-lock.json generated
View file

@ -1,13 +1,14 @@
{
"name": "app",
"version": "1.4.0",
"version": "1.5.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "app",
"version": "1.3.3",
"version": "1.5.0",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"@react-three/drei": "^10.7.7",
"@react-three/fiber": "^9.5.0",
"@types/three": "^0.183.1",
@ -32,7 +33,8 @@
"three": "^0.183.2",
"three-bvh-csg": "^0.0.18",
"three-mesh-bvh": "^0.9.9",
"ws": "^8.21.0"
"ws": "^8.21.0",
"zod": "^4.4.3"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
@ -1304,6 +1306,18 @@
"dev": true,
"license": "MIT"
},
"node_modules/@hono/node-server": {
"version": "1.19.14",
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz",
"integrity": "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==",
"license": "MIT",
"engines": {
"node": ">=18.14.1"
},
"peerDependencies": {
"hono": "^4"
}
},
"node_modules/@humanfs/core": {
"version": "0.19.1",
"resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz",
@ -1605,6 +1619,68 @@
"integrity": "sha512-CZWV/q6TTe8ta61cZXjfnnHsfWIdFhms03M9T7Cnd5y2mdpylJM0rF1qRq+wsQVRMLz1OYPVEBU9ph2Bx8cxrg==",
"license": "Apache-2.0"
},
"node_modules/@modelcontextprotocol/sdk": {
"version": "1.29.0",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz",
"integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==",
"license": "MIT",
"dependencies": {
"@hono/node-server": "^1.19.9",
"ajv": "^8.17.1",
"ajv-formats": "^3.0.1",
"content-type": "^1.0.5",
"cors": "^2.8.5",
"cross-spawn": "^7.0.5",
"eventsource": "^3.0.2",
"eventsource-parser": "^3.0.0",
"express": "^5.2.1",
"express-rate-limit": "^8.2.1",
"hono": "^4.11.4",
"jose": "^6.1.3",
"json-schema-typed": "^8.0.2",
"pkce-challenge": "^5.0.0",
"raw-body": "^3.0.0",
"zod": "^3.25 || ^4.0",
"zod-to-json-schema": "^3.25.1"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"@cfworker/json-schema": "^4.1.1",
"zod": "^3.25 || ^4.0"
},
"peerDependenciesMeta": {
"@cfworker/json-schema": {
"optional": true
},
"zod": {
"optional": false
}
}
},
"node_modules/@modelcontextprotocol/sdk/node_modules/ajv": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
"license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.3",
"fast-uri": "^3.0.1",
"json-schema-traverse": "^1.0.0",
"require-from-string": "^2.0.2"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/epoberezkin"
}
},
"node_modules/@modelcontextprotocol/sdk/node_modules/json-schema-traverse": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
"license": "MIT"
},
"node_modules/@monogrid/gainmap-js": {
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/@monogrid/gainmap-js/-/gainmap-js-3.4.0.tgz",
@ -2678,6 +2754,45 @@
"url": "https://github.com/sponsors/epoberezkin"
}
},
"node_modules/ajv-formats": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",
"integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",
"license": "MIT",
"dependencies": {
"ajv": "^8.0.0"
},
"peerDependencies": {
"ajv": "^8.0.0"
},
"peerDependenciesMeta": {
"ajv": {
"optional": true
}
}
},
"node_modules/ajv-formats/node_modules/ajv": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
"license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.3",
"fast-uri": "^3.0.1",
"json-schema-traverse": "^1.0.0",
"require-from-string": "^2.0.2"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/epoberezkin"
}
},
"node_modules/ajv-formats/node_modules/json-schema-traverse": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
"license": "MIT"
},
"node_modules/ajv-keywords": {
"version": "3.5.2",
"resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz",
@ -5370,6 +5485,27 @@
"node": ">= 0.6"
}
},
"node_modules/eventsource": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
"integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",
"license": "MIT",
"dependencies": {
"eventsource-parser": "^3.0.1"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/eventsource-parser": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.0.tgz",
"integrity": "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==",
"license": "MIT",
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/expand-template": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",
@ -5429,6 +5565,24 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/express-rate-limit": {
"version": "8.5.2",
"resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.2.tgz",
"integrity": "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A==",
"license": "MIT",
"dependencies": {
"ip-address": "^10.2.0"
},
"engines": {
"node": ">= 16"
},
"funding": {
"url": "https://github.com/sponsors/express-rate-limit"
},
"peerDependencies": {
"express": ">= 4.11"
}
},
"node_modules/express/node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
@ -5496,7 +5650,6 @@
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"dev": true,
"license": "MIT"
},
"node_modules/fast-json-stable-stringify": {
@ -5513,6 +5666,22 @@
"dev": true,
"license": "MIT"
},
"node_modules/fast-uri": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.3.tgz",
"integrity": "sha512-i70LwGWUduXqzicKXWshooq+sWL1K3WUU5rKZNG/0i3a1OSoX3HqhH5WbWwTmqWfor4urUakGPiRQcleRZTwOg==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fastify"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fastify"
}
],
"license": "BSD-3-Clause"
},
"node_modules/fd-slicer": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz",
@ -6315,6 +6484,15 @@
"integrity": "sha512-E3a5VwgXimGHwpRGV+WxRTKeSp2DW5DI5MWv34ulL3t5UNmyJWCQ1KmLEHbYzcfThfXG8amBL+fCYPneGHC4VA==",
"license": "Apache-2.0"
},
"node_modules/hono": {
"version": "4.12.30",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.30.tgz",
"integrity": "sha512-emn+JoJjrN9YTpRDS5it/UI2SO9BAE37T6I3d963RxcZ81G9A4pr2SZTEiiaiKbzx+NKRg5BZ89fCL7gCJCUog==",
"license": "MIT",
"engines": {
"node": ">=16.9.0"
}
},
"node_modules/hosted-git-info": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-4.1.0.tgz",
@ -6603,7 +6781,6 @@
"version": "10.2.0",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",
"integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==",
"devOptional": true,
"license": "MIT",
"engines": {
"node": ">= 12"
@ -6837,6 +7014,15 @@
"node": ">=10"
}
},
"node_modules/jose": {
"version": "6.2.3",
"resolved": "https://registry.npmjs.org/jose/-/jose-6.2.3.tgz",
"integrity": "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@ -6884,6 +7070,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/json-schema-typed": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz",
"integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",
"license": "BSD-2-Clause"
},
"node_modules/json-stable-stringify-without-jsonify": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz",
@ -9256,6 +9448,15 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/pkce-challenge": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",
"integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",
"license": "MIT",
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/plist": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/plist/-/plist-3.1.1.tgz",
@ -11800,15 +12001,23 @@
}
},
"node_modules/zod": {
"version": "4.3.6",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
"dev": true,
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",
"integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
},
"node_modules/zod-to-json-schema": {
"version": "3.25.2",
"resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz",
"integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==",
"license": "ISC",
"peerDependencies": {
"zod": "^3.25.28 || ^4"
}
},
"node_modules/zod-validation-error": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/zod-validation-error/-/zod-validation-error-4.0.2.tgz",

View file

@ -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,7 @@
"dist:dir": "npm run build && electron-builder --dir"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"@react-three/drei": "^10.7.7",
"@react-three/fiber": "^9.5.0",
"@types/three": "^0.183.1",
@ -50,7 +52,8 @@
"three": "^0.183.2",
"three-bvh-csg": "^0.0.18",
"three-mesh-bvh": "^0.9.9",
"ws": "^8.21.0"
"ws": "^8.21.0",
"zod": "^4.4.3"
},
"devDependencies": {
"@eslint/js": "^9.39.4",

View file

@ -15,6 +15,7 @@ import { fileURLToPath } from 'node:url';
import si from 'systeminformation';
import { WebSocket as WsWebSocket } from 'ws';
import tencentcloudSdk from 'tencentcloud-sdk-nodejs-intl-en';
import { mountMcp } from './mcp/http.js';
// Node 20 (bundled by Electron 33) has no global WebSocket, so fall back to the
// `ws` package. Newer Node runtimes (dev) expose a global WebSocket we can reuse.
@ -191,6 +192,51 @@ if (HAS_DIST) {
app.use(express.static(DIST_DIR));
}
// App-level event stream (SSE). Lets an open browser UI learn about mutations
// made outside of it (e.g. by an MCP client) and refetch instead of showing
// stale data until the next manual refresh.
const appEventSubscribers = new Set();
function publishAppEvent(event) {
const serialized = `data: ${JSON.stringify({ timestamp: Date.now(), ...event })}\n\n`;
for (const response of appEventSubscribers) {
response.write(serialized);
}
}
app.get('/api/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
res.flushHeaders?.();
res.write('retry: 1000\n\n');
appEventSubscribers.add(res);
const heartbeat = setInterval(() => {
res.write(': keep-alive\n\n');
}, 15000);
req.on('close', () => {
clearInterval(heartbeat);
appEventSubscribers.delete(res);
});
});
// MCP server endpoint (POST /mcp) — lets any MCP client (Claude, ChatGPT,
// local LLMs) automate the app. Tools loop back through this server's own
// REST API, so SQLite stays behind this single process. Gated by
// settings.mcp (enabled/token) in mcp/http.js.
mountMcp(app, {
baseUrl: `http://127.0.0.1:${PORT}`,
getSettings,
notifyMutation: (projectId, detail) => publishAppEvent({
type: 'externalMutation',
projectId: projectId ?? null,
...(detail || {})
})
});
// Multer Config for Asset Uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
@ -7779,7 +7825,7 @@ async function migrateWikiIfNeeded() {
if (HAS_DIST) {
app.use((req, res, next) => {
if (req.method !== 'GET') return next();
if (/^\/(api|assets|wiki-media)(\/|$)/.test(req.path)) return next();
if (/^\/(api|assets|wiki-media|mcp)(\/|$)/.test(req.path)) return next();
res.sendFile(path.join(DIST_DIR, 'index.html'));
});
}

View file

@ -79,6 +79,30 @@ export function ProjectProvider({ children }) {
fetchProjects()
}, [fetchProjects])
// App-level event stream: the backend publishes `externalMutation` events
// when something outside this browser (e.g. an MCP client / AI agent)
// changes data. Refresh the project list and let open pages refetch via a
// window event so the UI doesn't sit on stale state until a manual reload.
useEffect(() => {
if (typeof EventSource === 'undefined') return undefined
const eventSource = new EventSource(`${API_BASE}/events`)
eventSource.onmessage = (event) => {
let payload
try {
payload = JSON.parse(event.data)
} catch {
return
}
if (payload?.type !== 'externalMutation') return
fetchProjects()
window.dispatchEvent(new CustomEvent('genstudio:external-mutation', { detail: payload }))
}
eventSource.onerror = () => {}
return () => eventSource.close()
}, [fetchProjects])
const createProject = async (projectData) => {
try {
const res = await fetch(`${API_BASE}/projects`, {

View file

@ -668,6 +668,21 @@ export default function GraphPage({ project }) {
}
}, [getComfyWorkflows, updateComfyWorkflow])
// Bumped when something outside this browser (e.g. an MCP client / AI
// agent) mutates this project — re-runs the loadGraph effect below.
const [externalReloadTick, setExternalReloadTick] = useState(0)
useEffect(() => {
const handleExternalMutation = (event) => {
const targetProjectId = event?.detail?.projectId
if (targetProjectId == null || Number(targetProjectId) === Number(project.id)) {
setExternalReloadTick(tick => tick + 1)
}
}
window.addEventListener('genstudio:external-mutation', handleExternalMutation)
return () => window.removeEventListener('genstudio:external-mutation', handleExternalMutation)
}, [project.id])
useEffect(() => {
let cancelled = false
@ -704,7 +719,7 @@ export default function GraphPage({ project }) {
return () => {
cancelled = true
}
}, [getProjectConnections, getProjectNodes, handleDeleteNode, project.id, setEdges, setNodes])
}, [getProjectConnections, getProjectNodes, handleDeleteNode, project.id, setEdges, setNodes, externalReloadTick])
const handleCreateNode = useCallback(async (nodeTypeName, initialData = {}) => {
const nextIndex = nodes.length

View file

@ -342,6 +342,22 @@ export default function KanbanPage() {
setCardAttributes(attributesData)
}
// Reload board data when something outside this browser (e.g. an MCP
// client / AI agent) mutates this project.
useEffect(() => {
const handleExternalMutation = (event) => {
const targetProjectId = event?.detail?.projectId
if (targetProjectId != null && Number(targetProjectId) !== Number(projectId)) return
refreshProjectAssets().catch(() => {})
refreshCardAttributes().catch(() => {})
}
window.addEventListener('genstudio:external-mutation', handleExternalMutation)
return () => window.removeEventListener('genstudio:external-mutation', handleExternalMutation)
// refreshCardAttributes is re-created per render; the listener only needs
// a working copy, so deps stay minimal to avoid re-subscribing every render.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [projectId, refreshProjectAssets])
const closePendingComfyProgressSubscription = () => {
pendingComfyProgressSubscriptionRef.current?.()
pendingComfyProgressSubscriptionRef.current = null

View file

@ -188,6 +188,12 @@ export const DEFAULT_SETTINGS = {
port: '8300'
},
custom: []
},
// MCP automation endpoint (POST /mcp on the backend). With no token set,
// only loopback clients may connect; a token allows remote MCP clients.
mcp: {
enabled: true,
token: ''
}
};