putObjectSourceUrl
Download files from a specified URL and upload them directly to a Tencent Cloud COS storage bucket, specifying the target directory and file name.
Instructions
通过 url下载文件并将文件上传到存储桶
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| fileName | No | 文件名 (存在存储桶里的名称) | |
| sourceUrl | Yes | 可下载的文件 url | |
| targetDir | No | 目标目录 (存在存储桶的哪个目录) |
Implementation Reference
- src/services/cos/cos.service.ts:281-313 (handler)Core implementation of putObjectSourceUrl: validates params, downloads file stream from sourceUrl using axios, generates filename if missing, builds COS key, pipes stream to COS putObject, returns structured success/error response.async uploadFileSourceUrl(params: UploadFileParams) { // 验证并解析参数 const validParams = UploadFileParamsSchema.parse(params); const { targetDir = '', fileName, sourceUrl } = validParams; try { const response = await axios({ method: 'get', url: sourceUrl, responseType: 'stream' }); const actualFileName = fileName ? fileName : generateOutPutFileId(''); const cosPath = this.buildCosPath(actualFileName, targetDir); const req = response.data; const passThrough = new PassThrough(); const result = await this.cos.putObject({ Bucket: this.bucket, Region:this.region, Key: cosPath, Body: req.pipe(passThrough), }); return { isSuccess: true, message: '上传成功', data: result, }; } catch (error) { return { isSuccess: false, message: '上传失败', data: error, }; } }
- src/server.ts:221-248 (registration)Registers the 'putObjectSourceUrl' tool in the MCP server, defines input schema with zod validators, and delegates execution to CosService.uploadFileSourceUrl, formatting response for MCP.server.tool( 'putObjectSourceUrl', '通过 url下载文件并将文件上传到存储桶', { sourceUrl: z.string().describe('可下载的文件 url'), fileName: z.string().optional().describe('文件名 (存在存储桶里的名称)'), targetDir: z .string() .optional() .describe('目标目录 (存在存储桶的哪个目录)'), }, async ({ sourceUrl, fileName, targetDir}) => { const res = await COSInstance.uploadFileSourceUrl({ targetDir, fileName, sourceUrl, }); return { content: [ { type: 'text', text: JSON.stringify(res.data, null, 2), }, ], isError: !res.isSuccess, }; }, );
- Zod schema definition for UploadFileParams type, used to validate inputs in uploadFileSourceUrl and other upload methods (note: sourceUrl made optional here for reuse).export const UploadFileParamsSchema = z.object({ filePath: z.string().optional(), targetDir: z.string().optional(), fileName: z.string().optional(), sourceUrl: z.string().optional() }); export type UploadFileParams = z.infer<typeof UploadFileParamsSchema>;
- Helper method to construct the full COS object key by combining targetDir (normalized) and fileName.private buildCosPath(fileName: string, targetDir?: string): string { if (!targetDir) { return fileName; } // 规范化目标目录:移除头尾斜杠 const normalizedDir = targetDir.replace(/^\/+|\/+$/g, ''); return normalizedDir ? `${normalizedDir}/${fileName}` : fileName; }