返回 AiToEarn
mcp.utils.ts
1 import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
2 import type { AiAvailabilityService } from '../../ai-availability'
3 import { lookup } from 'node:dns/promises'
4 import { BlockList } from 'node:net'
5 import { createSdkMcpServer, InferShape, McpSdkServerConfigWithInstance, tool } from '@anthropic-ai/claude-agent-sdk'
6 import { Client } from '@modelcontextprotocol/sdk/client/index.js'
7 import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
8 import { Logger } from '@nestjs/common'
9 import { AppException, FileUtil, getErrorMessage, ResponseCode } from '@yikart/common'
10 import { z } from 'zod'
11
12 // ==================== 媒体 URL 安全校验 ====================
13
14 /**
15 * 校验传给 ffmpeg/ffprobe 的媒体 URL 是否安全:
16 * - 必须是合法的 http/https URL(拒绝 file:// 等非 http scheme,避免读取本地文件)
17 * - trim 后不允许以 '-' 开头,避免被 ffmpeg 当作命令行选项解析
18 * @param mediaUrl 用户传入的媒体 URL
19 * @throws AppException URL 不合法时抛出
20 */
21 export function assertSafeMediaUrl(mediaUrl: string): void {
22 const trimmedUrl = mediaUrl.trim()
23 if (trimmedUrl.startsWith('-')) {
24 throw new AppException(ResponseCode.ValidationFailed, `Invalid media URL: "${mediaUrl}", URL must not start with '-'`)
25 }
26
27 let parsedUrl: URL
28 try {
29 parsedUrl = new URL(trimmedUrl)
30 }
31 catch {
32 throw new AppException(ResponseCode.ValidationFailed, `Invalid media URL: "${mediaUrl}", expected a valid http(s) URL`)
33 }
34
35 if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
36 throw new AppException(ResponseCode.ValidationFailed, `Invalid media URL: "${mediaUrl}", only http/https URLs are supported`)
37 }
38
39 if (!parsedUrl.hostname) {
40 throw new AppException(ResponseCode.ValidationFailed, `Invalid media URL: "${mediaUrl}", missing hostname`)
41 }
42 }
43
44 const blockedMediaAddresses = new BlockList()
45 for (const [network, prefix] of [
46 ['0.0.0.0', 8],
47 ['10.0.0.0', 8],
48 ['100.64.0.0', 10],
49 ['127.0.0.0', 8],
50 ['169.254.0.0', 16],
51 ['172.16.0.0', 12],
52 ['192.0.0.0', 24],
53 ['192.168.0.0', 16],
54 ['198.18.0.0', 15],
55 ['224.0.0.0', 4],
56 ['240.0.0.0', 4],
57 ] as const) {
58 blockedMediaAddresses.addSubnet(network, prefix, 'ipv4')
59 }
60 for (const [network, prefix] of [
61 ['::', 128],
62 ['::1', 128],
63 ['64:ff9b::', 96],
64 ['fc00::', 7],
65 ['fe80::', 10],
66 ['ff00::', 8],
67 ] as const) {
68 blockedMediaAddresses.addSubnet(network, prefix, 'ipv6')
69 }
70
71 async function assertPublicMediaHost(url: URL): Promise<void> {
72 const hostname = url.hostname.replace(/^\[|\]$/g, '')
73 const addresses = await lookup(hostname, { all: true, verbatim: true }).catch(() => {
74 throw new AppException(ResponseCode.ValidationFailed, `Invalid media URL: "${url.href}", hostname cannot be resolved`)
75 })
76 const blocked = addresses.some(({ address, family }) => blockedMediaAddresses.check(address, family === 6 ? 'ipv6' : 'ipv4'))
77 if (blocked) {
78 throw new AppException(ResponseCode.ValidationFailed, `Invalid media URL: "${url.href}", private or reserved network addresses are not allowed`)
79 }
80 }
81
82 /**
83 * 在交给 ffmpeg/ffprobe 之前解析媒体 URL,防止 SSRF:
84 * - 自有存储(cdnEndpoint / endpoint)地址直接放行,私有化部署时它们通常就是内网地址
85 * - 其余地址逐跳跟随重定向,每一跳都要求解析到公网地址,ffmpeg 拿到的是最终地址
86 * @param mediaUrl 用户传入的媒体 URL
87 * @returns 可以交给 ffmpeg/ffprobe 的最终 URL
88 * @throws AppException URL 不合法、指向内网/保留地址或重定向过多时抛出
89 */
90 export async function resolveSafeMediaUrl(mediaUrl: string): Promise<string> {
91 assertSafeMediaUrl(mediaUrl)
92 let currentUrl = new URL(mediaUrl.trim())
93 if (FileUtil.isStorageUrl(currentUrl.href)) {
94 return currentUrl.href
95 }
96
97 for (let hop = 0; hop <= 5; hop++) {
98 await assertPublicMediaHost(currentUrl)
99 const response = await fetch(currentUrl, {
100 redirect: 'manual',
101 headers: { range: 'bytes=0-0' },
102 signal: AbortSignal.timeout(15000),
103 })
104 await response.body?.cancel()
105 const location = response.headers.get('location')
106 if (response.status < 300 || response.status >= 400 || !location) {
107 return currentUrl.href
108 }
109 const nextUrl = new URL(location, currentUrl).href
110 assertSafeMediaUrl(nextUrl)
111 currentUrl = new URL(nextUrl)
112 }
113
114 throw new AppException(ResponseCode.ValidationFailed, `Invalid media URL: "${mediaUrl}", too many redirects`)
115 }
116
117 // httpproxy is required for https inputs when http_proxy is set
118 export const FFMPEG_REMOTE_PROTOCOL_WHITELIST = 'http,https,tls,tcp,httpproxy'
119
120 // ==================== SRT 时间戳工具函数 ====================
121
122 /**
123 * 将 SRT 时间戳转换为毫秒
124 * @param srtTimestamp SRT 格式时间戳 (HH:MM:SS,sss)
125 * @returns 毫秒数
126 */
127 export function srtTimestampToMs(srtTimestamp: string): number {
128 const [rest, millisecondsString] = srtTimestamp.split(',')
129 const milliseconds = Number.parseInt(millisecondsString)
130 const [hours, minutes, seconds] = rest.split(':').map(x => Number.parseInt(x))
131 const result = milliseconds * 0.001 + seconds + 60 * minutes + 3600 * hours
132
133 // fix odd JS roundings, e.g. timestamp '00:01:20,460' result is 80.46000000000001
134 return Math.round(result * 1000)
135 }
136
137 /**
138 * 将秒数转换为 SRT 时间戳格式
139 * @param seconds 秒数
140 * @returns SRT 格式时间戳 (HH:MM:SS,sss)
141 */
142 export function secondsToSrtTimestamp(seconds: number): string {
143 const hours = Math.floor(seconds / 3600)
144 const minutes = Math.floor((seconds % 3600) / 60)
145 const secs = Math.floor(seconds % 60)
146 const millis = Math.round((seconds % 1) * 1000)
147 return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')},${millis.toString().padStart(3, '0')}`
148 }
149
150 type ContentInput = string | unknown[] | Record<string, unknown>
151
152 /**
153 * 将输入内容转换为 CallToolResult 的 content 格式
154 */
155 function normalizeContent(input: ContentInput): CallToolResult['content'] {
156 if (typeof input === 'string') {
157 return [{ type: 'text', text: input }]
158 }
159 if (Array.isArray(input)) {
160 if (input.length > 0 && typeof input[0] === 'object' && input[0] !== null && 'type' in input[0]) {
161 return input as CallToolResult['content']
162 }
163 return [{ type: 'text', text: JSON.stringify(input) }]
164 }
165 if (typeof input === 'object' && input !== null) {
166 return [{ type: 'text', text: JSON.stringify(input) }]
167 }
168 return [{ type: 'text', text: String(input) }]
169 }
170
171 /**
172 * 创建成功结果
173 * @param content 内容,可以是字符串、数组或对象
174 */
175 export function successResult(content: ContentInput): CallToolResult {
176 return {
177 content: normalizeContent(content),
178 }
179 }
180
181 /**
182 * 创建错误结果
183 * @param message 错误消息,可以是字符串、数组或对象
184 */
185 export function errorResult(message: ContentInput): CallToolResult {
186 return {
187 content: normalizeContent(message),
188 isError: true,
189 }
190 }
191
192 /**
193 * 包装工具定义,自动添加日志、错误处理和可用性监控
194 * @param logger Logger 实例
195 * @param toolName 工具名称
196 * @param description 工具描述
197 * @param schema Zod Object schema 用于类型验证
198 * @param handler 业务逻辑处理器
199 * @param aiAvailability AI 可用性监控服务
200 * @returns tool 函数的返回值
201 */
202 export function wrapTool<T extends z.ZodRawShape>(
203 logger: Logger,
204 toolName: string,
205 description: string,
206 schema: T,
207 handler: (params: InferShape<T>) => Promise<CallToolResult>,
208 aiAvailability: AiAvailabilityService,
209 ) {
210 const availabilityContext = { provider: 'mcp', operation: toolName, module: 'agent' }
211
212 return tool(
213 toolName,
214 description,
215 schema,
216 async (params) => {
217 try {
218 const result = await aiAvailability.execute(
219 availabilityContext,
220 () => handler(params),
221 )
222 return result
223 }
224 catch (error) {
225 const errMessage = getErrorMessage(error)
226
227 if (error instanceof AppException) {
228 logger.warn({ toolName, code: error.code }, `Tool business error: ${errMessage}`)
229 return errorResult(errMessage)
230 }
231
232 logger.fatal({ toolName, params }, 'Tool handler error')
233 logger.fatal(error, `Tool handler error ${toolName}`)
234 return errorResult(errMessage)
235 }
236 },
237 )
238 }
239
240 // ==================== 格式化工具函数 ====================
241
242 /**
243 * 需要过滤的字段列表(时间戳和 MongoDB 元数据)
244 */
245 const FILTER_FIELDS = ['createdAt', 'updatedAt', 'deletedAt', '__v', '_id']
246
247 /**
248 * 过滤对象中的不必要字段
249 * @param obj 原始对象
250 * @param keepFields 保留的字段白名单(可选)
251 */
252 function filterFields<T extends Record<string, unknown>>(obj: T, keepFields?: string[]): Partial<T> {
253 if (!obj || typeof obj !== 'object')
254 return obj
255
256 const filtered: Partial<T> = {}
257
258 for (const [key, value] of Object.entries(obj)) {
259 if (keepFields && !keepFields.includes(key))
260 continue
261
262 if (!keepFields && FILTER_FIELDS.includes(key))
263 continue
264
265 filtered[key as keyof T] = value as T[keyof T]
266 }
267
268 return filtered
269 }
270
271 /**
272 * 将对象转换为 YAML 格式字符串(键值对形式)
273 * @param obj 对象
274 * @param keepFields 保留的字段白名单(可选)
275 */
276 export function formatObject<T extends Record<string, unknown>>(obj: T, keepFields?: string[]): string {
277 if (!obj)
278 return ''
279
280 const filtered = filterFields(obj, keepFields)
281 const lines: string[] = []
282
283 for (const [key, value] of Object.entries(filtered)) {
284 if (value === null || value === undefined)
285 continue
286
287 let formattedValue: string
288 if (typeof value === 'object' && !Array.isArray(value)) {
289 formattedValue = JSON.stringify(value)
290 }
291 else if (Array.isArray(value)) {
292 formattedValue = value.join(', ')
293 }
294 else {
295 formattedValue = String(value)
296 }
297
298 lines.push(`${key}: ${formattedValue}`)
299 }
300
301 return lines.join('\n')
302 }
303
304 /**
305 * 将数组转换为格式化列表
306 * @param list 数组
307 * @param formatter 每项的格式化函数
308 */
309 export function formatList<T>(list: T[], formatter?: (item: T, index: number) => string): string {
310 if (!list || list.length === 0)
311 return 'No data'
312
313 const lines: string[] = [`Total ${list.length}:`]
314
315 list.forEach((item, index) => {
316 const formatted = formatter ? formatter(item, index) : String(item)
317 lines.push(`${index + 1}. ${formatted}`)
318 })
319
320 return lines.join('\n')
321 }
322
323 // ==================== HTTP MCP 桥接 ====================
324
325 /**
326 * 创建 HTTP MCP 桥接服务器,将 HTTP MCP 转换为 SDK MCP
327 * @param name - MCP 服务器名称
328 * @param url - HTTP MCP 端点 URL
329 * @param headers - HTTP 请求头(用于认证)
330 * @returns SDK MCP Server 配置
331 */
332 export async function createHttpBridgeServer(
333 name: string,
334 url: string,
335 headers: Record<string, string>,
336 ): Promise<McpSdkServerConfigWithInstance> {
337 const transport = new StreamableHTTPClientTransport(new URL(url), {
338 requestInit: { headers },
339 })
340 const client = new Client(
341 { name, version: '1.0.0' },
342 { capabilities: {} },
343 )
344
345 await client.connect(transport)
346 const { tools } = await client.listTools()
347
348 const sdkTools = tools.map((mcpTool) => {
349 // @ts-expect-error - mcpTool.inputSchema 类型不完全匹配 z.fromJSONSchema 预期的 JSONSchema 类型
350 const zodSchema = z.fromJSONSchema(mcpTool.inputSchema)
351
352 // @ts-expect-error - zodSchema 可能是 ZodObject 或其他类型,我们需要提取 shape
353 const schema: z.ZodRawShape = zodSchema.shape || {}
354
355 return tool(
356 mcpTool.name,
357 mcpTool.description || '',
358 schema,
359 async (params) => {
360 const result = await client.callTool({
361 name: mcpTool.name,
362 arguments: params,
363 })
364 return result as CallToolResult
365 },
366 )
367 })
368
369 return createSdkMcpServer({
370 name,
371 version: '1.0.0',
372 tools: sdkTools,
373 })
374 }
375
375 lines TYPESCRIPT