free-api-mcp-server 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/.env.example ADDED
@@ -0,0 +1,35 @@
1
+ # 复制为 .env 后按需修改;全部变量也可由进程环境注入(PM2/CLI 均可)
2
+
3
+ # 02 开放层地址(唯一上游)
4
+ FREE_API_BASE_URL=https://www.open-api.aiconvg.xin
5
+
6
+ # 传输形态:stdio | http
7
+ MCP_TRANSPORT=stdio
8
+
9
+ # stdio 模式必填:用户的许可证令牌(门户自助发牌获得)
10
+ # FREE_API_TOKEN=
11
+
12
+ # http 模式
13
+ MCP_HTTP_PORT=3210
14
+ # 允许的 Origin(逗号分隔;留空表示不校验,仅限自有反代之后使用)
15
+ # MCP_ALLOWED_ORIGINS=
16
+
17
+ # —— 试用层(仅托管 HTTP;stdio 不生效)——
18
+ # 内置试用许可证(走 CRM 发牌创建 free 档,仅服务端持有;不设置则试用关闭,无令牌一律 401)
19
+ # TRIAL_LICENSE_TOKEN=
20
+ # 试用额度(按 IP+能力计数):TTS 10 / ASR 5 / OCR 5(submit_asr_job 与 speech_to_text 共用 ASR 池)
21
+ # TRIAL_TTS_LIMIT=3
22
+ # TRIAL_ASR_LIMIT=2
23
+ # TRIAL_OCR_LIMIT=2
24
+ # 全平台当日试用总次数熔断
25
+ # TRIAL_DAILY_CAP=200
26
+ # 试用窗口期(小时,IP 首次试用后计时,期内不重发)
27
+ # TRIAL_TTL_HOURS=24
28
+ # Redis(fail-closed:不可用即拒绝试用,正式令牌不受影响)
29
+ # REDIS_URL=redis://127.0.0.1:6379
30
+ # REDIS_DB=1
31
+ # 注册引导链接
32
+ # TRIAL_SIGNUP_URL=https://www.free-api.aiconvg.xin
33
+
34
+ # 日志:debug | info | warn | error
35
+ LOG_LEVEL=info
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 aiconvg
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,90 @@
1
- # Temporary Holding Version
1
+ # free-api MCP Server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 把免费 / 付费的 **TTS · ASR · OCR · 多角色配音 · 视频转文字** 开放能力,以标准 MCP 工具暴露给任意 MCP 客户端(Trae / Claude / Cursor / 魔搭 Playground 等)。
4
+
5
+ 本服务是纯协议适配层:不存数据、不发牌、不做计费;上游为 `https://www.open-api.aiconvg.xin`,额度与计费都在上游按你的令牌结算。
6
+
7
+ ## 特性
8
+
9
+ - 运行于 Node.js,STDIO 协议(`npx -y free-api-mcp-server` 即可拉起);托管到云函数(如魔搭 / 阿里云函数计算)后会自动转 SSE 并带平台鉴权。
10
+ - **每个用户填自己的许可证令牌**(`FREE_API_TOKEN`),计费/额度归属各自账户,互不影响。
11
+ - 共 **13 个工具**(7 个免费能力 + 6 个付费能力)。
12
+
13
+ ## 13 个工具
14
+
15
+ | # | 工具 | 分组 | 计费 | 说明 |
16
+ |---|---|---|---|---|
17
+ | 1 | `list_voices` | 免费 | 否 | 可用音色白名单(免费开源音色);调 `text_to_speech` 前必查 |
18
+ | 2 | `get_account` | 免费 | 否 | 档位(free/paid)、当日额度用量、令牌有效期 |
19
+ | 3 | `text_to_speech` | 免费 | 占免费日额度(失败不扣) | 文本≤300 字符 → 可播 `audioUrl`(默认 24h 有效);`engine` 可选 standard/premium |
20
+ | 4 | `speech_to_text` | 免费 | 占免费日额度(失败不扣) | 同步短音频 ≤60s / ≤8MB |
21
+ | 5 | `submit_asr_job` | 免费 | 提交即占日额度,失败自动返还 | 长音频异步任务,返回 `taskId` |
22
+ | 6 | `get_asr_job` | 免费 | 否 | 轮询长音频任务(queued/running/done/failed) |
23
+ | 7 | `ocr_image` | 免费 | 占免费日额度(失败不扣) | 单图 ≤8MB;`mode=auto/full/structured` |
24
+ | 8 | `list_dubbing_voices` | 付费·配音 | 否(查询不计费) | 配音音色目录,返回 `creditsPerChar` |
25
+ | 9 | `dubbing_submit` | 付费·配音 | 按音色单价/字(失败不扣、取消全额解冻) | 多角色配音:`segments=[{voice,text}]`;小任务同步、大任务 202+`taskId` |
26
+ | 10 | `get_dubbing_task` | 付费·配音 | 否 | 轮询配音任务 |
27
+ | 11 | `cancel_dubbing_task` | 付费·配音 | 否 | 取消未完成任务,冻结积分立即解冻 |
28
+ | 12 | `submit_video_transcribe` | 付费·视频 | 转写稿 5 字 1 积分(失败全额解冻) | 抖音/B站/YouTube/快手/小红书/TikTok 链接或分享文案 → `taskId` |
29
+ | 13 | `get_video_transcribe` | 付费·视频 | 否 | 轮询视频转写(返回 text / markdown 分段 / 字数 / 实扣积分) |
30
+
31
+ > 「免费」= 标准引擎、按每日免费额度计量、不扣积分;「付费」= 按积分计费(配音按字、视频按字数)。查询/轮询类工具不计费。
32
+
33
+ ## 鉴权与配置
34
+
35
+ 先到 **https://www.free-api.aiconvg.xin** 注册获取免费许可证令牌(免费档每日 TTS 100 / ASR 50 / OCR 50 次),填入 `FREE_API_TOKEN`。
36
+
37
+ ```json
38
+ {
39
+ "mcpServers": {
40
+ "free-api": {
41
+ "command": "npx",
42
+ "args": ["-y", "free-api-mcp-server"],
43
+ "env": {
44
+ "FREE_API_BASE_URL": "https://www.open-api.aiconvg.xin",
45
+ "FREE_API_TOKEN": "<你的许可证令牌>"
46
+ }
47
+ }
48
+ }
49
+ }
50
+ ```
51
+
52
+ | 环境变量 | 必填 | 说明 |
53
+ |---|---|---|
54
+ | `FREE_API_TOKEN` | ✅ | 你的许可证令牌(用户各自填写) |
55
+ | `FREE_API_BASE_URL` | ✅ | 固定 `https://www.open-api.aiconvg.xin` |
56
+ | `MCP_TRANSPORT` | 默认 stdio | 托管场景保持 stdio(平台自动转 SSE) |
57
+ | `LOG_LEVEL` | 可选 | `debug/info/warn/error`,默认 info;日志走 stderr,stdout 只承载协议 |
58
+
59
+ 本地直跑:
60
+
61
+ ```bash
62
+ FREE_API_TOKEN=<你的令牌> FREE_API_BASE_URL=https://www.open-api.aiconvg.xin npx -y free-api-mcp-server
63
+ ```
64
+
65
+ ## 调用示例
66
+
67
+ - `list_voices { "lang": "zh" }`
68
+ - `text_to_speech { "text": "你好,欢迎使用", "voice": "zh_CN-huayan-medium", "speed": 1.0 }` → 返回 `audioUrl`
69
+ - `speech_to_text { "audioUrl": "https://example.com/a.mp3" }`
70
+ - `ocr_image { "imageUrl": "https://example.com/a.png", "mode": "full" }`
71
+ - `dubbing_submit { "segments": [{ "voice": "...", "text": "第一句" }, { "voice": "...", "text": "第二句" }] }`
72
+ - `submit_video_transcribe { "url": "https://v.douyin.com/xxxx/" }` → `get_video_transcribe { "taskId": "..." }`
73
+
74
+ > `audioUrl` / `imageUrl` / 视频链接必须是**公网可访问 URL**,本地文件路径不支持。
75
+
76
+ ## 额度与计费
77
+
78
+ - 免费档:每日 TTS 100 / ASR 50 / OCR 50 次(`get_account` 可查 used/limit/remaining)。
79
+ - 付费能力:配音按音色单价/字、视频转写稿 5 字 1 积分;预占—结算,按实际结算,失败/取消全额解冻。
80
+ - 失败不扣:上游失败自动返还/解冻。
81
+
82
+ ## 错误码
83
+
84
+ - `AUTH_REQUIRED`:令牌缺失/无效 → 引导注册。
85
+ - `INVALID_PARAM`:入参校验失败(本地拦截,不触上游)。
86
+ - `UPSTREAM_UNAVAILABLE`:上游网络不可达,稍后重试。
87
+
88
+ ## 许可
89
+
90
+ MIT,见 [LICENSE](LICENSE)。
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "free-api-mcp-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "mcpName": "io.github.aiconvg/free-api-mcp",
5
+ "type": "module",
6
+ "description": "MCP server exposing the free TTS/ASR/OCR open API (voices, tts, asr, ocr, account, dubbing, video) over stdio and Streamable HTTP",
7
+ "license": "MIT",
8
+ "author": "aiconvg",
9
+ "keywords": ["mcp", "model-context-protocol", "modelcontextprotocol", "tts", "asr", "ocr", "text-to-speech", "speech-to-text", "dubbing", "video-transcription", "ai"],
10
+ "homepage": "https://www.free-api.aiconvg.xin",
11
+ "repository": { "type": "git", "url": "git+https://github.com/aiconvg/free-api-mcp-server.git" },
12
+ "bugs": { "url": "https://github.com/aiconvg/free-api-mcp-server/issues" },
13
+ "main": "src/index.js",
14
+ "publishConfig": { "access": "public", "registry": "https://registry.npmjs.org" },
15
+ "bin": {
16
+ "free-api-mcp": "src/index.js"
17
+ },
18
+ "files": [
19
+ "src/",
20
+ "server.json",
21
+ "README.md",
22
+ ".env.example"
23
+ ],
24
+ "engines": {
25
+ "node": ">=20"
26
+ },
27
+ "scripts": {
28
+ "start": "node src/index.js",
29
+ "smoke": "node test/smoke.stdio.js",
30
+ "verify": "node scripts/verify.mjs",
31
+ "verify:live": "node scripts/verify.mjs --live"
32
+ },
33
+ "dependencies": {
34
+ "@modelcontextprotocol/sdk": "1.20.2",
35
+ "express": "4.21.2",
36
+ "redis": "4.7.0",
37
+ "zod": "3.25.76"
38
+ }
39
+ }
package/server.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-09-29/server.schema.json",
3
+ "name": "io.github.aiconvg/free-api-mcp",
4
+ "description": "Free API MCP server: text-to-speech, speech-to-text, ASR jobs, OCR, multi-voice dubbing and video transcription over the free open API. Per-user Bearer token; standard engine free.",
5
+ "version": "0.1.0",
6
+ "packages": [
7
+ {
8
+ "registryType": "npm",
9
+ "identifier": "free-api-mcp-server",
10
+ "version": "0.1.0",
11
+ "transport": {
12
+ "type": "stdio"
13
+ }
14
+ }
15
+ ],
16
+ "remotes": [
17
+ {
18
+ "type": "streamable-http",
19
+ "url": "https://www.open-api.aiconvg.xin/mcp"
20
+ }
21
+ ]
22
+ }
package/src/context.js ADDED
@@ -0,0 +1,46 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+
3
+ // 请求级上下文:HTTP 传输下由 Express 中间件写入 { token, trial },
4
+ // tool handler 读取。trial = { active, tool, remaining, limits, rollbackToken }。
5
+ // stdio 模式为单会话,启动时写入进程级默认令牌作为兜底。
6
+ // 禁止在 HTTP 路径用全局变量传令牌(并发会串号)。
7
+ export const requestContext = new AsyncLocalStorage();
8
+
9
+ let defaultToken = null;
10
+
11
+ export function setDefaultToken(token) {
12
+ defaultToken = token || null;
13
+ }
14
+
15
+ export function getRequestToken() {
16
+ const ctx = requestContext.getStore();
17
+ return ctx?.token || defaultToken;
18
+ }
19
+
20
+ export function getRequestTrial() {
21
+ const ctx = requestContext.getStore();
22
+ return ctx?.trial || null;
23
+ }
24
+
25
+ // 真实客户端 IP(HTTP 传输下由 http.js 逐请求写入,stdio 下为 null)。
26
+ // 用于回源头透传 X-Ca-Client-IP,让 BFF 的 openRate 能按真实用户分流。
27
+ export function getRequestClientIp() {
28
+ const ctx = requestContext.getStore();
29
+ return ctx?.clientIp || null;
30
+ }
31
+
32
+ export function log(level, msg, data = undefined) {
33
+ const entry = { ts: new Date().toISOString(), level, msg };
34
+ if (data) entry.data = data;
35
+ // stdio 传输下 stdout 是协议通道,日志只能走 stderr
36
+ process.stderr.write(JSON.stringify(entry) + '\n');
37
+ }
38
+
39
+ export const logger = {
40
+ debug: (msg, data) => {
41
+ if (process.env.LOG_LEVEL === 'debug') log('debug', msg, data);
42
+ },
43
+ info: (msg, data) => log('info', msg, data),
44
+ warn: (msg, data) => log('warn', msg, data),
45
+ error: (msg, data) => log('error', msg, data),
46
+ };
package/src/http.js ADDED
@@ -0,0 +1,115 @@
1
+ // HTTP 传输:Streamable HTTP + /healthz。
2
+ // 令牌:每次请求从 Authorization: Bearer 提取,用 AsyncLocalStorage 传给 handler(请求级隔离)。
3
+ // 试用:无令牌 + TRIAL_LICENSE_TOKEN 已配置 → 进入试用上下文(IP 计数),
4
+ // Redis 不可用时 fail-closed,只放行只读工具并提示注册。
5
+ import express from 'express';
6
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
7
+ import { requestContext, logger } from './context.js';
8
+ import { buildServer } from './server.js';
9
+ import { initTrialStore, trialStoreAvailable } from './lib/trialStore.js';
10
+ import { trialEnabled } from './lib/trial.js';
11
+
12
+ const PORT = Number(process.env.MCP_HTTP_PORT || 3210);
13
+ const ALLOWED_ORIGINS = (process.env.MCP_ALLOWED_ORIGINS || '')
14
+ .split(',').map((s) => s.trim()).filter(Boolean);
15
+
16
+ function extractBearer(req) {
17
+ const h = req.headers.authorization || '';
18
+ const m = /^Bearer\s+(.+)$/i.exec(h);
19
+ return m ? m[1].trim() : null;
20
+ }
21
+
22
+ // 真实客户端 IP 提取。信任边界:**只有当连接对端是本机回环**(自有反代 -> 本进程)
23
+ // 时才信任反代覆写的转发头——反代用 X-Real-IP 覆盖,客户端自带的 X-Real-IP/XFF 一律被盖掉、伪造不了。
24
+ // 非回环对端(理论上不应出现,端口只绑回环)一律直接用连接 IP,不信任任何头;
25
+ // 优先取 X-Real-IP,取不到再回退。
26
+ function isLoopback(addr) {
27
+ return addr === '127.0.0.1' || addr === '::1' || addr === '::ffff:127.0.0.1';
28
+ }
29
+ function normalizeIp(ip) {
30
+ let s = String(ip || '').trim();
31
+ if (s.startsWith('::ffff:')) s = s.slice(7);
32
+ return s;
33
+ }
34
+ export function clientIp(req) {
35
+ const remote = req.socket?.remoteAddress || 'unknown';
36
+ // 非回环对端:不信任任何转发头
37
+ if (!isLoopback(remote)) return normalizeIp(remote) || remote;
38
+ // 回环对端(自有反代):优先 X-Real-IP(上游覆写,不可伪造)
39
+ const xri = req.headers['x-real-ip'];
40
+ if (typeof xri === 'string' && xri.trim()) return normalizeIp(xri) || remote;
41
+ // 回退:兼容旧部署——XFF 末位为回环则取倒数第二位
42
+ const xff = req.headers['x-forwarded-for'];
43
+ if (typeof xff === 'string' && xff.length > 0) {
44
+ const parts = xff.split(',').map((s) => s.trim()).filter(Boolean);
45
+ const last = parts[parts.length - 1];
46
+ if (isLoopback(last)) return parts.length >= 2 ? normalizeIp(parts[parts.length - 2]) : remote;
47
+ // XFF 无回环尾:末位即真实客户端
48
+ if (parts.length >= 1) return normalizeIp(parts[parts.length - 1]);
49
+ }
50
+ return remote;
51
+ }
52
+
53
+ export async function runHttp() {
54
+ await initTrialStore();
55
+ const server = buildServer();
56
+ const app = express();
57
+ app.disable('x-powered-by');
58
+ app.use(express.json({ limit: '1mb' }));
59
+
60
+ app.get('/healthz', (_req, res) => {
61
+ res.json({
62
+ ok: true,
63
+ transport: 'http',
64
+ trial: trialEnabled() ? (trialStoreAvailable() ? 'ready' : 'degraded') : 'off',
65
+ });
66
+ });
67
+
68
+ // Origin 白名单(SDK 只在 DNS rebinding 校验里做 Host,Origin 需自行把关)
69
+ app.use('/mcp', (req, res, next) => {
70
+ const origin = req.headers.origin;
71
+ if (origin && ALLOWED_ORIGINS.length > 0 && !ALLOWED_ORIGINS.includes(origin)) {
72
+ return res.status(403).json({ error: 'origin not allowed' });
73
+ }
74
+ next();
75
+ });
76
+
77
+ app.all('/mcp', (req, res) => {
78
+ const token = extractBearer(req);
79
+ // 无令牌:试用启用且存储可用 → 试用上下文;否则放行让 handler 抛 AUTH_REQUIRED(引导注册)
80
+ let trialCtx = null;
81
+ if (!token && trialEnabled()) {
82
+ if (trialStoreAvailable()) {
83
+ trialCtx = { active: true, ip: clientIp(req) };
84
+ } // Redis 不可用:fail-closed,不计费工具会被闸门拦下引导注册
85
+ }
86
+ requestContext.run({ token, trial: trialCtx, clientIp: clientIp(req) }, async () => {
87
+ // 每请求一个传输实例(无会话态,最简且并发安全)
88
+ const transport = new StreamableHTTPServerTransport({
89
+ sessionIdGenerator: undefined,
90
+ enableJsonResponse: true,
91
+ });
92
+ res.on('close', () => transport.close());
93
+ try {
94
+ await server.connect(transport);
95
+ await transport.handleRequest(req, res, req.body);
96
+ } catch (e) {
97
+ logger.error('http.request_error', { err: String(e?.stack || e) });
98
+ if (!res.headersSent) {
99
+ res.status(500).json({ error: 'internal error' });
100
+ }
101
+ }
102
+ });
103
+ });
104
+
105
+ await new Promise((resolve, reject) => {
106
+ // 只监听回环:托管端点仅经反代对外,避免端口直接暴露公网
107
+ const srv = app.listen(PORT, '127.0.0.1', () => {
108
+ logger.info('http.started', { port: PORT, origins: ALLOWED_ORIGINS.length || 'any' });
109
+ resolve();
110
+ });
111
+ srv.on('error', reject);
112
+ });
113
+ // 阻止进程退出:保持事件循环活跃(nohup/后台启动时无活跃句柄会立即 exit)
114
+ setInterval(() => {}, 1 << 30);
115
+ }
package/src/index.js ADDED
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env node
2
+ // 入口:按 MCP_TRANSPORT 选择 stdio 或 http。
3
+ // stdio:令牌来自 FREE_API_TOKEN(进程环境,客户端配置里注入)。
4
+ // http:令牌来自每次请求的 Authorization: Bearer <token>(见 http.js 中间件)。
5
+ import { runStdio } from './stdio.js';
6
+ import { runHttp } from './http.js';
7
+
8
+ const transport = (process.env.MCP_TRANSPORT || 'stdio').toLowerCase();
9
+
10
+ if (transport === 'stdio') {
11
+ if (!process.env.FREE_API_TOKEN) {
12
+ process.stderr.write('[fatal] stdio 模式必须设置 FREE_API_TOKEN 环境变量\n');
13
+ process.exit(1);
14
+ }
15
+ runStdio(process.env.FREE_API_TOKEN).catch((e) => {
16
+ process.stderr.write(`[fatal] ${e?.stack || e}\n`);
17
+ process.exit(1);
18
+ });
19
+ } else if (transport === 'http') {
20
+ runHttp().catch((e) => {
21
+ process.stderr.write(`[fatal] ${e?.stack || e}\n`);
22
+ process.exit(1);
23
+ });
24
+ } else {
25
+ process.stderr.write(`[fatal] 未知的 MCP_TRANSPORT: ${transport}(支持 stdio | http)\n`);
26
+ process.exit(1);
27
+ }
@@ -0,0 +1,88 @@
1
+ import { getRequestToken, getRequestTrial, getRequestClientIp, logger } from '../context.js';
2
+ import { trialToken } from './trial.js';
3
+
4
+ // 上游错误 envelope 见 openapi 契约 components.schemas.Error:
5
+ // { code, message, requestId, retryAfter?, resetAt?, quota? }
6
+ export class UpstreamError extends Error {
7
+ constructor(payload, httpStatus) {
8
+ super(payload?.message || 'upstream error');
9
+ this.name = 'UpstreamError';
10
+ this.code = payload?.code || 'INTERNAL_ERROR';
11
+ this.requestId = payload?.requestId || null;
12
+ this.retryAfter = payload?.retryAfter ?? null;
13
+ this.resetAt = payload?.resetAt ?? null;
14
+ this.quota = payload?.quota ?? null;
15
+ this.httpStatus = httpStatus;
16
+ }
17
+ }
18
+
19
+ export class AuthRequiredError extends Error {
20
+ constructor(message) {
21
+ super(message);
22
+ this.name = 'AuthRequiredError';
23
+ this.code = 'AUTH_REQUIRED';
24
+ }
25
+ }
26
+
27
+ const BASE_URL = (process.env.FREE_API_BASE_URL || '').replace(/\/+$/, '');
28
+ // 02 反代 60s 超时不可调,客户端不得自设更短超时掐断长合成
29
+ const REQUEST_TIMEOUT_MS = 75_000;
30
+
31
+ function authHeaders() {
32
+ // 试用模式:无用户令牌,改用内置试用许可证(仅托管 HTTP 会出现)
33
+ const trial = getRequestTrial();
34
+ const token = getRequestToken() || (trial?.active ? trialToken() : null);
35
+ if (!token) throw new AuthRequiredError('未配置访问令牌:请先注册并获取免费许可证,再配置 Bearer token 后重试。');
36
+ // 主契约 licenseToken 通道:专用头优先;Bearer 形态生产已打开
37
+ return { 'X-License-Token': token };
38
+ }
39
+
40
+ async function callApi(method, path, body = undefined) {
41
+ if (!BASE_URL) throw new AuthRequiredError('服务端未配置 FREE_API_BASE_URL');
42
+ const headers = { ...authHeaders() };
43
+ // 透传真实客户端 IP 给 BFF:BFF openRate.clientIp 优先认 X-Ca-Client-IP,
44
+ // 用于「仅 MCP 应用(app26)按真实用户 5/s 分流」。stdio 无请求上下文时不加。
45
+ const clientIp = getRequestClientIp();
46
+ if (clientIp) headers['X-Ca-Client-IP'] = clientIp;
47
+ const opts = { method, headers, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) };
48
+ if (body !== undefined) {
49
+ headers['Content-Type'] = 'application/json';
50
+ opts.body = JSON.stringify(body);
51
+ }
52
+ logger.info('upstream.call', { method, path });
53
+ let res;
54
+ try {
55
+ res = await fetch(`${BASE_URL}${path}`, opts);
56
+ } catch (e) {
57
+ logger.error('upstream.network_error', { path, err: String(e?.cause || e) });
58
+ const err = new UpstreamError({ code: 'UPSTREAM_UNAVAILABLE', message: '上游网络不可达,请稍后重试' }, 503);
59
+ err.retryable = true;
60
+ throw err;
61
+ }
62
+ let payload = null;
63
+ try {
64
+ payload = await res.json();
65
+ } catch {
66
+ payload = null;
67
+ }
68
+ if (!res.ok) throw new UpstreamError(payload, res.status);
69
+ return payload;
70
+ }
71
+
72
+ export const api = {
73
+ listVoices: (lang) => callApi('GET', `/v1/voices${lang ? `?lang=${encodeURIComponent(lang)}` : ''}`),
74
+ getAccount: () => callApi('GET', '/v1/account'),
75
+ // 计费端点:失败不消耗额度(后端自动返还预占);本层不做自动重试
76
+ tts: ({ text, voice, speed, format, engine }) => callApi('POST', '/v1/tts', { text, voice, ...(speed !== undefined ? { speed } : {}), ...(format ? { format } : {}), ...(engine ? { engine } : {}) }),
77
+ asrSync: ({ audioUrl, lang, engine }) => callApi('POST', '/v1/asr', { audioUrl, ...(lang ? { lang } : {}), ...(engine ? { engine } : {}) }),
78
+ asrSubmit: ({ audioUrl, lang, engine }) => callApi('POST', '/v1/asr/jobs', { audioUrl, ...(lang ? { lang } : {}), ...(engine ? { engine } : {}) }),
79
+ asrGet: (taskId) => callApi('GET', `/v1/asr/jobs/${encodeURIComponent(taskId)}`),
80
+ ocr: ({ imageUrl, mode }) => callApi('POST', '/v1/ocr', { imageUrl, ...(mode ? { mode } : {}) }),
81
+ // ── 付费能力(积分计费,2026-11-06 接入):失败同样不自动重试 ──
82
+ dubbingVoices: () => callApi('GET', '/v1/dubbing/voices'),
83
+ dubbingSubmit: ({ segments }) => callApi('POST', '/v1/dubbing', { segments }),
84
+ dubbingGet: (taskId) => callApi('GET', `/v1/dubbing/tasks/${encodeURIComponent(taskId)}`),
85
+ dubbingCancel: (taskId) => callApi('POST', `/v1/dubbing/tasks/${encodeURIComponent(taskId)}/cancel`, {}),
86
+ videoSubmit: (url) => callApi('POST', '/v1/video/transcribe', { url }),
87
+ videoGet: (taskId) => callApi('GET', `/v1/video/transcribe/${encodeURIComponent(taskId)}`),
88
+ };
@@ -0,0 +1,42 @@
1
+ import { UpstreamError } from './apiClient.js';
2
+
3
+ // MCP 的 isError 内容只放文本;把上游错误码翻译成 Agent 可直接执行的下一步动作。
4
+ const HINTS = {
5
+ UNAUTHORIZED: '令牌无效或缺失。请到 https://www.free-api.aiconvg.xin 注册获取免费许可证,并在客户端配置 Authorization: Bearer <token> 后重试。',
6
+ VOICE_NOT_ALLOWED: '音色不在开放白名单。先调用 list_voices 查看可用音色,再从中选择 voice 参数。',
7
+ INVALID_PARAM: '入参不合法。请检查必填字段与取值范围(TTS 文本 ≤300 字符、speed 0.5–2.0)。不要使用本地文件路径,音频/图片必须是公网可访问 URL。',
8
+ TEXT_TOO_LONG: '文本超过 300 字符上限(付费音色硬限,2026-11-09 由 2000 收敛)。请分段合成后拼接播放。',
9
+ PAYLOAD_TOO_LARGE: '资源超过上限(同步 ASR/OCR ≤8MB;异步 submit_asr_job ≤50MB)。请压缩后重新上传,或改用更短的音频(同步 ASR 还要求 ≤60 秒,长音频改用 submit_asr_job)。',
10
+ RATE_LIMITED: '触发限速。按 retryAfter 秒数等待后重试。',
11
+ QUOTA_EXCEEDED: '当日额度用尽。额度按能力维度(tts/asr/ocr)与日总量分别封顶,以 quota 中被撑爆的维度为准;本会话请停止计费调用,额度将于 resetAt(北京时间 08:00)恢复。补充方案:① POST /v1/quota-pack 购买当日额度包(1,000 积分 = +50 次,tts/asr/ocr 通用,每日最多 2 包,当日有效)——标准引擎立即恢复,无需换引擎;② 付费引擎(premium)按积分计费、不占日额度——登录 https://www.free-api.aiconvg.xin 顶部「充值」购买积分后,请求中传 engine:"premium"(仅付费档可用);③ 等待次日重置后继续使用标准引擎。',
12
+ UPSTREAM_OVERLOAD: '上游过载。可稍后按 retryAfter 重试(不计费工具可重试,计费工具由用户决定)。',
13
+ UPSTREAM_UNAVAILABLE: '上游暂不可用。可稍后重试(不计费工具可重试,计费工具由用户决定)。',
14
+ FEATURE_DISABLED: '该能力需要付费档位。免费/试用额度仅限标准免费引擎,不能调用 premium。',
15
+ NOT_FOUND: '任务或产物不存在(异步任务结果保留 24 小时)。请核对 taskId。',
16
+ APP_DISABLED: '应用已被禁用,请联系平台。',
17
+ INSUFFICIENT_CREDITS: '积分余额不足(付费能力按积分计费:多角色配音按音色单价/字、视频转写每 5 字 1 积分)。请登录 https://www.free-api.aiconvg.xin 顶部「充值」购买积分(1 元起,10 元赠 5%、50 元赠 10%)后重试;当前余额可用 get_account 查看。提示:先用 list_dubbing_voices 选免费开源音色(0 积分)可零成本完成配音。',
18
+ };
19
+
20
+ export function errorToMcpContent(err) {
21
+ if (err instanceof UpstreamError) {
22
+ const lines = [`[${err.code}] ${err.message}`, '', HINTS[err.code] || ''].filter(Boolean);
23
+ if (err.retryAfter != null) lines.push(`retryAfter: ${err.retryAfter}s`);
24
+ if (err.resetAt) lines.push(`resetAt: ${err.resetAt}`);
25
+ if (err.quota) lines.push(`quota: ${JSON.stringify(err.quota)}`);
26
+ if (err.requestId) lines.push(`requestId: ${err.requestId}`);
27
+ return { isError: true, content: [{ type: 'text', text: lines.join('\n') }] };
28
+ }
29
+ if (err?.code === 'AUTH_REQUIRED') {
30
+ return {
31
+ isError: true,
32
+ content: [{
33
+ type: 'text',
34
+ text: `[AUTH_REQUIRED] ${err.message}\n注册入口:https://www.free-api.aiconvg.xin\n配置示例(客户端 MCP 配置):\n"env": { "FREE_API_TOKEN": "<你的令牌>" }`,
35
+ }],
36
+ };
37
+ }
38
+ return {
39
+ isError: true,
40
+ content: [{ type: 'text', text: `[INTERNAL_ERROR] ${err?.message || String(err)}` }],
41
+ };
42
+ }
@@ -0,0 +1,59 @@
1
+ import { logger } from '../context.js';
2
+ import { readFileSync } from 'node:fs';
3
+
4
+ // 试用层(仅托管 HTTP):无 Bearer 令牌的请求改用内置试用许可证调上游,
5
+ // 计数与封顶在 trialStore(Redis,fail-closed)。stdio 模式不经过这里。
6
+
7
+ const SIGNUP_URL = process.env.TRIAL_SIGNUP_URL || 'https://www.free-api.aiconvg.xin';
8
+
9
+ // 支持两种配置方式:
10
+ // 1) TRIAL_LICENSE_TOKEN=<token 字面量>(.env 或环境变量)
11
+ // 2) TRIAL_LICENSE_TOKEN_FILE=<路径>(如 data/.trial_token,600 权限,gitignore)
12
+ // 文件方式避免令牌进入 pm2 dump / .env 等持久面。
13
+ function loadTrialToken() {
14
+ if (process.env.TRIAL_LICENSE_TOKEN) return process.env.TRIAL_LICENSE_TOKEN;
15
+ const f = process.env.TRIAL_LICENSE_TOKEN_FILE;
16
+ if (!f) return '';
17
+ try {
18
+ return readFileSync(f, 'utf8').trim();
19
+ } catch {
20
+ console.error('[trial] TRIAL_LICENSE_TOKEN_FILE 无法读取:', f);
21
+ return '';
22
+ }
23
+ }
24
+
25
+ export function trialEnabled() {
26
+ return !!loadTrialToken();
27
+ }
28
+
29
+ export function trialToken() {
30
+ return loadTrialToken();
31
+ }
32
+
33
+ export function trialLimits() {
34
+ return {
35
+ text_to_speech: Number(process.env.TRIAL_TTS_LIMIT || 10),
36
+ speech_to_text: Number(process.env.TRIAL_ASR_LIMIT || 5),
37
+ submit_asr_job: Number(process.env.TRIAL_ASR_LIMIT || 5),
38
+ ocr_image: Number(process.env.TRIAL_OCR_LIMIT || 5),
39
+ };
40
+ }
41
+
42
+ export const TRIALABLE_TOOLS = new Set(Object.keys(trialLimits()));
43
+
44
+ // 试用模式的错误与引导文案(AUTH_REQUIRED 为 MCP 本地码,02 不返回它)
45
+ export function trialExhaustedMessage(used, limit) {
46
+ return [
47
+ '[AUTH_REQUIRED] 免费试用次数已用完' + (limit != null ? `(本能力上限 ${limit} 次)` : '') + '。',
48
+ `注册免费账号即可获得每日额度(TTS 100 / ASR 50 / OCR 50 次):${SIGNUP_URL}`,
49
+ '拿到令牌后,在客户端 MCP 配置的 env 里设置 FREE_API_TOKEN 即可继续使用。',
50
+ ].join('\n');
51
+ }
52
+
53
+ export function trialRemainingNote(tool, remaining, limits) {
54
+ return `(试用模式:${tool} 剩余 ${remaining} 次;注册后每日额度更高 — ${SIGNUP_URL})`;
55
+ }
56
+
57
+ export function logTrial(event, data = {}) {
58
+ logger.info(`trial.${event}`, data);
59
+ }
@@ -0,0 +1,91 @@
1
+ import { createClient } from 'redis';
2
+ import { createHash } from 'node:crypto';
3
+ import { logger } from '../context.js';
4
+
5
+ // 试用计数(仅托管 HTTP):
6
+ // trial:ip:<sha256(ip)> → 该 IP 的试用资格(首次置 1,TTL = TRIAL_TTL_HOURS)
7
+ // trial:use:<ipHash>:<tool> → 该 IP 按能力已用次数(TTL 同上)
8
+ // trial:global:<yyyymmdd> → 全平台当日试用总次数(TTL 48h)
9
+ // 设计约束:
10
+ // - fail-closed:Redis 不可用 → 拒绝试用(正式令牌路径不经过这里,不受影响)
11
+ // - 以 IP 为主键、会话为辅:客户端重连换 sessionId 也刷不了额度
12
+ // - INCR 原子扣减,先扣后调上游;上游失败由调用方回滚(rollbackUse)
13
+
14
+ const TTL_MS = Number(process.env.TRIAL_TTL_HOURS || 24) * 3600 * 1000;
15
+
16
+ let client = null;
17
+
18
+ function ipHash(ip) {
19
+ return createHash('sha256').update(ip).digest('hex').slice(0, 24);
20
+ }
21
+
22
+ export async function initTrialStore() {
23
+ const url = process.env.REDIS_URL;
24
+ if (!url) {
25
+ logger.warn('trial.disabled', { reason: 'REDIS_URL not set' });
26
+ return null;
27
+ }
28
+ client = createClient({ url, database: Number(process.env.REDIS_DB || 1) });
29
+ client.on('error', (e) => logger.error('trial.redis_error', { err: String(e?.message || e) }));
30
+ await client.connect();
31
+ logger.info('trial.redis_connected', {});
32
+ return client;
33
+ }
34
+
35
+ export function trialStoreAvailable() {
36
+ return !!client && client.isOpen;
37
+ }
38
+
39
+ // 返回 { allowed, remaining, usedThisCall, limits } 或 { allowed: false, reason }
40
+ export async function consumeTrial(ip, tool, limits) {
41
+ if (!trialStoreAvailable()) return { allowed: false, reason: 'store_unavailable' };
42
+ const h = ipHash(ip);
43
+ try {
44
+ // IP 试用资格键:首次写入(TTL=窗口期),期内不重发
45
+ await client.set(`trial:ip:${h}`, '1', { NX: true, PX: TTL_MS });
46
+ const limit = limits[tool];
47
+ if (!limit) return { allowed: false, reason: 'tool_not_trialable' };
48
+
49
+ // 全平台日上限(先查后占,占不中直接拒)
50
+ const day = new Date().toISOString().slice(0, 10).replace(/-/g, '');
51
+ const gKey = `trial:global:${day}`;
52
+ const gUsed = await client.incr(gKey);
53
+ if (gUsed === 1) await client.expire(gKey, 48 * 3600);
54
+ const dailyCap = Number(process.env.TRIAL_DAILY_CAP || 200);
55
+ if (gUsed > dailyCap) {
56
+ await client.decr(gKey);
57
+ return { allowed: false, reason: 'global_cap' };
58
+ }
59
+
60
+ const uKey = `trial:use:${h}:${tool}`;
61
+ const used = await client.incr(uKey);
62
+ if (used === 1) await client.expire(uKey, TTL_MS);
63
+ if (used > limit) {
64
+ await client.decr(uKey);
65
+ await client.decr(gKey);
66
+ return { allowed: false, reason: 'exhausted', used: used - 1, limit };
67
+ }
68
+ return {
69
+ allowed: true,
70
+ usedThisCall: used,
71
+ remaining: Math.max(0, limit - used),
72
+ limits,
73
+ ipKey: uKey,
74
+ gKey,
75
+ };
76
+ } catch (e) {
77
+ logger.error('trial.consume_error', { err: String(e?.message || e) });
78
+ return { allowed: false, reason: 'store_unavailable' };
79
+ }
80
+ }
81
+
82
+ // 上游调用失败时回滚本次扣减(额度在后端本就"失败不扣",MCP 试用计数保持同口径)
83
+ export async function rollbackTrial(token) {
84
+ if (!trialStoreAvailable() || !token) return;
85
+ try {
86
+ await client.decr(token.ipKey);
87
+ await client.decr(token.gKey);
88
+ } catch (e) {
89
+ logger.warn('trial.rollback_error', { err: String(e?.message || e) });
90
+ }
91
+ }
package/src/server.js ADDED
@@ -0,0 +1,151 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import {
3
+ ListToolsRequestSchema,
4
+ CallToolRequestSchema,
5
+ } from '@modelcontextprotocol/sdk/types.js';
6
+ import { getRequestTrial, logger } from './context.js';
7
+ import { errorToMcpContent } from './lib/errors.js';
8
+ import { consumeTrial, rollbackTrial, trialStoreAvailable } from './lib/trialStore.js';
9
+ import { TRIALABLE_TOOLS, trialLimits, trialExhaustedMessage, trialRemainingNote, logTrial } from './lib/trial.js';
10
+ import { listVoicesTool } from './tools/voices.js';
11
+ import { getAccountTool } from './tools/account.js';
12
+ import { ttsTool } from './tools/tts.js';
13
+ import { asrSyncTool } from './tools/asrSync.js';
14
+ import { asrSubmitTool } from './tools/asrSubmit.js';
15
+ import { asrGetTool } from './tools/asrGet.js';
16
+ import { ocrTool } from './tools/ocr.js';
17
+ import { dubbingVoicesTool, dubbingSubmitTool, dubbingGetTool, dubbingCancelTool } from './tools/dubbing.js';
18
+ import { videoSubmitTool, videoGetTool } from './tools/video.js';
19
+ import { readFileSync } from 'node:fs';
20
+ import { fileURLToPath } from 'node:url';
21
+
22
+ // 版本单一事实源:以 package.json.version 为准,避免运行时 Server 版本与包版本漂移
23
+ // (此前此处写死 '0.2.0',与 package.json/server.json 的 0.1.0 不一致)。
24
+ const PKG_VERSION = JSON.parse(
25
+ readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8'),
26
+ ).version;
27
+
28
+ // 工具注册表:每个工具 { name, description, inputSchema, zodSchema, handler }
29
+ // handler 只依赖 apiClient,不 import SDK 类型,便于以后换传输或被 Skill 复用。
30
+ // 注:GET /v1/artifacts/{fileName} 有意不映射(audioUrl 已是带签名的公网直链,
31
+ // 且该端点返回二进制流,不适合文本型工具结果)——见 docs/工具拆分说明.md。
32
+ // 2026-11-06:付费能力接入(多角色配音 / 视频链接转文字,积分计费,不在试用层)。
33
+ export const TOOLS = [
34
+ listVoicesTool,
35
+ getAccountTool,
36
+ ttsTool,
37
+ asrSyncTool,
38
+ asrSubmitTool,
39
+ asrGetTool,
40
+ ocrTool,
41
+ dubbingVoicesTool,
42
+ dubbingSubmitTool,
43
+ dubbingGetTool,
44
+ dubbingCancelTool,
45
+ videoSubmitTool,
46
+ videoGetTool,
47
+ ];
48
+
49
+ export const TOOL_COUNT = TOOLS.length;
50
+
51
+ // MCP 工具注解(tools/list 的 annotations 字段,平台自动发现/审核依赖):
52
+ // readOnlyHint:只读工具=true(不改外部状态);openWorldHint=true(均访问外部开放 API / 公网 URL);
53
+ // destructiveHint 全部=false(无破坏性删除);idempotentHint 按语义:只读/取消类可重复=true,计费/建任务类=false。
54
+ const READ_ONLY_TOOLS = new Set([
55
+ 'list_voices', 'get_account', 'list_dubbing_voices',
56
+ 'get_asr_job', 'get_dubbing_task', 'get_video_transcribe',
57
+ ]);
58
+ const IDEMPOTENT_TOOLS = new Set([...READ_ONLY_TOOLS, 'cancel_dubbing_task']);
59
+ export const TOOL_ANNOTATIONS = Object.fromEntries(
60
+ TOOLS.map((t) => [t.name, {
61
+ readOnlyHint: READ_ONLY_TOOLS.has(t.name),
62
+ destructiveHint: false,
63
+ idempotentHint: IDEMPOTENT_TOOLS.has(t.name),
64
+ openWorldHint: true,
65
+ }]),
66
+ );
67
+
68
+ export function buildServer() {
69
+ const server = new Server(
70
+ { name: 'free-api-mcp', version: PKG_VERSION },
71
+ { capabilities: { tools: {} } },
72
+ );
73
+
74
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
75
+ tools: TOOLS.map((t) => ({
76
+ name: t.name,
77
+ title: t.title,
78
+ description: t.description,
79
+ inputSchema: t.inputSchema,
80
+ annotations: TOOL_ANNOTATIONS[t.name],
81
+ })),
82
+ }));
83
+
84
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
85
+ const name = req.params?.name;
86
+ const args = req.params?.arguments || {};
87
+ const tool = TOOLS.find((t) => t.name === name);
88
+ if (!tool) {
89
+ return {
90
+ isError: true,
91
+ content: [{ type: 'text', text: `[INVALID_PARAM] 未知工具: ${name}` }],
92
+ };
93
+ }
94
+ const parsed = tool.zodSchema.safeParse(args);
95
+ if (!parsed.success) {
96
+ return {
97
+ isError: true,
98
+ content: [{
99
+ type: 'text',
100
+ text: `[INVALID_PARAM] 入参校验失败: ${parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'} ${i.message}`).join('; ')}`,
101
+ }],
102
+ };
103
+ }
104
+
105
+ // 试用闸门(仅托管 HTTP 无令牌请求):计费工具先扣试用计数,失败回滚
106
+ const trial = getRequestTrial();
107
+ let trialTicket = null;
108
+ if (trial?.active && TRIALABLE_TOOLS.has(name)) {
109
+ if (!trialStoreAvailable()) {
110
+ return {
111
+ isError: true,
112
+ content: [{ type: 'text', text: '[AUTH_REQUIRED] 试用服务暂不可用,请注册后使用:https://www.free-api.aiconvg.xin' }],
113
+ };
114
+ }
115
+ const limits = trialLimits();
116
+ const ticket = await consumeTrial(trial.ip, name, limits);
117
+ if (!ticket.allowed) {
118
+ logTrial('denied', { tool: name, reason: ticket.reason });
119
+ return {
120
+ isError: true,
121
+ content: [{ type: 'text', text: trialExhaustedMessage(ticket.used, ticket.limit) }],
122
+ };
123
+ }
124
+ trialTicket = ticket;
125
+ logTrial('consume', { tool: name, used: ticket.usedThisCall, remaining: ticket.remaining });
126
+ }
127
+
128
+ const started = Date.now();
129
+ try {
130
+ const result = await tool.handler(parsed.data);
131
+ logger.info('tool.call', { tool: name, ms: Date.now() - started, ok: true });
132
+ let text = JSON.stringify(result, null, 2);
133
+ if (trialTicket) {
134
+ text += `\n\n${trialRemainingNote(name, trialTicket.remaining, trialTicket.limits)}`;
135
+ }
136
+ return { content: [{ type: 'text', text }] };
137
+ } catch (err) {
138
+ logger.warn('tool.call', {
139
+ tool: name,
140
+ ms: Date.now() - started,
141
+ ok: false,
142
+ code: err?.code || 'INTERNAL_ERROR',
143
+ });
144
+ // 上游失败:后端不扣额度,试用计数同口径回滚
145
+ if (trialTicket) await rollbackTrial(trialTicket);
146
+ return errorToMcpContent(err);
147
+ }
148
+ });
149
+
150
+ return server;
151
+ }
package/src/stdio.js ADDED
@@ -0,0 +1,12 @@
1
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
2
+ import { setDefaultToken, logger } from './context.js';
3
+ import { buildServer } from './server.js';
4
+
5
+ export async function runStdio(token) {
6
+ const server = buildServer();
7
+ const transport = new StdioServerTransport();
8
+ // stdio 是单会话:令牌设为进程级默认,后续所有工具调用共用
9
+ setDefaultToken(token);
10
+ await server.connect(transport);
11
+ logger.info('stdio.started', {});
12
+ }
@@ -0,0 +1,15 @@
1
+ import { z } from 'zod';
2
+ import { api } from '../lib/apiClient.js';
3
+
4
+ export const getAccountTool = {
5
+ name: 'get_account',
6
+ title: '查询额度与账户状态',
7
+ description:
8
+ '查询当前令牌的应用档位(free/paid)、各能力当日额度用量(tts/asr/ocr 的 used/limit/remaining)、' +
9
+ '额度重置时间与许可证有效期。只读,不消耗额度。',
10
+ inputSchema: { type: 'object', properties: {} },
11
+ zodSchema: z.object({}),
12
+ async handler() {
13
+ return api.getAccount();
14
+ },
15
+ };
@@ -0,0 +1,22 @@
1
+ import { z } from 'zod';
2
+ import { api } from '../lib/apiClient.js';
3
+
4
+ export const asrGetTool = {
5
+ name: 'get_asr_job',
6
+ title: '查询长音频任务结果',
7
+ description:
8
+ '按 taskId 查询异步转写任务状态:queued/running(带 segments_done/processed_s 进度)、' +
9
+ 'done(返回 text/segments)、failed(error 字段,额度已自动返还)。不计费、不重复扣额度,' +
10
+ '可安全重复轮询;任务结果保留 24 小时。',
11
+ inputSchema: {
12
+ type: 'object',
13
+ required: ['taskId'],
14
+ properties: {
15
+ taskId: { type: 'string', description: 'submit_asr_job 返回的任务 ID' },
16
+ },
17
+ },
18
+ zodSchema: z.object({ taskId: z.string().min(1, 'taskId 必填') }),
19
+ async handler(args) {
20
+ return api.asrGet(args.taskId);
21
+ },
22
+ };
@@ -0,0 +1,26 @@
1
+ import { z } from 'zod';
2
+ import { api } from '../lib/apiClient.js';
3
+
4
+ export const asrSubmitTool = {
5
+ name: 'submit_asr_job',
6
+ title: '提交长音频转写任务',
7
+ description:
8
+ '提交异步转写任务(长音频入口),立即返回 taskId。计费工具:提交即占 1 次当日 ASR 额度,' +
9
+ '任务失败时额度自动返还。audioUrl ≤ 50MB;提交后用 get_asr_job 轮询' +
10
+ '(建议首轮 3 秒、之后每 5 秒,总时长 ≤ 10 分钟,不要无限轮询)。单次调用不内部等待。',
11
+ inputSchema: {
12
+ type: 'object',
13
+ required: ['audioUrl'],
14
+ properties: {
15
+ audioUrl: { type: 'string', description: '长音频公网 URL,≤ 50MB(时长无 60 秒限制)' },
16
+ lang: { type: 'string', description: '语种,auto 自动判定(默认)' },
17
+ },
18
+ },
19
+ zodSchema: z.object({
20
+ audioUrl: z.string().url('audioUrl 必须是 http(s) 公网 URL'),
21
+ lang: z.string().optional(),
22
+ }),
23
+ async handler(args) {
24
+ return api.asrSubmit(args);
25
+ },
26
+ };
@@ -0,0 +1,28 @@
1
+ import { z } from 'zod';
2
+ import { api } from '../lib/apiClient.js';
3
+
4
+ export const asrSyncTool = {
5
+ name: 'speech_to_text',
6
+ title: '语音转文字(同步,短音频)',
7
+ description:
8
+ '转写 ≤ 60 秒、≤ 8MB 的短音频,同步返回文本与分段。计费工具(占 1 次当日 ASR 额度,失败不扣)。' +
9
+ 'audioUrl 必须是公网可访问 URL(wav/mp3/m4a);本地文件路径无法使用。' +
10
+ '更长的音频改用 submit_asr_job 提交异步任务。',
11
+ inputSchema: {
12
+ type: 'object',
13
+ required: ['audioUrl'],
14
+ properties: {
15
+ audioUrl: { type: 'string', description: '音频公网 URL,≤ 8MB 且 ≤ 60 秒' },
16
+ lang: { type: 'string', description: '语种,auto 自动判定(默认)' },
17
+ engine: { type: 'string', enum: ['standard', 'premium'], description: '引擎:默认 standard(免费);premium 需付费档,商业模型按积分计费' },
18
+ },
19
+ },
20
+ zodSchema: z.object({
21
+ audioUrl: z.string().url('audioUrl 必须是 http(s) 公网 URL'),
22
+ lang: z.string().optional(),
23
+ engine: z.enum(['standard', 'premium']).optional(),
24
+ }),
25
+ async handler(args) {
26
+ return api.asrSync(args);
27
+ },
28
+ };
@@ -0,0 +1,93 @@
1
+ import { z } from 'zod';
2
+ import { api } from '../lib/apiClient.js';
3
+
4
+ // ── 多角色配音(积分计费 · /v1/dubbing,2026-11-06 接入 MCP)──────────────
5
+ // 计费口径:按音色单价扣积分(商业音色如 Cherry 2 积分/字,开源免费音色 0 积分),
6
+ // 提交按预估冻结、只结算成功段、失败/取消全额解冻。计费工具:失败不自动重试。
7
+
8
+ export const dubbingVoicesTool = {
9
+ name: 'list_dubbing_voices',
10
+ title: '查询配音音色目录',
11
+ description:
12
+ '查询多角色配音可用的音色目录(70 个,含 21 个开源免费音色)。' +
13
+ '返回每个音色的 id、性别、语言、单价 creditsPerChar(免费音色为 0)。' +
14
+ '提交配音前先从这里选音色 id;不计费。',
15
+ inputSchema: { type: 'object', properties: {} },
16
+ zodSchema: z.object({}).optional(),
17
+ async handler() {
18
+ return api.dubbingVoices();
19
+ },
20
+ };
21
+
22
+ export const dubbingSubmitTool = {
23
+ name: 'dubbing_submit',
24
+ title: '提交多角色配音',
25
+ description:
26
+ '多角色配音:按 segments([{voice, text}],至少一段)合成带时间轴的语音,' +
27
+ '返回音频 URL 与 SRT 字幕。计费工具:按所选音色单价扣积分(免费音色 0 积分),' +
28
+ '小任务同步返回(audioUrl/srtUrl/creditCost),大任务异步 202 返回 taskId,' +
29
+ '用 get_dubbing_task 轮询(建议每 5 秒,不要无限轮询)。失败不自动重试。',
30
+ inputSchema: {
31
+ type: 'object',
32
+ required: ['segments'],
33
+ properties: {
34
+ segments: {
35
+ type: 'array',
36
+ minItems: 1,
37
+ description: '配音分段列表,按顺序合成',
38
+ items: {
39
+ type: 'object',
40
+ required: ['voice', 'text'],
41
+ properties: {
42
+ voice: { type: 'string', description: '音色 id(先 list_dubbing_voices 查询)' },
43
+ text: { type: 'string', description: '该段台词' },
44
+ },
45
+ },
46
+ },
47
+ },
48
+ },
49
+ zodSchema: z.object({
50
+ segments: z.array(z.object({
51
+ voice: z.string().min(1, 'voice 必填'),
52
+ text: z.string().min(1, 'text 必填'),
53
+ })).min(1, 'segments 至少一段').max(100, 'segments 最多 100 段'),
54
+ }),
55
+ async handler(args) {
56
+ return api.dubbingSubmit(args);
57
+ },
58
+ };
59
+
60
+ export const dubbingGetTool = {
61
+ name: 'get_dubbing_task',
62
+ title: '查询配音任务结果',
63
+ description:
64
+ '按 taskId 查询异步配音任务状态:处理中 / succeeded(返回 audioUrl、srtUrl、chargedCredits 实扣)/' +
65
+ 'partial(部分段失败,只结算成功段)/ failed / cancelled(全额解冻)。' +
66
+ '不计费、可安全重复轮询。',
67
+ inputSchema: {
68
+ type: 'object',
69
+ required: ['taskId'],
70
+ properties: { taskId: { type: 'string', description: 'dubbing_submit 异步返回的任务 ID' } },
71
+ },
72
+ zodSchema: z.object({ taskId: z.string().min(1, 'taskId 必填') }),
73
+ async handler(args) {
74
+ return api.dubbingGet(args.taskId);
75
+ },
76
+ };
77
+
78
+ export const dubbingCancelTool = {
79
+ name: 'cancel_dubbing_task',
80
+ title: '取消配音任务',
81
+ description:
82
+ '取消尚未完成的异步配音任务,已冻结的预估积分立即全额解冻。' +
83
+ '已完成(succeeded/partial)的任务不可取消。不计费。',
84
+ inputSchema: {
85
+ type: 'object',
86
+ required: ['taskId'],
87
+ properties: { taskId: { type: 'string', description: 'dubbing_submit 异步返回的任务 ID' } },
88
+ },
89
+ zodSchema: z.object({ taskId: z.string().min(1, 'taskId 必填') }),
90
+ async handler(args) {
91
+ return api.dubbingCancel(args.taskId);
92
+ },
93
+ };
@@ -0,0 +1,26 @@
1
+ import { z } from 'zod';
2
+ import { api } from '../lib/apiClient.js';
3
+
4
+ export const ocrTool = {
5
+ name: 'ocr_image',
6
+ title: '图片文字识别',
7
+ description:
8
+ '识别单张图片(png/jpg/webp,≤ 8MB)中的文字,返回 fullText 与分块(含置信度/坐标)。' +
9
+ '计费工具(占 1 次当日 OCR 额度,失败不扣)。imageUrl 必须是公网可访问 URL;' +
10
+ '本地文件路径无法使用。mode=full 只出全文,structured 出带坐标分块。',
11
+ inputSchema: {
12
+ type: 'object',
13
+ required: ['imageUrl'],
14
+ properties: {
15
+ imageUrl: { type: 'string', description: '图片公网 URL,≤ 8MB' },
16
+ mode: { type: 'string', enum: ['auto', 'full', 'structured'], description: '默认 auto' },
17
+ },
18
+ },
19
+ zodSchema: z.object({
20
+ imageUrl: z.string().url('imageUrl 必须是 http(s) 公网 URL'),
21
+ mode: z.enum(['auto', 'full', 'structured']).optional(),
22
+ }),
23
+ async handler(args) {
24
+ return api.ocr(args);
25
+ },
26
+ };
@@ -0,0 +1,33 @@
1
+ import { z } from 'zod';
2
+ import { api } from '../lib/apiClient.js';
3
+
4
+ export const ttsTool = {
5
+ name: 'text_to_speech',
6
+ title: '文本转语音',
7
+ description:
8
+ '把文本合成为可播放的语音,同步返回 audioUrl(自带 exp/sig 的公网直链,可直接播放,默认 24 小时有效)。' +
9
+ '计费工具(失败不扣)。text ≤ 300 字符(2026-11-09 收敛,付费音色硬限);voice 必须来自 list_voices,不要猜测音色名;' +
10
+ 'format 当前仅支持 wav。engine 可选:默认 standard(免费音色,占日额度,wav 输出);' +
11
+ '"premium"(仅付费档)用商业音色(如 Cherry)按积分计费、不占日额度,音色以充值页商业音色目录为准。',
12
+ inputSchema: {
13
+ type: 'object',
14
+ required: ['text', 'voice'],
15
+ properties: {
16
+ text: { type: 'string', maxLength: 300, description: '待合成文本,≤ 300 字符;超过请分段多次调用' },
17
+ voice: { type: 'string', description: '音色 ID,必须来自 list_voices 的返回(premium 引擎不受此限,可用商业音色)' },
18
+ speed: { type: 'number', minimum: 0.5, maximum: 2.0, description: '语速,0.5–2.0,默认 1.0(仅 standard)' },
19
+ format: { type: 'string', enum: ['wav'], description: '音频格式,当前仅 wav' },
20
+ engine: { type: 'string', enum: ['standard', 'premium'], description: '引擎:默认 standard(免费);premium 需付费档,按积分计费' },
21
+ },
22
+ },
23
+ zodSchema: z.object({
24
+ text: z.string().min(1, 'text 不能为空').max(300, 'text 超过 300 字符上限,请分段多次调用'),
25
+ voice: z.string().min(1, 'voice 必填(用 list_voices 查询)'),
26
+ speed: z.number().min(0.5).max(2.0).optional(),
27
+ format: z.enum(['wav']).optional(),
28
+ engine: z.enum(['standard', 'premium']).optional(),
29
+ }),
30
+ async handler(args) {
31
+ return api.tts(args);
32
+ },
33
+ };
@@ -0,0 +1,48 @@
1
+ import { z } from 'zod';
2
+ import { api } from '../lib/apiClient.js';
3
+
4
+ // ── 视频链接转文字(积分计费 · /v1/video/transcribe,2026-11-06 接入 MCP)──
5
+ // 计费口径:转写稿每 5 字 1 积分;提交后按「时长 × 保守字速」冻结,
6
+ // 按实际字数结算、估少补扣、失败全额解冻(上游 videoBilling 统一执行)。
7
+
8
+ export const videoSubmitTool = {
9
+ name: 'submit_video_transcribe',
10
+ title: '提交视频链接转文字',
11
+ description:
12
+ '把短视频/视频链接转成带时间轴的转写稿。支持抖音(含 v.douyin.com 分享短链、可直接粘整段分享文案)、' +
13
+ 'bilibili/b23.tv、YouTube、快手、小红书、TikTok。立即返回 taskId,用 get_video_transcribe 轮询' +
14
+ '(建议每 10 秒,1~2 分钟短视频通常 1 分钟内完成,不要无限轮询)。' +
15
+ '计费工具:转写稿每 5 字 1 积分,提交时按时长冻结积分(约 2 积分/秒),' +
16
+ '完成按实际字数结算、失败全额解冻;积分不足会在任务中失败并退回冻结。失败不自动重试。',
17
+ inputSchema: {
18
+ type: 'object',
19
+ required: ['url'],
20
+ properties: {
21
+ url: { type: 'string', description: '视频链接(平台分享短链或完整链接,也可传整段分享文案,服务端自动提取)' },
22
+ },
23
+ },
24
+ zodSchema: z.object({
25
+ url: z.string().min(8, 'url 必填').max(600, 'url 过长(如为分享文案请只保留链接所在文案 ≤600 字符)'),
26
+ }),
27
+ async handler(args) {
28
+ return api.videoSubmit(args.url);
29
+ },
30
+ };
31
+
32
+ export const videoGetTool = {
33
+ name: 'get_video_transcribe',
34
+ title: '查询视频转写任务结果',
35
+ description:
36
+ '按 taskId 查询视频转写任务:queued/downloading/transcribing/correcting(进行中)→ ' +
37
+ 'done(返回 text 转写稿、markdown 分段稿、chars 字数、credits 实扣积分)或 failed(error 字段,冻结已全额解冻)。' +
38
+ '不计费、可安全重复轮询。',
39
+ inputSchema: {
40
+ type: 'object',
41
+ required: ['taskId'],
42
+ properties: { taskId: { type: 'string', description: 'submit_video_transcribe 返回的任务 ID' } },
43
+ },
44
+ zodSchema: z.object({ taskId: z.string().min(1, 'taskId 必填') }),
45
+ async handler(args) {
46
+ return api.videoGet(args.taskId);
47
+ },
48
+ };
@@ -0,0 +1,20 @@
1
+ import { z } from 'zod';
2
+ import { api } from '../lib/apiClient.js';
3
+
4
+ export const listVoicesTool = {
5
+ name: 'list_voices',
6
+ title: '列出可用音色',
7
+ description:
8
+ '获取 TTS 可用音色列表(仅免费开源音色,不计额度)。调用 text_to_speech 前必须先从这里拿 voice 参数,' +
9
+ '直接猜测音色名会返回 VOICE_NOT_ALLOWED。',
10
+ inputSchema: {
11
+ type: 'object',
12
+ properties: {
13
+ lang: { type: 'string', description: '按语言筛选,如 zh / en / ja,默认 zh' },
14
+ },
15
+ },
16
+ zodSchema: z.object({ lang: z.string().optional() }),
17
+ async handler(args) {
18
+ return api.listVoices(args?.lang);
19
+ },
20
+ };