MCP: Can view/download assets
This commit is contained in:
parent
83d1bd3248
commit
8148a1d105
5 changed files with 132 additions and 24 deletions
10
docs/mcp.md
10
docs/mcp.md
|
|
@ -25,7 +25,7 @@ Settings live in the app database and can be changed via `POST /api/settings` wi
|
|||
### Claude Code
|
||||
|
||||
```sh
|
||||
claude mcp add --transport http gen-studio http://localhost:3001/mcp
|
||||
claude mcp add --transport http 3d-gen-studio http://localhost:3001/mcp
|
||||
```
|
||||
|
||||
### Claude Desktop
|
||||
|
|
@ -35,7 +35,7 @@ Add a custom connector (Settings → Connectors) with URL `http://localhost:3001
|
|||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"gen-studio": {
|
||||
"3d-gen-studio": {
|
||||
"command": "node",
|
||||
"args": ["C:/Git/3DGenStudio/mcp/stdio.js"]
|
||||
}
|
||||
|
|
@ -69,7 +69,7 @@ Connect with transport "Streamable HTTP" to `http://localhost:3001/mcp`.
|
|||
| 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` |
|
||||
| Assets | `list_assets`, `list_library_assets`, `view_asset`, `download_asset`, `upload_asset`, `link_asset`, `delete_asset` |
|
||||
| System | `get_settings` (secrets redacted), `get_system_stats` |
|
||||
|
||||
### Displaying results on graph nodes
|
||||
|
|
@ -82,7 +82,9 @@ In graph projects, pass `nodeId` to `run_workflow`, `generate_image`, `edit_imag
|
|||
|
||||
### 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.
|
||||
- `view_asset` returns the **actual image** as MCP image content, so the AI can visually inspect generated images (for meshes it returns the thumbnail preview when one exists). Inline viewing is capped at ~3.5 MB per image.
|
||||
- `download_asset` writes any asset file (image/mesh/workflow) to an absolute folder on the machine running the app.
|
||||
- Asset listings and results otherwise carry direct download URLs (`http://localhost:3001/assets/...`); local files are passed into tools by absolute path (`upload_asset`, `import_workflow filePath`, `run_workflow fileInputs`), and exports write to absolute folders.
|
||||
|
||||
## Requirements per capability
|
||||
|
||||
|
|
|
|||
|
|
@ -170,6 +170,25 @@ export function createProgressReporter(extra) {
|
|||
};
|
||||
}
|
||||
|
||||
// Locate an asset anywhere in a project's asset tree (top-level assets plus
|
||||
// nested edits/versions/children). Throws with a hint when the id is unknown.
|
||||
export async function findProjectAsset(api, projectId, assetId) {
|
||||
const assets = await api.apiJson('GET', '/assets', { query: { projectId } });
|
||||
const flat = [];
|
||||
const visit = asset => {
|
||||
if (!asset) return;
|
||||
flat.push(asset);
|
||||
for (const key of ['edits', 'versions', 'children']) {
|
||||
if (Array.isArray(asset[key])) asset[key].forEach(visit);
|
||||
}
|
||||
};
|
||||
(Array.isArray(assets) ? assets : []).forEach(visit);
|
||||
const asset = flat.find(a => Number(a?.id) === Number(assetId));
|
||||
if (!asset) throw new Error(`Asset ${assetId} not found in project ${projectId} (use list_assets to find valid ids).`);
|
||||
if (!asset.filename && !asset.filePath) throw new Error(`Asset ${assetId} has no stored file.`);
|
||||
return asset;
|
||||
}
|
||||
|
||||
// Attach a public URL to an asset record (and its nested edits/versions when
|
||||
// present) so MCP clients can download files without base64 round-trips.
|
||||
export function withAssetUrls(api, asset) {
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ Typical flows:
|
|||
- 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.
|
||||
- Seeing results: use view_asset to LOOK at a generated image (returns the actual image; for meshes it returns the thumbnail when available). Use download_asset to save any asset file to a local folder. Assets also carry direct download URLs in every response.
|
||||
|
||||
Note: interactive Mesh Editor sculpting/painting and Image Editor pixel edits are browser-only and not exposed here. If the app UI is open in a browser, it may need a refresh to show changes made through these tools.`;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import { z } from 'zod';
|
||||
import { Buffer } from 'node:buffer';
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { toolHandler, withAssetUrls } from '../client.js';
|
||||
import { toolHandler, withAssetUrls, findProjectAsset } from '../client.js';
|
||||
|
||||
const MIME_BY_EXT = {
|
||||
'.png': 'image/png',
|
||||
|
|
@ -16,6 +17,34 @@ const MIME_BY_EXT = {
|
|||
'.json': 'application/json'
|
||||
};
|
||||
|
||||
// MCP image blocks Claude can actually see. Cap the raw size so the base64
|
||||
// payload stays under typical model/image limits (~5 MB base64).
|
||||
const VIEWABLE_IMAGE_MIME = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif']);
|
||||
const MAX_VIEW_BYTES = 3.5 * 1024 * 1024;
|
||||
|
||||
function imageMimeOf(filePath) {
|
||||
return MIME_BY_EXT[path.extname(String(filePath || '')).toLowerCase()] || null;
|
||||
}
|
||||
|
||||
// Resolve what file a view/download request points at: an image asset's own
|
||||
// file, or — for meshes — its thumbnail when viewing.
|
||||
function resolveViewTarget(asset) {
|
||||
const file = asset.filename || asset.filePath;
|
||||
const mime = imageMimeOf(file);
|
||||
if (mime && VIEWABLE_IMAGE_MIME.has(mime)) {
|
||||
return { file, mime, note: null };
|
||||
}
|
||||
if (asset.thumbnail) {
|
||||
const thumbMime = imageMimeOf(asset.thumbnail) || 'image/png';
|
||||
return {
|
||||
file: asset.thumbnail,
|
||||
mime: thumbMime,
|
||||
note: `This is the thumbnail preview of "${asset.name}" (${String(asset.type || 'asset')}), not the file itself. Use download_asset for the full file.`
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function registerAssetTools(server, { api, notifyMutation }) {
|
||||
server.registerTool('list_assets', {
|
||||
title: 'List project assets',
|
||||
|
|
@ -88,6 +117,81 @@ export function registerAssetTools(server, { api, notifyMutation }) {
|
|||
return withAssetUrls(api, asset);
|
||||
}));
|
||||
|
||||
server.registerTool('view_asset', {
|
||||
title: 'View asset (image)',
|
||||
description: 'SEE a project asset: returns the actual image so it can be visually inspected. For image assets returns the image itself; for meshes returns the thumbnail preview when one exists. Use this after generating images to check the results. For raw file access use download_asset.',
|
||||
inputSchema: {
|
||||
projectId: z.number().int(),
|
||||
assetId: z.number().int().describe('Asset id (from list_assets or a generation result)')
|
||||
},
|
||||
annotations: { readOnlyHint: true }
|
||||
}, async ({ projectId, assetId } = {}) => {
|
||||
try {
|
||||
const asset = await findProjectAsset(api, projectId, assetId);
|
||||
const target = resolveViewTarget(asset);
|
||||
if (!target) {
|
||||
return {
|
||||
isError: true,
|
||||
content: [{
|
||||
type: 'text',
|
||||
text: `Asset ${assetId} ("${asset.name}", type ${asset.type}) has no viewable image or thumbnail. Use download_asset to save the file locally instead.`
|
||||
}]
|
||||
};
|
||||
}
|
||||
|
||||
const buffer = await api.fetchAssetBuffer(target.file);
|
||||
if (buffer.length > MAX_VIEW_BYTES) {
|
||||
return {
|
||||
isError: true,
|
||||
content: [{
|
||||
type: 'text',
|
||||
text: `Asset file is too large to view inline (${(buffer.length / 1024 / 1024).toFixed(1)} MB). Use download_asset to save it locally, or open its URL: ${api.assetUrl(target.file)}`
|
||||
}]
|
||||
};
|
||||
}
|
||||
|
||||
const info = {
|
||||
id: asset.id,
|
||||
name: asset.name,
|
||||
type: asset.type,
|
||||
width: asset.width || undefined,
|
||||
height: asset.height || undefined,
|
||||
url: api.assetUrl(asset.filename || asset.filePath)
|
||||
};
|
||||
return {
|
||||
content: [
|
||||
{ type: 'image', data: buffer.toString('base64'), mimeType: target.mime },
|
||||
{ type: 'text', text: (target.note ? `${target.note}\n` : '') + JSON.stringify(info) }
|
||||
]
|
||||
};
|
||||
} catch (err) {
|
||||
return { isError: true, content: [{ type: 'text', text: String(err?.message || err) }] };
|
||||
}
|
||||
});
|
||||
|
||||
server.registerTool('download_asset', {
|
||||
title: 'Download asset to disk',
|
||||
description: 'Save a project asset\'s file (image, mesh, or workflow) into an absolute folder on the machine running 3D Gen Studio, so it can be opened or inspected from the filesystem.',
|
||||
inputSchema: {
|
||||
projectId: z.number().int(),
|
||||
assetId: z.number().int(),
|
||||
folder: z.string().min(1).describe('Absolute output folder'),
|
||||
fileName: z.string().optional().describe('Output file name (defaults to the asset\'s stored file name)')
|
||||
},
|
||||
annotations: { readOnlyHint: true }
|
||||
}, toolHandler(async ({ projectId, assetId, folder, fileName }) => {
|
||||
const asset = await findProjectAsset(api, projectId, assetId);
|
||||
const assetFile = asset.filename || asset.filePath;
|
||||
const buffer = await api.fetchAssetBuffer(assetFile);
|
||||
// Reuse the server's export endpoint — it writes arbitrary files under an
|
||||
// absolute folder with basename sanitization.
|
||||
const form = new FormData();
|
||||
form.append('folder', folder);
|
||||
form.append('files', new Blob([buffer]), fileName || path.basename(String(assetFile)) || `asset-${assetId}`);
|
||||
const written = await api.apiForm('POST', '/export/mesh', form);
|
||||
return { ...written, sizeBytes: buffer.length, asset: { id: asset.id, name: asset.name, type: asset.type } };
|
||||
}));
|
||||
|
||||
server.registerTool('delete_asset', {
|
||||
title: 'Delete asset',
|
||||
description: 'PERMANENTLY delete an asset from a project. Set confirm=true to proceed.',
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { z } from 'zod';
|
||||
import { Buffer } from 'node:buffer';
|
||||
import path from 'node:path';
|
||||
import { toolHandler, createProgressReporter, withAssetUrls } from '../client.js';
|
||||
import { toolHandler, createProgressReporter, withAssetUrls, findProjectAsset } from '../client.js';
|
||||
|
||||
// Local mesh services behind the Node proxy. auto_uv/auto_retopo/repair/
|
||||
// convert_fbx run on the Python mesh-tools service (:8200), auto_rig on the
|
||||
|
|
@ -15,23 +15,6 @@ const OPERATIONS = {
|
|||
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',
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue