post-engineer-mcp 1.12.4 → 1.30.0

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.
package/dist/tools.js CHANGED
@@ -14,33 +14,23 @@ const LibraryImageFields = {
14
14
  const PersonaLibraryImageInputShape = z.object(LibraryImageFields);
15
15
  export const CreatePersonaShape = {
16
16
  name: z.string().min(1, 'Name is required').describe('Name of the persona'),
17
- avatarUrl: z.string().url().optional().nullable().describe('Public URL to the persona avatar image (use list_faces for stock face URLs)'),
17
+ // REQUIRED: every persona has a face. A video without one is a per-video
18
+ // choice (generate_persona_videos options.faceless), never a persona one.
19
+ avatarUrl: z
20
+ .string()
21
+ .url()
22
+ .describe('REQUIRED. Public URL to the persona avatar image (use list_faces for stock face URLs). Every persona has a face; "no face" is chosen per video with generate_persona_videos options.faceless.'),
18
23
  voiceId: z.string().default('alloy').describe('Voice ID to use (e.g. alloy, echo)'),
19
24
  language: z.string().default('en-US').describe('Language code (e.g. pt-BR, en-US)'),
20
25
  videoAspect: z.enum(['9:16', '16:9']).default('9:16').describe('Video aspect ratio'),
21
26
  scriptPrompt: z.string().optional().default('').describe('System prompt instructions for video scripts'),
22
27
  paragraphNumber: z.number().int().min(1).max(10).default(1).describe('Number of paragraphs'),
23
28
  niche: z.string().optional().default('General').describe('Content niche topic'),
24
- faceMixPercent: z.number().min(0).max(100).default(50),
25
- faceQuality: z.enum(['ok', 'very_good']).default('very_good'),
26
- images: z.array(PersonaLibraryImageInputShape).max(MAX_LIBRARY_IMAGES).optional().describe(`Up to ${MAX_LIBRARY_IMAGES} local image files of the same person for the persona image library. Each video deterministically picks the best-matching image by tag. Requires a non-faceless persona: avatarUrl must be set, because the server rejects library images for faceless personas.`),
29
+ faceQuality: z.enum(['ok', 'very_good']).default('very_good').describe('Face resolution of the rendered videos: ok (480p, 2 tokens/video) or very_good (720p, 3 tokens/video)'),
30
+ images: z.array(PersonaLibraryImageInputShape).max(MAX_LIBRARY_IMAGES).optional().describe(`Up to ${MAX_LIBRARY_IMAGES} local image files of the same person for the persona image library. Each video deterministically picks the best-matching image by tag.`),
27
31
  imagePrimaryIndex: z.number().int().min(0).max(MAX_LIBRARY_IMAGES - 1).optional().describe('Index into images[] marking the primary library image (no primary is set when omitted)'),
28
32
  };
29
- export const CreatePersonaSchema = z.object(CreatePersonaShape).superRefine((value, ctx) => {
30
- // Domain rule encoded at parse time (the round-4 standing rule: encode
31
- // domain rules in the zod schema): library images are rejected
32
- // server-side for faceless personas, so require the avatar up front.
33
- // The client keeps its own check as defense in depth.
34
- const hasImages = (value.images?.length ?? 0) > 0;
35
- const hasAvatar = value.avatarUrl !== undefined && value.avatarUrl !== null && value.avatarUrl.length > 0;
36
- if (hasImages && !hasAvatar) {
37
- ctx.addIssue({
38
- code: z.ZodIssueCode.custom,
39
- path: ['avatarUrl'],
40
- message: 'avatarUrl is required when images are provided: library images need a persona avatar (faceless personas cannot have an image library).',
41
- });
42
- }
43
- });
33
+ export const CreatePersonaSchema = z.object(CreatePersonaShape);
44
34
  export const ListPersonasShape = {};
45
35
  export const ListPersonasSchema = z.object(ListPersonasShape);
46
36
  export const ListVoicesShape = {};
@@ -78,6 +68,88 @@ export const CancelScheduleShape = {
78
68
  scheduleId: z.string().min(1, 'scheduleId is required').describe('The ID of the schedule to cancel'),
79
69
  };
80
70
  export const CancelScheduleSchema = z.object(CancelScheduleShape);
71
+ export const GetSlotShape = {
72
+ slotId: z
73
+ .string()
74
+ .min(1, 'slotId is required')
75
+ .describe('The slot ID (the slotId field from list_posts or generate_persona_videos).'),
76
+ };
77
+ export const GetSlotSchema = z.object(GetSlotShape);
78
+ export const UpdateSlotTopicShape = {
79
+ slotId: z
80
+ .string()
81
+ .min(1, 'slotId is required')
82
+ .describe('The slot ID (the slotId field from list_posts or generate_persona_videos).'),
83
+ topic: z
84
+ .string()
85
+ .min(1, 'topic is required')
86
+ .describe('The new topic text for the slot. Only a slot that has not started generating (status pending/awaiting) can be edited; published or mid-flight slots are rejected.'),
87
+ };
88
+ export const UpdateSlotTopicSchema = z.object(UpdateSlotTopicShape);
89
+ export const DeleteSlotShape = {
90
+ slotId: z
91
+ .string()
92
+ .min(1, 'slotId is required')
93
+ .describe('The slot ID to delete. Only pending (awaiting) or failed slots can be deleted; published or mid-flight slots are rejected. The schedule\'s last slot cannot be deleted — delete the whole schedule with cancel_schedule instead.'),
94
+ };
95
+ export const DeleteSlotSchema = z.object(DeleteSlotShape);
96
+ export const ListVideoGenerationsShape = {
97
+ limit: z
98
+ .number()
99
+ .int()
100
+ .min(1)
101
+ .max(200)
102
+ .optional()
103
+ .describe('Max generations to return (1-200). Defaults to 50, newest first.'),
104
+ };
105
+ export const ListVideoGenerationsSchema = z.object(ListVideoGenerationsShape);
106
+ export const GetVideoGenerationShape = {
107
+ generationId: z
108
+ .string()
109
+ .min(1, 'generationId is required')
110
+ .describe('The generation ID (the generationId field from list_video_generations).'),
111
+ };
112
+ export const GetVideoGenerationSchema = z.object(GetVideoGenerationShape);
113
+ export const ListTokenTransactionsShape = {
114
+ limit: z
115
+ .number()
116
+ .int()
117
+ .min(1)
118
+ .max(100)
119
+ .optional()
120
+ .describe('Max transactions to return (1-100). Defaults to 20, newest first.'),
121
+ offset: z
122
+ .number()
123
+ .int()
124
+ .min(0)
125
+ .optional()
126
+ .describe('How many newest transactions to skip for paging. Defaults to 0.'),
127
+ };
128
+ export const ListTokenTransactionsSchema = z.object(ListTokenTransactionsShape);
129
+ export const GetPersonaDeletePreviewShape = {
130
+ personaId: z
131
+ .string()
132
+ .min(1, 'personaId is required')
133
+ .describe('The persona ID to preview deletion for. Read-only: shows what deleting the persona would remove (counts plus per-video download links).'),
134
+ };
135
+ export const GetPersonaDeletePreviewSchema = z.object(GetPersonaDeletePreviewShape);
136
+ export const DeletePersonaShape = {
137
+ personaId: z
138
+ .string()
139
+ .min(1, 'personaId is required')
140
+ .describe('The persona ID to delete. DESTRUCTIVE and irreversible: deletes the persona, all its schedules and slots, all generated videos, and the image library. No token refunds — prepaid tokens for pending slots are forfeited. Call get_persona_delete_preview first to see exactly what will be removed.'),
141
+ };
142
+ export const DeletePersonaSchema = z.object(DeletePersonaShape);
143
+ export const DisconnectAccountShape = {
144
+ provider: z
145
+ .enum(['youtube', 'instagram', 'linkedin', 'bluesky'])
146
+ .describe('The social platform of the account to disconnect.'),
147
+ providerAccountId: z
148
+ .string()
149
+ .min(1, 'providerAccountId is required')
150
+ .describe('The account ID on that provider (the channelId / igUserId / providerAccountId / did field from list_social_accounts).'),
151
+ };
152
+ export const DisconnectAccountSchema = z.object(DisconnectAccountShape);
81
153
  export const GetTokenBalanceShape = {};
82
154
  export const GetTokenBalanceSchema = z.object(GetTokenBalanceShape);
83
155
  // Loopback hosts for which a plain http: media/webhook URL is tolerated
@@ -115,11 +187,15 @@ const PublishingAccountIdsShape = {
115
187
  blueskyAccountIds: z.array(z.string().min(1)).optional().describe('Bluesky DIDs (the did field from list_social_accounts). Required when providers includes bluesky.'),
116
188
  };
117
189
  export const GeneratePersonaVideosShape = {
118
- // personaId is REQUIRED even for faceless videos: the API has no
119
- // standalone-generation flow, so a persona record always anchors the
120
- // schedule. Faceless drops the face via options.faceless (the persona
121
- // voice, niche, and script prompt still apply).
122
- personaId: z.string().min(1, 'personaId is required').describe('The ID of the persona to generate videos with. REQUIRED even for faceless videos — set options.faceless to true to drop the face.'),
190
+ // Optional since migration 012: a faceless post can be defined entirely by
191
+ // options. A persona is not only a face — it is where the voice, the script
192
+ // prompt, the aspect ratio and the niche come from, so a post without one
193
+ // must supply them (or at least a voice) via options.
194
+ personaId: z
195
+ .string()
196
+ .min(1, 'personaId must be a non-empty string when provided')
197
+ .optional()
198
+ .describe('The persona to generate videos with. Omit for a faceless post with no persona: in that case set options.faceless and options.voiceId (or options.audioUrl), plus options.scriptPrompt / videoAspect / language / niche as needed. With a persona these options still override it.'),
123
199
  // The array bounds live in the shape (not a .refine): the MCP SDK parses
124
200
  // tool args against the raw shape, so a whole-object refine would be a
125
201
  // hollow claim on the tool path (round 26 learning).
@@ -127,35 +203,48 @@ export const GeneratePersonaVideosShape = {
127
203
  .array(z.string().min(1, 'Each topic must be a non-empty string'))
128
204
  .min(1, 'Provide at least one video topic')
129
205
  .max(10, 'At most 10 topics per call')
130
- .describe('Video topics, one per video (1-10). The server assigns each topic a publish slot: topic i goes to day startAt\'s date + floor(i/times.length) at the i-th sorted time.'),
206
+ .describe('Video topics, one per video (1-10). In scheduled mode the server assigns each topic a publish slot: topic i goes to day startAt\'s date + floor(i/times.length) at the i-th sorted time. In asap mode each video publishes the moment its generation finishes.'),
131
207
  providers: z
132
208
  .array(z.enum(['youtube', 'instagram', 'linkedin', 'bluesky']))
133
209
  .min(1, 'Provide at least one provider')
134
210
  .describe('Where to publish the videos.'),
135
211
  ...PublishingAccountIdsShape,
212
+ // Publish mode: 'scheduled' (default) distributes publish slots across
213
+ // startAt + times; 'asap' publishes each video the moment generation
214
+ // finishes, with no scheduled time. In asap mode startAt and times must
215
+ // NOT be set (the handler fails fast on a stray plan).
216
+ mode: z
217
+ .enum(['scheduled', 'asap'])
218
+ .default('scheduled')
219
+ .describe("Publish mode: 'scheduled' (default) slots each video across startAt + times; 'asap' publishes each video the moment generation finishes, with no scheduled time — do not set startAt or times."),
136
220
  startAt: z
137
221
  .string()
138
- .min(1, 'startAt is required')
139
222
  .refine((value) => !Number.isNaN(Date.parse(value)), {
140
223
  message: 'startAt must be a valid ISO datetime (e.g. "2026-10-02T20:00:00")',
141
224
  })
142
- .describe('When the first publish slot may start: ISO datetime. A naive "2026-10-02T20:00:00" is wall-clock in timezone. Slots before startAt are skipped; every slot must be 3h–30d ahead.'),
225
+ .optional()
226
+ .describe('When the first publish slot may start: ISO datetime. A naive "2026-10-02T20:00:00" is wall-clock in timezone. Required unless mode is \'asap\'. Slots before startAt are skipped; every slot must be 3h–30d ahead.'),
143
227
  times: z
144
228
  .array(z
145
229
  .string()
146
230
  .regex(/^([01]\d|2[0-3]):[0-5]\d$/, 'Each time must be HH:MM in 24-hour format (e.g. "09:30", "20:00")'))
147
231
  .min(1, 'Provide at least one publish time')
148
- .describe('Daily publish times in HH:MM 24-hour format.'),
149
- timezone: z.string().min(1).default('UTC').describe('IANA timezone for a naive startAt and the HH:MM times, e.g. "Europe/Lisbon". Defaults to UTC.'),
232
+ .optional()
233
+ .describe('Daily publish times in HH:MM 24-hour format. Required unless mode is \'asap\'.'),
234
+ timezone: z.string().min(1).default('UTC').describe('IANA timezone for a naive startAt and the HH:MM times, e.g. "Europe/Lisbon". Defaults to UTC. Display-only when mode is \'asap\'.'),
150
235
  options: z
151
236
  .object({
152
- faceless: z.boolean().optional().describe('Generate faceless (no face). personaId is still required: the persona voice, niche, and script prompt still apply.'),
237
+ faceless: z.boolean().optional().describe('Generate faceless (no face). With a persona this drops only the face — the persona voice, niche and script prompt still apply. Without a persona it is REQUIRED.'),
153
238
  audioUrl: httpsUrlField('audioUrl').optional().describe('Public URL of custom audio for the videos (overrides the persona voice).'),
154
239
  imageId: z.string().min(1, 'imageId must be a non-empty string').optional().describe('Library image ID to use for every video (overrides the deterministic per-video selection; see list_persona_images).'),
155
240
  scriptPrompt: z.string().optional().describe('Script prompt override applied to every video in this call.'),
156
241
  scriptPrompts: z.array(z.string().min(1)).optional().describe('Per-topic script prompt overrides; must have one entry per topic.'),
157
242
  voiceId: z.string().min(1, 'voiceId must be a non-empty string').optional().describe('Voice ID override (see list_voices).'),
158
243
  webhookUrl: httpsUrlField('webhookUrl').optional().describe('Callback URL the server POSTs to when each video reaches a terminal state (completed/failed).'),
244
+ videoAspect: z.enum(['9:16', '16:9']).optional().describe('Frame shape. Overrides the persona when one is given; a post without a persona defaults to 9:16.'),
245
+ paragraphNumber: z.number().int().min(1).max(10).optional().describe('Paragraph count (1-10). Overrides the persona when one is given.'),
246
+ language: z.string().min(1).max(32).optional().describe('Spoken language code, e.g. pt-BR. Overrides the persona when one is given.'),
247
+ niche: z.string().min(1).max(300).optional().describe('Content niche. Overrides the persona when one is given.'),
159
248
  })
160
249
  .optional()
161
250
  .describe('Generation options applied to the videos in this call.'),
@@ -214,10 +303,10 @@ export const GetVideoTaskProgressShape = {
214
303
  };
215
304
  export const GetVideoTaskProgressSchema = z.object(GetVideoTaskProgressShape);
216
305
  export async function handleCreatePersona(client, args) {
217
- // Re-parse with the refined schema: the MCP SDK parses tool args from the
218
- // raw shape only, so the superRefine cross-field rule would otherwise never
219
- // fire on the tool path. A parse failure becomes a loud isError via
220
- // handleLibraryCall, before any file is read.
306
+ // Re-parse with the full schema: the MCP SDK parses tool args from the
307
+ // raw shape only, so required-field failures (like a missing avatarUrl)
308
+ // would otherwise never fire on the tool path. A parse failure becomes a
309
+ // loud isError via handleLibraryCall, before any file is read.
221
310
  return handleLibraryCall(() => client.createPersona(CreatePersonaSchema.parse(args)), 'creating persona', 'Persona created successfully');
222
311
  }
223
312
  export async function handleListPersonas(client) {
@@ -330,6 +419,482 @@ export async function handleListPosts(client, args) {
330
419
  export async function handleCancelSchedule(client, args) {
331
420
  return handleLibraryCall(() => client.cancelSchedule(args.scheduleId), 'cancelling schedule', 'Schedule cancelled successfully');
332
421
  }
422
+ export async function handleGetSlot(client, args) {
423
+ try {
424
+ const narrowed = narrowSlotDetail(await client.getSlot(args.slotId));
425
+ const slot = narrowed.slot;
426
+ const humanSummary = `Slot ${slot.id ?? args.slotId}: "${slot.topic ?? '(untitled)'}" — ${slot.status ?? 'unknown'}, scheduled for ${slot.slotAt ?? '(unscheduled)'}.`;
427
+ return {
428
+ content: [
429
+ {
430
+ type: 'text',
431
+ text: `${humanSummary}\n${JSON.stringify(narrowed, null, 2)}`,
432
+ },
433
+ ],
434
+ };
435
+ }
436
+ catch (error) {
437
+ if (error instanceof ApiError && error.code !== null) {
438
+ return {
439
+ content: [
440
+ {
441
+ type: 'text',
442
+ text: `Error getting slot: ${JSON.stringify({
443
+ code: error.code,
444
+ message: sanitizeEngineError(getErrorMessage(error)),
445
+ field: error.field,
446
+ })}`,
447
+ },
448
+ ],
449
+ isError: true,
450
+ };
451
+ }
452
+ return {
453
+ content: [
454
+ {
455
+ type: 'text',
456
+ text: `Error getting slot: ${getErrorMessage(error)}`,
457
+ },
458
+ ],
459
+ isError: true,
460
+ };
461
+ }
462
+ }
463
+ export async function handleUpdateSlotTopic(client, args) {
464
+ try {
465
+ const result = (await client.updateSlotTopic(args.slotId, args.topic));
466
+ const topic = typeof result.topic === 'string' ? result.topic : args.topic;
467
+ return {
468
+ content: [
469
+ {
470
+ type: 'text',
471
+ text: `Slot ${args.slotId} topic updated to "${topic}".\n${JSON.stringify({ success: true, topic }, null, 2)}`,
472
+ },
473
+ ],
474
+ };
475
+ }
476
+ catch (error) {
477
+ if (error instanceof ApiError && error.code !== null) {
478
+ return {
479
+ content: [
480
+ {
481
+ type: 'text',
482
+ text: `Error updating slot topic: ${JSON.stringify({
483
+ code: error.code,
484
+ message: sanitizeEngineError(getErrorMessage(error)),
485
+ field: error.field,
486
+ })}`,
487
+ },
488
+ ],
489
+ isError: true,
490
+ };
491
+ }
492
+ return {
493
+ content: [
494
+ {
495
+ type: 'text',
496
+ text: `Error updating slot topic: ${getErrorMessage(error)}`,
497
+ },
498
+ ],
499
+ isError: true,
500
+ };
501
+ }
502
+ }
503
+ export async function handleDeleteSlot(client, args) {
504
+ return handleLibraryCall(() => client.deleteSlot(args.slotId), 'deleting slot', `Slot ${args.slotId} deleted`);
505
+ }
506
+ export async function handleListVideoGenerations(client, args) {
507
+ try {
508
+ const generations = narrowVideoGenerations(await client.listVideoGenerations(args.limit));
509
+ const humanSummary = `${generations.length} video generation(s) in history (newest first).`;
510
+ return {
511
+ content: [
512
+ {
513
+ type: 'text',
514
+ text: `${humanSummary}\n${JSON.stringify({ generations }, null, 2)}`,
515
+ },
516
+ ],
517
+ };
518
+ }
519
+ catch (error) {
520
+ if (error instanceof ApiError && error.code !== null) {
521
+ return {
522
+ content: [
523
+ {
524
+ type: 'text',
525
+ text: `Error listing video generations: ${JSON.stringify({
526
+ code: error.code,
527
+ message: sanitizeEngineError(getErrorMessage(error)),
528
+ field: error.field,
529
+ })}`,
530
+ },
531
+ ],
532
+ isError: true,
533
+ };
534
+ }
535
+ return {
536
+ content: [
537
+ {
538
+ type: 'text',
539
+ text: `Error listing video generations: ${getErrorMessage(error)}`,
540
+ },
541
+ ],
542
+ isError: true,
543
+ };
544
+ }
545
+ }
546
+ export async function handleGetVideoGeneration(client, args) {
547
+ try {
548
+ const result = (await client.getVideoGeneration(args.generationId));
549
+ const generation = narrowVideoGeneration(result !== null && typeof result === 'object' ? result.generation : null);
550
+ const humanSummary = `Generation ${generation.generationId ?? args.generationId}: "${generation.videoSubject ?? '(untitled)'}" — ${generation.status ?? 'unknown'}.`;
551
+ return {
552
+ content: [
553
+ {
554
+ type: 'text',
555
+ text: `${humanSummary}\n${JSON.stringify({ generation }, null, 2)}`,
556
+ },
557
+ ],
558
+ };
559
+ }
560
+ catch (error) {
561
+ if (error instanceof ApiError && error.code !== null) {
562
+ return {
563
+ content: [
564
+ {
565
+ type: 'text',
566
+ text: `Error getting video generation: ${JSON.stringify({
567
+ code: error.code,
568
+ message: sanitizeEngineError(getErrorMessage(error)),
569
+ field: error.field,
570
+ })}`,
571
+ },
572
+ ],
573
+ isError: true,
574
+ };
575
+ }
576
+ return {
577
+ content: [
578
+ {
579
+ type: 'text',
580
+ text: `Error getting video generation: ${getErrorMessage(error)}`,
581
+ },
582
+ ],
583
+ isError: true,
584
+ };
585
+ }
586
+ }
587
+ /** Narrows one video_generations row. Anything the API adds later rides
588
+ * through unparsed — the projection only pins what the tool renders and
589
+ * documents. */
590
+ function narrowVideoGeneration(row) {
591
+ const record = typeof row === 'object' && row !== null ? row : {};
592
+ const str = (value) => typeof value === 'string' ? value : null;
593
+ return {
594
+ id: str(record.id),
595
+ generationId: str(record.generationId),
596
+ engineTaskId: str(record.engineTaskId),
597
+ personaName: str(record.personaName),
598
+ videoSubject: str(record.videoSubject),
599
+ status: str(record.status),
600
+ errorCode: str(record.errorCode),
601
+ tokensRefunded: typeof record.tokensRefunded === 'boolean' ? record.tokensRefunded : null,
602
+ createdAt: str(record.createdAt),
603
+ completedAt: str(record.completedAt),
604
+ };
605
+ }
606
+ /** Narrows the GET /api/persona/video-generations envelope to the pinned
607
+ * row fields. */
608
+ function narrowVideoGenerations(result) {
609
+ const record = typeof result === 'object' && result !== null
610
+ ? result
611
+ : {};
612
+ const raw = Array.isArray(record.generations) ? record.generations : [];
613
+ return raw.map((row) => narrowVideoGeneration(row));
614
+ }
615
+ export async function handleListTokenTransactions(client, args) {
616
+ try {
617
+ const narrowed = narrowTokenTransactions(await client.listTokenTransactions(args.limit, args.offset));
618
+ const shown = narrowed.transactions.length;
619
+ const humanSummary = `Token ledger: showing ${shown} of ${narrowed.total ?? '?'} transaction(s) (newest first). ` +
620
+ `Negative amounts are spends, positive amounts are credits.`;
621
+ return {
622
+ content: [
623
+ {
624
+ type: 'text',
625
+ text: `${humanSummary}\n${JSON.stringify(narrowed, null, 2)}`,
626
+ },
627
+ ],
628
+ };
629
+ }
630
+ catch (error) {
631
+ if (error instanceof ApiError && error.code !== null) {
632
+ return {
633
+ content: [
634
+ {
635
+ type: 'text',
636
+ text: `Error listing token transactions: ${JSON.stringify({
637
+ code: error.code,
638
+ message: sanitizeEngineError(getErrorMessage(error)),
639
+ field: error.field,
640
+ })}`,
641
+ },
642
+ ],
643
+ isError: true,
644
+ };
645
+ }
646
+ return {
647
+ content: [
648
+ {
649
+ type: 'text',
650
+ text: `Error listing token transactions: ${getErrorMessage(error)}`,
651
+ },
652
+ ],
653
+ isError: true,
654
+ };
655
+ }
656
+ }
657
+ export async function handleGetPersonaDeletePreview(client, args) {
658
+ try {
659
+ const narrowed = narrowDeletePreview(await client.getPersonaDeletePreview(args.personaId));
660
+ const counts = narrowed.counts;
661
+ const humanSummary = `Deleting persona "${narrowed.persona.name ?? args.personaId}" would remove ` +
662
+ `${counts.schedules ?? '?'} schedule(s), ${counts.upcomingSlots ?? '?'} upcoming slot(s), ` +
663
+ `${counts.publishedSlots ?? '?'} published slot(s), ${counts.generatedVideos ?? '?'} generated video(s), ` +
664
+ `and ${counts.personaImages ?? '?'} library image(s). No token refunds.`;
665
+ return {
666
+ content: [
667
+ {
668
+ type: 'text',
669
+ text: `${humanSummary}\n${JSON.stringify(narrowed, null, 2)}`,
670
+ },
671
+ ],
672
+ };
673
+ }
674
+ catch (error) {
675
+ if (error instanceof ApiError && error.code !== null) {
676
+ return {
677
+ content: [
678
+ {
679
+ type: 'text',
680
+ text: `Error getting persona delete preview: ${JSON.stringify({
681
+ code: error.code,
682
+ message: sanitizeEngineError(getErrorMessage(error)),
683
+ field: error.field,
684
+ })}`,
685
+ },
686
+ ],
687
+ isError: true,
688
+ };
689
+ }
690
+ return {
691
+ content: [
692
+ {
693
+ type: 'text',
694
+ text: `Error getting persona delete preview: ${getErrorMessage(error)}`,
695
+ },
696
+ ],
697
+ isError: true,
698
+ };
699
+ }
700
+ }
701
+ export async function handleDeletePersona(client, args) {
702
+ try {
703
+ await client.deletePersona(args.personaId);
704
+ return {
705
+ content: [
706
+ {
707
+ type: 'text',
708
+ text: `Persona ${args.personaId} deleted: the persona, all its schedules and slots, ` +
709
+ `all generated videos, and the image library are gone. No token refunds were issued.`,
710
+ },
711
+ ],
712
+ };
713
+ }
714
+ catch (error) {
715
+ if (error instanceof ApiError && error.code !== null) {
716
+ return {
717
+ content: [
718
+ {
719
+ type: 'text',
720
+ text: `Error deleting persona: ${JSON.stringify({
721
+ code: error.code,
722
+ message: sanitizeEngineError(getErrorMessage(error)),
723
+ field: error.field,
724
+ })}`,
725
+ },
726
+ ],
727
+ isError: true,
728
+ };
729
+ }
730
+ return {
731
+ content: [
732
+ {
733
+ type: 'text',
734
+ text: `Error deleting persona: ${getErrorMessage(error)}`,
735
+ },
736
+ ],
737
+ isError: true,
738
+ };
739
+ }
740
+ }
741
+ export async function handleDisconnectAccount(client, args) {
742
+ try {
743
+ await client.disconnectAccount(args.provider, args.providerAccountId);
744
+ return {
745
+ content: [
746
+ {
747
+ type: 'text',
748
+ text: `Account ${args.providerAccountId} (${args.provider}) disconnected.`,
749
+ },
750
+ ],
751
+ };
752
+ }
753
+ catch (error) {
754
+ if (error instanceof ApiError && error.code !== null) {
755
+ return {
756
+ content: [
757
+ {
758
+ type: 'text',
759
+ text: `Error disconnecting account: ${JSON.stringify({
760
+ code: error.code,
761
+ message: sanitizeEngineError(getErrorMessage(error)),
762
+ field: error.field,
763
+ })}`,
764
+ },
765
+ ],
766
+ isError: true,
767
+ };
768
+ }
769
+ return {
770
+ content: [
771
+ {
772
+ type: 'text',
773
+ text: `Error disconnecting account: ${getErrorMessage(error)}`,
774
+ },
775
+ ],
776
+ isError: true,
777
+ };
778
+ }
779
+ }
780
+ /** Narrows the GET /api/persona/delete-preview envelope: the persona, the
781
+ * removal counts, and the per-video download links. Anything the API adds
782
+ * later rides through unparsed. */
783
+ function narrowDeletePreview(result) {
784
+ const record = typeof result === 'object' && result !== null
785
+ ? result
786
+ : {};
787
+ const persona = typeof record.persona === 'object' && record.persona !== null
788
+ ? record.persona
789
+ : {};
790
+ const counts = typeof record.counts === 'object' && record.counts !== null
791
+ ? record.counts
792
+ : {};
793
+ const rawVideos = Array.isArray(record.videos) ? record.videos : [];
794
+ const str = (value) => typeof value === 'string' ? value : null;
795
+ const num = (value) => typeof value === 'number' ? value : null;
796
+ const bool = (value) => typeof value === 'boolean' ? value : null;
797
+ return {
798
+ persona: { id: str(persona.id), name: str(persona.name) },
799
+ counts: {
800
+ schedules: num(counts.schedules),
801
+ upcomingSlots: num(counts.upcomingSlots),
802
+ publishedSlots: num(counts.publishedSlots),
803
+ failedSlots: num(counts.failedSlots),
804
+ generatedVideos: num(counts.generatedVideos),
805
+ personaImages: num(counts.personaImages),
806
+ },
807
+ videos: rawVideos.map((video) => {
808
+ const v = typeof video === 'object' && video !== null
809
+ ? video
810
+ : {};
811
+ return {
812
+ taskId: str(v.taskId),
813
+ topic: str(v.topic),
814
+ status: str(v.status),
815
+ downloadUrl: str(v.downloadUrl),
816
+ };
817
+ }),
818
+ videosTruncated: bool(record.videosTruncated),
819
+ linksIncomplete: bool(record.linksIncomplete),
820
+ };
821
+ }
822
+ /** Narrows the GET /api/billing/transactions envelope. Anything the API
823
+ * adds later rides through unparsed — the projection only pins what the
824
+ * tool renders and documents. */
825
+ function narrowTokenTransactions(result) {
826
+ const record = typeof result === 'object' && result !== null
827
+ ? result
828
+ : {};
829
+ const raw = Array.isArray(record.transactions) ? record.transactions : [];
830
+ const str = (value) => typeof value === 'string' ? value : null;
831
+ const num = (value) => typeof value === 'number' ? value : null;
832
+ return {
833
+ transactions: raw.map((row) => {
834
+ const r = typeof row === 'object' && row !== null ? row : {};
835
+ return {
836
+ id: str(r.id),
837
+ amount: num(r.amount),
838
+ type: str(r.type),
839
+ description: str(r.description),
840
+ reason: str(r.reason),
841
+ generationId: str(r.generationId),
842
+ createdAt: str(r.createdAt),
843
+ };
844
+ }),
845
+ total: num(record.total),
846
+ limit: num(record.limit),
847
+ offset: num(record.offset),
848
+ };
849
+ }
850
+ /** Narrows the GET /api/schedule/slots/[slotId] envelope to the fields the
851
+ * tool contract promises: the slot row, its schedule, and the persona.
852
+ * Anything the API adds later rides through unparsed — the projection only
853
+ * pins what the tool renders and documents. */
854
+ function narrowSlotDetail(result) {
855
+ const record = typeof result === 'object' && result !== null
856
+ ? result
857
+ : {};
858
+ const slot = typeof record.slot === 'object' && record.slot !== null
859
+ ? record.slot
860
+ : {};
861
+ const schedule = typeof record.schedule === 'object' && record.schedule !== null
862
+ ? record.schedule
863
+ : null;
864
+ const persona = typeof record.persona === 'object' && record.persona !== null
865
+ ? record.persona
866
+ : null;
867
+ const str = (value) => typeof value === 'string' ? value : null;
868
+ const num = (value) => typeof value === 'number' ? value : null;
869
+ const providers = Array.isArray(schedule?.providers)
870
+ ? schedule.providers.filter((p) => typeof p === 'string')
871
+ : [];
872
+ return {
873
+ slot: {
874
+ id: str(slot.id),
875
+ scheduleId: str(slot.scheduleId),
876
+ slotAt: str(slot.slotAt),
877
+ status: str(slot.status),
878
+ topic: str(slot.topic),
879
+ taskId: str(slot.taskId),
880
+ progress: num(slot.progress),
881
+ stage: str(slot.stage),
882
+ error: str(slot.error),
883
+ publishedAt: str(slot.publishedAt),
884
+ },
885
+ schedule: schedule === null
886
+ ? null
887
+ : {
888
+ id: str(schedule.id),
889
+ providers,
890
+ publishMode: str(schedule.publishMode),
891
+ timezone: str(schedule.timezone),
892
+ },
893
+ persona: persona === null
894
+ ? null
895
+ : { id: str(persona.id), name: str(persona.name) },
896
+ };
897
+ }
333
898
  export async function handleGetTokenBalance(client) {
334
899
  return handleLibraryCall(() => client.getTokenBalance(), 'getting token balance');
335
900
  }
@@ -413,10 +978,10 @@ export function sanitizeEngineError(error) {
413
978
  * without them (empty-body sentinel, 404 shape) is reported with
414
979
  * explicit nulls rather than silently dropping fields. */
415
980
  function narrowTaskProgress(result) {
416
- const data = typeof result === 'object' && result !== null && 'data' in result
417
- ? result.data
981
+ const payload = typeof result === 'object' && result !== null && 'body' in result
982
+ ? result.body
418
983
  : undefined;
419
- const record = typeof data === 'object' && data !== null ? data : {};
984
+ const record = typeof payload === 'object' && payload !== null ? payload : {};
420
985
  const get = (key) => key in record ? record[key] : undefined;
421
986
  const taskId = get('task_id');
422
987
  const state = get('state');
@@ -438,6 +1003,18 @@ export async function handleGetVideoTaskProgress(client, args) {
438
1003
  }
439
1004
  export async function handleGeneratePersonaVideos(client, args) {
440
1005
  try {
1006
+ // The MCP SDK parses tool args against the raw shape, so a whole-object
1007
+ // refine would be a hollow claim on the tool path (round 26 learning):
1008
+ // the mode/plan consistency rule lives here instead, where it always
1009
+ // runs. A stray schedule plan 400s server-side; name the rule before
1010
+ // the client fires.
1011
+ const mode = args.mode ?? 'scheduled';
1012
+ if (mode === 'asap' && (args.startAt !== undefined || args.times !== undefined)) {
1013
+ throw new Error("startAt and times must not be set when mode is 'asap'.");
1014
+ }
1015
+ if (mode === 'scheduled' && (args.startAt === undefined || args.times === undefined)) {
1016
+ throw new Error("startAt and times are required when mode is 'scheduled'.");
1017
+ }
441
1018
  const narrowed = narrowScheduledVideos(await client.generatePersonaVideos({
442
1019
  personaId: args.personaId,
443
1020
  topics: args.topics,
@@ -446,6 +1023,7 @@ export async function handleGeneratePersonaVideos(client, args) {
446
1023
  instagramAccountIds: args.instagramAccountIds,
447
1024
  linkedinAccountIds: args.linkedinAccountIds,
448
1025
  blueskyAccountIds: args.blueskyAccountIds,
1026
+ mode,
449
1027
  startAt: args.startAt,
450
1028
  times: args.times,
451
1029
  timezone: args.timezone,
@@ -460,7 +1038,9 @@ export async function handleGeneratePersonaVideos(client, args) {
460
1038
  const scheduleId = narrowed.schedule.id ?? '(unknown id)';
461
1039
  const humanSummary = narrowed.replayed
462
1040
  ? `Replayed idempotent schedule ${scheduleId}: ${slotCount} publish slot(s) (no new videos generated).`
463
- : `Scheduled ${slotCount} video(s) in schedule ${scheduleId}: each video is generated and auto-published at its slot.`;
1041
+ : narrowed.schedule.mode === 'asap'
1042
+ ? `Generating ${slotCount} video(s) in schedule ${scheduleId}: each video publishes as soon as its generation finishes (ASAP mode).`
1043
+ : `Scheduled ${slotCount} video(s) in schedule ${scheduleId}: each video is generated and auto-published at its slot.`;
464
1044
  const slotLines = narrowed.slots.map((slot, i) => `${i + 1}. ${slot.topic ?? '(untitled)'} → ${slot.slotAt ?? '(unscheduled)'} [${slot.status ?? 'unknown'}${slot.taskId ? `, task ${slot.taskId}` : ''}]`);
465
1045
  return {
466
1046
  content: [
@@ -504,9 +1084,10 @@ export async function handleGeneratePersonaVideos(client, args) {
504
1084
  }
505
1085
  }
506
1086
  /** Narrows the generate-and-schedule success envelope to the fields the
507
- * tool contract promises: the schedule id, one row per publish slot, and
508
- * the replayed flag. Anything the API adds later rides through unparsed —
509
- * the projection only pins what the tool renders and documents. */
1087
+ * tool contract promises: the schedule id and publish mode, one row per
1088
+ * publish slot, and the replayed flag. Anything the API adds later rides
1089
+ * through unparsed — the projection only pins what the tool renders and
1090
+ * documents. */
510
1091
  function narrowScheduledVideos(result) {
511
1092
  const record = typeof result === 'object' && result !== null
512
1093
  ? result
@@ -517,7 +1098,7 @@ function narrowScheduledVideos(result) {
517
1098
  const rawSlots = Array.isArray(record.slots) ? record.slots : [];
518
1099
  const str = (value) => typeof value === 'string' ? value : null;
519
1100
  return {
520
- schedule: { id: str(schedule.id) },
1101
+ schedule: { id: str(schedule.id), mode: str(schedule.mode) },
521
1102
  slots: rawSlots.map((slot) => {
522
1103
  const s = typeof slot === 'object' && slot !== null
523
1104
  ? slot