ai84-mcp 0.0.0-stage → 0.1.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 +95 -2
- package/dist/api/client.js +148 -0
- package/dist/config.js +57 -0
- package/dist/errors.js +23 -0
- package/dist/files/download.js +119 -0
- package/dist/files/upload.js +148 -0
- package/dist/index.js +19 -0
- package/dist/jobs/wait.js +45 -0
- package/dist/server.js +33 -0
- package/dist/tools/account.js +87 -0
- package/dist/tools/catalog.js +198 -0
- package/dist/tools/clone.js +121 -0
- package/dist/tools/common.js +209 -0
- package/dist/tools/dialogue.js +155 -0
- package/dist/tools/kinds.js +25 -0
- package/dist/tools/media.js +310 -0
- package/dist/tools/split.js +542 -0
- package/dist/tools/tasks.js +105 -0
- package/dist/tools/tts.js +162 -0
- package/package.json +46 -4
package/README.md
CHANGED
|
@@ -1,3 +1,96 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ai84-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Use [AI84.pro](https://ai84.pro) from your AI assistant. Through this MCP server, Claude Desktop, Claude Code, Cursor and other MCP clients can turn text into speech, voice multi-speaker dialogues, transcribe audio and video, change voices, dub videos into other languages and clone voices, all with your AI84 credits.
|
|
4
|
+
|
|
5
|
+
The server runs on your own computer. Results (audio, subtitles, transcripts, dubbed videos) are saved to a folder on your machine, `~/Desktop/ai84` by default.
|
|
6
|
+
|
|
7
|
+
## Requirements
|
|
8
|
+
|
|
9
|
+
- [Node.js](https://nodejs.org) 20.3 or newer.
|
|
10
|
+
- An AI84 account on the paid tier. Creating jobs with an API key needs purchased credits.
|
|
11
|
+
- Your AI84 API key, from the API page of the dashboard: <https://ai84.pro/app/api-document>.
|
|
12
|
+
|
|
13
|
+
## Setup
|
|
14
|
+
|
|
15
|
+
### Claude Desktop
|
|
16
|
+
|
|
17
|
+
Open *Settings → Developer → Edit Config* and add the server to `claude_desktop_config.json`:
|
|
18
|
+
|
|
19
|
+
```json
|
|
20
|
+
{
|
|
21
|
+
"mcpServers": {
|
|
22
|
+
"ai84": {
|
|
23
|
+
"command": "npx",
|
|
24
|
+
"args": ["-y", "ai84-mcp"],
|
|
25
|
+
"env": { "AI84_API_KEY": "your-api-key" }
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Restart Claude Desktop. On Windows, if `npx` is not found, use `"command": "cmd"` with `"args": ["/c", "npx", "-y", "ai84-mcp"]`.
|
|
32
|
+
|
|
33
|
+
### Claude Code
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
claude mcp add ai84 -e AI84_API_KEY=your-api-key -- npx -y ai84-mcp
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Cursor
|
|
40
|
+
|
|
41
|
+
Add the same block as Claude Desktop to `~/.cursor/mcp.json` (all projects) or `.cursor/mcp.json` (one project).
|
|
42
|
+
|
|
43
|
+
## Settings
|
|
44
|
+
|
|
45
|
+
| Variable | Default | Meaning |
|
|
46
|
+
|---|---|---|
|
|
47
|
+
| `AI84_API_KEY` | (required) | Your AI84 API key. |
|
|
48
|
+
| `AI84_MCP_OUTPUT_DIR` | `~/Desktop/ai84` | Folder where results are saved. A relative path is taken from your home folder. |
|
|
49
|
+
| `AI84_MCP_WAIT_SECONDS` | `50` | How long one tool call waits for a job. Longer jobs return a `job_id`; the assistant calls `get_job` to keep waiting. Many clients stop a tool call after 60 seconds, so keep it under that. |
|
|
50
|
+
| `AI84_API_BASE_URL` | `https://api.ai84.pro` | API address. Leave as is. |
|
|
51
|
+
|
|
52
|
+
## Tools
|
|
53
|
+
|
|
54
|
+
| Tool | What it does |
|
|
55
|
+
|---|---|
|
|
56
|
+
| `get_account` | Credit balance, paid tier, credits expiring soon, team quota, how many jobs may run at once |
|
|
57
|
+
| `list_models` | Speech models for ElevenLabs or MiniMax |
|
|
58
|
+
| `search_voices` | Search the ElevenLabs voice library |
|
|
59
|
+
| `search_minimax_voices` | Search the MiniMax voice library |
|
|
60
|
+
| `list_favorite_voices` | Voices you saved as favorites on ai84.pro |
|
|
61
|
+
| `text_to_speech` | Text to speech with an ElevenLabs voice, optional SRT subtitles |
|
|
62
|
+
| `minimax_text_to_speech` | Text to speech with a MiniMax voice or one of your cloned voices |
|
|
63
|
+
| `text_to_dialogue` | A multi-speaker dialogue in one audio file |
|
|
64
|
+
| `estimate_dialogue_cost` | Credit cost of a dialogue before you create it |
|
|
65
|
+
| `speech_to_text` | Transcribe an audio or video file (text, SRT or JSON) |
|
|
66
|
+
| `voice_changer` | Re-voice a recording with another voice |
|
|
67
|
+
| `dubbing` | Dub an audio or video file into another language |
|
|
68
|
+
| `clone_voice` | Clone a voice from a 10 to 290 second sample (MiniMax) |
|
|
69
|
+
| `list_cloned_voices` | Your cloned voices |
|
|
70
|
+
| `delete_cloned_voice` | Delete one of your cloned voices |
|
|
71
|
+
| `split_create_project` | Create a multi-scene project: one voice, many text scenes |
|
|
72
|
+
| `split_list_projects` / `split_get_project` | List projects / show one with its scenes |
|
|
73
|
+
| `split_add_scenes` / `split_update_scene` | Add scenes / edit a scene |
|
|
74
|
+
| `split_generate` | Generate audio for every scene, or regenerate one scene |
|
|
75
|
+
| `split_delete_project` | Delete a project |
|
|
76
|
+
| `get_job` | Keep waiting for a job and save its files |
|
|
77
|
+
| `list_tasks` | Your recent jobs with their status and links |
|
|
78
|
+
|
|
79
|
+
Tools that create jobs cost credits, as they do on the website.
|
|
80
|
+
|
|
81
|
+
## Notes
|
|
82
|
+
|
|
83
|
+
- Files are named after the job, e.g. `tts-<job_id>.mp3`. Calling `get_job` again for a finished job reuses the saved file.
|
|
84
|
+
- Split projects are saved in `split-<project_id>/`, one file per scene (`scene-<position>-<scene_id>.mp3`). A hidden file there, `.ai84-saved.json`, records which audio each file holds: a scene is downloaded again only when its audio changed, and a regenerated scene replaces its file under the same name.
|
|
85
|
+
- Download links in the results stop working shortly after midnight Vietnam time (UTC+7). Call `get_job` or `list_tasks` again for a fresh link.
|
|
86
|
+
- Speech to text, voice changer, dubbing and voice cloning read the file from the path you give, so the file must be on this computer.
|
|
87
|
+
- Sending a large file (over about 100MB on a slow connection), or cloning a voice, can take longer than your app allows for one tool call. If a call is cut off, the job may still have been created and charged: check `list_tasks` (with `type` `dubbing` for dubbing), your speech to text history on ai84.pro, or `list_cloned_voices` before trying again.
|
|
88
|
+
|
|
89
|
+
## Hướng dẫn nhanh (tiếng Việt)
|
|
90
|
+
|
|
91
|
+
1. Cài Node.js 20.3 trở lên.
|
|
92
|
+
2. Lấy API key ở <https://ai84.pro/app/api-document>. Tài khoản cần có credit trả phí.
|
|
93
|
+
3. Thêm khối cấu hình ở mục **Setup** vào Claude Desktop, Claude Code hoặc Cursor, thay `your-api-key` bằng key của bạn.
|
|
94
|
+
4. Khởi động lại ứng dụng, rồi nhờ trợ lý AI, ví dụ: "Đọc đoạn văn này bằng giọng nữ tiếng Việt và lưu thành mp3".
|
|
95
|
+
|
|
96
|
+
File kết quả được lưu vào `~/Desktop/ai84`.
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Ai84Client = exports.MAX_JSON_BYTES = exports.API_KEY_PAGE = void 0;
|
|
4
|
+
exports.toApiError = toApiError;
|
|
5
|
+
const errors_1 = require("../errors");
|
|
6
|
+
exports.API_KEY_PAGE = 'https://ai84.pro/app/api-document';
|
|
7
|
+
const REQUEST_TIMEOUT_MS = 60_000;
|
|
8
|
+
exports.MAX_JSON_BYTES = 1024 * 1024;
|
|
9
|
+
const MAX_DETAIL_CHARS = 1_000;
|
|
10
|
+
function text(value) {
|
|
11
|
+
return typeof value === 'string' && value.trim() !== '' ? value.trim() : null;
|
|
12
|
+
}
|
|
13
|
+
function seconds(value) {
|
|
14
|
+
const n = typeof value === 'string' ? Number(value) : value;
|
|
15
|
+
return typeof n === 'number' && Number.isFinite(n) && n >= 0 ? Math.ceil(n) : null;
|
|
16
|
+
}
|
|
17
|
+
function isCode(value) {
|
|
18
|
+
return value !== null && /^[A-Z][A-Z0-9_]+$/.test(value);
|
|
19
|
+
}
|
|
20
|
+
function describeFailure(err) {
|
|
21
|
+
if (err instanceof Error) {
|
|
22
|
+
if (err.name === 'TimeoutError')
|
|
23
|
+
return 'the request timed out';
|
|
24
|
+
if (err.name === 'AbortError')
|
|
25
|
+
return 'the request was cancelled';
|
|
26
|
+
return err.message.replace(/\.+$/, '');
|
|
27
|
+
}
|
|
28
|
+
return String(err).replace(/\.+$/, '');
|
|
29
|
+
}
|
|
30
|
+
async function toApiError(res) {
|
|
31
|
+
let body = {};
|
|
32
|
+
try {
|
|
33
|
+
const data = await res.json();
|
|
34
|
+
if (data !== null && typeof data === 'object' && !Array.isArray(data)) {
|
|
35
|
+
body = Object.fromEntries(Object.entries(data));
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
catch { }
|
|
39
|
+
const error = text(body.error);
|
|
40
|
+
const message = text(body.message);
|
|
41
|
+
const code = text(body.error_code) ?? (isCode(error) ? error : null);
|
|
42
|
+
const retryAfter = seconds(body.retry_after) ?? seconds(body.retryAfter) ?? seconds(res.headers.get('retry-after'));
|
|
43
|
+
let summary = message ?? (isCode(error) ? null : error) ?? `Request failed with HTTP ${res.status}.`;
|
|
44
|
+
const details = body.issues ?? body.details;
|
|
45
|
+
if (details !== undefined) {
|
|
46
|
+
summary += ` Details: ${JSON.stringify(details).slice(0, MAX_DETAIL_CHARS)}`;
|
|
47
|
+
}
|
|
48
|
+
if (res.status === 401) {
|
|
49
|
+
summary = `The AI84 API rejected the API key (${summary}). Check AI84_API_KEY; you can copy your key from ${exports.API_KEY_PAGE}.`;
|
|
50
|
+
}
|
|
51
|
+
else if (res.status === 429 && retryAfter !== null) {
|
|
52
|
+
summary += ` Try again in ${retryAfter} seconds.`;
|
|
53
|
+
}
|
|
54
|
+
return new errors_1.ApiError(res.status, summary, code, retryAfter);
|
|
55
|
+
}
|
|
56
|
+
class Ai84Client {
|
|
57
|
+
config;
|
|
58
|
+
fetchFn;
|
|
59
|
+
constructor(config, fetchFn = fetch) {
|
|
60
|
+
this.config = config;
|
|
61
|
+
this.fetchFn = fetchFn;
|
|
62
|
+
}
|
|
63
|
+
get(path, schema, options = {}) {
|
|
64
|
+
return this.request('GET', path, schema, options);
|
|
65
|
+
}
|
|
66
|
+
post(path, schema, options = {}) {
|
|
67
|
+
return this.request('POST', path, schema, options);
|
|
68
|
+
}
|
|
69
|
+
put(path, schema, options = {}) {
|
|
70
|
+
return this.request('PUT', path, schema, options);
|
|
71
|
+
}
|
|
72
|
+
patch(path, schema, options = {}) {
|
|
73
|
+
return this.request('PATCH', path, schema, options);
|
|
74
|
+
}
|
|
75
|
+
delete(path, schema, options = {}) {
|
|
76
|
+
return this.request('DELETE', path, schema, options);
|
|
77
|
+
}
|
|
78
|
+
async request(method, path, schema, options = {}) {
|
|
79
|
+
const apiKey = this.config.apiKey;
|
|
80
|
+
if (apiKey === null) {
|
|
81
|
+
throw new errors_1.UserInputError(`AI84_API_KEY is not set. Add your AI84 API key to this MCP server's environment; you can copy it from ${exports.API_KEY_PAGE}.`);
|
|
82
|
+
}
|
|
83
|
+
const headers = { 'xi-api-key': apiKey, accept: 'application/json' };
|
|
84
|
+
let body;
|
|
85
|
+
if (options.json !== undefined) {
|
|
86
|
+
headers['content-type'] = 'application/json';
|
|
87
|
+
body = JSON.stringify(options.json);
|
|
88
|
+
const bytes = Buffer.byteLength(body);
|
|
89
|
+
if (bytes > exports.MAX_JSON_BYTES) {
|
|
90
|
+
throw new errors_1.UserInputError(`This request is ${(bytes / exports.MAX_JSON_BYTES).toFixed(2)}MB; the API takes at most 1MB per request. Send less text per call (Vietnamese and other accented text uses more bytes per character).`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
else if (options.form !== undefined) {
|
|
94
|
+
body = options.form;
|
|
95
|
+
}
|
|
96
|
+
const res = await this.send(this.url(path, options.query), { method, headers, body }, options);
|
|
97
|
+
if (!res.ok)
|
|
98
|
+
throw await toApiError(res);
|
|
99
|
+
let data = {};
|
|
100
|
+
if (res.status !== 204) {
|
|
101
|
+
try {
|
|
102
|
+
data = await res.json();
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
throw new errors_1.ApiError(res.status, 'The AI84 API returned a response that is not JSON.', null, null);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const parsed = schema.safeParse(data);
|
|
109
|
+
if (!parsed.success) {
|
|
110
|
+
throw new errors_1.ApiError(res.status, `Unexpected response from the AI84 API for ${method} ${path}.`, null, null);
|
|
111
|
+
}
|
|
112
|
+
return parsed.data;
|
|
113
|
+
}
|
|
114
|
+
async download(url, signal) {
|
|
115
|
+
const headers = {};
|
|
116
|
+
if (this.config.apiKey !== null &&
|
|
117
|
+
new URL(url).origin === new URL(this.config.apiBaseUrl).origin) {
|
|
118
|
+
headers['xi-api-key'] = this.config.apiKey;
|
|
119
|
+
}
|
|
120
|
+
const res = await this.send(url, { method: 'GET', headers }, { signal, timeoutMs: 30 * 60_000 });
|
|
121
|
+
if (!res.ok) {
|
|
122
|
+
throw new errors_1.ApiError(res.status, `Could not download the result file (HTTP ${res.status}).`, null, null);
|
|
123
|
+
}
|
|
124
|
+
return res;
|
|
125
|
+
}
|
|
126
|
+
url(path, query) {
|
|
127
|
+
const url = new URL(this.config.apiBaseUrl + path);
|
|
128
|
+
for (const [key, value] of Object.entries(query ?? {})) {
|
|
129
|
+
if (value !== undefined && value !== null)
|
|
130
|
+
url.searchParams.set(key, String(value));
|
|
131
|
+
}
|
|
132
|
+
return url.toString();
|
|
133
|
+
}
|
|
134
|
+
async send(url, init, options) {
|
|
135
|
+
const signals = [AbortSignal.timeout(options.timeoutMs ?? REQUEST_TIMEOUT_MS)];
|
|
136
|
+
if (options.signal !== undefined)
|
|
137
|
+
signals.push(options.signal);
|
|
138
|
+
try {
|
|
139
|
+
const redirect = 'xi-api-key' in init.headers ? 'error' : 'follow';
|
|
140
|
+
return await this.fetchFn(url, { ...init, redirect, signal: AbortSignal.any(signals) });
|
|
141
|
+
}
|
|
142
|
+
catch (err) {
|
|
143
|
+
const target = url.startsWith(this.config.apiBaseUrl) ? 'the AI84 API' : 'the file host';
|
|
144
|
+
throw new errors_1.ApiError(0, `Could not reach ${target}: ${describeFailure(err)}.`, null, null);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
exports.Ai84Client = Ai84Client;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DEFAULT_WAIT_SECONDS = exports.DEFAULT_OUTPUT_DIR = exports.DEFAULT_API_BASE_URL = void 0;
|
|
4
|
+
exports.loadConfig = loadConfig;
|
|
5
|
+
const node_os_1 = require("node:os");
|
|
6
|
+
const node_path_1 = require("node:path");
|
|
7
|
+
const zod_1 = require("zod");
|
|
8
|
+
exports.DEFAULT_API_BASE_URL = 'https://api.ai84.pro';
|
|
9
|
+
exports.DEFAULT_OUTPUT_DIR = (0, node_path_1.join)('~', 'Desktop', 'ai84');
|
|
10
|
+
exports.DEFAULT_WAIT_SECONDS = 50;
|
|
11
|
+
function expandHome(path, home) {
|
|
12
|
+
if (path === '~')
|
|
13
|
+
return home;
|
|
14
|
+
if (path.startsWith('~/') || path.startsWith('~\\'))
|
|
15
|
+
return (0, node_path_1.join)(home, path.slice(2));
|
|
16
|
+
return path;
|
|
17
|
+
}
|
|
18
|
+
const optionalText = zod_1.z
|
|
19
|
+
.string()
|
|
20
|
+
.optional()
|
|
21
|
+
.transform(value => value?.trim() || undefined);
|
|
22
|
+
const envSchema = zod_1.z.object({
|
|
23
|
+
AI84_API_KEY: optionalText,
|
|
24
|
+
AI84_API_BASE_URL: optionalText,
|
|
25
|
+
AI84_MCP_OUTPUT_DIR: optionalText,
|
|
26
|
+
AI84_MCP_WAIT_SECONDS: optionalText,
|
|
27
|
+
});
|
|
28
|
+
const waitSecondsSchema = zod_1.z.coerce.number().finite().positive();
|
|
29
|
+
const baseUrlSchema = zod_1.z.url({ protocol: /^https?$/ });
|
|
30
|
+
function readWaitSeconds(raw) {
|
|
31
|
+
if (raw === undefined)
|
|
32
|
+
return exports.DEFAULT_WAIT_SECONDS;
|
|
33
|
+
const parsed = waitSecondsSchema.safeParse(raw);
|
|
34
|
+
if (!parsed.success) {
|
|
35
|
+
throw new Error(`AI84_MCP_WAIT_SECONDS must be a positive number of seconds, got "${raw}"`);
|
|
36
|
+
}
|
|
37
|
+
return parsed.data;
|
|
38
|
+
}
|
|
39
|
+
function readBaseUrl(raw) {
|
|
40
|
+
const value = raw ?? exports.DEFAULT_API_BASE_URL;
|
|
41
|
+
const parsed = baseUrlSchema.safeParse(value);
|
|
42
|
+
if (!parsed.success) {
|
|
43
|
+
throw new Error(`AI84_API_BASE_URL must be a URL starting with https:// or http://, got "${value}"`);
|
|
44
|
+
}
|
|
45
|
+
const url = new URL(parsed.data);
|
|
46
|
+
return url.origin + url.pathname.replace(/\/+$/, '');
|
|
47
|
+
}
|
|
48
|
+
function loadConfig(env = process.env, home = (0, node_os_1.homedir)()) {
|
|
49
|
+
const vars = envSchema.parse(env);
|
|
50
|
+
const expanded = expandHome(vars.AI84_MCP_OUTPUT_DIR ?? exports.DEFAULT_OUTPUT_DIR, home);
|
|
51
|
+
return {
|
|
52
|
+
apiKey: vars.AI84_API_KEY ?? null,
|
|
53
|
+
apiBaseUrl: readBaseUrl(vars.AI84_API_BASE_URL),
|
|
54
|
+
outputDir: (0, node_path_1.isAbsolute)(expanded) ? expanded : (0, node_path_1.resolve)(home, expanded),
|
|
55
|
+
waitSeconds: readWaitSeconds(vars.AI84_MCP_WAIT_SECONDS),
|
|
56
|
+
};
|
|
57
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ApiError = exports.UserInputError = void 0;
|
|
4
|
+
class UserInputError extends Error {
|
|
5
|
+
constructor(message) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = 'UserInputError';
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
exports.UserInputError = UserInputError;
|
|
11
|
+
class ApiError extends Error {
|
|
12
|
+
status;
|
|
13
|
+
code;
|
|
14
|
+
retryAfterSeconds;
|
|
15
|
+
constructor(status, message, code, retryAfterSeconds) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.status = status;
|
|
18
|
+
this.code = code;
|
|
19
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
20
|
+
this.name = 'ApiError';
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
exports.ApiError = ApiError;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SAVED_LIST_NAME = void 0;
|
|
4
|
+
exports.safeFileName = safeFileName;
|
|
5
|
+
exports.extensionFromUrl = extensionFromUrl;
|
|
6
|
+
exports.resultFilePath = resultFilePath;
|
|
7
|
+
exports.saveResultFile = saveResultFile;
|
|
8
|
+
const node_crypto_1 = require("node:crypto");
|
|
9
|
+
const node_fs_1 = require("node:fs");
|
|
10
|
+
const promises_1 = require("node:fs/promises");
|
|
11
|
+
const node_path_1 = require("node:path");
|
|
12
|
+
const node_stream_1 = require("node:stream");
|
|
13
|
+
const promises_2 = require("node:stream/promises");
|
|
14
|
+
const errors_1 = require("../errors");
|
|
15
|
+
function safeFileName(name) {
|
|
16
|
+
return name.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '') || 'file';
|
|
17
|
+
}
|
|
18
|
+
function extensionFromUrl(url, fallback) {
|
|
19
|
+
if (!URL.canParse(url))
|
|
20
|
+
return fallback;
|
|
21
|
+
const ext = (0, node_path_1.extname)(new URL(url).pathname).toLowerCase();
|
|
22
|
+
return /^\.[a-z0-9]{1,5}$/.test(ext) ? ext : fallback;
|
|
23
|
+
}
|
|
24
|
+
function resultFilePath(url, dir, baseName, fallbackExt) {
|
|
25
|
+
return (0, node_path_1.join)(dir, safeFileName(baseName) + extensionFromUrl(url, fallbackExt));
|
|
26
|
+
}
|
|
27
|
+
async function exists(path) {
|
|
28
|
+
try {
|
|
29
|
+
await (0, promises_1.access)(path);
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const inflight = new Map();
|
|
37
|
+
exports.SAVED_LIST_NAME = '.ai84-saved.json';
|
|
38
|
+
const savedLists = new Map();
|
|
39
|
+
const savedListWrites = new Map();
|
|
40
|
+
function partialPath(target) {
|
|
41
|
+
return `${target}.${process.pid}-${(0, node_crypto_1.randomBytes)(4).toString('hex')}.part`;
|
|
42
|
+
}
|
|
43
|
+
async function readSavedList(dir) {
|
|
44
|
+
try {
|
|
45
|
+
const parsed = JSON.parse(await (0, promises_1.readFile)((0, node_path_1.join)(dir, exports.SAVED_LIST_NAME), 'utf8'));
|
|
46
|
+
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
47
|
+
return new Map(Object.entries(parsed).filter((entry) => {
|
|
48
|
+
return typeof entry[1] === 'string';
|
|
49
|
+
}));
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
catch { }
|
|
53
|
+
return new Map();
|
|
54
|
+
}
|
|
55
|
+
function savedList(dir) {
|
|
56
|
+
const known = savedLists.get(dir);
|
|
57
|
+
if (known !== undefined)
|
|
58
|
+
return known;
|
|
59
|
+
const loaded = readSavedList(dir);
|
|
60
|
+
savedLists.set(dir, loaded);
|
|
61
|
+
return loaded;
|
|
62
|
+
}
|
|
63
|
+
async function rememberSaved(dir, name, link) {
|
|
64
|
+
const list = await savedList(dir);
|
|
65
|
+
list.set(name, link);
|
|
66
|
+
const write = (savedListWrites.get(dir) ?? Promise.resolve()).then(async () => {
|
|
67
|
+
const path = (0, node_path_1.join)(dir, exports.SAVED_LIST_NAME);
|
|
68
|
+
const partial = partialPath(path);
|
|
69
|
+
try {
|
|
70
|
+
await (0, promises_1.writeFile)(partial, JSON.stringify(Object.fromEntries(list), null, 1));
|
|
71
|
+
await (0, promises_1.rename)(partial, path);
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
await (0, promises_1.rm)(partial, { force: true });
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
savedListWrites.set(dir, write);
|
|
78
|
+
await write;
|
|
79
|
+
}
|
|
80
|
+
async function download(client, url, target, replaceOnChange) {
|
|
81
|
+
const dir = (0, node_path_1.dirname)(target);
|
|
82
|
+
const name = (0, node_path_1.basename)(target);
|
|
83
|
+
const link = new URL(url).pathname;
|
|
84
|
+
if (replaceOnChange) {
|
|
85
|
+
if ((await savedList(dir)).get(name) === link && (await exists(target)))
|
|
86
|
+
return target;
|
|
87
|
+
}
|
|
88
|
+
else if (await exists(target)) {
|
|
89
|
+
return target;
|
|
90
|
+
}
|
|
91
|
+
const res = await client.download(url);
|
|
92
|
+
if (res.body === null)
|
|
93
|
+
throw new errors_1.ApiError(res.status, 'The result file was empty.', null, null);
|
|
94
|
+
const partial = partialPath(target);
|
|
95
|
+
try {
|
|
96
|
+
await (0, promises_2.pipeline)(node_stream_1.Readable.fromWeb(res.body), (0, node_fs_1.createWriteStream)(partial));
|
|
97
|
+
await (0, promises_1.rename)(partial, target);
|
|
98
|
+
}
|
|
99
|
+
catch (err) {
|
|
100
|
+
await (0, promises_1.rm)(partial, { force: true });
|
|
101
|
+
throw err;
|
|
102
|
+
}
|
|
103
|
+
if (replaceOnChange)
|
|
104
|
+
await rememberSaved(dir, name, link);
|
|
105
|
+
return target;
|
|
106
|
+
}
|
|
107
|
+
async function saveResultFile(client, url, dir, baseName, fallbackExt, replaceOnChange = false) {
|
|
108
|
+
if (!URL.canParse(url)) {
|
|
109
|
+
throw new Error('The file link is not ready yet. Ask for the result again to get a fresh link.');
|
|
110
|
+
}
|
|
111
|
+
const target = resultFilePath(url, dir, baseName, fallbackExt);
|
|
112
|
+
const running = inflight.get(target);
|
|
113
|
+
if (running !== undefined)
|
|
114
|
+
return running;
|
|
115
|
+
const job = (0, promises_1.mkdir)(dir, { recursive: true }).then(() => download(client, url, target, replaceOnChange));
|
|
116
|
+
inflight.set(target, job);
|
|
117
|
+
job.then(() => inflight.delete(target), () => inflight.delete(target));
|
|
118
|
+
return job;
|
|
119
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CHUNKED_UPLOAD_THRESHOLD_BYTES = exports.FILE_RULES = void 0;
|
|
4
|
+
exports.inspectLocalFile = inspectLocalFile;
|
|
5
|
+
exports.fileBlob = fileBlob;
|
|
6
|
+
exports.fileForm = fileForm;
|
|
7
|
+
exports.uploadInChunks = uploadInChunks;
|
|
8
|
+
const node_fs_1 = require("node:fs");
|
|
9
|
+
const promises_1 = require("node:fs/promises");
|
|
10
|
+
const node_os_1 = require("node:os");
|
|
11
|
+
const node_path_1 = require("node:path");
|
|
12
|
+
const zod_1 = require("zod");
|
|
13
|
+
const errors_1 = require("../errors");
|
|
14
|
+
const wait_1 = require("../jobs/wait");
|
|
15
|
+
const MB = 1024 * 1024;
|
|
16
|
+
exports.FILE_RULES = {
|
|
17
|
+
speech_to_text: {
|
|
18
|
+
extensions: [
|
|
19
|
+
'.mp3',
|
|
20
|
+
'.wav',
|
|
21
|
+
'.m4a',
|
|
22
|
+
'.flac',
|
|
23
|
+
'.ogg',
|
|
24
|
+
'.aac',
|
|
25
|
+
'.webm',
|
|
26
|
+
'.opus',
|
|
27
|
+
'.aiff',
|
|
28
|
+
'.mp4',
|
|
29
|
+
'.mov',
|
|
30
|
+
'.mkv',
|
|
31
|
+
],
|
|
32
|
+
maxBytes: 500 * MB,
|
|
33
|
+
},
|
|
34
|
+
dubbing: { extensions: ['.mp4', '.mov', '.mkv', '.mp3', '.wav', '.m4a'], maxBytes: 500 * MB },
|
|
35
|
+
voice_changer: { extensions: ['.mp3', '.wav', '.m4a'], maxBytes: 100 * MB },
|
|
36
|
+
clone_voice: { extensions: ['.mp3', '.m4a', '.wav', '.ogg', '.flac'], maxBytes: 20 * MB },
|
|
37
|
+
};
|
|
38
|
+
const MIME_TYPES = {
|
|
39
|
+
'.mp3': 'audio/mpeg',
|
|
40
|
+
'.wav': 'audio/wav',
|
|
41
|
+
'.m4a': 'audio/mp4',
|
|
42
|
+
'.flac': 'audio/flac',
|
|
43
|
+
'.ogg': 'audio/ogg',
|
|
44
|
+
'.aac': 'audio/aac',
|
|
45
|
+
'.webm': 'audio/webm',
|
|
46
|
+
'.opus': 'audio/opus',
|
|
47
|
+
'.aiff': 'audio/aiff',
|
|
48
|
+
'.mp4': 'video/mp4',
|
|
49
|
+
'.mov': 'video/quicktime',
|
|
50
|
+
'.mkv': 'video/x-matroska',
|
|
51
|
+
};
|
|
52
|
+
exports.CHUNKED_UPLOAD_THRESHOLD_BYTES = 50 * MB;
|
|
53
|
+
const MAX_CHUNK_ATTEMPTS = 3;
|
|
54
|
+
const chunkRetryDelayMs = (attempt) => (attempt === 1 ? 1_000 : 3_000);
|
|
55
|
+
const UPLOAD_TIMEOUT_MS = 30 * 60_000;
|
|
56
|
+
function formatSize(bytes) {
|
|
57
|
+
return `${Math.round((bytes / MB) * 10) / 10}MB`;
|
|
58
|
+
}
|
|
59
|
+
async function inspectLocalFile(filePath, kind) {
|
|
60
|
+
const expanded = filePath === '~' || filePath.startsWith('~/') || filePath.startsWith('~\\')
|
|
61
|
+
? (0, node_path_1.join)((0, node_os_1.homedir)(), filePath.slice(1))
|
|
62
|
+
: filePath;
|
|
63
|
+
if (!(0, node_path_1.isAbsolute)(expanded)) {
|
|
64
|
+
throw new errors_1.UserInputError(`file_path must be an absolute path, got "${filePath}".`);
|
|
65
|
+
}
|
|
66
|
+
let size;
|
|
67
|
+
try {
|
|
68
|
+
const info = await (0, promises_1.stat)(expanded);
|
|
69
|
+
if (!info.isFile())
|
|
70
|
+
throw new errors_1.UserInputError(`${expanded} is not a file.`);
|
|
71
|
+
size = info.size;
|
|
72
|
+
}
|
|
73
|
+
catch (err) {
|
|
74
|
+
if (err instanceof errors_1.UserInputError)
|
|
75
|
+
throw err;
|
|
76
|
+
throw new errors_1.UserInputError(`Cannot read ${expanded}: the file does not exist or is not readable.`);
|
|
77
|
+
}
|
|
78
|
+
const rule = exports.FILE_RULES[kind];
|
|
79
|
+
const ext = (0, node_path_1.extname)(expanded).toLowerCase();
|
|
80
|
+
const allowed = rule.extensions;
|
|
81
|
+
if (!allowed.includes(ext)) {
|
|
82
|
+
throw new errors_1.UserInputError(`Unsupported file type "${ext || 'none'}". Accepted: ${rule.extensions.join(', ')}.`);
|
|
83
|
+
}
|
|
84
|
+
if (size === 0)
|
|
85
|
+
throw new errors_1.UserInputError(`${expanded} is empty.`);
|
|
86
|
+
if (size > rule.maxBytes) {
|
|
87
|
+
throw new errors_1.UserInputError(`The file is ${formatSize(size)}, over the ${formatSize(rule.maxBytes)} limit.`);
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
path: expanded,
|
|
91
|
+
name: (0, node_path_1.basename)(expanded),
|
|
92
|
+
size,
|
|
93
|
+
mimeType: MIME_TYPES[ext] ?? 'application/octet-stream',
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
function fileBlob(file) {
|
|
97
|
+
return (0, node_fs_1.openAsBlob)(file.path, { type: file.mimeType });
|
|
98
|
+
}
|
|
99
|
+
async function fileForm(file, field, fields) {
|
|
100
|
+
const form = new FormData();
|
|
101
|
+
form.append(field, await fileBlob(file), file.name);
|
|
102
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
103
|
+
if (value !== undefined)
|
|
104
|
+
form.append(key, String(value));
|
|
105
|
+
}
|
|
106
|
+
return form;
|
|
107
|
+
}
|
|
108
|
+
const initSchema = zod_1.z.object({
|
|
109
|
+
upload_uuid: zod_1.z.string(),
|
|
110
|
+
chunk_size: zod_1.z.number().int().positive(),
|
|
111
|
+
total_chunks: zod_1.z.number().int().positive(),
|
|
112
|
+
});
|
|
113
|
+
const okSchema = zod_1.z.object({ success: zod_1.z.boolean().optional() });
|
|
114
|
+
async function uploadInChunks(client, file, service, { signal, onChunk, sleep = wait_1.defaultSleep } = {}) {
|
|
115
|
+
const init = await client.post('/v2/upload/init', initSchema, {
|
|
116
|
+
json: { file_name: file.name, file_size: file.size, mime_type: file.mimeType, service },
|
|
117
|
+
signal,
|
|
118
|
+
});
|
|
119
|
+
const blob = await fileBlob(file);
|
|
120
|
+
for (let index = 0; index < init.total_chunks; index++) {
|
|
121
|
+
const start = index * init.chunk_size;
|
|
122
|
+
const chunk = blob.slice(start, Math.min(start + init.chunk_size, file.size));
|
|
123
|
+
for (let attempt = 1;; attempt++) {
|
|
124
|
+
const form = new FormData();
|
|
125
|
+
form.append('chunk', chunk, file.name);
|
|
126
|
+
try {
|
|
127
|
+
await client.put(`/v2/upload/${init.upload_uuid}/chunk/${index}`, okSchema, {
|
|
128
|
+
form,
|
|
129
|
+
signal,
|
|
130
|
+
timeoutMs: UPLOAD_TIMEOUT_MS,
|
|
131
|
+
});
|
|
132
|
+
await onChunk?.(index + 1, init.total_chunks);
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
catch (err) {
|
|
136
|
+
const retryable = err instanceof errors_1.ApiError && (err.status === 0 || err.status >= 500);
|
|
137
|
+
if (!retryable || attempt >= MAX_CHUNK_ATTEMPTS || signal?.aborted)
|
|
138
|
+
throw err;
|
|
139
|
+
await sleep(chunkRetryDelayMs(attempt));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
await client.post(`/v2/upload/${init.upload_uuid}/complete`, okSchema, {
|
|
144
|
+
signal,
|
|
145
|
+
timeoutMs: UPLOAD_TIMEOUT_MS,
|
|
146
|
+
});
|
|
147
|
+
return init.upload_uuid;
|
|
148
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
const stdio_1 = require("@modelcontextprotocol/server/stdio");
|
|
5
|
+
const config_1 = require("./config");
|
|
6
|
+
const server_1 = require("./server");
|
|
7
|
+
async function main() {
|
|
8
|
+
const config = (0, config_1.loadConfig)();
|
|
9
|
+
const server = (0, server_1.createServer)(config);
|
|
10
|
+
await server.connect(new stdio_1.StdioServerTransport());
|
|
11
|
+
console.error(`ai84-mcp ready (API ${config.apiBaseUrl}, files saved to ${config.outputDir})`);
|
|
12
|
+
if (config.apiKey === null) {
|
|
13
|
+
console.error('AI84_API_KEY is not set: every tool will ask for it.');
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
main().catch(err => {
|
|
17
|
+
console.error(err instanceof Error ? err.message : err);
|
|
18
|
+
process.exit(1);
|
|
19
|
+
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.defaultSleep = void 0;
|
|
4
|
+
exports.isTerminal = isTerminal;
|
|
5
|
+
exports.pollDelayMs = pollDelayMs;
|
|
6
|
+
exports.waitForJob = waitForJob;
|
|
7
|
+
exports.normalizeStatus = normalizeStatus;
|
|
8
|
+
function isTerminal(status) {
|
|
9
|
+
return status === 'done' || status === 'failed';
|
|
10
|
+
}
|
|
11
|
+
function pollDelayMs(poll) {
|
|
12
|
+
return [2_000, 2_000, 3_000, 4_000][poll] ?? 5_000;
|
|
13
|
+
}
|
|
14
|
+
const defaultSleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
|
15
|
+
exports.defaultSleep = defaultSleep;
|
|
16
|
+
async function waitForJob(fetchState, options) {
|
|
17
|
+
const sleep = options.sleep ?? exports.defaultSleep;
|
|
18
|
+
const now = options.now ?? Date.now;
|
|
19
|
+
const deadline = now() + options.waitSeconds * 1_000;
|
|
20
|
+
for (let poll = 0;; poll++) {
|
|
21
|
+
const state = await fetchState();
|
|
22
|
+
if (isTerminal(state.status))
|
|
23
|
+
return { state, timedOut: false };
|
|
24
|
+
const delay = pollDelayMs(poll);
|
|
25
|
+
if (options.signal?.aborted || now() + delay > deadline)
|
|
26
|
+
return { state, timedOut: true };
|
|
27
|
+
await options.onPoll?.(poll + 1, state.status, state.progress);
|
|
28
|
+
await sleep(delay);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function normalizeStatus(status) {
|
|
32
|
+
switch (status.toLowerCase()) {
|
|
33
|
+
case 'done':
|
|
34
|
+
case 'completed':
|
|
35
|
+
return 'done';
|
|
36
|
+
case 'failed':
|
|
37
|
+
case 'error':
|
|
38
|
+
return 'failed';
|
|
39
|
+
case 'queued':
|
|
40
|
+
case 'pending':
|
|
41
|
+
return 'queued';
|
|
42
|
+
default:
|
|
43
|
+
return 'processing';
|
|
44
|
+
}
|
|
45
|
+
}
|