Fixed MCP in Graph Page for Image Generation

This commit is contained in:
Bruno Fargnoli 2026-07-16 21:14:09 +02:00
parent ba534b5b42
commit 83d1bd3248
5 changed files with 150 additions and 13 deletions

View file

@ -72,6 +72,10 @@ Connect with transport "Streamable HTTP" to `http://localhost:3001/mcp`.
| Assets | `list_assets`, `list_library_assets`, `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.
### 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).

View file

@ -33,6 +33,7 @@ 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.
- 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.

81
mcp/nodeResults.js Normal file
View file

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

View file

@ -1,5 +1,6 @@
import { z } from 'zod';
import { toolHandler, createProgressReporter } from '../client.js';
import { attachResultsToNode } from '../nodeResults.js';
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
@ -25,35 +26,56 @@ function buildMeshPollRequest(submit, base) {
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.',
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.',
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')
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, ...body }) => {
}, toolHandler(async ({ projectId, nodeId, ...body }) => {
const result = await api.apiJson('POST', '/images/generate', { body: { projectId, ...body } });
let nodeAttachment = null;
if (nodeId) {
nodeAttachment = await attachResultsToNode(api, {
projectId,
nodeId,
assets: [{ ...result, type: result?.type || 'image' }],
metadata: { lastAction: 'image-api' }
});
}
notifyMutation(projectId);
return result;
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. For ComfyUI-based edits use run_workflow instead.',
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. 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, ...body }) => {
}, toolHandler(async ({ projectId, nodeId, ...body }) => {
const result = await api.apiJson('POST', '/image-edits/api', { body: { projectId, ...body } });
let nodeAttachment = null;
const savedEdits = Array.isArray(result?.savedEdits) ? result.savedEdits : [];
if (nodeId && savedEdits.length > 0) {
nodeAttachment = await attachResultsToNode(api, {
projectId,
nodeId,
assets: savedEdits.map(edit => ({ id: edit.id, name: edit.name || body.name, type: 'image' })),
metadata: { lastAction: 'image-edit-api' }
});
}
notifyMutation(projectId);
return result;
return nodeAttachment ? { ...result, nodeAttachment } : result;
}));
server.registerTool('generate_mesh', {
@ -65,6 +87,7 @@ export function registerActionTools(server, { api, notifyMutation }) {
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)'),
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, …'),
@ -73,7 +96,7 @@ export function registerActionTools(server, { api, notifyMutation }) {
}
}, toolHandler(async (args, extra) => {
const {
projectId, selectedApi, name, prompt, imageSource, cardId, parentAssetId,
projectId, selectedApi, name, prompt, imageSource, nodeId, cardId, parentAssetId,
options = {}, timeoutSeconds = 1200, pollIntervalSeconds = 10
} = args;
const reportProgress = createProgressReporter(extra);
@ -112,8 +135,17 @@ export function registerActionTools(server, { api, notifyMutation }) {
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 lastStatus;
return nodeAttachment ? { ...lastStatus, nodeAttachment } : lastStatus;
}
if (lastStatus?.status === 'error') {
throw new Error(lastStatus.error || 'Mesh generation failed');

View file

@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import { toolHandler, createProgressReporter } from '../client.js';
import { attachResultsToNode } from '../nodeResults.js';
// Strip the raw graph JSON from workflow records so list responses stay small.
function summarizeWorkflow(workflow) {
@ -103,13 +104,14 @@ export function registerWorkflowTools(server, { api, notifyMutation }) {
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.',
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. 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)'),
nodeId: z.number().int().optional().describe('Graph node to attach the results to (graph projects) — 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 (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(),
@ -118,7 +120,7 @@ export function registerWorkflowTools(server, { api, notifyMutation }) {
}
}, toolHandler(async (args, extra) => {
const {
workflowId, projectId, inputs = {}, fileInputs, cardId, name,
workflowId, projectId, inputs = {}, fileInputs, nodeId, cardId, name,
parentAssetId, persistProcessingCard, persistGeneratedAssets, timeoutSeconds = 600
} = args;
const reportProgress = createProgressReporter(extra);
@ -186,10 +188,27 @@ export function registerWorkflowTools(server, { api, notifyMutation }) {
}
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 (nodeId && projectId) {
nodeAttachment = await attachResultsToNode(api, {
projectId,
nodeId,
assets,
metadata: { lastAction: 'comfy-workflow', promptId }
});
notifyMutation(projectId);
}
return {
status: 'completed',
promptId,
assets: Array.isArray(result) ? result : (result ? [result] : [])
assets,
...(nodeAttachment ? { nodeAttachment } : {})
};
} finally {
if (timer) clearTimeout(timer);