UNPKG

@kolbo/mcp

Version:

Kolbo AI MCP Server - Generate images, videos, music, speech, and sound effects from Claude Code

531 lines (499 loc) • 37.9 kB
/* ⛔ BACKWARD COMPATIBILITY: Tool names and arg names below are a PUBLIC * CONTRACT. Never rename, remove, or break an existing tool/arg — old cached * `npx @kolbo/mcp` installs in the wild will break silently. Add new tools or * new OPTIONAL args only. Full rules: ../index.js top-of-file and CLAUDE.md. */ const { z } = require('zod'); const FormData = require('form-data'); const { resolveToBuffer: sharedResolveToBuffer, VISUAL_DNA_MAX_BYTES, projectScopeReadField, compactList } = require('./_shared'); const { UI, uiResult, listResult } = require('../apps'); // Reference sheets are a blocking multi-panel render; the 120s client default // aborted them mid-flight while the server finished and charged anyway. const CHARACTER_SHEET_TIMEOUT_MS = Number(process.env.KOLBO_CHARACTER_SHEET_TIMEOUT_MS) || 600000; // Visual DNA caps reference media at 25MB per file (stricter than the // default _shared.resolveToBuffer cap — DNA profiles only need enough // source signal to extract features, not full-quality media). function resolveToBuffer(source, kind, options = {}) { return sharedResolveToBuffer(source, kind, { maxBytes: VISUAL_DNA_MAX_BYTES, allowLocalFiles: !options.remote, }); } function registerVisualDnaTools(server, client, options = {}) { // ─── create_visual_dna ───────────────────────────────────── server.tool( 'create_visual_dna', 'Create a Visual DNA profile from reference media: any mix of up to 4 images, 1 video (3-10s) and 1 voice clip (5-30s). ANY ONE of them is enough — a video-only DNA (its frames are analyzed and a mid-clip frame becomes its face) or a voice-only DNA (dna_type must be "character"; image models skip a DNA with no image or video). Each item can be a public URL or an absolute local file path. Files capped at 25MB each. Those stills are ALL packed into later generations (every image slot the model has, or a white grid if only one leftover slot remains) — so they must share one identity and one vibe. Character DNA: only that person (anonymous crowd OK, no second hero). Environment/location DNA: the place only — empty or anonymous crowd, NEVER a main character or recognizable hero face. Product: only that product. Style: one art direction. Separate states (day/night, clean/bloody) = separate DNAs. For EVERY DNA type, a reference sheet dramatically improves consistency (character turnaround / product details / location angles / style board) — offer to generate one with `generate_character_sheet` (matching `sheet_type`) first, then pass its URL as `character_sheet_url` here (see that tool). A sheet uploaded as one of the images is recognized automatically — never present an ordinary photo as a sheet. To use the DNA\'s own clips in a video generation, pass `videos[0].url` in reference_videos and `audio_clips[0].url` in reference_audio_urls (tag them @VideoN / @AudioN); the server labels them as this character.', { name: z.string().describe('Name of the Visual DNA profile. **Pick a short, lowercase, no-space single token** (e.g. `maya`, `tokyo_neon`, `brand_red`, `esther_model`) — never names with spaces (`Sarah Johnson` ❌). The user/LLM types this as `@<name>` inside generation prompts, and the @ parser stops at the first space, so `@Sarah Johnson` matches only `Sarah` and the binding silently drops. Multi-word concepts should use underscores or be a single token. Names are case-insensitive on lookup, but **reserved** values rejected on creation: `Image1`, `Image2`, …, `Video1`, …, `Audio1`, … (any-language characters allowed; max 100 chars).'), dna_type: z.string().optional().describe('Type: "character", "style", "product", "scene", "environment". Default: "character"'), prompt_helper: z.string().optional().describe('Optional description/notes to guide DNA extraction'), description: z.string().optional().describe('Alias for `prompt_helper`. Accepted because every tool here REPORTS this field as `description`, so callers round-trip that name back in; without the alias zod stripped it and the notes were silently lost. Ignored when `prompt_helper` is also given.'), images: z.array(z.string()).optional().describe('Array of image sources (URLs or absolute local paths). Max 4. All of them can reach the model on later gens — same subject, same vibe only; no extra heroes on character DNAs, no main characters on environment DNAs.'), video: z.string().optional().describe('Optional 3-10s video of the subject (URL or absolute local path). Enough on its own: its frames are analyzed for identity.'), audio: z.string().optional().describe('Optional audio source (URL or absolute local path) — the character\'s voice, 5-30s of clean speech. Stored on the DNA and used two ways: (1) as REFERENCE AUDIO in video generation — pass this DNA\'s `audio_clips[0].url` in reference_audio_urls on a model with audio slots (Seedance 2.x, Wan 3.0) and the server tells the model it is that character\'s voice (the web app attaches it for the user; over the API you pass it); (2) as the source for a real speaking voice, but ONLY when you ask for one — see `voice_source`.'), voice_source: z.enum(['none', 'clone', 'assign', 'design']).optional().describe('What to do about a SPEAKING voice. **Pass "none" when the audio is just a reference clip** (the usual case for video work) — the clip is stored and usable as video reference audio, and nothing else happens. "clone" mints an ElevenLabs voice from the uploaded audio, which consumes a voice slot and may EVICT another of the user\'s voices to free one; it also makes the DNA addressable as `dna_<id>` in text-to-speech. "assign" points at an existing voice (pass `assigned_voice_id`). "design" generates a voice from the character\'s look. ⚠️ Omitting this while passing `audio` keeps the legacy behaviour and CLONES — pass "none" explicitly unless the user asked for a voice.'), assigned_voice_id: z.string().optional().describe('Voice to attach when voice_source="assign" — a `custom_<id>` from the user\'s clones or a voice_id from `list_voices`.'), character_sheet_url: z.string().optional().describe('URL of a reference sheet (from `generate_character_sheet`, any sheet_type) to set as the DNA\'s primary reference. Works for ALL DNA types — character turnaround, product detail sheet, location sheet, or style board — and is the single biggest consistency booster. Omit only when the user declines.'), project_id: z.string().optional().describe('Create the DNA inside this project so every teammate with edit access to it can list, fetch and generate with it (pass the same project_id to list_visual_dnas / get_visual_dna / generations). Requires edit access to the project. Omit for a private DNA.') }, async ({ name, dna_type, prompt_helper, description, images, video, audio, voice_source, assigned_voice_id, character_sheet_url, project_id }) => { const helper = prompt_helper !== undefined ? prompt_helper : description; if (!name || !name.trim()) { throw new Error('name is required'); } const imageList = Array.isArray(images) ? images.filter(Boolean) : []; if (imageList.length > 4) { throw new Error('Maximum 4 images allowed'); } if (imageList.length === 0 && !video && !audio) { throw new Error('At least one media reference (image, video, or audio) is required'); } // Resolve all sources to buffers in parallel. const [imageFiles, videoFile, audioFile] = await Promise.all([ Promise.all(imageList.map(src => resolveToBuffer(src, 'image', options))), video ? resolveToBuffer(video, 'video', options) : Promise.resolve(null), audio ? resolveToBuffer(audio, 'audio', options) : Promise.resolve(null) ]).catch((cause) => { throw new Error(`Visual DNA reference preparation failed before submission; this attempt did not create a profile. ${cause.message}`, { cause }); }); const form = new FormData(); form.append('name', name); if (dna_type) form.append('dnaType', dna_type); if (helper) form.append('promptHelper', helper); if (character_sheet_url) form.append('characterSheetUrl', character_sheet_url); // Omitted stays omitted: the server infers 'clone' from a present audio clip, which is the // long-standing behaviour older installs depend on. Only an explicit choice is forwarded. if (voice_source) form.append('voiceSource', voice_source); if (assigned_voice_id) form.append('assignedVoiceId', assigned_voice_id); if (project_id) form.append('project_id', project_id); for (const f of imageFiles) { form.append('images', f.buffer, { filename: f.filename, contentType: f.contentType }); } if (videoFile) { form.append('videos', videoFile.buffer, { filename: videoFile.filename, contentType: videoFile.contentType }); } if (audioFile) { form.append('audio', audioFile.buffer, { filename: audioFile.filename, contentType: audioFile.contentType }); } const result = await client.postMultipart('/v1/visual-dna', form); return { content: [{ type: 'text', text: JSON.stringify(result.visual_dna || result, null, 2) }] }; } ); // ─── list_visual_dnas ────────────────────────────────────── server.tool( 'list_visual_dnas', 'List the user\'s OWN Visual DNA profiles. This is almost always what you want — "my characters", ' + '"which DNAs do I have", picking a DNA for a generation. Pass `project_id` to also include a shared ' + 'project\'s DNAs (teammates\' assets on that project). ' + 'Kolbo ALSO ships a large library of ~1000 global cast/preset DNAs — those are NOT returned by default ' + 'because dumping them buries the user\'s own handful. Only pass scope="global" (optionally with ' + '`collection` and `search`) when the user explicitly wants to BROWSE the preset cast — e.g. "find me a ' + 'character", "show me street style models", "I need a location DNA" — and they have not named one of ' + 'their own. Use scope="all" only if the user genuinely wants both at once. ' + 'The response reports `total` and `_truncated`; when there are more matches than one ' + 'page holds, raise `limit` or walk `page` — do not tell the user the extras do not exist.', { scope: z.enum(['all', 'personal', 'global', 'organization']).optional().describe('Default: "personal" — the user\'s own DNAs (plus a shared project\'s when project_id is set). "global" = the ~1000 system cast/preset DNAs, for browsing when the user needs a character and has none of their own. "organization" = org-shared. "all" = everything, rarely wanted.'), search: z.string().optional().describe('Search by name, tags, or description (case-insensitive). Matches at WORD STARTS, so "man" finds "Man"/"Manager" but not "woman" or "romantic". Name matches are ranked first.'), collection: z.string().optional().describe('Filter global presets by collection: cast, influencers, props, locations, styles, street'), tags: z.string().optional().describe('Comma-separated tags to filter by (OR logic)'), page: z.number().optional().describe('Page number, 1-indexed. Default: 1. Needed to reach the global cast beyond the first page.'), limit: z.number().optional().describe('Results per page, max 100. Default: 50'), project_id: projectScopeReadField }, async ({ scope, search, collection, tags, page, limit, project_id } = {}) => { const params = new URLSearchParams(); // Default to the user's OWN DNAs. The API defaults to "all", which pulls // in ~1000 global cast presets and buries the handful the user actually // made. Global is opt-in via scope="global" (browse the preset cast). // Shared-project assets still come through project_id, independently. const effectiveScope = scope || 'personal'; if (effectiveScope !== 'all') params.set('scope', effectiveScope); if (search) params.set('search', search); if (collection) params.set('collection', collection); if (tags) params.set('tags', tags); // Always paged. Without these the ~1000-item global cast came back whole and // was silently cut to the display cap, so nothing past the first screen was // reachable through this tool at all. params.set('page', String(page && page > 0 ? Math.floor(page) : 1)); params.set('limit', String(limit && limit > 0 ? Math.min(Math.floor(limit), 100) : 50)); if (project_id) params.set('project_id', project_id); const qs = params.toString(); const result = await client.get(`/v1/visual-dna${qs ? '?' + qs : ''}`); const dnas = result.visual_dnas || []; const total = result.total != null ? result.total : (result.count || dnas.length); // Full profiles measured 74,310 chars — the embedded analysis/description // blobs are large and the model only needs enough to pick an id. // `has_voice_reference` rides along because it changes what a DNA DOES in a generation: // such a DNA brings its own voice as reference audio on models with audio slots. Without // it the model has to fetch each DNA in full just to find out. const text = compactList(dnas, { fields: ['id', 'name', 'type', 'dna_type', 'folder_id', 'tags', 'thumbnail', 'description', 'sheet_url', 'has_voice_reference'], cap: 60, total, note: 'Narrow with `search`, `tags`, or `collection`, or pass `page`/`limit` for the rest; get_visual_dna returns one in full.', }); // Always ship structuredContent. Kolbo Code does NOT advertise MCP Apps, so // gating the grid payload on appsEnabled() sent it text only; the host then // rebuilt items from the compactList text, whose field names are // `filename`/`url` — not the `title`/`thumbnail` the grid renders — so every // tile came out black and unlabelled. Same reasoning as listResult(). return uiResult(UI.mediaGrid, text, { widget: 'media-grid', title: 'Visual DNA Profiles', items: dnas.map(d => ({ id: d.id, title: d.name, subtitle: (d.dna_type || '') + (Array.isArray(d.tags) && d.tags.length ? ' · ' + d.tags.slice(0, 3).join(', ') : ''), thumbnail: d.sheet_url || d.thumbnail_url || d.thumbnail, url: d.sheet_url || d.thumbnail_url || d.thumbnail, media_type: 'image', use_hint: 'Use Visual DNA "{TITLE}" (id: {ID}) in my next generation for character/style consistency.' })), total, has_more: !!result.has_more, page: page && page > 0 ? Math.floor(page) : 1, page_tool: 'list_visual_dnas', next_args: result.has_more ? { scope, search, collection, tags, project_id, page: (page && page > 0 ? Math.floor(page) : 1) + 1, limit } : undefined }); } ); // ─── get_visual_dna ──────────────────────────────────────── server.tool( 'get_visual_dna', 'Fetch a single Visual DNA profile by ID. Returns the full stored description, character attributes, and all reference images. Internal extraction system prompts are not exposed. To fetch a teammate\'s Visual DNA that lives in a shared project, pass project_id (you need edit+ on it).', { visual_dna_id: z.string().describe('The Visual DNA profile ID'), project_id: projectScopeReadField }, async ({ visual_dna_id, project_id }) => { const suffix = project_id ? `?project_id=${encodeURIComponent(project_id)}` : ''; const result = await client.get(`/v1/visual-dna/${encodeURIComponent(visual_dna_id)}` + suffix); return { content: [{ type: 'text', text: JSON.stringify(result.visual_dna || result, null, 2) }] }; } ); // ─── update_visual_dna ───────────────────────────────────── server.tool( 'update_visual_dna', 'Edit an existing Visual DNA in place — name, description, type, character sheet, stills, video, audio, or character attributes. NEVER delete and recreate a DNA to change any of those: the old id is what generations, sessions, and @Name bindings already point at. Providing `images` REPLACES the whole still set (max 4) and re-analyzes the profile. Omit images to keep current stills. `video` / `audio` replace only that clip; pass "" to remove it (a voice-only DNA must stay a character). Owner only; global presets cannot be edited (import first).', { visual_dna_id: z.string().describe('Visual DNA id from list_visual_dnas / create_visual_dna.'), name: z.string().optional().describe('New name. Same no-space single-token rule as create_visual_dna — @Name binding stops at the first space.'), dna_type: z.string().optional().describe('Type: "character", "style", "product", "scene", "environment". Changing type re-analyzes the profile.'), prompt_helper: z.string().optional().describe('New description / intent notes. Replaces the old ones and re-synthesizes the DNA analysis when the text actually changes. Pass "" to clear.'), description: z.string().optional().describe('Alias for `prompt_helper`. Accepted because every tool here REPORTS this field as `description`, so callers round-trip that name back in; without the alias zod stripped it and the edit silently did nothing. Ignored when `prompt_helper` is also given.'), images: z.array(z.string()).optional().describe('Full replacement still set (URLs or absolute local paths). Max 4. Omit to keep current stills. Same purity rules as create: one identity, one vibe.'), video: z.string().optional().describe('Replacement video source (URL or absolute local path). Pass "" to remove the DNA\'s video.'), audio: z.string().optional().describe('Replacement audio source (URL or absolute local path). Pass "" to remove the DNA\'s voice clip.'), character_sheet_url: z.string().optional().describe('New reference sheet URL (from generate_character_sheet). Sets the DNA\'s primary sheet without replacing stills.'), remove_character_sheet: z.boolean().optional().describe('If true, clears the stored character sheet. Do not combine with character_sheet_url.'), gender: z.string().optional().describe('Character attribute (character DNAs).'), ethnicity: z.string().optional().describe('Character attribute (character DNAs).'), body_type: z.string().optional().describe('Character attribute (character DNAs).'), hair_color: z.string().optional().describe('Character attribute (character DNAs).'), eye_color: z.string().optional().describe('Character attribute (character DNAs).'), skin_tone: z.string().optional().describe('Character attribute (character DNAs).'), age_range: z.string().optional().describe('Character attribute (character DNAs).'), specific_age: z.number().optional().describe('Character attribute (character DNAs).') }, async ({ visual_dna_id, name, dna_type, prompt_helper, description, images, video, audio, character_sheet_url, remove_character_sheet, gender, ethnicity, body_type, hair_color, eye_color, skin_tone, age_range, specific_age }) => { const helper = prompt_helper !== undefined ? prompt_helper : description; const imageList = Array.isArray(images) ? images.filter(Boolean) : []; if (imageList.length > 4) throw new Error('Maximum 4 images allowed'); const hasMedia = imageList.length > 0 || !!video || !!audio; const removeVideo = video === ''; const removeAudio = audio === ''; const hasMeta = name !== undefined || dna_type !== undefined || helper !== undefined || character_sheet_url !== undefined || remove_character_sheet !== undefined || removeVideo || removeAudio || gender !== undefined || ethnicity !== undefined || body_type !== undefined || hair_color !== undefined || eye_color !== undefined || skin_tone !== undefined || age_range !== undefined || specific_age !== undefined; if (!hasMedia && !hasMeta) { throw new Error('Provide at least one field to update'); } const attrs = { ...(gender !== undefined ? { gender } : {}), ...(ethnicity !== undefined ? { ethnicity } : {}), ...(body_type !== undefined ? { body_type } : {}), ...(hair_color !== undefined ? { hair_color } : {}), ...(eye_color !== undefined ? { eye_color } : {}), ...(skin_tone !== undefined ? { skin_tone } : {}), ...(age_range !== undefined ? { age_range } : {}), ...(specific_age !== undefined ? { specific_age } : {}) }; const path = `/v1/visual-dna/${encodeURIComponent(visual_dna_id)}`; if (!hasMedia) { const body = { ...attrs }; if (name !== undefined) body.name = name; if (dna_type !== undefined) body.dna_type = dna_type; if (helper !== undefined) body.prompt_helper = helper; if (character_sheet_url !== undefined) body.character_sheet_url = character_sheet_url; if (remove_character_sheet !== undefined) body.remove_character_sheet = remove_character_sheet; if (removeVideo) body.remove_video = true; if (removeAudio) body.remove_audio = true; const result = await client.put(path, body); return { content: [{ type: 'text', text: JSON.stringify({ visual_dna: result.visual_dna || result, _hint: 'DNA updated in place — keep using this same id and the new stored name in @tags.' }, null, 2) }] }; } const [imageFiles, videoFile, audioFile] = await Promise.all([ Promise.all(imageList.map(src => resolveToBuffer(src, 'image', options))), video ? resolveToBuffer(video, 'video', options) : Promise.resolve(null), audio ? resolveToBuffer(audio, 'audio', options) : Promise.resolve(null) ]); const form = new FormData(); if (name !== undefined) form.append('name', name); if (dna_type) form.append('dnaType', dna_type); if (helper !== undefined) form.append('promptHelper', helper); if (character_sheet_url) form.append('characterSheetUrl', character_sheet_url); if (remove_character_sheet !== undefined) { form.append('removeCharacterSheet', remove_character_sheet ? 'true' : 'false'); } if (removeVideo) form.append('removeVideo', 'true'); if (removeAudio) form.append('removeAudio', 'true'); for (const [k, v] of Object.entries(attrs)) form.append(k, String(v)); for (const f of imageFiles) { form.append('images', f.buffer, { filename: f.filename, contentType: f.contentType }); } if (videoFile) { form.append('videos', videoFile.buffer, { filename: videoFile.filename, contentType: videoFile.contentType }); } if (audioFile) { form.append('audio', audioFile.buffer, { filename: audioFile.filename, contentType: audioFile.contentType }); } const result = await client.putMultipart(path, form); return { content: [{ type: 'text', text: JSON.stringify({ visual_dna: result.visual_dna || result, _hint: 'DNA updated in place — keep using this same id and the new stored name in @tags.' }, null, 2) }] }; } ); // ─── delete_visual_dna ───────────────────────────────────── server.tool( 'delete_visual_dna', 'Permanently delete a Visual DNA profile. Only the owner can delete. Do NOT use this to rename, restyle, swap stills, or change a description — that is `update_visual_dna`. Confirm with the user before deleting a DNA they did not just create.', { visual_dna_id: z.string().describe('The Visual DNA profile ID to delete') }, async ({ visual_dna_id }) => { const result = await client.delete(`/v1/visual-dna/${encodeURIComponent(visual_dna_id)}`); return { content: [{ type: 'text', text: JSON.stringify({ success: true, message: result.message || 'Visual DNA deleted' }, null, 2) }] }; } ); // ─── generate_character_sheet ────────────────────────────── server.tool( 'generate_character_sheet', "Generates a reference sheet image for a Visual DNA from 1 or more reference image URLs. Charges credits: before the user creates a Visual DNA, offer a sheet (it improves consistency) and run it only when they agree. sheet_type: character = multi-angle turnaround; product = angles plus branding, material and construction close-ups; environment = location angles plus one signature detail (no main character or recognizable face; an anonymous crowd is fine); style = one look applied to six varied subjects. Use reference images of one identity and look. The sheet keeps the reference's art style (2D stays 2D, photo stays photo). Returns character_sheet_url: pass it as character_sheet_url to create_visual_dna with the matching dna_type. Models: mirage-film-2 (3 credits) suits cinematic environments and invented characters; GPT Image 2.5 Flare or Sunburst and nano-banana-2 suit reference fidelity and legible text. This tool does not run GPT Image 2.6 or Nano Banana 2.1; for those, use generate_image_edit with the character-sheet preset. For a film or ad, make a sheet for each character, location and prop the script needs and confirm the set with the user before generating video.", { image_urls: z.array(z.string()).min(1).describe('Reference image URLs of the subject (for characters: front/side/varied angles work best). Use generated-image URLs or upload_media output.'), sheet_type: z.enum(['character', 'character_headless', 'character_bible', 'product', 'environment', 'style']).optional().describe('Sheet layout. character = front/back/face turnaround. character_headless = wardrobe/body refs with a headless front panel (use when clothing must change without fighting the face sheet). character_bible = denser production model-sheet (turnaround + faces + wardrobe + color swatches). product / environment / style = matching DNA types. Defaults to character. This IS the Character Sheet / Headless / Bible preset — do not call list_presets for those names.'), model: z.string().optional().describe('Image model for the sheet. Default GPT Image 2.5 Flare edit. Accepts gpt-image-2.5-flare / gpt-image-2.5-sunburst, gpt-image-2 and nano-banana-2. GPT Image 2.6 and Nano Banana 2.1 are not supported by this tool yet (the server maps them to the 2.5 / Nano Banana 2 rows).'), resolution: z.enum(['2K', '4K']).optional().describe('Sheet resolution. 2K or 4K only — never 1K. Default 2K. Use 4K for character_bible, high-detail leads, or when the user asks.') }, async ({ image_urls, sheet_type, model, resolution }) => { // The endpoint is blocking and a 2K multi-panel sheet routinely runs past the // 120s default: the MCP aborted while kolbo-api kept going, finished, and // billed — the user saw "Failed" for a sheet they had already paid for. const result = await client.post( '/v1/visual-dna/character-sheet', { image_urls, ...(sheet_type ? { sheet_type } : {}), ...(model ? { model } : {}), ...(resolution ? { resolution } : {}), }, { timeoutMs: CHARACTER_SHEET_TIMEOUT_MS }, ); // `urls` is NOT redundant with character_sheet_url. Every generation-card // reader keys on `urls` — the MCP's own widget (apps/widgets/generation.js), // kolbo-code's kolbo-operation.ts mediaUrls(), and its operation.js urlsOf(). // Kolbo Code mounts a generation card for ANY tool named `generate_*`, so // returning only character_sheet_url gave the card zero URLs and it rendered // "No output received / Failed" on top of a sheet that generated fine and was // already billed — and "Try Again" then double-charged. `widget`/`phase` mark // the payload as a completed generation so the card stops falling back to the // stale `phase: "review"` envelope built before the tool ran. const urls = result.character_sheet_url ? [result.character_sheet_url] : []; return { content: [{ type: 'text', text: JSON.stringify({ character_sheet_url: result.character_sheet_url, urls, widget: 'generation', phase: 'completed', kind: 'image', credits_used: result.credits_used, _hint: 'Show the sheet to the user, then pass character_sheet_url to create_visual_dna (new DNA) or update_visual_dna (existing DNA). Never delete and recreate.' }, null, 2) }] }; } ); // ─── Visual DNA folders (organize characters) ────────────── // Folders are user-scoped and flat. Only PERSONAL Visual DNAs can live in // folders — global/organization presets are rejected by the server. server.tool( 'list_visual_dna_folders', 'List the user\'s Visual DNA folders with per-folder item counts. Use to organize large character casts: find the right folder before moving a DNA, or show the user how their characters are grouped. To list the DNAs INSIDE a folder, call `list_visual_dnas` and filter by the `folder_id` field on each profile.', {}, async () => { const result = await client.get('/v1/visual-dna/folders'); const folders = result.folders || []; const text = JSON.stringify({ folders, count: result.count || 0 }, null, 2); return listResult(text, { widget: 'list', title: 'Visual DNA Folders', items: folders.map(f => ({ id: f.id, title: f.name, meta: f.item_count != null ? (f.item_count + (f.item_count === 1 ? ' DNA' : ' DNAs')) : null, use_hint: 'List Visual DNAs in my "{TITLE}" folder (folder_id: {ID}).' })), total: folders.length }); } ); server.tool( 'create_visual_dna_folder', 'Create a Visual DNA folder for organizing characters (e.g. "Main Cast", "Villains", "Film X Characters"). Folder names are unique per user (409 on duplicates). Then use `move_visual_dna_to_folder` to file DNAs into it.', { name: z.string().describe('Folder name (max 100 chars, unique per user).'), color: z.string().optional().describe('Optional hex color for the folder chip, e.g. "#FF5733".') }, async ({ name, color }) => { const body = { name }; if (color) body.color = color; const result = await client.post('/v1/visual-dna/folders', body); return { content: [{ type: 'text', text: JSON.stringify(result.folder, null, 2) }] }; } ); server.tool( 'update_visual_dna_folder', 'Rename and/or recolor a Visual DNA folder.', { folder_id: z.string().describe('The folder id (from list_visual_dna_folders).'), name: z.string().describe('New folder name (required by the server — pass the current name to keep it).'), color: z.string().optional().describe('New hex color, e.g. "#00AA00".') }, async ({ folder_id, name, color }) => { const body = { name }; if (color !== undefined) body.color = color; const result = await client.put(`/v1/visual-dna/folders/${encodeURIComponent(folder_id)}`, body); return { content: [{ type: 'text', text: JSON.stringify(result.folder, null, 2) }] }; } ); server.tool( 'delete_visual_dna_folder', 'Delete a Visual DNA folder. The DNAs inside are NOT deleted — they move back to the root level (response includes items_moved_to_root). Safe to call without confirmation for empty folders; mention the contents-move when the folder has items.', { folder_id: z.string().describe('The folder id to delete.') }, async ({ folder_id }) => { const result = await client.delete(`/v1/visual-dna/folders/${encodeURIComponent(folder_id)}`); return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] }; } ); server.tool( 'move_visual_dna_to_folder', 'Move a Visual DNA into a folder, or back to root. Personal DNAs only — global presets must be imported first, and organization DNAs cannot go in personal folders. When creating many characters for a project, create a folder first and file each DNA as you go.', { visual_dna_id: z.string().describe('The Visual DNA profile id to move.'), folder_id: z.string().nullable().describe('Target folder id (from list_visual_dna_folders), or null to move the DNA back to root.') }, async ({ visual_dna_id, folder_id }) => { const result = await client.put(`/v1/visual-dna/${encodeURIComponent(visual_dna_id)}/folder`, { folder_id: folder_id ?? null }); return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] }; } ); registerVisualDnaTransferTools(server, client); } // ─── Visual DNA transfer (send DNAs to another account) ────── function registerVisualDnaTransferTools(server, client) { server.tool( 'transfer_visual_dna', 'Send one or more Visual DNAs you OWN to another Kolbo account (by email). Nothing changes until they accept (in the app, or via `respond_visual_dna_transfer`) within 7 days. On accept they get their OWN copy of each DNA (new ids, same references, description and voice settings; renamed "Name (1)" if they already have that name). `keep_sender_copy` (default true) keeps yours; false = a MOVE — your originals go to trash on accept. Global, organization and still-generating DNAs cannot be sent. Cloned/designed custom voices stay owned by you. ALWAYS confirm the recipient email, the DNA list and the keep-copy choice with the user before calling.', { visual_dna_ids: z.array(z.string()).min(1).max(50).describe('Visual DNA ids you own (from list_visual_dnas). 1-50.'), email: z.string().describe('Email of the EXISTING Kolbo account that should receive them.'), keep_sender_copy: z.boolean().optional().describe('Keep your own copy after they accept. Default: true. false = move (your originals are trashed on accept).'), }, async ({ visual_dna_ids, email, keep_sender_copy }) => { const result = await client.post('/v1/visual-dna-transfers', { visual_dna_ids, email, ...(keep_sender_copy === undefined ? {} : { keep_sender_copy }), }); return { content: [{ type: 'text', text: JSON.stringify(result.transfer, null, 2) }] }; } ); server.tool( 'list_visual_dna_transfers', 'List Visual DNA transfer requests. `direction: incoming` (default) = DNAs other people want to send you; `outgoing` = ones you sent. Defaults to pending only. Use the `id` with `respond_visual_dna_transfer`.', { direction: z.enum(['incoming', 'outgoing']).optional().describe('Default: incoming.'), status: z.enum(['pending', 'accepted', 'declined', 'cancelled', 'expired', 'failed']).optional().describe('Default: pending.'), }, async ({ direction, status }) => { const params = new URLSearchParams(); if (direction) params.set('direction', direction); if (status) params.set('status', status); const qs = params.toString(); const result = await client.get(`/v1/visual-dna-transfers${qs ? '?' + qs : ''}`); return { content: [{ type: 'text', text: JSON.stringify(result.transfers || [], null, 2) }] }; } ); server.tool( 'respond_visual_dna_transfer', 'Act on a Visual DNA transfer request. `accept` / `decline` = you are the recipient; `cancel` = you sent it. Accept adds copies to your library and returns their NEW ids in `copies` — use those ids (and their names as @Name tags) in generations. Confirm with the user before accepting.', { transfer_id: z.string().describe('Transfer id from list_visual_dna_transfers.'), action: z.enum(['accept', 'decline', 'cancel']), }, async ({ transfer_id, action }) => { const id = encodeURIComponent(transfer_id); // Explicit paths (not `/${action}`) so check-parity can see each route. let result; if (action === 'cancel') result = await client.delete(`/v1/visual-dna-transfers/${id}`); else if (action === 'accept') result = await client.post(`/v1/visual-dna-transfers/${id}/accept`, {}); else result = await client.post(`/v1/visual-dna-transfers/${id}/decline`, {}); return { content: [{ type: 'text', text: JSON.stringify(result.transfer, null, 2) }] }; } ); } module.exports = { registerVisualDnaTools };