@simpligen/mcp 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/tools.js +511 -510
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simpligen/mcp",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "MCP server for SimpliGen -- drive local/cloud AI image & video generation from an agent.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/tools.js CHANGED
@@ -1,510 +1,511 @@
1
- // packages/mcp-server/src/tools.js
2
- // Registers SimpliGen MCP tools on an McpServer-shaped object. Each tool calls a
3
- // ControlApiClient method and returns the JSON result as text content; client
4
- // errors become an isError tool result (so the agent sees the errorCode/message).
5
- import { z } from 'zod';
6
- import { buildResultImageContent } from './resultImage.js';
7
-
8
- export const TOOL_NAMES = [
9
- 'list_capabilities', 'get_status', 'start_engine', 'stop_engine', 'restart_engine',
10
- 'list_projects', 'create_project',
11
- 'upload_file', 'generate', 'list_loras', 'get_job', 'wait_for_result', 'list_jobs',
12
- 'cancel_job', 'prepare_preset', 'get_result_image',
13
- 'list_characters', 'get_character', 'list_character_features', 'list_character_presets',
14
- 'remove_character', 'create_character', 'generate_character_image', 'generate_character_video',
15
- 'generate_character_frame', 'animate_character', 'set_character_preset',
16
- 'enhance_character_media', 'regenerate_character_base',
17
- 'list_recipe_blocks', 'compose_recipe', 'validate_recipe', 'list_recipes', 'get_recipe', 'publish_recipe',
18
- 'run_recipe', 'get_recipe_run', 'wait_for_recipe_run', 'list_recipe_runs', 'cancel_recipe_run',
19
- 'list_subjects', 'list_products', 'create_product', 'remove_product',
20
- ];
21
-
22
- const ok = (data) => ({ content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] });
23
- const fail = (err) => ({ isError: true, content: [{ type: 'text', text: `${err.errorCode ? err.errorCode + ': ' : ''}${err.message || String(err)}` }] });
24
- const wrap = (fn) => async (args) => { try { return ok(await fn(args)); } catch (e) { return fail(e); } };
25
-
26
- export function registerTools(server, client) {
27
- server.registerTool('list_capabilities',
28
- { title: 'List capabilities', description: 'List every SimpliGen preset the agent can generate with (image/video), its inputs/options, whether it is installed locally (localReady) and cloud-eligible + credit cost.', inputSchema: {} },
29
- wrap(() => client.getCapabilities()));
30
-
31
- server.registerTool('get_status',
32
- { title: 'Get status', description: 'Engine running state, whether cloud is connected, credit balance, and the active project.', inputSchema: {} },
33
- wrap(() => client.getStatus()));
34
-
35
- // The engine's lifecycle. get_status could always report it was down and
36
- // there was nothing an agent could do about it but ask the human to click
37
- // Start (user report, 2026-09-24). Install, update and repair stay out of
38
- // reach on purpose: those are multi-GB downloads that belong in front of a
39
- // person.
40
- server.registerTool('start_engine',
41
- { title: 'Start engine', description: 'Start the local engine if it is not already running. Returns the engine state; a cold boot can outlast the call, in which case engineStarting is true and get_status tells you when it is up. Does nothing if the engine is already running, and will not install one that is missing.', inputSchema: {} },
42
- wrap(() => client.startEngine()));
43
-
44
- server.registerTool('stop_engine',
45
- { title: 'Stop engine', description: 'Stop the local engine. Frees its VRAM; cloud generation is unaffected.', inputSchema: {} },
46
- wrap(() => client.stopEngine()));
47
-
48
- server.registerTool('restart_engine',
49
- { title: 'Restart engine', description: 'Restart the local engine. Use it after installing or removing a custom node, or when the engine is wedged.', inputSchema: {} },
50
- wrap(() => client.restartEngine()));
51
-
52
- server.registerTool('list_projects',
53
- { title: 'List projects', description: 'List projects (output containers).', inputSchema: {} },
54
- wrap(() => client.listProjects()));
55
-
56
- server.registerTool('create_project',
57
- { title: 'Create project', description: 'Create a new project (output container).', inputSchema: { name: z.string().describe('Project name') } },
58
- wrap(({ name }) => client.createProject(name)));
59
-
60
- server.registerTool('upload_file',
61
- { title: 'Upload a file', description: 'Upload a local image/video file and get an opaque handle to pass as image/referenceImages/video in generate.', inputSchema: { path: z.string().describe('Absolute local file path') } },
62
- wrap(({ path }) => client.uploadFile(path)));
63
-
64
- server.registerTool('generate',
65
- {
66
- title: 'Generate', description: 'Start an image or video generation. Inputs (image/referenceImages/video) are handles from upload_file. backend: local | cloud | auto. Returns a jobId; poll with wait_for_result or get_job.',
67
- inputSchema: {
68
- presetId: z.string(), mediaType: z.enum(['image', 'video']), prompt: z.string(),
69
- packId: z.string().optional(), backend: z.enum(['local', 'cloud', 'auto']).optional(),
70
- negativePrompt: z.string().optional(), project: z.string().optional(),
71
- image: z.string().optional().describe('upload_file handle'),
72
- // A bare handle still works, so every agent written against the old
73
- // schema keeps working. The object form carries the per-image label,
74
- // which is the DESCRIPTION the app asks for when list_capabilities says
75
- // inputs.referenceImages.requiresDescriptions is true (LTX 2.5
76
- // Multi-Reference builds one appearance line per subject from it).
77
- // Sending images without it on such a preset runs, but the subjects
78
- // blur together, which is indistinguishable from the model being bad.
79
- referenceImages: z.array(z.union([
80
- z.string(),
81
- z.object({
82
- handle: z.string().describe('upload_file handle'),
83
- label: z.string().optional().describe('What this reference IS, e.g. "a woman with red hair". Required in spirit when the preset reports requiresDescriptions.'),
84
- }),
85
- ])).optional().describe('upload_file handles, or {handle, label} when the preset wants a description per reference'),
86
- video: z.string().optional().describe('upload_file handle (driving video)'),
87
- // The App has accepted these three since 1.58.0; this schema never
88
- // offered them, so no agent could drive an audio preset at all: the
89
- // error said needs_audio and there was nowhere to put a sound
90
- // (mavr1k_, 2026-10-01). Passing it inside `options` does not work
91
- // either, since preflight reads the top level.
92
- audio: z.string().optional().describe('upload_file handle for the PRIMARY audio track (lip-sync / audio-to-video presets). Required when list_capabilities reports inputs.acceptsAudio true, optional when it reports "optional".'),
93
- referenceAudios: z.array(z.union([
94
- z.string(),
95
- z.object({ handle: z.string(), durationSeconds: z.number().optional() }),
96
- ])).optional().describe('upload_file handles for reference SOUNDS (a voice per subject, where the preset pairs them with references).'),
97
- referenceVideos: z.array(z.union([
98
- z.string(),
99
- z.object({
100
- handle: z.string(),
101
- soundtrackMode: z.enum(['own', 'file', 'none']).optional().describe("Where this clip's sound comes from; defaults to 'own'."),
102
- durationSeconds: z.number().optional(),
103
- }),
104
- ])).optional().describe('upload_file handles for reference CLIPS (MiniMax H3 scene chaining chains on a clip).'),
105
- // Appended to the prompt by the app's own dialogue formatter, so the
106
- // wording matches what the preset was tuned on. MiniMax H3 lip-syncs
107
- // to it; sending it to a preset that does not declare supportsDialogue
108
- // changes nothing.
109
- dialogue: z.string().optional().describe('A spoken line for the character, when list_capabilities reports inputs.supportsDialogue.'),
110
- dialogueDelivery: z.string().optional().describe('How the line is delivered, e.g. "urgent", "whispered". Only meaningful with dialogue.'),
111
- loras: z.array(z.object({ name: z.string().describe('LoRA display name from list_loras'), weight: z.number().optional().describe('Strength; defaults to the LoRA default') })).optional().describe('LoRAs to apply. Local backend only, and only for presets where inputs.supportsLoras is true. Use the LoRA trigger words in the prompt so it activates.'),
112
- // .passthrough(), not the zod default: a plain z.object STRIPS every key it
113
- // does not name, silently. The App's /generate accepts any Advanced
114
- // Control the preset declares (unlock, shift, high_steps, ...) and
115
- // list_capabilities advertises them under options.controls, so an agent
116
- // was told a control exists, sent it, and got the preset default back
117
- // with no error: unlock: 1 arrived at the graph as 0.5 (Melvyl, 1.63.0).
118
- // The App applies only what the preset declares and ignores the rest,
119
- // so forwarding everything is safe. Known fields stay named so the
120
- // agent still sees them in the tool's schema.
121
- options: z.object({
122
- resolution: z.string().optional().describe('Resolution tier label; see list_capabilities -> options.resolution.'),
123
- aspectRatio: z.string().optional().describe('Aspect ratio, e.g. "1:1", "16:9", "9:16" (portrait/vertical), "4:3", "3:4". See list_capabilities -> options.aspectRatio for the values each preset accepts. Defaults to 1:1 for images (16:9 for video) if omitted.'),
124
- durationSeconds: z.number().optional(),
125
- steps: z.number().optional(),
126
- cfg: z.number().optional(),
127
- seed: z.number().optional(),
128
- negativePrompt: z.string().optional(),
129
- fasterAttention: z.boolean().optional().describe('Accelerator toggle; absent = preset default.'),
130
- solAttn: z.boolean().optional().describe('Accelerator toggle; absent = preset default.'),
131
- spectrum: z.boolean().optional().describe('Accelerator toggle; absent = preset default.'),
132
- }).passthrough().optional().describe('Run options. Besides the named fields, pass ANY Advanced Control the preset declares under list_capabilities -> options.controls (for example unlock, shift, high_steps) as a top-level key of this object, using the value range that map gives. A key the preset does not declare is ignored.'),
133
- },
134
- },
135
- wrap((args) => client.generate(args)));
136
-
137
- server.registerTool('list_loras',
138
- { title: 'List LoRAs', description: 'List the installed user LoRAs (name, base model, trigger words) so you can pass them in generate -> loras.', inputSchema: {} },
139
- wrap(() => client.listLoras()));
140
-
141
- server.registerTool('get_job',
142
- { title: 'Get job', description: 'Status + result of a generation job. resultPath is the local file when completed.', inputSchema: { jobId: z.string() } },
143
- wrap(({ jobId }) => client.getJob(jobId)));
144
-
145
- server.registerTool('list_jobs',
146
- { title: 'List jobs', description: 'Recent generation jobs.', inputSchema: {} },
147
- wrap(() => client.listJobs()));
148
-
149
- server.registerTool('cancel_job',
150
- { title: 'Cancel job', description: 'Cancel a queued/running job.', inputSchema: { jobId: z.string() } },
151
- wrap(({ jobId }) => client.cancelJob(jobId)));
152
-
153
- server.registerTool('prepare_preset',
154
- { title: 'Prepare preset', description: 'Start downloading a local preset\'s models (so it becomes localReady). Poll list_capabilities for localReady.', inputSchema: { presetId: z.string(), mediaType: z.enum(['image', 'video']), packId: z.string().optional() } },
155
- wrap((args) => client.preparePreset(args)));
156
-
157
- // Convenience: poll get_job until terminal or timeout (no extra endpoint).
158
- server.registerTool('wait_for_result',
159
- { title: 'Wait for result', description: 'Block until a job completes or fails (or the timeout). Returns the final job (resultPath when completed).', inputSchema: { jobId: z.string(), timeoutSeconds: z.number().optional(), pollMs: z.number().optional() } },
160
- wrap(async ({ jobId, timeoutSeconds = 300, pollMs = 2000 }) => {
161
- const deadline = Date.now() + timeoutSeconds * 1000;
162
- // eslint-disable-next-line no-constant-condition
163
- while (true) {
164
- const { job } = await client.getJob(jobId);
165
- if (!job || job.status === 'completed' || job.status === 'failed') return job;
166
- if (Date.now() >= deadline) return { ...job, note: 'timeout_still_running' };
167
- await new Promise((r) => setTimeout(r, pollMs));
168
- }
169
- }));
170
-
171
- // Return a completed job's result image inline (an MCP image block) so the
172
- // agent can actually display it. Images only; video/unreadable -> path note.
173
- server.registerTool('get_result_image',
174
- { title: 'Get result image', description: 'Return a completed job\'s result image inline as a viewable image so it can be displayed in chat. Large images are re-encoded to a full-resolution WebP preview that fits the client size cap; the uncompressed original file path is always included in the caption. Video results return the file path instead. Call after the job is completed.', inputSchema: { jobId: z.string(), maxBytes: z.number().optional().describe('Inline byte budget before re-encoding/resizing (default ~700KB raw)') } },
175
- async ({ jobId, maxBytes }) => {
176
- try {
177
- const { job } = await client.getJob(jobId);
178
- return await buildResultImageContent(job, { budgetBytes: maxBytes });
179
- } catch (e) {
180
- return fail(e);
181
- }
182
- });
183
-
184
- // ---- Character Studio tools ----
185
-
186
- server.registerTool('list_characters',
187
- { title: 'List characters', description: 'List all saved characters in Character Studio.', inputSchema: {} },
188
- wrap(() => client.listCharacters()));
189
-
190
- server.registerTool('get_character',
191
- { title: 'Get character', description: 'Get a single character by ID, including its current base portrait and identity features.', inputSchema: { characterId: z.string() } },
192
- wrap(({ characterId }) => client.getCharacter(characterId)));
193
-
194
- server.registerTool('list_character_features',
195
- { title: 'List character features', description: 'List available feature categories and their options (e.g. hairColor, eyeColor) for use with create_character identity.', inputSchema: {} },
196
- wrap(() => client.listCharacterFeatures()));
197
-
198
- server.registerTool('list_character_presets',
199
- { title: 'List character presets', description: 'List generation presets available for Character Studio. Returns base, identityEdit, and i2v presets as well as enhanceImage and enhanceVideo presets (each with supportedScales). Use the returned ids as presetId/imagePresetId/videoPresetId/basePresetId arguments in other character tools.', inputSchema: {} },
200
- wrap(() => client.listCharacterPresets()));
201
-
202
- server.registerTool('remove_character',
203
- { title: 'Remove character', description: 'Permanently delete a character and its associated data.', inputSchema: { characterId: z.string() } },
204
- wrap(({ characterId }) => client.removeCharacter(characterId)));
205
-
206
- server.registerTool('create_character',
207
- {
208
- title: 'Create character',
209
- description: 'Create a new character. Three paths: (1) describe -- pass gender and identity features from list_character_features with mode "generate"; the server builds a base portrait automatically and this tool waits until ready. (2) upload as base -- pass baseFilePath pointing to a local image with mode "upload"; the image becomes the base portrait immediately. (3) vision recreate -- describe path but fill identity by having the agent analyse a reference photo first; the agent extracts features and passes them as identity.',
210
- inputSchema: {
211
- name: z.string().describe('Display name for the character'),
212
- gender: z.enum(['woman', 'man', 'nonbinary']),
213
- mode: z.enum(['generate', 'upload']).describe('generate: build base portrait from description; upload: use a provided image as base'),
214
- identity: z.record(z.string()).optional().describe('An object of featureId to optionId pairs chosen from list_character_features (e.g. { hairColor: "black", eyeColor: "green" }). Do not include gender here; pass gender separately.'),
215
- baseFilePath: z.string().optional().describe('Absolute local image path; required for mode "upload"'),
216
- timeoutSeconds: z.number().optional().describe('Max seconds to wait for base portrait generation (default 300, mode generate only)'),
217
- pollMs: z.number().optional().describe('Poll interval in milliseconds (default 2000, mode generate only)'),
218
- },
219
- },
220
- async ({ name, gender, mode, identity, baseFilePath, timeoutSeconds, pollMs }) => {
221
- try {
222
- if (mode === 'upload') {
223
- const up = await client.uploadFile(baseFilePath);
224
- const char = await client.createCharacter({ name, gender, mode: 'upload', identity, baseHandle: up.handle });
225
- return ok({ ...char, ready: true });
226
- }
227
- // mode === 'generate': create then poll until base_image_url is set
228
- const c = await client.createCharacter({ name, gender, mode: 'generate', identity });
229
- const { characterId } = c;
230
- const deadline = Date.now() + (timeoutSeconds ?? 300) * 1000;
231
- while (true) {
232
- const { character } = await client.getCharacter(characterId);
233
- if (character?.base_image_url) return ok(character);
234
- if (Date.now() >= deadline) return ok({ ...character, base_pending: true });
235
- await new Promise((r) => setTimeout(r, pollMs ?? 2000));
236
- }
237
- } catch (e) {
238
- return fail(e);
239
- }
240
- });
241
-
242
- server.registerTool('generate_character_image',
243
- {
244
- title: 'Generate character image',
245
- description: 'Generate one or more images of a character in a scene. Returns jobIds; use wait_for_result then get_result_image for each. Pass presetId to override the default image preset (ids from list_character_presets).',
246
- inputSchema: {
247
- characterId: z.string(),
248
- prompt: z.string(),
249
- aspect: z.enum(['16:9', '9:16', '1:1']).optional(),
250
- count: z.number().optional(),
251
- presetId: z.string().optional().describe('Override image preset (id from list_character_presets)'),
252
- },
253
- },
254
- wrap(({ characterId, prompt, aspect, count, presetId }) => {
255
- const args = { prompt, aspect, count };
256
- if (presetId !== undefined) args.presetId = presetId;
257
- return client.generateCharacterImage(characterId, args);
258
- }));
259
-
260
- server.registerTool('generate_character_video',
261
- {
262
- title: 'Generate character video',
263
- description: 'Generate a short video of a character in a scene. Internally generates a frame then animates it (I2V). Returns frameJobId and videoJobId; use wait_for_result then get_result_image on videoJobId. Use framePresetId to override the image-frame preset and videoPresetId to override the video/animate preset (ids from list_character_presets).',
264
- inputSchema: {
265
- characterId: z.string(),
266
- prompt: z.string(),
267
- motion: z.string().optional().describe('Optional motion description or style hint'),
268
- aspect: z.enum(['16:9', '9:16', '1:1']).optional(),
269
- timeoutSeconds: z.number().optional().describe('Max seconds to wait for the frame job (default 300)'),
270
- pollMs: z.number().optional().describe('Poll interval in milliseconds (default 2000)'),
271
- framePresetId: z.string().optional().describe('Override image-frame preset (id from list_character_presets)'),
272
- videoPresetId: z.string().optional().describe('Override video/animate preset (id from list_character_presets)'),
273
- },
274
- },
275
- async ({ characterId, prompt, motion, aspect, timeoutSeconds = 300, pollMs = 2000, framePresetId, videoPresetId }) => {
276
- try {
277
- // 1. Generate a frame (still image for I2V)
278
- const { jobIds: [frameJobId] } = await client.generateCharacterFrame(characterId, { prompt, aspect, presetId: framePresetId });
279
- // 2. Wait for frame to complete
280
- const deadline = Date.now() + timeoutSeconds * 1000;
281
- while (true) {
282
- const { job: frameJob } = await client.getJob(frameJobId);
283
- if (frameJob?.status === 'completed') break;
284
- if (frameJob?.status === 'failed') return fail({ message: `Frame job failed: ${frameJobId}`, errorCode: 'frame_failed' });
285
- if (Date.now() >= deadline) return fail({ message: `Frame job timed out: ${frameJobId}`, errorCode: 'frame_timeout' });
286
- await new Promise((r) => setTimeout(r, pollMs));
287
- }
288
- // 3. Animate from the completed frame
289
- const { jobIds: [videoJobId] } = await client.animateCharacter(characterId, { frameJobId, motion, aspect, presetId: videoPresetId });
290
- return ok({ frameJobId, videoJobId });
291
- } catch (e) { return fail(e); }
292
- });
293
-
294
- // ---- New Character Studio tools (Task 4) ----
295
-
296
- server.registerTool('generate_character_frame',
297
- {
298
- title: 'Generate character frame',
299
- description: 'Generate a start-frame image for a character that you can review or enhance before animating. Returns jobIds; use wait_for_result then get_result_image. Pass presetId to override the frame-image preset (ids from list_character_presets).',
300
- inputSchema: {
301
- characterId: z.string(),
302
- prompt: z.string(),
303
- aspect: z.enum(['16:9', '9:16', '1:1']).optional(),
304
- presetId: z.string().optional().describe('Override image preset (id from list_character_presets)'),
305
- },
306
- },
307
- wrap(({ characterId, prompt, aspect, presetId }) => {
308
- const args = { prompt, aspect };
309
- if (presetId !== undefined) args.presetId = presetId;
310
- return client.generateCharacterFrame(characterId, args);
311
- }));
312
-
313
- server.registerTool('animate_character',
314
- {
315
- title: 'Animate character',
316
- description: 'Animate a character from a completed image/frame job or a local file path (I2V). jobId may be any completed character image, frame, or upscale job. Returns jobIds; use wait_for_result then get_result_image. Pass videoPresetId to override the video preset (ids from list_character_presets).',
317
- inputSchema: {
318
- characterId: z.string(),
319
- jobId: z.string().optional().describe('Any completed character image/frame/upscale jobId to use as the source frame'),
320
- filePath: z.string().optional().describe('Absolute local image path to use as the source frame'),
321
- motion: z.string().optional().describe('Optional motion description or style hint'),
322
- aspect: z.enum(['16:9', '9:16', '1:1']).optional(),
323
- videoPresetId: z.string().optional().describe('Override video/animate preset (id from list_character_presets)'),
324
- },
325
- },
326
- wrap(({ characterId, jobId, filePath, motion, aspect, videoPresetId }) =>
327
- client.animateCharacter(characterId, { frameJobId: jobId, framePath: filePath, motion, aspect, presetId: videoPresetId })));
328
-
329
- server.registerTool('set_character_preset',
330
- {
331
- title: 'Set character preset',
332
- description: 'Set sticky per-character default presets for image and/or video generation. Ids come from list_character_presets. Pass null to clear a preset back to the system default.',
333
- inputSchema: {
334
- characterId: z.string(),
335
- imagePresetId: z.string().nullable().optional().describe('Default image preset id (null to clear)'),
336
- videoPresetId: z.string().nullable().optional().describe('Default video preset id (null to clear)'),
337
- },
338
- },
339
- wrap(({ characterId, imagePresetId, videoPresetId }) => client.setCharacterPreset(characterId, { imagePresetId, videoPresetId })));
340
-
341
- server.registerTool('enhance_character_media',
342
- {
343
- title: 'Enhance character media',
344
- description: 'Upscale a generated image/video, a local file, or the character base portrait (target: "base"). Returns a jobId; use wait_for_result then get_result_image. scale sets the upscale factor; keepResolution upscales then resizes back to source size for a sharper same-size result; applyAsBase replaces the character base portrait with the upscaled result. Enhance presets come from list_character_presets (enhanceImage/enhanceVideo, each with supportedScales).',
345
- inputSchema: {
346
- characterId: z.string(),
347
- jobId: z.string().optional().describe('Completed job whose result to enhance'),
348
- filePath: z.string().optional().describe('Absolute local image/video path to enhance'),
349
- target: z.enum(['base']).optional().describe('Pass "base" to enhance the character base portrait'),
350
- mediaType: z.enum(['image', 'video']).optional(),
351
- presetId: z.string().optional().describe('Enhance preset id from list_character_presets'),
352
- scale: z.number().optional().describe('Upscale factor (e.g. 2 for 2x)'),
353
- keepResolution: z.boolean().optional().describe('Upscale then resize back to source dimensions for a sharper same-size result'),
354
- applyAsBase: z.boolean().optional().describe('Replace the character base portrait with the upscaled result'),
355
- },
356
- },
357
- wrap(({ characterId, jobId, filePath, target, mediaType, presetId, scale, keepResolution, applyAsBase }) =>
358
- client.enhanceCharacterMedia(characterId, { jobId, filePath, target, mediaType, presetId, scale, keepResolution, applyAsBase })));
359
-
360
- server.registerTool('regenerate_character_base',
361
- {
362
- title: 'Regenerate character base',
363
- description: 'Switch the base model and regenerate the base portrait IN PLACE (no new character created). Replaces the current base when completed. Uses basePresetId from list_character_presets. Optionally update identity features at the same time. Polls until completed, then auto-accepts the new base.',
364
- inputSchema: {
365
- characterId: z.string(),
366
- basePresetId: z.string().optional().describe('Base-generation preset id from list_character_presets'),
367
- identity: z.record(z.string()).optional().describe('Updated identity feature map (featureId -> optionId) to apply alongside the new base'),
368
- timeoutSeconds: z.number().optional().describe('Max seconds to wait for the base job (default 300)'),
369
- pollMs: z.number().optional().describe('Poll interval in milliseconds (default 2000)'),
370
- },
371
- },
372
- async ({ characterId, basePresetId, identity, timeoutSeconds = 300, pollMs = 2000 }) => {
373
- try {
374
- const { baseJobId } = await client.regenerateCharacterBase(characterId, { basePresetId, identity });
375
- const deadline = Date.now() + timeoutSeconds * 1000;
376
- while (true) {
377
- const { job } = await client.getJob(baseJobId);
378
- if (job?.status === 'completed') {
379
- await client.acceptBase(characterId, { altImageId: baseJobId });
380
- return ok(await client.getCharacter(characterId));
381
- }
382
- if (job?.status === 'failed') return fail({ message: `Base regeneration job failed: ${baseJobId}`, errorCode: 'base_failed' });
383
- if (Date.now() >= deadline) return ok({ baseJobId, note: 'timeout_still_running' });
384
- await new Promise((r) => setTimeout(r, pollMs));
385
- }
386
- } catch (e) { return fail(e); }
387
- });
388
-
389
- // --- Recipe authoring: compose multi-step recipes out of packs/presets ---
390
-
391
- const recipeStep = z.object({
392
- preset: z.string().describe('The preset this step runs, as "packId:presetId" (from list_recipe_blocks).'),
393
- entry: z.string().optional().describe('Entry point: create-image | create-video | edit-image | upscale. Inferred from the preset when omitted.'),
394
- promptInput: z.object({ key: z.string().optional(), label: z.string().optional() }).optional()
395
- .describe('Name this step\'s prompt input, or set key to an existing input to SHARE a prompt. Default: a dedicated prompt input per step.'),
396
- negativePrompt: z.string().optional(),
397
- params: z.record(z.any()).optional().describe('Param bindings, literal or { from: "input:<key>" } (e.g. aspectRatio, seed, duration).'),
398
- }).passthrough();
399
-
400
- const recipeInput = z.object({
401
- key: z.string().describe('Unique slug referenced as input:<key>.'),
402
- kind: z.string().describe('subject | text | image | video | reference | audio | select | color | number | toggle'),
403
- label: z.string().optional(),
404
- required: z.boolean().optional(),
405
- }).passthrough();
406
-
407
- const recipeSpec = z.object({
408
- name: z.string().describe('Recipe name shown to end users.'),
409
- description: z.string().optional(),
410
- category: z.string().optional().describe('e.g. product | ugc'),
411
- mature: z.boolean().optional().describe('Creator-declared: this recipe produces adult content.'),
412
- // Accepted, not for the benefit of third parties (breaking them is fine), but
413
- // because an agent composing a recipe mid-transition would otherwise DROP the
414
- // classification, which publishes adult content as unclassified (TASK-472).
415
- nsfw: z.boolean().optional().describe('Deprecated alias for `mature`.'),
416
- version: z.string().optional().describe('Creator-facing semver, default 1.0.0.'),
417
- inputs: z.array(recipeInput).optional().describe('Extra user-facing inputs (subjects, choices, media holes). A prompt input is auto-created per step, so you rarely list prompts here.'),
418
- steps: z.array(recipeStep).min(1).describe('The pipeline in order. Each step pins a preset; media output flows into the next step automatically, and a subject input seeds a reference port.'),
419
- });
420
-
421
- server.registerTool('list_recipe_blocks',
422
- { title: 'List recipe blocks', description: 'The building blocks for authoring a recipe: entry points (create-image/video, edit-image, upscale) and every preset usable as a step, each with its port contract (inputs it needs, what it produces, which entry points it fits). Call this before compose_recipe to choose presets.', inputSchema: {} },
423
- wrap(() => client.listRecipeBlocks()));
424
-
425
- server.registerTool('compose_recipe',
426
- { title: 'Compose a recipe', description: 'Author a new recipe from a high-level spec and save it as a draft. You give an ordered list of steps (each pinned to a preset from list_recipe_blocks) plus any extra inputs; SimpliGen auto-wires the ports, media chain, and per-step prompt inputs and validates it. Returns { recipeId, valid, errors }. Anyone can compose; publishing later needs a connected account.', inputSchema: { spec: recipeSpec } },
427
- wrap(({ spec }) => client.composeRecipe({ spec })));
428
-
429
- server.registerTool('validate_recipe',
430
- { title: 'Validate a recipe', description: 'Dry-run without saving: pass a `spec` to compose+validate it, or a `config` to validate an existing recipe config. Returns precise errors (unbound ports, missing presets, type mismatches, cycles) to fix before compose_recipe.', inputSchema: { spec: recipeSpec.optional(), config: z.record(z.any()).optional() } },
431
- wrap((args) => client.validateRecipe(args)));
432
-
433
- server.registerTool('list_recipes',
434
- { title: 'List recipes', description: 'List every recipe on this device: the ones installed from the Store into UGC Studio / Product Studio (category ugc | product) and drafts authored here. Each entry carries its `inputs` (key, kind, label, required, options) so you know what run_recipe needs: a `subject` input takes a character id from list_characters (or a product id), image/video/audio inputs take upload_file handles, text/select/number inputs take plain values.', inputSchema: {} },
435
- wrap(() => client.listRecipes()));
436
-
437
- // --- Running an installed recipe (what drives the UGC + Product Studios) ---
438
-
439
- server.registerTool('run_recipe',
440
- {
441
- title: 'Run a recipe',
442
- description: 'Run an installed recipe (from list_recipes) with its inputs filled: the same multi-step pipeline UGC Studio / Product Studio runs when a person clicks Generate, so results land in the Gallery grouped the same way. `inputs` is keyed by input key; a subject input takes a character/product id, media inputs take upload_file handles. engine: local (default when every step is installed) | cloud | auto. Returns a runId; poll with wait_for_recipe_run or get_recipe_run. Cloud runs are priced up front and count against this agent\'s spend cap.',
443
- inputSchema: {
444
- id: z.string().describe('Recipe id from list_recipes'),
445
- inputs: z.record(z.any()).describe('Input values keyed by the recipe\'s input keys (see list_recipes -> inputs).'),
446
- engine: z.enum(['local', 'cloud', 'auto']).optional().describe('Where the steps render. auto = local if every step is installed, else cloud when connected.'),
447
- },
448
- },
449
- wrap(({ id, inputs, engine }) => client.runRecipe(id, { inputs: inputs || {}, ...(engine ? { engine } : {}) })));
450
-
451
- server.registerTool('get_recipe_run',
452
- { title: 'Get a recipe run', description: 'Status of a recipe run: overall status (running | completed | failed | cancelled), each step with its status and resultPath, and resultPath = the final output once done.', inputSchema: { runId: z.string().describe('Run id from run_recipe') } },
453
- wrap(({ runId }) => client.getRecipeRun(runId)));
454
-
455
- server.registerTool('wait_for_recipe_run',
456
- { title: 'Wait for a recipe run', description: 'Block until a recipe run completes, fails, is cancelled, or the timeout passes. Returns the final run (resultPath when completed). Multi-step video recipes can take several minutes; call again if it returns timeout_still_running.', inputSchema: { runId: z.string(), timeoutSeconds: z.number().optional(), pollMs: z.number().optional() } },
457
- wrap(async ({ runId, timeoutSeconds = 600, pollMs = 3000 }) => {
458
- const deadline = Date.now() + timeoutSeconds * 1000;
459
- // eslint-disable-next-line no-constant-condition
460
- while (true) {
461
- const { run } = await client.getRecipeRun(runId);
462
- if (run && ['completed', 'failed', 'cancelled'].includes(run.status)) return { run };
463
- if (Date.now() >= deadline) return { run, note: 'timeout_still_running' };
464
- await new Promise((r) => setTimeout(r, pollMs));
465
- }
466
- }));
467
-
468
- server.registerTool('list_recipe_runs',
469
- { title: 'List recipe runs', description: 'Recent runs of a recipe (newest first) with their status and results.', inputSchema: { id: z.string().describe('Recipe id') } },
470
- wrap(({ id }) => client.listRecipeRuns(id)));
471
-
472
- // --- Products + subjects: what a recipe's `subject` inputs take ---
473
-
474
- server.registerTool('list_subjects',
475
- { title: 'List subjects', description: 'Every subject a recipe\'s `subject` input can take: characters and products (id, type, name). Use a character id from list_characters or a product id from list_products / create_product.', inputSchema: {} },
476
- wrap(() => client.listSubjects()));
477
-
478
- server.registerTool('list_products',
479
- { title: 'List products', description: 'The products saved on this device (a product = a named thing with a base photo, used by Product Studio and UGC recipes).', inputSchema: {} },
480
- wrap(() => client.listProducts()));
481
-
482
- server.registerTool('create_product',
483
- {
484
- title: 'Create a product',
485
- description: 'Save a product from a photo so recipes can use it: upload the photo with upload_file first, then pass its handle. The description and category are woven into recipe prompts, so describe what it is and how it looks. Returns the productId to pass as a `subject` input in run_recipe.',
486
- inputSchema: {
487
- name: z.string().describe('Product name shown in the app'),
488
- image: z.string().describe('upload_file handle of the product photo (clean, well-lit, product centred)'),
489
- description: z.string().optional().describe('What it is and looks like, e.g. "a matte black ceramic coffee mug with a wooden lid"'),
490
- category: z.string().optional().describe('e.g. skincare | beverage | electronics'),
491
- },
492
- },
493
- wrap(({ name, image, description, category }) => client.createProduct({ name, image, description, category })));
494
-
495
- server.registerTool('remove_product',
496
- { title: 'Remove a product', description: 'Delete a product and its photo from this device.', inputSchema: { id: z.string() } },
497
- wrap(({ id }) => client.removeProduct(id)));
498
-
499
- server.registerTool('cancel_recipe_run',
500
- { title: 'Cancel a recipe run', description: 'Stop a running recipe: no further steps start; a local in-flight step is interrupted (a cloud step already running finishes server-side and is saved).', inputSchema: { runId: z.string() } },
501
- wrap(({ runId }) => client.cancelRecipeRun(runId)));
502
-
503
- server.registerTool('get_recipe',
504
- { title: 'Get a recipe', description: 'Get a saved recipe and its full config by id.', inputSchema: { id: z.string().describe('Recipe id from compose_recipe or list_recipes') } },
505
- wrap(({ id }) => client.getRecipe(id)));
506
-
507
- server.registerTool('publish_recipe',
508
- { title: 'Publish a recipe', description: 'Submit a saved recipe to the SimpliGen Creator Marketplace (queued for human review). Requires a connected account: if none, returns not_connected and the user connects once in Settings, then this succeeds on the same recipe. priceTokens sets an optional one-time price (0 or omitted = free). Every preset the recipe uses must be a distributable first-party pack.', inputSchema: { id: z.string().describe('Recipe id to publish'), changelog: z.string().optional(), priceTokens: z.number().optional().describe('One-time price in tokens (0/omitted = free).') } },
509
- wrap(({ id, changelog, priceTokens }) => client.publishRecipe(id, { changelog, priceTokens })));
510
- }
1
+ // packages/mcp-server/src/tools.js
2
+ // Registers SimpliGen MCP tools on an McpServer-shaped object. Each tool calls a
3
+ // ControlApiClient method and returns the JSON result as text content; client
4
+ // errors become an isError tool result (so the agent sees the errorCode/message).
5
+ import { z } from 'zod';
6
+ import { buildResultImageContent } from './resultImage.js';
7
+
8
+ export const TOOL_NAMES = [
9
+ 'list_capabilities', 'get_status', 'start_engine', 'stop_engine', 'restart_engine',
10
+ 'list_projects', 'create_project',
11
+ 'upload_file', 'generate', 'list_loras', 'get_job', 'wait_for_result', 'list_jobs',
12
+ 'cancel_job', 'prepare_preset', 'get_result_image',
13
+ 'list_characters', 'get_character', 'list_character_features', 'list_character_presets',
14
+ 'remove_character', 'create_character', 'generate_character_image', 'generate_character_video',
15
+ 'generate_character_frame', 'animate_character', 'set_character_preset',
16
+ 'enhance_character_media', 'regenerate_character_base',
17
+ 'list_recipe_blocks', 'compose_recipe', 'validate_recipe', 'list_recipes', 'get_recipe', 'publish_recipe',
18
+ 'run_recipe', 'get_recipe_run', 'wait_for_recipe_run', 'list_recipe_runs', 'cancel_recipe_run',
19
+ 'list_subjects', 'list_products', 'create_product', 'remove_product',
20
+ ];
21
+
22
+ const ok = (data) => ({ content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] });
23
+ const fail = (err) => ({ isError: true, content: [{ type: 'text', text: `${err.errorCode ? err.errorCode + ': ' : ''}${err.message || String(err)}` }] });
24
+ const wrap = (fn) => async (args) => { try { return ok(await fn(args)); } catch (e) { return fail(e); } };
25
+
26
+ export function registerTools(server, client) {
27
+ server.registerTool('list_capabilities',
28
+ { title: 'List capabilities', description: 'List every SimpliGen preset the agent can generate with (image/video), its inputs/options, whether it is installed locally (localReady) and cloud-eligible + credit cost.', inputSchema: {} },
29
+ wrap(() => client.getCapabilities()));
30
+
31
+ server.registerTool('get_status',
32
+ { title: 'Get status', description: 'Engine running state, whether cloud is connected, credit balance, and the active project.', inputSchema: {} },
33
+ wrap(() => client.getStatus()));
34
+
35
+ // The engine's lifecycle. get_status could always report it was down and
36
+ // there was nothing an agent could do about it but ask the human to click
37
+ // Start (user report, 2026-09-24). Install, update and repair stay out of
38
+ // reach on purpose: those are multi-GB downloads that belong in front of a
39
+ // person.
40
+ server.registerTool('start_engine',
41
+ { title: 'Start engine', description: 'Start the local engine if it is not already running. Returns the engine state; a cold boot can outlast the call, in which case engineStarting is true and get_status tells you when it is up. Does nothing if the engine is already running, and will not install one that is missing.', inputSchema: {} },
42
+ wrap(() => client.startEngine()));
43
+
44
+ server.registerTool('stop_engine',
45
+ { title: 'Stop engine', description: 'Stop the local engine. Frees its VRAM; cloud generation is unaffected.', inputSchema: {} },
46
+ wrap(() => client.stopEngine()));
47
+
48
+ server.registerTool('restart_engine',
49
+ { title: 'Restart engine', description: 'Restart the local engine. Use it after installing or removing a custom node, or when the engine is wedged.', inputSchema: {} },
50
+ wrap(() => client.restartEngine()));
51
+
52
+ server.registerTool('list_projects',
53
+ { title: 'List projects', description: 'List projects (output containers).', inputSchema: {} },
54
+ wrap(() => client.listProjects()));
55
+
56
+ server.registerTool('create_project',
57
+ { title: 'Create project', description: 'Create a new project (output container).', inputSchema: { name: z.string().describe('Project name') } },
58
+ wrap(({ name }) => client.createProject(name)));
59
+
60
+ server.registerTool('upload_file',
61
+ { title: 'Upload a file', description: 'Upload a local image/video file and get an opaque handle to pass as image/referenceImages/video in generate.', inputSchema: { path: z.string().describe('Absolute local file path') } },
62
+ wrap(({ path }) => client.uploadFile(path)));
63
+
64
+ server.registerTool('generate',
65
+ {
66
+ title: 'Generate', description: 'Start an image or video generation. Inputs (image/referenceImages/video) are handles from upload_file. backend: local | cloud | auto. Returns a jobId; poll with wait_for_result or get_job.',
67
+ inputSchema: {
68
+ presetId: z.string(), mediaType: z.enum(['image', 'video']), prompt: z.string(),
69
+ packId: z.string().optional(), backend: z.enum(['local', 'cloud', 'auto']).optional(),
70
+ negativePrompt: z.string().optional(), project: z.string().optional(),
71
+ image: z.string().optional().describe('upload_file handle'),
72
+ // A bare handle still works, so every agent written against the old
73
+ // schema keeps working. The object form carries the per-image label,
74
+ // which is the DESCRIPTION the app asks for when list_capabilities says
75
+ // inputs.referenceImages.requiresDescriptions is true (LTX 2.5
76
+ // Multi-Reference builds one appearance line per subject from it).
77
+ // Sending images without it on such a preset runs, but the subjects
78
+ // blur together, which is indistinguishable from the model being bad.
79
+ referenceImages: z.array(z.union([
80
+ z.string(),
81
+ z.object({
82
+ handle: z.string().describe('upload_file handle'),
83
+ label: z.string().optional().describe('What this reference IS, e.g. "a woman with red hair". Required in spirit when the preset reports requiresDescriptions.'),
84
+ }),
85
+ ])).optional().describe('upload_file handles, or {handle, label} when the preset wants a description per reference'),
86
+ video: z.string().optional().describe('upload_file handle (driving video)'),
87
+ // The App has accepted these three since 1.58.0; this schema never
88
+ // offered them, so no agent could drive an audio preset at all: the
89
+ // error said needs_audio and there was nowhere to put a sound
90
+ // (mavr1k_, 2026-10-01). Passing it inside `options` does not work
91
+ // either, since preflight reads the top level.
92
+ audio: z.string().optional().describe('upload_file handle for the PRIMARY audio track (lip-sync / audio-to-video presets). Required when list_capabilities reports inputs.acceptsAudio true, optional when it reports "optional".'),
93
+ referenceAudios: z.array(z.union([
94
+ z.string(),
95
+ z.object({ handle: z.string(), durationSeconds: z.number().optional() }),
96
+ ])).optional().describe('upload_file handles for reference SOUNDS (a voice per subject, where the preset pairs them with references).'),
97
+ referenceVideos: z.array(z.union([
98
+ z.string(),
99
+ z.object({
100
+ handle: z.string(),
101
+ soundtrackMode: z.enum(['own', 'file', 'none']).optional().describe("Where this clip's sound comes from: 'own' (the clip's own audio, the default), 'file' (another upload, see soundtrack), or 'none' (silent)."),
102
+ soundtrack: z.string().optional().describe("upload_file handle for the audio to use. Required with soundtrackMode 'file', ignored otherwise."),
103
+ durationSeconds: z.number().optional(),
104
+ }),
105
+ ])).optional().describe('upload_file handles for reference CLIPS (MiniMax H3 scene chaining chains on a clip).'),
106
+ // Appended to the prompt by the app's own dialogue formatter, so the
107
+ // wording matches what the preset was tuned on. MiniMax H3 lip-syncs
108
+ // to it; sending it to a preset that does not declare supportsDialogue
109
+ // changes nothing.
110
+ dialogue: z.string().optional().describe('A spoken line for the character, when list_capabilities reports inputs.supportsDialogue.'),
111
+ dialogueDelivery: z.string().optional().describe('How the line is delivered, e.g. "urgent", "whispered". Only meaningful with dialogue.'),
112
+ loras: z.array(z.object({ name: z.string().describe('LoRA display name from list_loras'), weight: z.number().optional().describe('Strength; defaults to the LoRA default') })).optional().describe('LoRAs to apply. Local backend only, and only for presets where inputs.supportsLoras is true. Use the LoRA trigger words in the prompt so it activates.'),
113
+ // .passthrough(), not the zod default: a plain z.object STRIPS every key it
114
+ // does not name, silently. The App's /generate accepts any Advanced
115
+ // Control the preset declares (unlock, shift, high_steps, ...) and
116
+ // list_capabilities advertises them under options.controls, so an agent
117
+ // was told a control exists, sent it, and got the preset default back
118
+ // with no error: unlock: 1 arrived at the graph as 0.5 (Melvyl, 1.63.0).
119
+ // The App applies only what the preset declares and ignores the rest,
120
+ // so forwarding everything is safe. Known fields stay named so the
121
+ // agent still sees them in the tool's schema.
122
+ options: z.object({
123
+ resolution: z.string().optional().describe('Resolution tier label; see list_capabilities -> options.resolution.'),
124
+ aspectRatio: z.string().optional().describe('Aspect ratio, e.g. "1:1", "16:9", "9:16" (portrait/vertical), "4:3", "3:4". See list_capabilities -> options.aspectRatio for the values each preset accepts. Defaults to 1:1 for images (16:9 for video) if omitted.'),
125
+ durationSeconds: z.number().optional(),
126
+ steps: z.number().optional(),
127
+ cfg: z.number().optional(),
128
+ seed: z.number().optional(),
129
+ negativePrompt: z.string().optional(),
130
+ fasterAttention: z.boolean().optional().describe('Accelerator toggle; absent = preset default.'),
131
+ solAttn: z.boolean().optional().describe('Accelerator toggle; absent = preset default.'),
132
+ spectrum: z.boolean().optional().describe('Accelerator toggle; absent = preset default.'),
133
+ }).passthrough().optional().describe('Run options. Besides the named fields, pass ANY Advanced Control the preset declares under list_capabilities -> options.controls (for example unlock, shift, high_steps) as a top-level key of this object, using the value range that map gives. A key the preset does not declare is ignored.'),
134
+ },
135
+ },
136
+ wrap((args) => client.generate(args)));
137
+
138
+ server.registerTool('list_loras',
139
+ { title: 'List LoRAs', description: 'List the installed user LoRAs (name, base model, trigger words) so you can pass them in generate -> loras.', inputSchema: {} },
140
+ wrap(() => client.listLoras()));
141
+
142
+ server.registerTool('get_job',
143
+ { title: 'Get job', description: 'Status + result of a generation job. resultPath is the local file when completed.', inputSchema: { jobId: z.string() } },
144
+ wrap(({ jobId }) => client.getJob(jobId)));
145
+
146
+ server.registerTool('list_jobs',
147
+ { title: 'List jobs', description: 'Recent generation jobs.', inputSchema: {} },
148
+ wrap(() => client.listJobs()));
149
+
150
+ server.registerTool('cancel_job',
151
+ { title: 'Cancel job', description: 'Cancel a queued/running job.', inputSchema: { jobId: z.string() } },
152
+ wrap(({ jobId }) => client.cancelJob(jobId)));
153
+
154
+ server.registerTool('prepare_preset',
155
+ { title: 'Prepare preset', description: 'Start downloading a local preset\'s models (so it becomes localReady). Poll list_capabilities for localReady.', inputSchema: { presetId: z.string(), mediaType: z.enum(['image', 'video']), packId: z.string().optional() } },
156
+ wrap((args) => client.preparePreset(args)));
157
+
158
+ // Convenience: poll get_job until terminal or timeout (no extra endpoint).
159
+ server.registerTool('wait_for_result',
160
+ { title: 'Wait for result', description: 'Block until a job completes or fails (or the timeout). Returns the final job (resultPath when completed).', inputSchema: { jobId: z.string(), timeoutSeconds: z.number().optional(), pollMs: z.number().optional() } },
161
+ wrap(async ({ jobId, timeoutSeconds = 300, pollMs = 2000 }) => {
162
+ const deadline = Date.now() + timeoutSeconds * 1000;
163
+ // eslint-disable-next-line no-constant-condition
164
+ while (true) {
165
+ const { job } = await client.getJob(jobId);
166
+ if (!job || job.status === 'completed' || job.status === 'failed') return job;
167
+ if (Date.now() >= deadline) return { ...job, note: 'timeout_still_running' };
168
+ await new Promise((r) => setTimeout(r, pollMs));
169
+ }
170
+ }));
171
+
172
+ // Return a completed job's result image inline (an MCP image block) so the
173
+ // agent can actually display it. Images only; video/unreadable -> path note.
174
+ server.registerTool('get_result_image',
175
+ { title: 'Get result image', description: 'Return a completed job\'s result image inline as a viewable image so it can be displayed in chat. Large images are re-encoded to a full-resolution WebP preview that fits the client size cap; the uncompressed original file path is always included in the caption. Video results return the file path instead. Call after the job is completed.', inputSchema: { jobId: z.string(), maxBytes: z.number().optional().describe('Inline byte budget before re-encoding/resizing (default ~700KB raw)') } },
176
+ async ({ jobId, maxBytes }) => {
177
+ try {
178
+ const { job } = await client.getJob(jobId);
179
+ return await buildResultImageContent(job, { budgetBytes: maxBytes });
180
+ } catch (e) {
181
+ return fail(e);
182
+ }
183
+ });
184
+
185
+ // ---- Character Studio tools ----
186
+
187
+ server.registerTool('list_characters',
188
+ { title: 'List characters', description: 'List all saved characters in Character Studio.', inputSchema: {} },
189
+ wrap(() => client.listCharacters()));
190
+
191
+ server.registerTool('get_character',
192
+ { title: 'Get character', description: 'Get a single character by ID, including its current base portrait and identity features.', inputSchema: { characterId: z.string() } },
193
+ wrap(({ characterId }) => client.getCharacter(characterId)));
194
+
195
+ server.registerTool('list_character_features',
196
+ { title: 'List character features', description: 'List available feature categories and their options (e.g. hairColor, eyeColor) for use with create_character identity.', inputSchema: {} },
197
+ wrap(() => client.listCharacterFeatures()));
198
+
199
+ server.registerTool('list_character_presets',
200
+ { title: 'List character presets', description: 'List generation presets available for Character Studio. Returns base, identityEdit, and i2v presets as well as enhanceImage and enhanceVideo presets (each with supportedScales). Use the returned ids as presetId/imagePresetId/videoPresetId/basePresetId arguments in other character tools.', inputSchema: {} },
201
+ wrap(() => client.listCharacterPresets()));
202
+
203
+ server.registerTool('remove_character',
204
+ { title: 'Remove character', description: 'Permanently delete a character and its associated data.', inputSchema: { characterId: z.string() } },
205
+ wrap(({ characterId }) => client.removeCharacter(characterId)));
206
+
207
+ server.registerTool('create_character',
208
+ {
209
+ title: 'Create character',
210
+ description: 'Create a new character. Three paths: (1) describe -- pass gender and identity features from list_character_features with mode "generate"; the server builds a base portrait automatically and this tool waits until ready. (2) upload as base -- pass baseFilePath pointing to a local image with mode "upload"; the image becomes the base portrait immediately. (3) vision recreate -- describe path but fill identity by having the agent analyse a reference photo first; the agent extracts features and passes them as identity.',
211
+ inputSchema: {
212
+ name: z.string().describe('Display name for the character'),
213
+ gender: z.enum(['woman', 'man', 'nonbinary']),
214
+ mode: z.enum(['generate', 'upload']).describe('generate: build base portrait from description; upload: use a provided image as base'),
215
+ identity: z.record(z.string()).optional().describe('An object of featureId to optionId pairs chosen from list_character_features (e.g. { hairColor: "black", eyeColor: "green" }). Do not include gender here; pass gender separately.'),
216
+ baseFilePath: z.string().optional().describe('Absolute local image path; required for mode "upload"'),
217
+ timeoutSeconds: z.number().optional().describe('Max seconds to wait for base portrait generation (default 300, mode generate only)'),
218
+ pollMs: z.number().optional().describe('Poll interval in milliseconds (default 2000, mode generate only)'),
219
+ },
220
+ },
221
+ async ({ name, gender, mode, identity, baseFilePath, timeoutSeconds, pollMs }) => {
222
+ try {
223
+ if (mode === 'upload') {
224
+ const up = await client.uploadFile(baseFilePath);
225
+ const char = await client.createCharacter({ name, gender, mode: 'upload', identity, baseHandle: up.handle });
226
+ return ok({ ...char, ready: true });
227
+ }
228
+ // mode === 'generate': create then poll until base_image_url is set
229
+ const c = await client.createCharacter({ name, gender, mode: 'generate', identity });
230
+ const { characterId } = c;
231
+ const deadline = Date.now() + (timeoutSeconds ?? 300) * 1000;
232
+ while (true) {
233
+ const { character } = await client.getCharacter(characterId);
234
+ if (character?.base_image_url) return ok(character);
235
+ if (Date.now() >= deadline) return ok({ ...character, base_pending: true });
236
+ await new Promise((r) => setTimeout(r, pollMs ?? 2000));
237
+ }
238
+ } catch (e) {
239
+ return fail(e);
240
+ }
241
+ });
242
+
243
+ server.registerTool('generate_character_image',
244
+ {
245
+ title: 'Generate character image',
246
+ description: 'Generate one or more images of a character in a scene. Returns jobIds; use wait_for_result then get_result_image for each. Pass presetId to override the default image preset (ids from list_character_presets).',
247
+ inputSchema: {
248
+ characterId: z.string(),
249
+ prompt: z.string(),
250
+ aspect: z.enum(['16:9', '9:16', '1:1']).optional(),
251
+ count: z.number().optional(),
252
+ presetId: z.string().optional().describe('Override image preset (id from list_character_presets)'),
253
+ },
254
+ },
255
+ wrap(({ characterId, prompt, aspect, count, presetId }) => {
256
+ const args = { prompt, aspect, count };
257
+ if (presetId !== undefined) args.presetId = presetId;
258
+ return client.generateCharacterImage(characterId, args);
259
+ }));
260
+
261
+ server.registerTool('generate_character_video',
262
+ {
263
+ title: 'Generate character video',
264
+ description: 'Generate a short video of a character in a scene. Internally generates a frame then animates it (I2V). Returns frameJobId and videoJobId; use wait_for_result then get_result_image on videoJobId. Use framePresetId to override the image-frame preset and videoPresetId to override the video/animate preset (ids from list_character_presets).',
265
+ inputSchema: {
266
+ characterId: z.string(),
267
+ prompt: z.string(),
268
+ motion: z.string().optional().describe('Optional motion description or style hint'),
269
+ aspect: z.enum(['16:9', '9:16', '1:1']).optional(),
270
+ timeoutSeconds: z.number().optional().describe('Max seconds to wait for the frame job (default 300)'),
271
+ pollMs: z.number().optional().describe('Poll interval in milliseconds (default 2000)'),
272
+ framePresetId: z.string().optional().describe('Override image-frame preset (id from list_character_presets)'),
273
+ videoPresetId: z.string().optional().describe('Override video/animate preset (id from list_character_presets)'),
274
+ },
275
+ },
276
+ async ({ characterId, prompt, motion, aspect, timeoutSeconds = 300, pollMs = 2000, framePresetId, videoPresetId }) => {
277
+ try {
278
+ // 1. Generate a frame (still image for I2V)
279
+ const { jobIds: [frameJobId] } = await client.generateCharacterFrame(characterId, { prompt, aspect, presetId: framePresetId });
280
+ // 2. Wait for frame to complete
281
+ const deadline = Date.now() + timeoutSeconds * 1000;
282
+ while (true) {
283
+ const { job: frameJob } = await client.getJob(frameJobId);
284
+ if (frameJob?.status === 'completed') break;
285
+ if (frameJob?.status === 'failed') return fail({ message: `Frame job failed: ${frameJobId}`, errorCode: 'frame_failed' });
286
+ if (Date.now() >= deadline) return fail({ message: `Frame job timed out: ${frameJobId}`, errorCode: 'frame_timeout' });
287
+ await new Promise((r) => setTimeout(r, pollMs));
288
+ }
289
+ // 3. Animate from the completed frame
290
+ const { jobIds: [videoJobId] } = await client.animateCharacter(characterId, { frameJobId, motion, aspect, presetId: videoPresetId });
291
+ return ok({ frameJobId, videoJobId });
292
+ } catch (e) { return fail(e); }
293
+ });
294
+
295
+ // ---- New Character Studio tools (Task 4) ----
296
+
297
+ server.registerTool('generate_character_frame',
298
+ {
299
+ title: 'Generate character frame',
300
+ description: 'Generate a start-frame image for a character that you can review or enhance before animating. Returns jobIds; use wait_for_result then get_result_image. Pass presetId to override the frame-image preset (ids from list_character_presets).',
301
+ inputSchema: {
302
+ characterId: z.string(),
303
+ prompt: z.string(),
304
+ aspect: z.enum(['16:9', '9:16', '1:1']).optional(),
305
+ presetId: z.string().optional().describe('Override image preset (id from list_character_presets)'),
306
+ },
307
+ },
308
+ wrap(({ characterId, prompt, aspect, presetId }) => {
309
+ const args = { prompt, aspect };
310
+ if (presetId !== undefined) args.presetId = presetId;
311
+ return client.generateCharacterFrame(characterId, args);
312
+ }));
313
+
314
+ server.registerTool('animate_character',
315
+ {
316
+ title: 'Animate character',
317
+ description: 'Animate a character from a completed image/frame job or a local file path (I2V). jobId may be any completed character image, frame, or upscale job. Returns jobIds; use wait_for_result then get_result_image. Pass videoPresetId to override the video preset (ids from list_character_presets).',
318
+ inputSchema: {
319
+ characterId: z.string(),
320
+ jobId: z.string().optional().describe('Any completed character image/frame/upscale jobId to use as the source frame'),
321
+ filePath: z.string().optional().describe('Absolute local image path to use as the source frame'),
322
+ motion: z.string().optional().describe('Optional motion description or style hint'),
323
+ aspect: z.enum(['16:9', '9:16', '1:1']).optional(),
324
+ videoPresetId: z.string().optional().describe('Override video/animate preset (id from list_character_presets)'),
325
+ },
326
+ },
327
+ wrap(({ characterId, jobId, filePath, motion, aspect, videoPresetId }) =>
328
+ client.animateCharacter(characterId, { frameJobId: jobId, framePath: filePath, motion, aspect, presetId: videoPresetId })));
329
+
330
+ server.registerTool('set_character_preset',
331
+ {
332
+ title: 'Set character preset',
333
+ description: 'Set sticky per-character default presets for image and/or video generation. Ids come from list_character_presets. Pass null to clear a preset back to the system default.',
334
+ inputSchema: {
335
+ characterId: z.string(),
336
+ imagePresetId: z.string().nullable().optional().describe('Default image preset id (null to clear)'),
337
+ videoPresetId: z.string().nullable().optional().describe('Default video preset id (null to clear)'),
338
+ },
339
+ },
340
+ wrap(({ characterId, imagePresetId, videoPresetId }) => client.setCharacterPreset(characterId, { imagePresetId, videoPresetId })));
341
+
342
+ server.registerTool('enhance_character_media',
343
+ {
344
+ title: 'Enhance character media',
345
+ description: 'Upscale a generated image/video, a local file, or the character base portrait (target: "base"). Returns a jobId; use wait_for_result then get_result_image. scale sets the upscale factor; keepResolution upscales then resizes back to source size for a sharper same-size result; applyAsBase replaces the character base portrait with the upscaled result. Enhance presets come from list_character_presets (enhanceImage/enhanceVideo, each with supportedScales).',
346
+ inputSchema: {
347
+ characterId: z.string(),
348
+ jobId: z.string().optional().describe('Completed job whose result to enhance'),
349
+ filePath: z.string().optional().describe('Absolute local image/video path to enhance'),
350
+ target: z.enum(['base']).optional().describe('Pass "base" to enhance the character base portrait'),
351
+ mediaType: z.enum(['image', 'video']).optional(),
352
+ presetId: z.string().optional().describe('Enhance preset id from list_character_presets'),
353
+ scale: z.number().optional().describe('Upscale factor (e.g. 2 for 2x)'),
354
+ keepResolution: z.boolean().optional().describe('Upscale then resize back to source dimensions for a sharper same-size result'),
355
+ applyAsBase: z.boolean().optional().describe('Replace the character base portrait with the upscaled result'),
356
+ },
357
+ },
358
+ wrap(({ characterId, jobId, filePath, target, mediaType, presetId, scale, keepResolution, applyAsBase }) =>
359
+ client.enhanceCharacterMedia(characterId, { jobId, filePath, target, mediaType, presetId, scale, keepResolution, applyAsBase })));
360
+
361
+ server.registerTool('regenerate_character_base',
362
+ {
363
+ title: 'Regenerate character base',
364
+ description: 'Switch the base model and regenerate the base portrait IN PLACE (no new character created). Replaces the current base when completed. Uses basePresetId from list_character_presets. Optionally update identity features at the same time. Polls until completed, then auto-accepts the new base.',
365
+ inputSchema: {
366
+ characterId: z.string(),
367
+ basePresetId: z.string().optional().describe('Base-generation preset id from list_character_presets'),
368
+ identity: z.record(z.string()).optional().describe('Updated identity feature map (featureId -> optionId) to apply alongside the new base'),
369
+ timeoutSeconds: z.number().optional().describe('Max seconds to wait for the base job (default 300)'),
370
+ pollMs: z.number().optional().describe('Poll interval in milliseconds (default 2000)'),
371
+ },
372
+ },
373
+ async ({ characterId, basePresetId, identity, timeoutSeconds = 300, pollMs = 2000 }) => {
374
+ try {
375
+ const { baseJobId } = await client.regenerateCharacterBase(characterId, { basePresetId, identity });
376
+ const deadline = Date.now() + timeoutSeconds * 1000;
377
+ while (true) {
378
+ const { job } = await client.getJob(baseJobId);
379
+ if (job?.status === 'completed') {
380
+ await client.acceptBase(characterId, { altImageId: baseJobId });
381
+ return ok(await client.getCharacter(characterId));
382
+ }
383
+ if (job?.status === 'failed') return fail({ message: `Base regeneration job failed: ${baseJobId}`, errorCode: 'base_failed' });
384
+ if (Date.now() >= deadline) return ok({ baseJobId, note: 'timeout_still_running' });
385
+ await new Promise((r) => setTimeout(r, pollMs));
386
+ }
387
+ } catch (e) { return fail(e); }
388
+ });
389
+
390
+ // --- Recipe authoring: compose multi-step recipes out of packs/presets ---
391
+
392
+ const recipeStep = z.object({
393
+ preset: z.string().describe('The preset this step runs, as "packId:presetId" (from list_recipe_blocks).'),
394
+ entry: z.string().optional().describe('Entry point: create-image | create-video | edit-image | upscale. Inferred from the preset when omitted.'),
395
+ promptInput: z.object({ key: z.string().optional(), label: z.string().optional() }).optional()
396
+ .describe('Name this step\'s prompt input, or set key to an existing input to SHARE a prompt. Default: a dedicated prompt input per step.'),
397
+ negativePrompt: z.string().optional(),
398
+ params: z.record(z.any()).optional().describe('Param bindings, literal or { from: "input:<key>" } (e.g. aspectRatio, seed, duration).'),
399
+ }).passthrough();
400
+
401
+ const recipeInput = z.object({
402
+ key: z.string().describe('Unique slug referenced as input:<key>.'),
403
+ kind: z.string().describe('subject | text | image | video | reference | audio | select | color | number | toggle'),
404
+ label: z.string().optional(),
405
+ required: z.boolean().optional(),
406
+ }).passthrough();
407
+
408
+ const recipeSpec = z.object({
409
+ name: z.string().describe('Recipe name shown to end users.'),
410
+ description: z.string().optional(),
411
+ category: z.string().optional().describe('e.g. product | ugc'),
412
+ mature: z.boolean().optional().describe('Creator-declared: this recipe produces adult content.'),
413
+ // Accepted, not for the benefit of third parties (breaking them is fine), but
414
+ // because an agent composing a recipe mid-transition would otherwise DROP the
415
+ // classification, which publishes adult content as unclassified (TASK-472).
416
+ nsfw: z.boolean().optional().describe('Deprecated alias for `mature`.'),
417
+ version: z.string().optional().describe('Creator-facing semver, default 1.0.0.'),
418
+ inputs: z.array(recipeInput).optional().describe('Extra user-facing inputs (subjects, choices, media holes). A prompt input is auto-created per step, so you rarely list prompts here.'),
419
+ steps: z.array(recipeStep).min(1).describe('The pipeline in order. Each step pins a preset; media output flows into the next step automatically, and a subject input seeds a reference port.'),
420
+ });
421
+
422
+ server.registerTool('list_recipe_blocks',
423
+ { title: 'List recipe blocks', description: 'The building blocks for authoring a recipe: entry points (create-image/video, edit-image, upscale) and every preset usable as a step, each with its port contract (inputs it needs, what it produces, which entry points it fits). Call this before compose_recipe to choose presets.', inputSchema: {} },
424
+ wrap(() => client.listRecipeBlocks()));
425
+
426
+ server.registerTool('compose_recipe',
427
+ { title: 'Compose a recipe', description: 'Author a new recipe from a high-level spec and save it as a draft. You give an ordered list of steps (each pinned to a preset from list_recipe_blocks) plus any extra inputs; SimpliGen auto-wires the ports, media chain, and per-step prompt inputs and validates it. Returns { recipeId, valid, errors }. Anyone can compose; publishing later needs a connected account.', inputSchema: { spec: recipeSpec } },
428
+ wrap(({ spec }) => client.composeRecipe({ spec })));
429
+
430
+ server.registerTool('validate_recipe',
431
+ { title: 'Validate a recipe', description: 'Dry-run without saving: pass a `spec` to compose+validate it, or a `config` to validate an existing recipe config. Returns precise errors (unbound ports, missing presets, type mismatches, cycles) to fix before compose_recipe.', inputSchema: { spec: recipeSpec.optional(), config: z.record(z.any()).optional() } },
432
+ wrap((args) => client.validateRecipe(args)));
433
+
434
+ server.registerTool('list_recipes',
435
+ { title: 'List recipes', description: 'List every recipe on this device: the ones installed from the Store into UGC Studio / Product Studio (category ugc | product) and drafts authored here. Each entry carries its `inputs` (key, kind, label, required, options) so you know what run_recipe needs: a `subject` input takes a character id from list_characters (or a product id), image/video/audio inputs take upload_file handles, text/select/number inputs take plain values.', inputSchema: {} },
436
+ wrap(() => client.listRecipes()));
437
+
438
+ // --- Running an installed recipe (what drives the UGC + Product Studios) ---
439
+
440
+ server.registerTool('run_recipe',
441
+ {
442
+ title: 'Run a recipe',
443
+ description: 'Run an installed recipe (from list_recipes) with its inputs filled: the same multi-step pipeline UGC Studio / Product Studio runs when a person clicks Generate, so results land in the Gallery grouped the same way. `inputs` is keyed by input key; a subject input takes a character/product id, media inputs take upload_file handles. engine: local (default when every step is installed) | cloud | auto. Returns a runId; poll with wait_for_recipe_run or get_recipe_run. Cloud runs are priced up front and count against this agent\'s spend cap.',
444
+ inputSchema: {
445
+ id: z.string().describe('Recipe id from list_recipes'),
446
+ inputs: z.record(z.any()).describe('Input values keyed by the recipe\'s input keys (see list_recipes -> inputs).'),
447
+ engine: z.enum(['local', 'cloud', 'auto']).optional().describe('Where the steps render. auto = local if every step is installed, else cloud when connected.'),
448
+ },
449
+ },
450
+ wrap(({ id, inputs, engine }) => client.runRecipe(id, { inputs: inputs || {}, ...(engine ? { engine } : {}) })));
451
+
452
+ server.registerTool('get_recipe_run',
453
+ { title: 'Get a recipe run', description: 'Status of a recipe run: overall status (running | completed | failed | cancelled), each step with its status and resultPath, and resultPath = the final output once done.', inputSchema: { runId: z.string().describe('Run id from run_recipe') } },
454
+ wrap(({ runId }) => client.getRecipeRun(runId)));
455
+
456
+ server.registerTool('wait_for_recipe_run',
457
+ { title: 'Wait for a recipe run', description: 'Block until a recipe run completes, fails, is cancelled, or the timeout passes. Returns the final run (resultPath when completed). Multi-step video recipes can take several minutes; call again if it returns timeout_still_running.', inputSchema: { runId: z.string(), timeoutSeconds: z.number().optional(), pollMs: z.number().optional() } },
458
+ wrap(async ({ runId, timeoutSeconds = 600, pollMs = 3000 }) => {
459
+ const deadline = Date.now() + timeoutSeconds * 1000;
460
+ // eslint-disable-next-line no-constant-condition
461
+ while (true) {
462
+ const { run } = await client.getRecipeRun(runId);
463
+ if (run && ['completed', 'failed', 'cancelled'].includes(run.status)) return { run };
464
+ if (Date.now() >= deadline) return { run, note: 'timeout_still_running' };
465
+ await new Promise((r) => setTimeout(r, pollMs));
466
+ }
467
+ }));
468
+
469
+ server.registerTool('list_recipe_runs',
470
+ { title: 'List recipe runs', description: 'Recent runs of a recipe (newest first) with their status and results.', inputSchema: { id: z.string().describe('Recipe id') } },
471
+ wrap(({ id }) => client.listRecipeRuns(id)));
472
+
473
+ // --- Products + subjects: what a recipe's `subject` inputs take ---
474
+
475
+ server.registerTool('list_subjects',
476
+ { title: 'List subjects', description: 'Every subject a recipe\'s `subject` input can take: characters and products (id, type, name). Use a character id from list_characters or a product id from list_products / create_product.', inputSchema: {} },
477
+ wrap(() => client.listSubjects()));
478
+
479
+ server.registerTool('list_products',
480
+ { title: 'List products', description: 'The products saved on this device (a product = a named thing with a base photo, used by Product Studio and UGC recipes).', inputSchema: {} },
481
+ wrap(() => client.listProducts()));
482
+
483
+ server.registerTool('create_product',
484
+ {
485
+ title: 'Create a product',
486
+ description: 'Save a product from a photo so recipes can use it: upload the photo with upload_file first, then pass its handle. The description and category are woven into recipe prompts, so describe what it is and how it looks. Returns the productId to pass as a `subject` input in run_recipe.',
487
+ inputSchema: {
488
+ name: z.string().describe('Product name shown in the app'),
489
+ image: z.string().describe('upload_file handle of the product photo (clean, well-lit, product centred)'),
490
+ description: z.string().optional().describe('What it is and looks like, e.g. "a matte black ceramic coffee mug with a wooden lid"'),
491
+ category: z.string().optional().describe('e.g. skincare | beverage | electronics'),
492
+ },
493
+ },
494
+ wrap(({ name, image, description, category }) => client.createProduct({ name, image, description, category })));
495
+
496
+ server.registerTool('remove_product',
497
+ { title: 'Remove a product', description: 'Delete a product and its photo from this device.', inputSchema: { id: z.string() } },
498
+ wrap(({ id }) => client.removeProduct(id)));
499
+
500
+ server.registerTool('cancel_recipe_run',
501
+ { title: 'Cancel a recipe run', description: 'Stop a running recipe: no further steps start; a local in-flight step is interrupted (a cloud step already running finishes server-side and is saved).', inputSchema: { runId: z.string() } },
502
+ wrap(({ runId }) => client.cancelRecipeRun(runId)));
503
+
504
+ server.registerTool('get_recipe',
505
+ { title: 'Get a recipe', description: 'Get a saved recipe and its full config by id.', inputSchema: { id: z.string().describe('Recipe id from compose_recipe or list_recipes') } },
506
+ wrap(({ id }) => client.getRecipe(id)));
507
+
508
+ server.registerTool('publish_recipe',
509
+ { title: 'Publish a recipe', description: 'Submit a saved recipe to the SimpliGen Creator Marketplace (queued for human review). Requires a connected account: if none, returns not_connected and the user connects once in Settings, then this succeeds on the same recipe. priceTokens sets an optional one-time price (0 or omitted = free). Every preset the recipe uses must be a distributable first-party pack.', inputSchema: { id: z.string().describe('Recipe id to publish'), changelog: z.string().optional(), priceTokens: z.number().optional().describe('One-time price in tokens (0/omitted = free).') } },
510
+ wrap(({ id, changelog, priceTokens }) => client.publishRecipe(id, { changelog, priceTokens })));
511
+ }