@avclabs.ai/media-mcp 0.2.1 → 0.3.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/README.md +245 -31
- package/README_CN.md +246 -32
- package/config.json +1 -0
- package/dist/image-enhancement.d.ts +3 -0
- package/dist/image-enhancement.d.ts.map +1 -0
- package/dist/image-enhancement.js +185 -0
- package/dist/image-enhancement.js.map +1 -0
- package/dist/sam3.d.ts +7 -0
- package/dist/sam3.d.ts.map +1 -1
- package/dist/sam3.js +148 -104
- package/dist/sam3.js.map +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.js +77 -53
- package/dist/server.js.map +1 -1
- package/dist/service-config.d.ts +62 -0
- package/dist/service-config.d.ts.map +1 -0
- package/dist/service-config.js +58 -0
- package/dist/service-config.js.map +1 -0
- package/dist/tooling.d.ts +42 -0
- package/dist/tooling.d.ts.map +1 -0
- package/dist/tooling.js +153 -0
- package/dist/tooling.js.map +1 -0
- package/dist/tos.d.ts +35 -0
- package/dist/tos.d.ts.map +1 -0
- package/dist/tos.js +281 -0
- package/dist/tos.js.map +1 -0
- package/dist/upload.d.ts +79 -0
- package/dist/upload.d.ts.map +1 -0
- package/dist/upload.js +190 -0
- package/dist/upload.js.map +1 -0
- package/dist/video-enhancement.d.ts.map +1 -1
- package/dist/video-enhancement.js +73 -153
- package/dist/video-enhancement.js.map +1 -1
- package/package.json +10 -5
package/dist/upload.d.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import FormData from 'form-data';
|
|
2
|
+
import type { Readable } from 'stream';
|
|
3
|
+
/**
|
|
4
|
+
* Upload module: take local media and return a `file_id`.
|
|
5
|
+
*
|
|
6
|
+
* What the two media hosts disagree about -- signature endpoint, response code convention,
|
|
7
|
+
* where the object key comes from -- lives behind a SignatureAdapter. Everything they agree
|
|
8
|
+
* on lives here: storage-form field canonicalisation, `file_id` derivation, error detail
|
|
9
|
+
* formatting, and the storage POST itself.
|
|
10
|
+
*/
|
|
11
|
+
export interface SignatureTransport {
|
|
12
|
+
/** POST a JSON payload to the host, returning the decoded response body. */
|
|
13
|
+
post(requestPath: string, payload: unknown): Promise<unknown>;
|
|
14
|
+
}
|
|
15
|
+
export interface SignatureTransportConfig {
|
|
16
|
+
baseUrl: string;
|
|
17
|
+
apiKey: string;
|
|
18
|
+
auth: 'bearer' | 'x-api-key';
|
|
19
|
+
}
|
|
20
|
+
export declare function createAxiosSignatureTransport(config: SignatureTransportConfig): SignatureTransport;
|
|
21
|
+
export interface StorageTransport {
|
|
22
|
+
/** POST the signed form to storage. Throws `TOS upload failed: …` on any non-success. */
|
|
23
|
+
submit(uploadUrl: string, form: FormData): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
export declare function createAxiosStorageTransport(): StorageTransport;
|
|
26
|
+
export interface StorageForm {
|
|
27
|
+
/** Absolute storage URL that receives the form. */
|
|
28
|
+
uploadUrl: string;
|
|
29
|
+
/** Pre-signed fields, `key` included, ready to append as-is. */
|
|
30
|
+
formFields: Record<string, string>;
|
|
31
|
+
}
|
|
32
|
+
export interface SignatureAdapter {
|
|
33
|
+
prepareUpload(fileName: string): Promise<StorageForm>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The enhancement host serves images and videos from one signature endpoint; only `file_type`
|
|
37
|
+
* separates them.
|
|
38
|
+
*/
|
|
39
|
+
export declare function createEnhanceSignatureAdapter(deps: {
|
|
40
|
+
transport: SignatureTransport;
|
|
41
|
+
fileType: 'image' | 'video';
|
|
42
|
+
}): SignatureAdapter;
|
|
43
|
+
/** The SAM3 host always sends images. Only the failure message convention differs from enhance. */
|
|
44
|
+
export declare function createSam3SignatureAdapter(deps: {
|
|
45
|
+
transport: SignatureTransport;
|
|
46
|
+
}): SignatureAdapter;
|
|
47
|
+
export interface UploadDeps {
|
|
48
|
+
adapter: SignatureAdapter;
|
|
49
|
+
storage: StorageTransport;
|
|
50
|
+
body: Buffer | Readable;
|
|
51
|
+
fileName: string;
|
|
52
|
+
}
|
|
53
|
+
export declare function uploadObject(deps: UploadDeps): Promise<{
|
|
54
|
+
fileId: string;
|
|
55
|
+
uploadUrl: string;
|
|
56
|
+
}>;
|
|
57
|
+
/** Pre-binds a signature adapter and the storage transport into the shape the tools call. */
|
|
58
|
+
export type MediaUploader = (body: Buffer | Readable, fileName: string) => Promise<{
|
|
59
|
+
fileId: string;
|
|
60
|
+
}>;
|
|
61
|
+
export declare function createMediaUploader(deps: {
|
|
62
|
+
adapter: SignatureAdapter;
|
|
63
|
+
storage: StorageTransport;
|
|
64
|
+
}): MediaUploader;
|
|
65
|
+
/**
|
|
66
|
+
* Canonicalise a signature response into storage-form fields.
|
|
67
|
+
*
|
|
68
|
+
* Never returns `key`: each host derives the object key differently, so the adapter supplies
|
|
69
|
+
* it. Tolerates both hosts' naming conventions, so a response that arrives in the other
|
|
70
|
+
* convention still yields a usable form.
|
|
71
|
+
*/
|
|
72
|
+
export declare function normalizeSignatureFields(response: Record<string, unknown>): Record<string, string>;
|
|
73
|
+
/** Last path segment of the upload URL, percent-decoded. */
|
|
74
|
+
export declare function parseFileIdFromUrl(uploadUrl: string): string;
|
|
75
|
+
export declare function checkLocalFile(filePath: string): {
|
|
76
|
+
filePath: string;
|
|
77
|
+
fileName: string;
|
|
78
|
+
};
|
|
79
|
+
//# sourceMappingURL=upload.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../src/upload.ts"],"names":[],"mappings":"AAGA,OAAO,QAAQ,MAAM,WAAW,CAAC;AACjC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAEvC;;;;;;;GAOG;AAIH,MAAM,WAAW,kBAAkB;IACjC,4EAA4E;IAC5E,IAAI,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC/D;AAED,MAAM,WAAW,wBAAwB;IAC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MAAM,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,EAAE,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAEvG,wBAAgB,mBAAmB,CAAC,IAAI,EAAE;IACxC,OAAO,EAAE,gBAAgB,CAAC;IAC1B,OAAO,EAAE,gBAAgB,CAAC;CAC3B,GAAG,aAAa,CAKhB;AAeD;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAkBlG;AAWD,4DAA4D;AAC5D,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAG5D;AA4BD,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAUvF"}
|
package/dist/upload.js
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import axios from 'axios';
|
|
2
|
+
import * as fs from 'fs';
|
|
3
|
+
import * as path from 'path';
|
|
4
|
+
import FormData from 'form-data';
|
|
5
|
+
export function createAxiosSignatureTransport(config) {
|
|
6
|
+
const client = axios.create({
|
|
7
|
+
baseURL: config.baseUrl.replace(/\/$/, ''),
|
|
8
|
+
headers: config.auth === 'bearer'
|
|
9
|
+
? { Authorization: `Bearer ${config.apiKey}`, 'Content-Type': 'application/json' }
|
|
10
|
+
: { 'X-API-Key': config.apiKey, 'Content-Type': 'application/json' },
|
|
11
|
+
timeout: 60000,
|
|
12
|
+
});
|
|
13
|
+
return {
|
|
14
|
+
async post(requestPath, payload) {
|
|
15
|
+
try {
|
|
16
|
+
const response = await client.post(requestPath, payload);
|
|
17
|
+
return response.data;
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
// Surface the host's own diagnostics, not axios's one-liner.
|
|
21
|
+
const detail = error.response
|
|
22
|
+
? `status=${error.response.status} data=${JSON.stringify(error.response.data)}`
|
|
23
|
+
: error.message;
|
|
24
|
+
throw new Error(detail);
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export function createAxiosStorageTransport() {
|
|
30
|
+
return {
|
|
31
|
+
async submit(uploadUrl, form) {
|
|
32
|
+
try {
|
|
33
|
+
await axios.post(uploadUrl, form, {
|
|
34
|
+
headers: form.getHeaders(),
|
|
35
|
+
maxBodyLength: Infinity,
|
|
36
|
+
maxContentLength: Infinity,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
const detail = error.response
|
|
41
|
+
? `status=${error.response.status} statusText=${error.response.statusText} data=${JSON.stringify(error.response.data)} url=${uploadUrl.substring(0, 80)}...`
|
|
42
|
+
: error.message;
|
|
43
|
+
throw new Error(`TOS upload failed: ${detail}`);
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
const ENHANCE_SIGNATURE_PATH = '/api/v3/contents/generations/tos-signature';
|
|
49
|
+
const SAM3_SIGNATURE_PATH = '/get_postsignature_url';
|
|
50
|
+
/**
|
|
51
|
+
* The enhancement host serves images and videos from one signature endpoint; only `file_type`
|
|
52
|
+
* separates them.
|
|
53
|
+
*/
|
|
54
|
+
export function createEnhanceSignatureAdapter(deps) {
|
|
55
|
+
return {
|
|
56
|
+
async prepareUpload(fileName) {
|
|
57
|
+
const body = await deps.transport.post(ENHANCE_SIGNATURE_PATH, {
|
|
58
|
+
file_type: deps.fileType,
|
|
59
|
+
file_name: fileName,
|
|
60
|
+
});
|
|
61
|
+
if (body.code !== 0 && body.code !== 200) {
|
|
62
|
+
throw new Error(body.message || 'Failed to get TOS signature');
|
|
63
|
+
}
|
|
64
|
+
const signature = body.data;
|
|
65
|
+
return {
|
|
66
|
+
uploadUrl: signature.url,
|
|
67
|
+
formFields: { key: keyFromUploadUrl(signature.url), ...normalizeSignatureFields(signature) },
|
|
68
|
+
};
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/** The SAM3 host always sends images. Only the failure message convention differs from enhance. */
|
|
73
|
+
export function createSam3SignatureAdapter(deps) {
|
|
74
|
+
return {
|
|
75
|
+
async prepareUpload(fileName) {
|
|
76
|
+
const body = await deps.transport.post(SAM3_SIGNATURE_PATH, {
|
|
77
|
+
file_type: 'image',
|
|
78
|
+
file_name: fileName,
|
|
79
|
+
});
|
|
80
|
+
if (body.code !== 0 && body.code !== 200) {
|
|
81
|
+
throw new Error(`get_postsignature_url error: ${body.message || 'unknown error'}`);
|
|
82
|
+
}
|
|
83
|
+
const signature = body.data;
|
|
84
|
+
if (!signature?.url) {
|
|
85
|
+
throw new Error('Missing upload URL in post signature response');
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
uploadUrl: signature.url,
|
|
89
|
+
formFields: { key: keyFromPolicyOrUploadUrl(signature), ...normalizeSignatureFields(signature) },
|
|
90
|
+
};
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
export async function uploadObject(deps) {
|
|
95
|
+
const form = await deps.adapter.prepareUpload(deps.fileName);
|
|
96
|
+
const payload = new FormData();
|
|
97
|
+
for (const [name, value] of Object.entries(form.formFields)) {
|
|
98
|
+
payload.append(name, value);
|
|
99
|
+
}
|
|
100
|
+
payload.append('file', deps.body, deps.fileName);
|
|
101
|
+
await deps.storage.submit(form.uploadUrl, payload);
|
|
102
|
+
return { fileId: parseFileIdFromUrl(form.uploadUrl), uploadUrl: form.uploadUrl };
|
|
103
|
+
}
|
|
104
|
+
export function createMediaUploader(deps) {
|
|
105
|
+
return async (body, fileName) => {
|
|
106
|
+
const { fileId } = await uploadObject({ ...deps, body, fileName });
|
|
107
|
+
return { fileId };
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
// ── shared, host-agnostic helpers ─────────────────────────────────────────────
|
|
111
|
+
/** Fields that describe the authorization itself rather than the storage form. */
|
|
112
|
+
const NOT_FORM_FIELDS = new Set(['url', 'file_id', 'key']);
|
|
113
|
+
/** Bare names the hosts hand back, and the `x-tos-` name storage actually wants. */
|
|
114
|
+
const TOS_FIELD_ALIASES = {
|
|
115
|
+
algorithm: 'x-tos-algorithm',
|
|
116
|
+
credential: 'x-tos-credential',
|
|
117
|
+
date: 'x-tos-date',
|
|
118
|
+
signature: 'x-tos-signature',
|
|
119
|
+
};
|
|
120
|
+
/**
|
|
121
|
+
* Canonicalise a signature response into storage-form fields.
|
|
122
|
+
*
|
|
123
|
+
* Never returns `key`: each host derives the object key differently, so the adapter supplies
|
|
124
|
+
* it. Tolerates both hosts' naming conventions, so a response that arrives in the other
|
|
125
|
+
* convention still yields a usable form.
|
|
126
|
+
*/
|
|
127
|
+
export function normalizeSignatureFields(response) {
|
|
128
|
+
const hasPolicy = Object.prototype.hasOwnProperty.call(response, 'policy');
|
|
129
|
+
const fields = {};
|
|
130
|
+
for (const [name, raw] of Object.entries(response)) {
|
|
131
|
+
if (NOT_FORM_FIELDS.has(name))
|
|
132
|
+
continue;
|
|
133
|
+
if (name === 'origin_policy') {
|
|
134
|
+
// The policy in its original JSON form. Only needed when the host did not already hand
|
|
135
|
+
// back a ready-to-post `policy`; taking both would duplicate the field.
|
|
136
|
+
if (!hasPolicy)
|
|
137
|
+
fields.policy = encodePolicy(raw);
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
fields[TOS_FIELD_ALIASES[name] ?? name] = String(raw);
|
|
141
|
+
}
|
|
142
|
+
return fields;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Storage accepts the policy either Base64-encoded or as raw JSON; volcengine-tos SDK versions
|
|
146
|
+
* differ in which one they hand back. Normalise to Base64.
|
|
147
|
+
*/
|
|
148
|
+
function encodePolicy(raw) {
|
|
149
|
+
const value = String(raw);
|
|
150
|
+
return value.trim().startsWith('{') ? Buffer.from(value, 'utf-8').toString('base64') : value;
|
|
151
|
+
}
|
|
152
|
+
/** Last path segment of the upload URL, percent-decoded. */
|
|
153
|
+
export function parseFileIdFromUrl(uploadUrl) {
|
|
154
|
+
const segments = new URL(uploadUrl).pathname.split('/');
|
|
155
|
+
return decodeURIComponent(segments.pop() || '');
|
|
156
|
+
}
|
|
157
|
+
function keyFromUploadUrl(uploadUrl) {
|
|
158
|
+
return decodeURIComponent(new URL(uploadUrl).pathname.slice(1));
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* The object key the SAM3 host authorises lives inside its policy conditions. If the policy is
|
|
162
|
+
* opaque (Base64, or missing entirely) the upload URL carries the same key.
|
|
163
|
+
*/
|
|
164
|
+
function keyFromPolicyOrUploadUrl(signature) {
|
|
165
|
+
const raw = signature.origin_policy ?? signature.policy;
|
|
166
|
+
if (typeof raw === 'string') {
|
|
167
|
+
try {
|
|
168
|
+
const parsed = JSON.parse(raw);
|
|
169
|
+
const entry = parsed?.conditions?.find((c) => c && typeof c === 'object' && 'key' in c);
|
|
170
|
+
if (entry?.key)
|
|
171
|
+
return String(entry.key);
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
// Opaque policy; the upload URL below carries the same key.
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return keyFromUploadUrl(signature.url);
|
|
178
|
+
}
|
|
179
|
+
export function checkLocalFile(filePath) {
|
|
180
|
+
if (!fs.existsSync(filePath)) {
|
|
181
|
+
throw new Error(`File does not exist: ${filePath}`);
|
|
182
|
+
}
|
|
183
|
+
const stats = fs.statSync(filePath);
|
|
184
|
+
const maxSize = 100 * 1024 * 1024;
|
|
185
|
+
if (stats.size > maxSize) {
|
|
186
|
+
throw new Error('File size exceeds 100MB limit');
|
|
187
|
+
}
|
|
188
|
+
return { filePath, fileName: path.basename(filePath) };
|
|
189
|
+
}
|
|
190
|
+
//# sourceMappingURL=upload.js.map
|
|
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,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;AACzD,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"video-enhancement.d.ts","sourceRoot":"","sources":["../src/video-enhancement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;
|
|
1
|
+
{"version":3,"file":"video-enhancement.d.ts","sourceRoot":"","sources":["../src/video-enhancement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAmCpE,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAkEnG"}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import axios from 'axios';
|
|
2
2
|
import * as fs from 'fs';
|
|
3
|
-
import * as path from 'path';
|
|
4
3
|
import { z } from 'zod';
|
|
5
|
-
import
|
|
4
|
+
import { checkLocalFile, formatRequestError, parseTosSignature, unwrapEnvelope, uploadToTos, } from './tos.js';
|
|
5
|
+
import { classifyStatus, POLL_REQUEST_TIMEOUT_MS, pollUntilTerminal, registerTool } from './tooling.js';
|
|
6
|
+
const PollIntervalSchema = z.number().min(0.5).max(30).default(5).describe('Polling interval in seconds (0.5-30), default 5');
|
|
7
|
+
const SyncTimeoutSchema = z.number().min(1).max(45).default(45).describe('Synchronous wait timeout in seconds (1-45), default 45. Returns task_id early when exceeded, use the task status tool to continue polling');
|
|
6
8
|
// Schemas
|
|
7
9
|
const CreateTaskSchema = z.object({
|
|
8
10
|
video_source: z.string().describe('Video URL or local file path (URL must be publicly accessible, login or signed links are not supported)'),
|
|
@@ -16,8 +18,8 @@ const EnhanceVideoSyncSchema = z.object({
|
|
|
16
18
|
video_source: z.string().describe('Video URL or local file path (URL must be publicly accessible, login or signed links are not supported)'),
|
|
17
19
|
type: z.enum(['url', 'local']).default('url').describe('Upload type: url=remote video, local=local file'),
|
|
18
20
|
resolution: z.enum(['480p', '540p', '720p', '1080p', '2k']).default('720p').describe('Target resolution, default 720p'),
|
|
19
|
-
poll_interval:
|
|
20
|
-
timeout:
|
|
21
|
+
poll_interval: PollIntervalSchema,
|
|
22
|
+
timeout: SyncTimeoutSchema,
|
|
21
23
|
});
|
|
22
24
|
export function setupVideoEnhancementTools(server, baseUrl, apiKey) {
|
|
23
25
|
const client = axios.create({
|
|
@@ -28,8 +30,7 @@ export function setupVideoEnhancementTools(server, baseUrl, apiKey) {
|
|
|
28
30
|
},
|
|
29
31
|
timeout: 60000,
|
|
30
32
|
});
|
|
31
|
-
|
|
32
|
-
server.tool('create_task', `Create a video enhancement task (asynchronous).
|
|
33
|
+
registerTool(server, 'create_task', `Create a video enhancement task (asynchronous).
|
|
33
34
|
|
|
34
35
|
Two upload methods are supported:
|
|
35
36
|
1. URL upload: provide a video URL
|
|
@@ -40,37 +41,18 @@ Parameters:
|
|
|
40
41
|
- type: "url" or "local"
|
|
41
42
|
- resolution: target resolution
|
|
42
43
|
|
|
43
|
-
After creating a task, a task_id is returned immediately. Use get_task_status to poll for results until status becomes "completed" or "failed".`, CreateTaskSchema.shape, async (args) =>
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
content: [{ type: 'text', text: JSON.stringify({ success: false, error: errorMessage }, null, 2) }],
|
|
54
|
-
};
|
|
55
|
-
}
|
|
44
|
+
After creating a task, a task_id is returned immediately. Use get_task_status to poll for results until status becomes "completed" or "failed".`, CreateTaskSchema.shape, async (args) => createTask(client, args.video_source, args.type, args.resolution));
|
|
45
|
+
registerTool(server, 'get_task_status', 'Query video enhancement task status. The status field can be: processing, completed, or failed. If status is processing, wait a few seconds and call this tool again to poll.', GetTaskStatusSchema.shape, async (args) => {
|
|
46
|
+
const result = await getTaskStatus(client, args.task_id);
|
|
47
|
+
return {
|
|
48
|
+
...result,
|
|
49
|
+
// registerTool marks isError on success===false: a terminal failed
|
|
50
|
+
// status is a failed query outcome, not a healthy poll tick.
|
|
51
|
+
success: classifyStatus(result.status) !== 'failed',
|
|
52
|
+
message: result.status === 'processing' ? 'Task is still processing, please check again later' : undefined,
|
|
53
|
+
};
|
|
56
54
|
});
|
|
57
|
-
|
|
58
|
-
server.tool('get_task_status', 'Query video enhancement task status. The status field can be: processing, completed, or failed. If status is processing, wait a few seconds and call this tool again to poll.', GetTaskStatusSchema.shape, async (args) => {
|
|
59
|
-
try {
|
|
60
|
-
const result = await getTaskStatus(client, args.task_id);
|
|
61
|
-
return {
|
|
62
|
-
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
|
63
|
-
};
|
|
64
|
-
}
|
|
65
|
-
catch (error) {
|
|
66
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
67
|
-
return {
|
|
68
|
-
content: [{ type: 'text', text: JSON.stringify({ success: false, error: errorMessage }, null, 2) }],
|
|
69
|
-
};
|
|
70
|
-
}
|
|
71
|
-
});
|
|
72
|
-
// enhance_video_sync tool
|
|
73
|
-
server.tool('enhance_video_sync', `Synchronously enhance video (blocks until completion).
|
|
55
|
+
registerTool(server, 'enhance_video_sync', `Synchronously enhance video (blocks until completion).
|
|
74
56
|
|
|
75
57
|
Two upload methods are supported:
|
|
76
58
|
1. URL upload: provide a video URL
|
|
@@ -81,125 +63,78 @@ Parameters:
|
|
|
81
63
|
- type: "url" or "local"
|
|
82
64
|
- resolution: target resolution
|
|
83
65
|
- poll_interval: polling interval in seconds
|
|
84
|
-
- timeout: synchronous wait timeout in seconds, default
|
|
66
|
+
- timeout: synchronous wait timeout in seconds, default 45
|
|
85
67
|
|
|
86
|
-
Best for short videos (estimated processing time < 1 minute). If the task is not completed within
|
|
87
|
-
try {
|
|
88
|
-
const result = await enhanceVideoSync(client, args.video_source, args.type, args.resolution, args.poll_interval, args.timeout);
|
|
89
|
-
return {
|
|
90
|
-
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
catch (error) {
|
|
94
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
95
|
-
return {
|
|
96
|
-
content: [{ type: 'text', text: JSON.stringify({ success: false, error: errorMessage }, null, 2) }],
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
function checkLocalFile(filePath) {
|
|
102
|
-
if (!fs.existsSync(filePath)) {
|
|
103
|
-
throw new Error(`File does not exist: ${filePath}`);
|
|
104
|
-
}
|
|
105
|
-
const stats = fs.statSync(filePath);
|
|
106
|
-
const maxSize = 100 * 1024 * 1024;
|
|
107
|
-
if (stats.size > maxSize) {
|
|
108
|
-
throw new Error('File size exceeds 100MB limit');
|
|
109
|
-
}
|
|
110
|
-
return { filePath, fileName: path.basename(filePath) };
|
|
68
|
+
Best for short videos (estimated processing time < 1 minute). If the task is not completed within the timeout, the tool returns early with a task_id. Use get_task_status to continue polling.`, EnhanceVideoSyncSchema.shape, async (args) => enhanceVideoSync(client, args.video_source, args.type, args.resolution, args.poll_interval, args.timeout));
|
|
111
69
|
}
|
|
112
70
|
async function getTosSignature(client, fileName) {
|
|
113
71
|
const response = await client.post('/api/v3/contents/generations/tos-signature', {
|
|
114
72
|
file_type: 'video',
|
|
115
73
|
file_name: fileName,
|
|
116
74
|
});
|
|
117
|
-
const
|
|
118
|
-
if (
|
|
119
|
-
throw new Error(
|
|
75
|
+
const unwrapped = unwrapEnvelope(response);
|
|
76
|
+
if (!unwrapped.ok) {
|
|
77
|
+
throw new Error(unwrapped.error);
|
|
120
78
|
}
|
|
121
|
-
return
|
|
122
|
-
}
|
|
123
|
-
async function uploadToTos(filePath, signatureData) {
|
|
124
|
-
const formData = new FormData();
|
|
125
|
-
const objectKey = decodeURIComponent(new URL(signatureData.url).pathname.slice(1));
|
|
126
|
-
formData.append('key', objectKey);
|
|
127
|
-
const fieldMapping = {
|
|
128
|
-
algorithm: 'x-tos-algorithm',
|
|
129
|
-
credential: 'x-tos-credential',
|
|
130
|
-
date: 'x-tos-date',
|
|
131
|
-
signature: 'x-tos-signature',
|
|
132
|
-
};
|
|
133
|
-
for (const [key, value] of Object.entries(signatureData)) {
|
|
134
|
-
if (key === 'url' || key === 'origin_policy')
|
|
135
|
-
continue;
|
|
136
|
-
const formKey = fieldMapping[key] || key;
|
|
137
|
-
formData.append(formKey, String(value));
|
|
138
|
-
}
|
|
139
|
-
const fileName = path.basename(filePath);
|
|
140
|
-
formData.append('file', fs.createReadStream(filePath), fileName);
|
|
141
|
-
const response = await axios.post(signatureData.url, formData, {
|
|
142
|
-
headers: formData.getHeaders(),
|
|
143
|
-
maxBodyLength: Infinity,
|
|
144
|
-
maxContentLength: Infinity,
|
|
145
|
-
});
|
|
146
|
-
if (response.status >= 400) {
|
|
147
|
-
const debugInfo = JSON.stringify({
|
|
148
|
-
status: response.status,
|
|
149
|
-
statusText: response.statusText,
|
|
150
|
-
data: response.data,
|
|
151
|
-
url: signatureData.url,
|
|
152
|
-
signatureFields: Object.keys(signatureData),
|
|
153
|
-
fileName,
|
|
154
|
-
fileSize: fs.statSync(filePath).size,
|
|
155
|
-
}, null, 2);
|
|
156
|
-
throw new Error(`TOS upload failed: ${response.status} ${response.statusText}\nDebug info: ${debugInfo}`);
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
function parseFileIdFromUrl(url) {
|
|
160
|
-
const pathname = new URL(url).pathname;
|
|
161
|
-
const segments = pathname.split('/');
|
|
162
|
-
return decodeURIComponent(segments.pop() || '');
|
|
79
|
+
return unwrapped.data;
|
|
163
80
|
}
|
|
164
81
|
async function createTask(client, videoSource, sourceType, resolution) {
|
|
165
82
|
let contentItem;
|
|
166
83
|
if (sourceType === 'local') {
|
|
167
|
-
const fileInfo = checkLocalFile(videoSource);
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
84
|
+
const fileInfo = checkLocalFile(videoSource, 'video');
|
|
85
|
+
// Step 1: Get TOS signature
|
|
86
|
+
let target;
|
|
87
|
+
try {
|
|
88
|
+
target = parseTosSignature(await getTosSignature(client, fileInfo.fileName));
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
throw new Error(`[Step 1: TOS signature failed] ${formatRequestError(error)}`);
|
|
92
|
+
}
|
|
93
|
+
// Step 2: Upload to TOS
|
|
94
|
+
try {
|
|
95
|
+
await uploadToTos(target, fs.createReadStream(videoSource), fileInfo.fileName);
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
throw new Error(`[Step 2: TOS upload failed] ${error.message}`);
|
|
99
|
+
}
|
|
100
|
+
contentItem = { type: 'video_file', file_id: target.fileId, file_name: fileInfo.fileName };
|
|
172
101
|
}
|
|
173
102
|
else {
|
|
174
103
|
contentItem = { type: 'video_url', video_url: { url: videoSource } };
|
|
175
104
|
}
|
|
105
|
+
// Step 3: Call video API
|
|
176
106
|
const payload = { model: 'avc-enhance', content: [contentItem], resolution };
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
return { success: false, error: data.message };
|
|
107
|
+
let response;
|
|
108
|
+
try {
|
|
109
|
+
response = await client.post('/api/v3/contents/generations/tasks', payload);
|
|
181
110
|
}
|
|
182
|
-
|
|
111
|
+
catch (error) {
|
|
112
|
+
throw new Error(`[Step 3: API call failed] ${formatRequestError(error)}`);
|
|
113
|
+
}
|
|
114
|
+
const unwrapped = unwrapEnvelope(response);
|
|
115
|
+
if (!unwrapped.ok) {
|
|
116
|
+
return { success: false, error: unwrapped.error };
|
|
117
|
+
}
|
|
118
|
+
return { success: true, task_id: unwrapped.data.task_id, status: unwrapped.data.status };
|
|
183
119
|
}
|
|
184
|
-
async function getTaskStatus(client, taskId) {
|
|
185
|
-
const response = await client.get(`/api/v3/contents/generations/tasks/${taskId}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
120
|
+
async function getTaskStatus(client, taskId, signal) {
|
|
121
|
+
const response = await client.get(`/api/v3/contents/generations/tasks/${encodeURIComponent(taskId)}`, {
|
|
122
|
+
timeout: POLL_REQUEST_TIMEOUT_MS,
|
|
123
|
+
signal,
|
|
124
|
+
});
|
|
125
|
+
const unwrapped = unwrapEnvelope(response);
|
|
126
|
+
if (!unwrapped.ok) {
|
|
127
|
+
throw new Error(unwrapped.error);
|
|
189
128
|
}
|
|
190
|
-
const result =
|
|
129
|
+
const result = unwrapped.data;
|
|
191
130
|
return {
|
|
192
|
-
success: true,
|
|
193
131
|
task_id: result.task_id,
|
|
194
132
|
status: result.status,
|
|
195
|
-
progress: result.progress
|
|
133
|
+
progress: result.progress ?? 0,
|
|
196
134
|
video_url: result.video_url,
|
|
197
|
-
debug_video_url_length: result.video_url?.length,
|
|
198
|
-
debug_video_url_full: result.video_url,
|
|
199
135
|
error_message: result.error_message,
|
|
200
136
|
created_at: result.created_at,
|
|
201
137
|
updated_at: result.updated_at,
|
|
202
|
-
message: result.status === 'processing' ? 'Task is still processing, please check again later' : undefined,
|
|
203
138
|
};
|
|
204
139
|
}
|
|
205
140
|
async function enhanceVideoSync(client, videoSource, sourceType, resolution, pollInterval, timeout) {
|
|
@@ -207,30 +142,15 @@ async function enhanceVideoSync(client, videoSource, sourceType, resolution, pol
|
|
|
207
142
|
if (!createResult.success) {
|
|
208
143
|
return createResult;
|
|
209
144
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
const elapsed = (Date.now() - startTime) / 1000;
|
|
221
|
-
if (elapsed >= timeout) {
|
|
222
|
-
return {
|
|
223
|
-
success: true,
|
|
224
|
-
status: 'processing',
|
|
225
|
-
task_id: taskId,
|
|
226
|
-
message: `Task is still processing (waited ${timeout} seconds). Please use get_task_status to continue polling.`,
|
|
227
|
-
note: 'The synchronous wait for this long-running task has been truncated. Switch to get_task_status polling.',
|
|
228
|
-
};
|
|
229
|
-
}
|
|
230
|
-
await sleep(pollInterval * 1000);
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
function sleep(ms) {
|
|
234
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
145
|
+
return pollUntilTerminal({
|
|
146
|
+
taskId: createResult.task_id,
|
|
147
|
+
timeoutSeconds: timeout,
|
|
148
|
+
pollIntervalSeconds: pollInterval,
|
|
149
|
+
continueHint: 'get_task_status',
|
|
150
|
+
fetchStatus: async (signal) => {
|
|
151
|
+
const { task_id, status, ...payload } = await getTaskStatus(client, createResult.task_id, signal);
|
|
152
|
+
return { status, payload };
|
|
153
|
+
},
|
|
154
|
+
});
|
|
235
155
|
}
|
|
236
156
|
//# sourceMappingURL=video-enhancement.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"video-enhancement.js","sourceRoot":"","sources":["../src/video-enhancement.ts"],"names":[],"mappings":"AACA,OAAO,KAAwB,MAAM,OAAO,CAAC;AAC7C,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,
|
|
1
|
+
{"version":3,"file":"video-enhancement.js","sourceRoot":"","sources":["../src/video-enhancement.ts"],"names":[],"mappings":"AACA,OAAO,KAAwB,MAAM,OAAO,CAAC;AAC7C,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,cAAc,EACd,kBAAkB,EAClB,iBAAiB,EACjB,cAAc,EACd,WAAW,GACZ,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,cAAc,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAExG,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,OAAO,C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