返回 AiToEarn
video-utils.mcp.ts
根目录 / project / aitoearn-backend / apps / aitoearn-ai / src / core / agent / mcp / video-utils.mcp.ts
1 import * as fs from 'node:fs'
2 import * as os from 'node:os'
3 import * as path from 'node:path'
4 import { createSdkMcpServer, McpSdkServerConfigWithInstance } from '@anthropic-ai/claude-agent-sdk'
5 import { Injectable, Logger } from '@nestjs/common'
6 import { AssetsService, VideoMetadataService } from '@yikart/assets'
7 import { FileUtil, UserType } from '@yikart/common'
8 import { AssetType } from '@yikart/mongodb'
9 import { execa } from 'execa'
10 import * as subtitle from 'subtitle'
11 import { z } from 'zod'
12 import { AiAvailabilityService } from '../../ai-availability'
13 import { ChatService } from '../../ai/chat'
14 import { VolcengineService } from '../../ai/libs/volcengine'
15 import { McpServerName } from '../agent.constants'
16 import { errorResult, FFMPEG_REMOTE_PROTOCOL_WHITELIST, resolveSafeMediaUrl, srtTimestampToMs, successResult, wrapTool } from './mcp.utils'
17
18 const getVolcVideoInfoSchema = z.object({
19 vids: z.array(z.string()).min(1).describe('Volcengine video VID list, supports vid://xxx format or plain VID string'),
20 })
21
22 const uploadAndGetVidSchema = z.object({
23 videoUrl: FileUtil.zodBuildUrl().nonoptional().describe('Video URL'),
24 })
25
26 const probeVideoMetadataSchema = z.object({
27 videoUrl: FileUtil.zodBuildUrl().nonoptional().describe('Video URL'),
28 })
29
30 const extractThumbnailSchema = z.object({
31 videoUrl: FileUtil.zodBuildUrl().nonoptional().describe('Video URL'),
32 timeInSeconds: z.number().min(0).default(1).describe('Time point in seconds to extract frame, default 1 second'),
33 })
34
35 const generateSubtitleSchema = z.object({
36 mediaUrl: FileUtil.zodBuildUrl().nonoptional().describe('Video or audio URL to transcribe'),
37 language: z.string().optional().describe('Target language code, e.g., "zh-CN", "en-US"'),
38 })
39
40 const srtNodesSchema = z.object({
41 start: z.string().describe('Start time in SRT format: HH:MM:SS,sss'),
42 end: z.string().describe('End time in SRT format: HH:MM:SS,sss'),
43 text: z.string().describe('Subtitle text'),
44 }).array()
45
46 export enum VideoUtilsToolName {
47 GetVolcVideoInfo = 'getVolcVideoInfo',
48 UploadAndGetVid = 'uploadAndGetVid',
49 ProbeVideoMetadata = 'probeVideoMetadata',
50 ExtractThumbnail = 'extractThumbnail',
51 GenerateSubtitle = 'generateSubtitle',
52 }
53
54 interface VideoInfoSuccess {
55 vid: string
56 duration: number
57 width: number
58 height: number
59 fileSize: number
60 format: string
61 bitrate: number
62 frameRate: number
63 codecName: string
64 }
65
66 interface VideoInfoError {
67 vid: string
68 error: string
69 }
70
71 @Injectable()
72 export class VideoUtilsMcp {
73 private readonly logger = new Logger(VideoUtilsMcp.name)
74
75 constructor(
76 private readonly volcengineService: VolcengineService,
77 private readonly assetsService: AssetsService,
78 private readonly aiAvailability: AiAvailabilityService,
79 private readonly videoMetadataService: VideoMetadataService,
80 private readonly chatService: ChatService,
81 ) {}
82
83 /**
84 * 获取火山引擎视频信息(仅支持 VID)
85 */
86 createGetVolcVideoInfoTool(_userId: string, _userType: UserType) {
87 return wrapTool(
88 this.logger,
89 VideoUtilsToolName.GetVolcVideoInfo,
90 `Get video information from Volcengine by VID. Use this after uploading video to Volcengine.
91
92 Use this tool to:
93 - Get video duration for time calculations
94 - Get video dimensions for canvas setup
95 - Get video metadata (format, bitrate, fps)
96
97 Input: Array of VIDs (supports "vid://xxx" format or plain VID string)
98 Returns: Array of { vid, duration, width, height, format, ... }`,
99 getVolcVideoInfoSchema.shape,
100 async ({ vids }) => {
101 const normalizedVids = vids.map((vid) => {
102 if (vid.startsWith('vid://')) {
103 return vid.replace('vid://', '')
104 }
105 return vid
106 })
107
108 const mediaInfos = await this.volcengineService.getMediaInfos({
109 Vids: normalizedVids.join(','),
110 })
111
112 const successResults: VideoInfoSuccess[] = []
113 const errorResults: VideoInfoError[] = []
114
115 for (let index = 0; index < normalizedVids.length; index++) {
116 const vid = normalizedVids[index]
117 const mediaInfo = mediaInfos.MediaInfoList?.[index]
118
119 if (!mediaInfo) {
120 errorResults.push({ vid, error: 'Video not found or inaccessible' })
121 continue
122 }
123
124 const sourceInfo = mediaInfo.SourceInfo
125 successResults.push({
126 vid,
127 duration: sourceInfo?.Duration || 0,
128 width: sourceInfo?.Width || 0,
129 height: sourceInfo?.Height || 0,
130 fileSize: sourceInfo?.Size || 0,
131 format: sourceInfo?.Format || 'unknown',
132 bitrate: sourceInfo?.Bitrate || 0,
133 frameRate: sourceInfo?.Fps || 0,
134 codecName: sourceInfo?.Codec || 'unknown',
135 })
136 }
137
138 if (successResults.length === 0) {
139 return errorResult(`All videos failed:\n${errorResults.map(r => `- vid://${r.vid}: ${r.error}`).join('\n')}`)
140 }
141
142 const infoMessages = successResults.map((videoInfo) => {
143 const durationMs = videoInfo.duration * 1000
144
145 return `**Video: vid://${videoInfo.vid}**
146 - Duration: ${videoInfo.duration} seconds (${durationMs} milliseconds)
147 - Resolution: ${videoInfo.width}x${videoInfo.height}
148 - File Size: ${(videoInfo.fileSize / 1024 / 1024).toFixed(2)} MB
149 - Format: ${videoInfo.format}
150 - Bitrate: ${(videoInfo.bitrate / 1000).toFixed(0)} kbps
151 - Frame Rate: ${videoInfo.frameRate} fps
152 - Codec: ${videoInfo.codecName}
153
154 **For video editing:**
155 - Use Source: "vid://${videoInfo.vid}"
156 - Video dimensions: ${videoInfo.width}x${videoInfo.height} (Canvas will be auto-detected if omitted in submitDirectEditTask)
157 - Full video TargetTime: [0, ${durationMs}]`
158 }).join('\n\n---\n\n')
159
160 let message = `Video Information Retrieved (${successResults.length}/${normalizedVids.length} successful):\n\n${infoMessages}`
161
162 if (errorResults.length > 0) {
163 message += `\n\n**Failed videos:**\n${errorResults.map(r => `- vid://${r.vid}: ${r.error}`).join('\n')}`
164 }
165
166 return successResult(message)
167 },
168 this.aiAvailability,
169 )
170 }
171
172 /**
173 * 上传视频到火山引擎并获取 VID
174 */
175 createUploadAndGetVidTool(_userId: string, _userType: UserType) {
176 return wrapTool(
177 this.logger,
178 VideoUtilsToolName.UploadAndGetVid,
179 `Upload a video from URL to Volcengine cloud and get VID. Required before video editing.
180
181 Use this tool to:
182 - Convert HTTP URL to VID for Volcengine video editing
183 - Get video information after upload
184
185 Returns: { vid, duration, width, height, ... }`,
186 uploadAndGetVidSchema.shape,
187 async ({ videoUrl }) => {
188 this.logger.debug({ url: videoUrl }, '[UploadAndGetVid] Uploading video URL to Volcengine')
189
190 const vid = await this.volcengineService.downloadUrlAndUploadAsStream(videoUrl)
191 this.logger.debug({ vid }, '[UploadAndGetVid] Video uploaded successfully')
192
193 const mediaInfos = await this.volcengineService.getMediaInfos({
194 Vids: vid,
195 })
196
197 const mediaInfo = mediaInfos.MediaInfoList?.[0]
198 if (!mediaInfo) {
199 return errorResult('Video uploaded but failed to retrieve information')
200 }
201
202 const sourceInfo = mediaInfo.SourceInfo
203 const duration = sourceInfo?.Duration || 0
204 const durationMs = duration * 1000
205
206 return successResult(`Video uploaded successfully!
207
208 **VID:** vid://${vid}
209 **Duration:** ${duration} seconds (${durationMs} milliseconds)
210 **Resolution:** ${sourceInfo?.Width || 0}x${sourceInfo?.Height || 0}
211 **Format:** ${sourceInfo?.Format || 'unknown'}
212 **Bitrate:** ${((sourceInfo?.Bitrate || 0) / 1000).toFixed(0)} kbps
213 **Frame Rate:** ${sourceInfo?.Fps || 0} fps
214
215 **For video editing:**
216 - Use Source: "vid://${vid}"
217 - Video dimensions: ${sourceInfo?.Width || 0}x${sourceInfo?.Height || 0} (Canvas will be auto-detected if omitted in submitDirectEditTask)
218 - Full video TargetTime: [0, ${durationMs}]`)
219 },
220 this.aiAvailability,
221 )
222 }
223
224 /**
225 * 使用 ffprobe 获取视频元数据(不上传)
226 */
227 createProbeVideoMetadataTool(_userId: string, _userType: UserType) {
228 return wrapTool(
229 this.logger,
230 VideoUtilsToolName.ProbeVideoMetadata,
231 `Probe video metadata from URL using ffprobe. Does NOT upload the video.
232
233 Use this tool when you only need video metadata (duration, dimensions) without editing:
234 - Display video information to user
235 - Check video properties before processing
236 - Validate video format
237
238 Returns: { width, height, duration, bitrate, frameRate }`,
239 probeVideoMetadataSchema.shape,
240 async ({ videoUrl }) => {
241 const safeVideoUrl = await resolveSafeMediaUrl(videoUrl)
242 this.logger.debug({ url: videoUrl }, '[ProbeVideoMetadata] Probing video metadata')
243
244 const metadata = await this.videoMetadataService.probeVideoMetadata(safeVideoUrl)
245
246 return successResult(`Video Metadata:
247 - Resolution: ${metadata.width}x${metadata.height}
248 - Duration: ${metadata.duration} seconds (${metadata.duration * 1000} milliseconds)
249 - Bitrate: ${(metadata.bitrate / 1000).toFixed(0)} kbps
250 - Frame Rate: ${metadata.frameRate} fps
251
252 Note: This video has NOT been uploaded to Volcengine. Use uploadAndGetVid if you need to edit it.`)
253 },
254 this.aiAvailability,
255 )
256 }
257
258 /**
259 * 提取视频缩略图
260 */
261 createExtractThumbnailTool(userId: string, _userType: UserType) {
262 return wrapTool(
263 this.logger,
264 VideoUtilsToolName.ExtractThumbnail,
265 'Extract a thumbnail from a video URL at a specified time point. Uses ffmpeg to directly stream from the URL without downloading the full video. Returns the uploaded thumbnail URL.',
266 extractThumbnailSchema.shape,
267 async ({ videoUrl, timeInSeconds }) => {
268 const safeVideoUrl = await resolveSafeMediaUrl(videoUrl)
269 this.logger.debug({ userId, videoUrl, timeInSeconds }, '[extractThumbnail] Starting thumbnail extraction')
270
271 const thumbnailBuffer = await this.videoMetadataService.extractThumbnailFromUrl(safeVideoUrl, timeInSeconds)
272 this.logger.debug({ size: thumbnailBuffer.length }, '[extractThumbnail] Frame extracted')
273
274 const result = await this.assetsService.uploadFromBuffer(userId, thumbnailBuffer, {
275 type: AssetType.VideoThumbnail,
276 mimeType: 'image/png',
277 filename: 'thumbnail.png',
278 })
279
280 this.logger.debug({ thumbnailUrl: result.url }, '[extractThumbnail] Thumbnail uploaded')
281
282 return successResult(`Thumbnail extracted and uploaded successfully. URL: ${result.url}`)
283 },
284 this.aiAvailability,
285 )
286 }
287
288 /**
289 * 使用 FFmpeg 从 URL 提取音频
290 */
291 private async extractAudioWithFFmpeg(mediaUrl: string): Promise<Buffer> {
292 const safeMediaUrl = await resolveSafeMediaUrl(mediaUrl)
293
294 const tempDir = os.tmpdir()
295 const outputPath = path.join(tempDir, `audio-${Date.now()}.mp3`)
296 try {
297 await execa('ffmpeg', [
298 '-protocol_whitelist',
299 FFMPEG_REMOTE_PROTOCOL_WHITELIST,
300 '-i',
301 safeMediaUrl,
302 '-map',
303 '0:a:0',
304 '-vn',
305 '-acodec',
306 'libmp3lame',
307 '-b:a',
308 '128k',
309 '-y',
310 outputPath,
311 ])
312
313 return fs.readFileSync(outputPath)
314 }
315 finally {
316 if (fs.existsSync(outputPath)) {
317 fs.unlinkSync(outputPath)
318 }
319 }
320 }
321
322 /**
323 * 构建字幕转录提示词
324 */
325 private buildSubtitlePrompt(language?: string): string {
326 const languageInstruction = language
327 ? `Transcribe the audio and translate into ${language}. All subtitle text must be in ${language}.`
328 : `Transcribe the audio in its original spoken language.`
329
330 return `${languageInstruction}
331
332 ## Rules
333
334 1. **Accuracy**: Only transcribe speech actually present in the audio. Never add or fabricate content.
335
336 2. **Timestamps**:
337 - Use SRT format: HH:MM:SS,sss (e.g., 00:00:01,500)
338 - Timestamps must accurately match when speech occurs in the audio
339 - The last subtitle should end near the actual end of speech
340 - Minimum subtitle duration: 1.5 seconds for readability
341
342 3. **Segmentation**: Split at natural speech pauses. Each subtitle should be a complete phrase.
343
344 4. **Translation** (if applicable): Translate naturally while preserving the original meaning.
345
346 ## Output Format
347
348 JSON array with SRT timestamps:
349 [
350 {"start": "00:00:00,500", "end": "00:00:03,000", "text": "Hello everyone."},
351 {"start": "00:00:03,500", "end": "00:00:06,000", "text": "Welcome to today's video."}
352 ]`
353 }
354
355 /**
356 * 生成字幕
357 */
358 createGenerateSubtitleTool(userId: string, userType: UserType) {
359 return wrapTool(
360 this.logger,
361 VideoUtilsToolName.GenerateSubtitle,
362 `Generate SRT subtitles from video or audio using AI transcription.
363
364 Parameters:
365 - mediaUrl: URL of the video or audio file to transcribe
366 - language (optional): Target language code (e.g., "zh-CN", "en-US", "ja-JP")
367
368 Returns the generated SRT subtitle file URL.
369
370 Use this tool when user wants to:
371 - 给视频加字幕 / Add subtitles to video
372 - 生成字幕 / Generate subtitles
373 - 视频转录 / Transcribe video
374 - 提取视频文字 / Extract text from video`,
375 generateSubtitleSchema.shape,
376 async ({ mediaUrl, language }) => {
377 this.logger.log({ mediaUrl, language }, 'Starting subtitle generation')
378
379 const audioBuffer = await this.extractAudioWithFFmpeg(mediaUrl)
380
381 const prompt = this.buildSubtitlePrompt(language)
382
383 this.logger.debug({ mediaUrl, language }, 'Calling Gemini for transcription')
384 const response = await this.chatService.userGeminiGenerateContent({
385 userId,
386 userType,
387 model: 'gemini-3.5-flash',
388 contents: [{
389 role: 'user',
390 parts: [
391 {
392 inlineData: {
393 mimeType: 'audio/mp3',
394 data: audioBuffer.toString('base64'),
395 },
396 },
397 { text: prompt },
398 ],
399 }],
400 config: {
401 responseMimeType: 'application/json',
402 responseJsonSchema: z.toJSONSchema(srtNodesSchema),
403 },
404 })
405
406 const responseText = response.text
407 if (!responseText) {
408 throw new Error('No response from Gemini')
409 }
410
411 const result = z.safeParse(srtNodesSchema, JSON.parse(responseText))
412 if (!result.success) {
413 throw new Error(`Invalid subtitle data: ${z.prettifyError(result.error)}`)
414 }
415 const subtitleData = result.data.map(node => ({
416 type: 'cue',
417 data: {
418 ...node,
419 start: srtTimestampToMs(node.start),
420 end: srtTimestampToMs(node.end),
421 },
422 } as const))
423
424 const srtContent = subtitle.stringifySync(subtitleData, { format: 'SRT' })
425
426 this.logger.debug('Uploading SRT file')
427 const srtBuffer = Buffer.from(srtContent, 'utf-8')
428 const uploadResult = await this.assetsService.uploadFromBuffer(userId, srtBuffer, {
429 type: AssetType.Subtitle,
430 mimeType: 'text/plain',
431 filename: `subtitle-${Date.now()}.srt`,
432 })
433
434 return successResult(`Subtitle generated successfully!
435 **SRT File URL:** ${uploadResult.url}
436 You can use this SRT URL in video editing to add subtitles.`)
437 },
438 this.aiAvailability,
439 )
440 }
441
442 createServer(userId: string, userType: UserType): McpSdkServerConfigWithInstance {
443 return createSdkMcpServer({
444 name: McpServerName.VideoUtils,
445 version: '1.0.0',
446 tools: [
447 this.createGetVolcVideoInfoTool(userId, userType),
448 this.createUploadAndGetVidTool(userId, userType),
449 this.createProbeVideoMetadataTool(userId, userType),
450 this.createExtractThumbnailTool(userId, userType),
451 // this.createGenerateSubtitleTool(userId, userType),
452 ],
453 })
454 }
455 }
456
456 lines TYPESCRIPT