free-api-mcp-server 0.0.0-stage → 0.2.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 +49 -0
- package/LICENSE +21 -0
- package/README.md +98 -2
- package/package.json +37 -4
- package/server.json +22 -0
- package/src/context.js +56 -0
- package/src/http.js +115 -0
- package/src/index.js +44 -0
- package/src/lib/apiClient.js +88 -0
- package/src/lib/errors.js +42 -0
- package/src/lib/guestGate.js +71 -0
- package/src/lib/localCounter.js +67 -0
- package/src/lib/trial.js +53 -0
- package/src/lib/trialStore.js +93 -0
- package/src/server.js +182 -0
- package/src/stdio.js +14 -0
- package/src/tools/account.js +15 -0
- package/src/tools/asrGet.js +22 -0
- package/src/tools/asrSubmit.js +26 -0
- package/src/tools/asrSync.js +28 -0
- package/src/tools/dubbing.js +93 -0
- package/src/tools/ocr.js +26 -0
- package/src/tools/tts.js +33 -0
- package/src/tools/video.js +48 -0
- package/src/tools/voices.js +20 -0
package/.env.example
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
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
|
+
# stdio 游客模式(免注册试用):未设 FREE_API_TOKEN 时,回退到内置游客试用令牌
|
|
13
|
+
# (TRIAL_LICENSE_TOKEN / TRIAL_LICENSE_TOKEN_FILE,见下方试用层)→ 进入游客模式,
|
|
14
|
+
# 每实例每北京日限次免费;由本地文件计数 + 上游 02 游客专用令牌双重兜底。
|
|
15
|
+
# TRIAL_LICENSE_TOKEN_FILE=data/.trial_token
|
|
16
|
+
|
|
17
|
+
# http 模式
|
|
18
|
+
MCP_HTTP_PORT=3210
|
|
19
|
+
# 允许的 Origin(逗号分隔;留空表示不校验,仅限自有反代之后使用)
|
|
20
|
+
# MCP_ALLOWED_ORIGINS=
|
|
21
|
+
|
|
22
|
+
# —— 试用 / 游客层(托管 HTTP 无令牌 + stdio 游客共用额度口径)——
|
|
23
|
+
# 内置游客试用许可证(走 CRM 发牌创建 free 档;仅服务端持有,绝不写进源码 / 公开包)
|
|
24
|
+
# TRIAL_LICENSE_TOKEN=
|
|
25
|
+
# TRIAL_LICENSE_TOKEN_FILE=data/.trial_token
|
|
26
|
+
# 游客每 IP / 每实例每日额度(北京日重置);只放 3 个可试能力:
|
|
27
|
+
# text_to_speech 30 / speech_to_text 15 / ocr_image 15
|
|
28
|
+
# submit_asr_job(长音频异步)、dubbing_*、video_* 游客一律禁用(见 guestGate.js)
|
|
29
|
+
# TRIAL_TTS_LIMIT=30
|
|
30
|
+
# TRIAL_ASR_LIMIT=15
|
|
31
|
+
# TRIAL_OCR_LIMIT=15
|
|
32
|
+
# stdio 本地计数(每实例)可单独覆盖(默认与上面三项一致)
|
|
33
|
+
# TRIAL_LOCAL_TTS_LIMIT=30
|
|
34
|
+
# TRIAL_LOCAL_ASR_LIMIT=15
|
|
35
|
+
# TRIAL_LOCAL_OCR_LIMIT=15
|
|
36
|
+
# stdio 本地计数文件路径(默认 tmpdir/free-api-mcp-trial-<北京日>.json)
|
|
37
|
+
# MCP_LOCAL_COUNTER_FILE=
|
|
38
|
+
# 全平台当日试用总次数熔断(北京日)
|
|
39
|
+
# TRIAL_DAILY_CAP=3000
|
|
40
|
+
# 试用窗口期(小时,IP 首次试用后计时,期内不重发)
|
|
41
|
+
# TRIAL_TTL_HOURS=24
|
|
42
|
+
# Redis(仅托管 HTTP 试用计数用;fail-closed:不可用即拒绝试用,正式令牌不受影响)
|
|
43
|
+
# REDIS_URL=redis://127.0.0.1:6379
|
|
44
|
+
# REDIS_DB=1
|
|
45
|
+
# 注册引导链接
|
|
46
|
+
# TRIAL_SIGNUP_URL=https://www.open-api.aiconvg.xin
|
|
47
|
+
|
|
48
|
+
# 日志:debug | info | warn | error
|
|
49
|
+
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,99 @@
|
|
|
1
|
-
#
|
|
1
|
+
# free-api MCP Server
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
- **游客默认可用(免注册)**:不填令牌也能直接试用(每实例 / 每 IP 每北京日 TTS 30 / ASR 15 / OCR 15 次);填 `FREE_API_TOKEN` 解锁完整额度与高阶能力。
|
|
11
|
+
- **每个用户填自己的许可证令牌**(`FREE_API_TOKEN`),计费/额度归属各自账户,互不影响。
|
|
12
|
+
- 共 **13 个工具**(7 个免费能力 + 6 个付费能力)。
|
|
13
|
+
|
|
14
|
+
## 13 个工具
|
|
15
|
+
|
|
16
|
+
| # | 工具 | 分组 | 计费 | 说明 |
|
|
17
|
+
|---|---|---|---|---|
|
|
18
|
+
| 1 | `list_voices` | 免费 | 否 | 可用音色白名单(免费开源音色);调 `text_to_speech` 前必查 |
|
|
19
|
+
| 2 | `get_account` | 免费 | 否 | 档位(free/paid)、当日额度用量、令牌有效期 |
|
|
20
|
+
| 3 | `text_to_speech` | 免费 | 占免费日额度(失败不扣) | 文本≤300 字符 → 可播 `audioUrl`(默认 24h 有效);`engine` 可选 standard/premium |
|
|
21
|
+
| 4 | `speech_to_text` | 免费 | 占免费日额度(失败不扣) | 同步短音频 ≤60s / ≤8MB |
|
|
22
|
+
| 5 | `submit_asr_job` | 免费 | 提交即占日额度,失败自动返还 | 长音频异步任务,返回 `taskId` |
|
|
23
|
+
| 6 | `get_asr_job` | 免费 | 否 | 轮询长音频任务(queued/running/done/failed) |
|
|
24
|
+
| 7 | `ocr_image` | 免费 | 占免费日额度(失败不扣) | 单图 ≤8MB;`mode=auto/full/structured` |
|
|
25
|
+
| 8 | `list_dubbing_voices` | 付费·配音 | 否(查询不计费) | 配音音色目录,返回 `creditsPerChar` |
|
|
26
|
+
| 9 | `dubbing_submit` | 付费·配音 | 按音色单价/字(失败不扣、取消全额解冻) | 多角色配音:`segments=[{voice,text}]`;小任务同步、大任务 202+`taskId` |
|
|
27
|
+
| 10 | `get_dubbing_task` | 付费·配音 | 否 | 轮询配音任务 |
|
|
28
|
+
| 11 | `cancel_dubbing_task` | 付费·配音 | 否 | 取消未完成任务,冻结积分立即解冻 |
|
|
29
|
+
| 12 | `submit_video_transcribe` | 付费·视频 | 转写稿 5 字 1 积分(失败全额解冻) | 抖音/B站/YouTube/快手/小红书/TikTok 链接或分享文案 → `taskId` |
|
|
30
|
+
| 13 | `get_video_transcribe` | 付费·视频 | 否 | 轮询视频转写(返回 text / markdown 分段 / 字数 / 实扣积分) |
|
|
31
|
+
|
|
32
|
+
> 「免费」= 标准引擎、按每日免费额度计量、不扣积分;「付费」= 按积分计费(配音按字、视频按字数)。查询/轮询类工具不计费。
|
|
33
|
+
|
|
34
|
+
## 鉴权与配置
|
|
35
|
+
|
|
36
|
+
### 游客试用(免注册,默认可用)
|
|
37
|
+
不填任何令牌时自动进入游客模式(stdio 走内置游客试用令牌 `TRIAL_LICENSE_TOKEN[_FILE]`,HTTP 走内置试用令牌),开箱即用:
|
|
38
|
+
- 每 IP(远程)/ 每实例(stdio)**每北京日**:`text_to_speech` 30 次、`speech_to_text` 15 次、`ocr_image` 15 次;
|
|
39
|
+
- 游客只放 `list_voices`、`get_account` + 上述 3 个能力;`submit_asr_job`(长音频异步)、配音、视频**不开放**(堵旁路);
|
|
40
|
+
- 真正可靠的全局限额由上游 02 游客专用令牌兜底,客户端计数仅作二级软限。
|
|
41
|
+
|
|
42
|
+
### 正式令牌(更高额度)
|
|
43
|
+
到 **https://www.open-api.aiconvg.xin** 注册获取免费许可证令牌(免费档每日 TTS 100 / ASR 50 / OCR 50 次),填入 `FREE_API_TOKEN`,额度/计费归属各自账户。
|
|
44
|
+
|
|
45
|
+
```json
|
|
46
|
+
{
|
|
47
|
+
"mcpServers": {
|
|
48
|
+
"free-api": {
|
|
49
|
+
"command": "npx",
|
|
50
|
+
"args": ["-y", "free-api-mcp-server"],
|
|
51
|
+
"env": {
|
|
52
|
+
"FREE_API_BASE_URL": "https://www.open-api.aiconvg.xin",
|
|
53
|
+
"FREE_API_TOKEN": "<你的许可证令牌>"
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
| 环境变量 | 必填 | 说明 |
|
|
61
|
+
|---|---|---|
|
|
62
|
+
| `FREE_API_TOKEN` | ✅ | 你的许可证令牌(用户各自填写) |
|
|
63
|
+
| `FREE_API_BASE_URL` | ✅ | 固定 `https://www.open-api.aiconvg.xin` |
|
|
64
|
+
| `MCP_TRANSPORT` | 默认 stdio | 托管场景保持 stdio(平台自动转 SSE) |
|
|
65
|
+
| `LOG_LEVEL` | 可选 | `debug/info/warn/error`,默认 info;日志走 stderr,stdout 只承载协议 |
|
|
66
|
+
|
|
67
|
+
本地直跑:
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
FREE_API_TOKEN=<你的令牌> FREE_API_BASE_URL=https://www.open-api.aiconvg.xin npx -y free-api-mcp-server
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## 调用示例
|
|
74
|
+
|
|
75
|
+
- `list_voices { "lang": "zh" }`
|
|
76
|
+
- `text_to_speech { "text": "你好,欢迎使用", "voice": "zh_CN-huayan-medium", "speed": 1.0 }` → 返回 `audioUrl`
|
|
77
|
+
- `speech_to_text { "audioUrl": "https://example.com/a.mp3" }`
|
|
78
|
+
- `ocr_image { "imageUrl": "https://example.com/a.png", "mode": "full" }`
|
|
79
|
+
- `dubbing_submit { "segments": [{ "voice": "...", "text": "第一句" }, { "voice": "...", "text": "第二句" }] }`
|
|
80
|
+
- `submit_video_transcribe { "url": "https://v.douyin.com/xxxx/" }` → `get_video_transcribe { "taskId": "..." }`
|
|
81
|
+
|
|
82
|
+
> `audioUrl` / `imageUrl` / 视频链接必须是**公网可访问 URL**,本地文件路径不支持。
|
|
83
|
+
|
|
84
|
+
## 额度与计费
|
|
85
|
+
|
|
86
|
+
- 游客试用(免注册):每 IP / 每实例每北京日 TTS 30 / ASR 15 / OCR 15 次(ASR 仅同步 `speech_to_text` ≤60s;不含长音频 `submit_asr_job` / 配音 / 视频)。
|
|
87
|
+
- 免费档(正式令牌):每日 TTS 100 / ASR 50 / OCR 50 次(`get_account` 可查 used/limit/remaining)。
|
|
88
|
+
- 付费能力:配音按音色单价/字、视频转写稿 5 字 1 积分;预占—结算,按实际结算,失败/取消全额解冻。
|
|
89
|
+
- 失败不扣:上游失败自动返还/解冻。
|
|
90
|
+
|
|
91
|
+
## 错误码
|
|
92
|
+
|
|
93
|
+
- `AUTH_REQUIRED`:令牌缺失/无效 → 引导注册。
|
|
94
|
+
- `INVALID_PARAM`:入参校验失败(本地拦截,不触上游)。
|
|
95
|
+
- `UPSTREAM_UNAVAILABLE`:上游网络不可达,稍后重试。
|
|
96
|
+
|
|
97
|
+
## 许可
|
|
98
|
+
|
|
99
|
+
MIT,见 [LICENSE](LICENSE)。
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "free-api-mcp-server",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.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.open-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.2.0",
|
|
6
|
+
"packages": [
|
|
7
|
+
{
|
|
8
|
+
"registryType": "npm",
|
|
9
|
+
"identifier": "free-api-mcp-server",
|
|
10
|
+
"version": "0.2.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,56 @@
|
|
|
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
|
+
// stdio 游客模式开关(进程级)。HTTP 路径恒为 false,互不影响。
|
|
11
|
+
let guestMode = false;
|
|
12
|
+
|
|
13
|
+
export function setDefaultToken(token) {
|
|
14
|
+
defaultToken = token || null;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function setGuestMode(v) {
|
|
18
|
+
guestMode = !!v;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function isGuestMode() {
|
|
22
|
+
return guestMode;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function getRequestToken() {
|
|
26
|
+
const ctx = requestContext.getStore();
|
|
27
|
+
return ctx?.token || defaultToken;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function getRequestTrial() {
|
|
31
|
+
const ctx = requestContext.getStore();
|
|
32
|
+
return ctx?.trial || null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// 真实客户端 IP(HTTP 传输下由 http.js 逐请求写入,stdio 下为 null)。
|
|
36
|
+
// 用于回源头透传 X-Ca-Client-IP,让 BFF 的 openRate 能按真实用户分流。
|
|
37
|
+
export function getRequestClientIp() {
|
|
38
|
+
const ctx = requestContext.getStore();
|
|
39
|
+
return ctx?.clientIp || null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function log(level, msg, data = undefined) {
|
|
43
|
+
const entry = { ts: new Date().toISOString(), level, msg };
|
|
44
|
+
if (data) entry.data = data;
|
|
45
|
+
// stdio 传输下 stdout 是协议通道,日志只能走 stderr
|
|
46
|
+
process.stderr.write(JSON.stringify(entry) + '\n');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export const logger = {
|
|
50
|
+
debug: (msg, data) => {
|
|
51
|
+
if (process.env.LOG_LEVEL === 'debug') log('debug', msg, data);
|
|
52
|
+
},
|
|
53
|
+
info: (msg, data) => log('info', msg, data),
|
|
54
|
+
warn: (msg, data) => log('warn', msg, data),
|
|
55
|
+
error: (msg, data) => log('error', msg, data),
|
|
56
|
+
};
|
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,44 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 入口:按 MCP_TRANSPORT 选择 stdio 或 http。
|
|
3
|
+
// stdio:令牌优先 FREE_API_TOKEN(正式令牌);无则回退游客试用令牌 TRIAL_LICENSE_TOKEN / TRIAL_LICENSE_TOKEN_FILE;两者皆无才 fatal。
|
|
4
|
+
// http:令牌来自每次请求的 Authorization: Bearer <token>(见 http.js 中间件)。
|
|
5
|
+
import { runStdio } from './stdio.js';
|
|
6
|
+
import { runHttp } from './http.js';
|
|
7
|
+
import { trialToken } from './lib/trial.js';
|
|
8
|
+
|
|
9
|
+
const transport = (process.env.MCP_TRANSPORT || 'stdio').toLowerCase();
|
|
10
|
+
|
|
11
|
+
if (transport === 'stdio') {
|
|
12
|
+
let token = process.env.FREE_API_TOKEN || '';
|
|
13
|
+
let guest = false;
|
|
14
|
+
if (!token) {
|
|
15
|
+
const trial = trialToken();
|
|
16
|
+
if (trial) {
|
|
17
|
+
token = trial;
|
|
18
|
+
guest = true;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
if (!token) {
|
|
22
|
+
process.stderr.write(
|
|
23
|
+
'[fatal] stdio 模式需设置 FREE_API_TOKEN(正式令牌),或提供 TRIAL_LICENSE_TOKEN / TRIAL_LICENSE_TOKEN_FILE 以游客试用\n',
|
|
24
|
+
);
|
|
25
|
+
process.exit(1);
|
|
26
|
+
}
|
|
27
|
+
if (guest) {
|
|
28
|
+
process.stderr.write(
|
|
29
|
+
'[info] 游客模式:限次免费试用(每实例每北京日有上限,全局限额由上游兜底)。注册获取更高每日额度 → https://www.open-api.aiconvg.xin\n',
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
runStdio(token, { guest }).catch((e) => {
|
|
33
|
+
process.stderr.write(`[fatal] ${e?.stack || e}\n`);
|
|
34
|
+
process.exit(1);
|
|
35
|
+
});
|
|
36
|
+
} else if (transport === 'http') {
|
|
37
|
+
runHttp().catch((e) => {
|
|
38
|
+
process.stderr.write(`[fatal] ${e?.stack || e}\n`);
|
|
39
|
+
process.exit(1);
|
|
40
|
+
});
|
|
41
|
+
} else {
|
|
42
|
+
process.stderr.write(`[fatal] 未知的 MCP_TRANSPORT: ${transport}(支持 stdio | http)\n`);
|
|
43
|
+
process.exit(1);
|
|
44
|
+
}
|
|
@@ -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.open-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.open-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.open-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.open-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
|
+
}
|