Open-source AI podcast clipper. Generate vertical clips with face tracking and burned-in captions. CLI, MCP server, web app.
Python ai-toolsauto-captionscaptionscliffmpegmcpmcp-serveropusclip-alternativepodcast-clipspodcastsshortform-videovertical-videowhisper
handlers: end-to-end type safety across MCP tool handlers
Nika Siradzea8d20ee3e092
diff --git a/src/handlers/batch-clips.handler.ts b/src/handlers/batch-clips.handler.tsindex 16242fd..d1462d4 100644--- a/src/handlers/batch-clips.handler.ts+++ b/src/handlers/batch-clips.handler.ts@@ -2,15 +2,25 @@ import { readFileSync } from "fs";import { PythonExecutor } from "../services/python-executor.js";import { FileManager } from "../services/file-manager.js";import { paths } from "../config/paths.js";+import { childLogger } from "../utils/logger.js";+import type {+ BatchClipsInput,+ BatchClipSpec,+ BatchClipsResult,+ SuggestedClip,+ UIState,+} from "../models/index.js";+const log = childLogger("batch-clips");const executor = new PythonExecutor();const fileManager = new FileManager();/** Load UI state from disk. Returns null if unavailable. */-function loadState(): Record<string, unknown> | null {+function loadState(): UIState | null {try {- return JSON.parse(readFileSync(paths.uiState, "utf-8"));- } catch {+ return JSON.parse(readFileSync(paths.uiState, "utf-8")) as UIState;+ } catch (err) {+ log.debug("UI state unavailable", { err: err instanceof Error ? err.message : err });return null;}}@@ -98,44 +108,37 @@ export const batchClipsToolDef = {},};-export async function handleBatchClips(- input: Record<string, unknown>-): Promise<string> {+export async function handleBatchClips(input: BatchClipsInput): Promise<string> {await fileManager.ensureDirectories();const state = loadState();- const settings = (state?.settings as Record<string, string>) || {};- const suggestions = (state?.suggestions as Array<Record<string, unknown>>) || [];- const transcript = state?.transcript as Record<string, unknown> | null;+ const settings = state?.settings ?? {};+ const suggestions: SuggestedClip[] = state?.suggestions ?? [];+ const transcript = state?.transcript ?? null;// Auto-resolve video path- const videoPath =- (input.video_path as string) || (state?.videoPath as string) || "";+ const videoPath = input.video_path || state?.videoPath || "";if (!videoPath) {return JSON.stringify({ error: "video_path is required (no video in session state)" });}// Auto-resolve transcript words- const transcriptWords =- (input.transcript_words as Array<unknown>) ||- (transcript?.words as Array<unknown>) ||- [];+ const transcriptWords = input.transcript_words ?? transcript?.words ?? [];// Build clips array: from export_selected, clip_numbers, or explicit clips- let clips: Array<Record<string, unknown>>;- const deselected = (state?.deselectedIndices as number[]) || [];+ let clips: BatchClipSpec[];+ const deselected = state?.deselectedIndices ?? [];- const buildClipFromSuggestion = (s: Record<string, unknown>, num: number) => ({+ const buildClipFromSuggestion = (s: SuggestedClip, num: number): BatchClipSpec => ({start_second: s.start_second,end_second: s.end_second,title: s.title || `clip_${num}`,- caption_style:- (s.suggested_caption_style as string) || settings.captionStyle || "hormozi",+ caption_style: s.suggested_caption_style || settings.captionStyle || "hormozi",crop_strategy: settings.cropStrategy || "speaker",allow_ass_fallback: input.allow_ass_fallback === true,logo_path: settings.logoPath || null,// Preserve multi-cut segments from suggestion- ...(Array.isArray(s.segments) && s.segments.length > 0 && { keep_segments: s.segments }),+ ...(s.segments && s.segments.length > 0 && { keep_segments: s.segments }),});if (input.export_selected) {@@ -152,11 +155,10 @@ export async function handleBatchClips(});}} else if (input.clip_numbers) {- const numbers = input.clip_numbers as number[];const errors: string[] = [];clips = [];- for (const num of numbers) {+ for (const num of input.clip_numbers) {const idx = num - 1;if (idx < 0 || idx >= suggestions.length) {errors.push(`Clip #${num} not found`);@@ -171,14 +173,14 @@ export async function handleBatchClips(});}} else if (input.clips) {- clips = input.clips as Array<Record<string, unknown>>;+ clips = input.clips;} else {return JSON.stringify({error: "Use export_selected=true, clip_numbers=[1, 3], or pass clips array",});}- const result = await executor.execute("batch_clips", {+ const result = await executor.execute<BatchClipsResult>("batch_clips", {video_path: videoPath,clips,transcript_words: transcriptWords,@@ -188,7 +190,10 @@ export async function handleBatchClips(logo_path: settings.logoPath || null,});- const data = result.data as Record<string, unknown>;+ if (!result.data) {+ throw new Error("Batch clip creation returned no data");+ }+ const data = result.data;return JSON.stringify({total_clips: data.total_clips,diff --git a/src/handlers/create-clip.handler.ts b/src/handlers/create-clip.handler.tsindex 3a78452..a946420 100644--- a/src/handlers/create-clip.handler.ts+++ b/src/handlers/create-clip.handler.ts@@ -2,16 +2,19 @@ import { readFileSync } from "fs";import { PythonExecutor } from "../services/python-executor.js";import { FileManager } from "../services/file-manager.js";import { paths } from "../config/paths.js";-import type { ClipResult } from "../models/index.js";+import type { ClipResult, CreateClipInput, SuggestedClip, UIState } from "../models/index.js";+import { childLogger } from "../utils/logger.js";+const log = childLogger("create-clip");const executor = new PythonExecutor();const fileManager = new FileManager();/** Load UI state from disk. Returns null if unavailable. */-function loadState(): Record<string, unknown> | null {+function loadState(): UIState | null {try {- return JSON.parse(readFileSync(paths.uiState, "utf-8"));- } catch {+ return JSON.parse(readFileSync(paths.uiState, "utf-8")) as UIState;+ } catch (err) {+ log.debug("UI state unavailable", { err: err instanceof Error ? err.message : err });return null;}}@@ -106,20 +109,18 @@ export const createClipToolDef = {},};-export async function handleCreateClip(- input: Record<string, unknown>-): Promise<string> {+export async function handleCreateClip(input: CreateClipInput): Promise<string> {await fileManager.ensureDirectories();const state = loadState();- const settings = (state?.settings as Record<string, string>) || {};- const suggestions = (state?.suggestions as Array<Record<string, unknown>>) || [];- const transcript = state?.transcript as Record<string, unknown> | null;+ const settings = state?.settings ?? {};+ const suggestions: SuggestedClip[] = state?.suggestions ?? [];+ const transcript = state?.transcript ?? null;// Resolve clip from suggestion number- let suggestion: Record<string, unknown> | null = null;+ let suggestion: SuggestedClip | null = null;if (input.clip_number != null) {- const idx = (input.clip_number as number) - 1;+ const idx = input.clip_number - 1;if (idx < 0 || idx >= suggestions.length) {return JSON.stringify({error: `Clip #${input.clip_number} not found. Available: 1-${suggestions.length}`,@@ -129,35 +130,22 @@ export async function handleCreateClip(}// Auto-resolve fields: explicit input > suggestion > state- const videoPath =- (input.video_path as string) || (state?.videoPath as string) || "";- const startSecond =- (input.start_second as number) ?? (suggestion?.start_second as number);- const endSecond =- (input.end_second as number) ?? (suggestion?.end_second as number);- const title =- (input.title as string) ||- (suggestion?.title as string) ||- "clip";+ const videoPath = input.video_path || state?.videoPath || "";+ const startSecond = input.start_second ?? suggestion?.start_second;+ const endSecond = input.end_second ?? suggestion?.end_second;+ const title = input.title || suggestion?.title || "clip";const captionStyle =- (input.caption_style as string) ||- (suggestion?.suggested_caption_style as string) ||+ input.caption_style ||+ suggestion?.suggested_caption_style ||settings.captionStyle ||"hormozi";- const cropStrategy =- (input.crop_strategy as string) || settings.cropStrategy || "speaker";- const logoPath =- (input.logo_path as string) || settings.logoPath || null;- const outroPath =- (input.outro_path as string) || settings.outroPath || null;- const transcriptWords =- (input.transcript_words as Array<unknown>) ||- (transcript?.words as Array<unknown>) ||- [];+ const cropStrategy = input.crop_strategy || settings.cropStrategy || "speaker";+ const logoPath = input.logo_path || settings.logoPath || null;+ const outroPath = input.outro_path || settings.outroPath || null;+ const transcriptWords = input.transcript_words ?? transcript?.words ?? [];// Pull multi-cut segments from suggestion (if available)- const keepSegments =- (suggestion?.segments as Array<{ start: number; end: number }>) || null;+ const keepSegments = suggestion?.segments ?? null;// Validate required fieldsif (!videoPath) {@@ -169,7 +157,7 @@ export async function handleCreateClip(});}- const result = await executor.execute("create_clip", {+ const result = await executor.execute<ClipResult>("create_clip", {video_path: videoPath,start_second: startSecond,end_second: endSecond,@@ -185,10 +173,13 @@ export async function handleCreateClip(...(keepSegments && { keep_segments: keepSegments }),});- const data = result.data as unknown as ClipResult;+ if (!result.data) {+ throw new Error("Clip creation returned no data");+ }+ const data = result.data;return JSON.stringify({- clip_number: input.clip_number || null,+ clip_number: input.clip_number ?? null,output_path: data.output_path,duration: data.duration,file_size_mb: data.file_size_mb,diff --git a/src/handlers/suggest-clips.handler.ts b/src/handlers/suggest-clips.handler.tsindex 9642f13..3e2d67c 100644--- a/src/handlers/suggest-clips.handler.ts+++ b/src/handlers/suggest-clips.handler.ts@@ -83,20 +83,24 @@ export const suggestClipsToolDef = {},};-export async function handleSuggestClips(- input: Record<string, unknown>-): Promise<string> {- const suggestions = input.suggestions as Array<{- title: string;- start_second: number;- end_second: number;- segments?: Array<{ start: number; end: number }>;- reasoning: string;- preview_text?: string;- content_type?: string;- score?: number;- suggested_caption_style?: string;- }>;+export interface RawSuggestion {+ title: string;+ start_second: number;+ end_second: number;+ segments?: Array<{ start: number; end: number }>;+ reasoning: string;+ preview_text?: string;+ content_type?: string;+ score?: number;+ suggested_caption_style?: string;+}++export interface SuggestClipsInput {+ suggestions: RawSuggestion[];+}++export async function handleSuggestClips(input: SuggestClipsInput): Promise<string> {+ const suggestions = input.suggestions;// Validate and enrich suggestionsconst enriched = suggestions.map((s, i) => {diff --git a/src/handlers/transcribe.handler.ts b/src/handlers/transcribe.handler.tsindex 5ba4ab0..9e8809c 100644--- a/src/handlers/transcribe.handler.ts+++ b/src/handlers/transcribe.handler.ts@@ -5,6 +5,14 @@ import type { TranscriptResult } from "../models/index.js";const executor = new PythonExecutor();const cache = new TranscriptCache();+export interface TranscribeInput {+ file_path: string;+ model_size?: "tiny" | "base" | "small" | "medium" | "large";+ language?: string;+ enable_diarization?: boolean;+ num_speakers?: number;+}+export const transcribeToolDef = {name: "transcribe_podcast",description:@@ -50,26 +58,21 @@ export const transcribeToolDef = {},};-export async function handleTranscribe(- input: Record<string, unknown>-): Promise<string> {- const filePath = input.file_path as string;- const modelSize = (input.model_size as string) || "base";- const language = input.language as string | undefined;+export async function handleTranscribe(input: TranscribeInput): Promise<string> {+ const filePath = input.file_path;+ const modelSize = input.model_size ?? "base";+ const language = input.language;const enableDiarization = input.enable_diarization !== false; // default true- const numSpeakers = input.num_speakers as number | undefined;+ const numSpeakers = input.num_speakers;// Check cache firstconst cached = await cache.get(filePath);if (cached) {- return JSON.stringify({- cached: true,- ...formatResult(cached as unknown as Record<string, unknown>),- });+ return JSON.stringify({ cached: true, ...formatResult(cached) });}// Execute transcription + diarization- const result = await executor.execute("transcribe", {+ const result = await executor.execute<TranscriptResult>("transcribe", {file_path: filePath,model_size: modelSize,language,@@ -77,21 +80,20 @@ export async function handleTranscribe(num_speakers: numSpeakers,});- const data = result.data as Record<string, unknown>;+ if (!result.data) {+ throw new Error("Transcription returned no data");+ }+ const data = result.data;// Cache the result- await cache.set(filePath, data as unknown as TranscriptResult);+ await cache.set(filePath, data);- return JSON.stringify({- cached: false,- ...formatResult(data),- });+ return JSON.stringify({ cached: false, ...formatResult(data) });}-function formatResult(data: Record<string, unknown>) {- const words = (data.words as Array<Record<string, unknown>>) || [];- const segments = (data.segments as Array<Record<string, unknown>>) || [];- const speakers = data.speakers as Record<string, unknown> | undefined;+function formatResult(data: TranscriptResult) {+ const words = data.words ?? [];+ const segments = data.segments ?? [];return {transcript: data.transcript,@@ -101,7 +103,7 @@ function formatResult(data: Record<string, unknown>) {language: data.language,word_count: words.length,segment_count: segments.length,- speakers: speakers || { num_speakers: 0, speakers: {} },- speaker_segments: data.speaker_segments || [],+ speakers: data.speakers ?? { num_speakers: 0, speakers: {} },+ speaker_segments: data.speaker_segments ?? [],};}diff --git a/src/models/index.ts b/src/models/index.tsindex 9b5622d..343d255 100644--- a/src/models/index.ts+++ b/src/models/index.ts@@ -6,10 +6,10 @@ export interface TaskRequest {params: Record<string, unknown>;}-export interface TaskResult {+export interface TaskResult<T = Record<string, unknown>> {task_id: string;status: "success" | "error";- data?: Record<string, unknown>;+ data?: T;error?: string;}@@ -94,6 +94,81 @@ export interface SuggestedClip {duration: number;reasoning: string;preview_text: string;+ segments?: Array<{ start: number; end: number }>;+ suggested_caption_style?: string;+ timestamp_display?: string;+ content_type?: string;+ score?: number;+}++export interface UIState {+ videoPath?: string;+ filePath?: string;+ transcript?: TranscriptResult | null;+ rawTranscriptText?: string;+ suggestions?: SuggestedClip[];+ deselectedIndices?: number[];+ settings?: {+ captionStyle?: string;+ cropStrategy?: string;+ logoPath?: string;+ outroPath?: string;+ };+ phase?: string;+ lastUpdated?: number;+}++export interface CreateClipInput {+ clip_number?: number;+ video_path?: string;+ start_second?: number;+ end_second?: number;+ title?: string;+ caption_style?: string;+ crop_strategy?: string;+ logo_path?: string;+ outro_path?: string;+ transcript_words?: WordTimestamp[];+ clean_fillers?: boolean;+ allow_ass_fallback?: boolean;+}++export interface BatchClipSpec {+ start_second: number;+ end_second: number;+ title?: string;+ caption_style?: string;+ crop_strategy?: string;+ logo_path?: string | null;+ allow_ass_fallback?: boolean;+ keep_segments?: Array<{ start: number; end: number }>;+}++export interface BatchClipsInput {+ video_path?: string;+ transcript_words?: WordTimestamp[];+ clip_numbers?: number[];+ clips?: BatchClipSpec[];+ export_selected?: boolean;+ clean_fillers?: boolean;+ allow_ass_fallback?: boolean;+}++export interface BatchClipsResult {+ total_clips: number;+ successful_clips: number;+ results: Array<{+ status: "success" | "error";+ output_path?: string;+ start_second?: number;+ end_second?: number;+ caption_style?: string;+ crop_strategy?: string;+ title?: string;+ file_size_mb?: number;+ duration?: number;+ error?: string;+ }>;}// === Asset Models ===diff --git a/src/services/python-executor.ts b/src/services/python-executor.tsindex a21581b..ad9d32b 100644--- a/src/services/python-executor.ts+++ b/src/services/python-executor.ts@@ -17,11 +17,11 @@ export class PythonExecutor {this.timeoutMs = timeoutMs;}- async execute(+ async execute<T = Record<string, unknown>>(taskType: TaskRequest["task_type"],params: Record<string, unknown>,onProgress?: ProgressCallback- ): Promise<TaskResult> {+ ): Promise<TaskResult<T>> {const taskId = uuidv4();const request: TaskRequest = {@@ -30,7 +30,7 @@ export class PythonExecutor {params,};- return new Promise<TaskResult>((resolve, reject) => {+ return new Promise<TaskResult<T>>((resolve, reject) => {const proc = spawn(paths.pythonPath, [paths.pythonBackend], {stdio: ["pipe", "pipe", "pipe"],env: {@@ -82,7 +82,7 @@ export class PythonExecutor {return;}- const result = JSON.parse(jsonMatch) as TaskResult;+ const result = JSON.parse(jsonMatch) as TaskResult<T>;if (result.status === "error") {reject(new Error(result.error || "Unknown Python error"));