free-api-mcp-server 0.2.7 → 0.2.8

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/package.json CHANGED
@@ -1,17 +1,37 @@
1
1
  {
2
2
  "name": "free-api-mcp-server",
3
- "version": "0.2.7",
3
+ "version": "0.2.8",
4
4
  "mcpName": "io.github.aiconvg/free-api-mcp",
5
5
  "type": "module",
6
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
7
  "license": "MIT",
8
8
  "author": "aiconvg",
9
- "keywords": ["mcp", "model-context-protocol", "modelcontextprotocol", "tts", "asr", "ocr", "text-to-speech", "speech-to-text", "dubbing", "video-transcription", "ai"],
9
+ "keywords": [
10
+ "mcp",
11
+ "model-context-protocol",
12
+ "modelcontextprotocol",
13
+ "tts",
14
+ "asr",
15
+ "ocr",
16
+ "text-to-speech",
17
+ "speech-to-text",
18
+ "dubbing",
19
+ "video-transcription",
20
+ "ai"
21
+ ],
10
22
  "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" },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/aiconvg/free-api-mcp-server.git"
26
+ },
27
+ "bugs": {
28
+ "url": "https://github.com/aiconvg/free-api-mcp-server/issues"
29
+ },
13
30
  "main": "src/index.js",
14
- "publishConfig": { "access": "public", "registry": "https://registry.npmjs.org" },
31
+ "publishConfig": {
32
+ "access": "public",
33
+ "registry": "https://registry.npmjs.org"
34
+ },
15
35
  "bin": {
16
36
  "free-api-mcp": "src/index.js"
17
37
  },
package/server.json CHANGED
@@ -2,12 +2,12 @@
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-09-29/server.schema.json",
3
3
  "name": "io.github.aiconvg/free-api-mcp",
4
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.7",
5
+ "version": "0.2.8",
6
6
  "packages": [
7
7
  {
8
8
  "registryType": "npm",
9
9
  "identifier": "free-api-mcp-server",
10
- "version": "0.2.7",
10
+ "version": "0.2.8",
11
11
  "transport": {
12
12
  "type": "stdio"
13
13
  }
package/src/http.js CHANGED
@@ -1,11 +1,13 @@
1
- // HTTP 传输:Streamable HTTP + /healthz。
1
+ // HTTP 传输:Streamable HTTP(仅 POST) + /healthz + /version。
2
2
  // 令牌:每次请求从 Authorization: Bearer 提取,用 AsyncLocalStorage 传给 handler(请求级隔离)。
3
3
  // 试用:无令牌 + TRIAL_LICENSE_TOKEN 已配置 → 进入试用上下文(IP 计数),
4
4
  // Redis 不可用时 fail-closed,只放行只读工具并提示注册。
5
+ // 说明:本服务只支持 POST /mcp(Streamable HTTP,JSON 响应),**不提供 SSE 推送**;
6
+ // 非 POST 的 /mcp 明确 405,/sse 明确 404,避免把 GET 塞进 transport 挂起。
5
7
  import express from 'express';
6
8
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
7
9
  import { requestContext, logger } from './context.js';
8
- import { buildServer } from './server.js';
10
+ import { buildServer, PKG_VERSION } from './server.js';
9
11
  import { initTrialStore, trialStoreAvailable } from './lib/trialStore.js';
10
12
  import { trialEnabled } from './lib/trial.js';
11
13
 
@@ -19,10 +21,12 @@ function extractBearer(req) {
19
21
  return m ? m[1].trim() : null;
20
22
  }
21
23
 
22
- // 真实客户端 IP 提取。信任边界:**只有当连接对端是本机回环**(自有反代 -> 本进程)
23
- // 时才信任反代覆写的转发头——反代用 X-Real-IP 覆盖,客户端自带的 X-Real-IP/XFF 一律被盖掉、伪造不了。
24
- // 非回环对端(理论上不应出现,端口只绑回环)一律直接用连接 IP,不信任任何头;
25
- // 优先取 X-Real-IP,取不到再回退。
24
+ // 真实客户端 IP 提取。信任边界:**只有当连接对端是本机回环**(自有 nginx 反代 127.0.0.1→8420)
25
+ // 时才信任 nginx 覆写的转发头——nginx 用 `proxy_set_header X-Real-IP $remote_addr` 覆盖,
26
+ // 客户端自带的 X-Real-IP/XFF 一律被盖掉、伪造不了。非回环对端(理论上不应出现,端口只绑回环)
27
+ // 一律直接用连接 IP,不信任任何头。
28
+ // ⚠ 两个域名 /mcp 都用 `X-Forwarded-For $proxy_add_x_forwarded_for`(无回环尾、末位是真实客户端),
29
+ // 旧逻辑「末位须为回环否则回退 socket」会把真实 IP 全塌成 127.0.0.1 一个桶,故改为 X-Real-IP 优先。
26
30
  function isLoopback(addr) {
27
31
  return addr === '127.0.0.1' || addr === '::1' || addr === '::ffff:127.0.0.1';
28
32
  }
@@ -35,7 +39,7 @@ export function clientIp(req) {
35
39
  const remote = req.socket?.remoteAddress || 'unknown';
36
40
  // 非回环对端:不信任任何转发头
37
41
  if (!isLoopback(remote)) return normalizeIp(remote) || remote;
38
- // 回环对端(自有反代):优先 X-Real-IP(上游覆写,不可伪造)
42
+ // 回环对端(自有 nginx):优先 X-Real-IP($remote_addr 覆写,不可伪造)
39
43
  const xri = req.headers['x-real-ip'];
40
44
  if (typeof xri === 'string' && xri.trim()) return normalizeIp(xri) || remote;
41
45
  // 回退:兼容旧部署——XFF 末位为回环则取倒数第二位
@@ -44,7 +48,7 @@ export function clientIp(req) {
44
48
  const parts = xff.split(',').map((s) => s.trim()).filter(Boolean);
45
49
  const last = parts[parts.length - 1];
46
50
  if (isLoopback(last)) return parts.length >= 2 ? normalizeIp(parts[parts.length - 2]) : remote;
47
- // XFF 无回环尾:末位即真实客户端
51
+ // proxy_add_x_forwarded_for 无回环尾:末位即真实客户端
48
52
  if (parts.length >= 1) return normalizeIp(parts[parts.length - 1]);
49
53
  }
50
54
  return remote;
@@ -60,11 +64,18 @@ export async function runHttp() {
60
64
  app.get('/healthz', (_req, res) => {
61
65
  res.json({
62
66
  ok: true,
67
+ name: 'free-api-mcp',
68
+ version: PKG_VERSION,
63
69
  transport: 'http',
64
70
  trial: trialEnabled() ? (trialStoreAvailable() ? 'ready' : 'degraded') : 'off',
65
71
  });
66
72
  });
67
73
 
74
+ // 版本自检(P1-6):无需工具调用即可探版本
75
+ app.get('/version', (_req, res) => {
76
+ res.json({ name: 'free-api-mcp', version: PKG_VERSION, transport: 'http' });
77
+ });
78
+
68
79
  // Origin 白名单(SDK 只在 DNS rebinding 校验里做 Host,Origin 需自行把关)
69
80
  app.use('/mcp', (req, res, next) => {
70
81
  const origin = req.headers.origin;
@@ -74,7 +85,8 @@ export async function runHttp() {
74
85
  next();
75
86
  });
76
87
 
77
- app.all('/mcp', (req, res) => {
88
+ // 仅 POST /mcp 进入 transport(Streamable HTTP,无会话态,每请求一个传输实例)
89
+ app.post('/mcp', (req, res) => {
78
90
  const token = extractBearer(req);
79
91
  // 无令牌:试用启用且存储可用 → 试用上下文;否则放行让 handler 抛 AUTH_REQUIRED(引导注册)
80
92
  let trialCtx = null;
@@ -84,7 +96,6 @@ export async function runHttp() {
84
96
  } // Redis 不可用:fail-closed,不计费工具会被闸门拦下引导注册
85
97
  }
86
98
  requestContext.run({ token, trial: trialCtx, clientIp: clientIp(req) }, async () => {
87
- // 每请求一个传输实例(无会话态,最简且并发安全)
88
99
  const transport = new StreamableHTTPServerTransport({
89
100
  sessionIdGenerator: undefined,
90
101
  enableJsonResponse: true,
@@ -102,10 +113,22 @@ export async function runHttp() {
102
113
  });
103
114
  });
104
115
 
116
+ // 非 POST 的 /mcp:明确 405(不再把 GET 塞进 transport 挂起 15s)
117
+ app.all('/mcp', (req, res) => {
118
+ res.set('Allow', 'POST').status(405)
119
+ .json({ error: 'Method Not Allowed: /mcp 仅支持 POST(Streamable HTTP,JSON 响应)' });
120
+ });
121
+
122
+ // 本服务不提供 SSE 推送:/sse 明确 404,避免被当作事件流
123
+ app.all('/sse', (req, res) => {
124
+ res.status(404)
125
+ .json({ error: 'Not Found: 本服务不提供 SSE/事件流;请用 POST /mcp(Streamable HTTP)' });
126
+ });
127
+
105
128
  await new Promise((resolve, reject) => {
106
- // 只监听回环:托管端点仅经反代对外,避免端口直接暴露公网
129
+ // 只监听回环:托管端点仅经 nginx 反代对外,避免端口直接暴露公网
107
130
  const srv = app.listen(PORT, '127.0.0.1', () => {
108
- logger.info('http.started', { port: PORT, origins: ALLOWED_ORIGINS.length || 'any' });
131
+ logger.info('http.started', { port: PORT, origins: ALLOWED_ORIGINS.length || 'any', version: PKG_VERSION });
109
132
  resolve();
110
133
  });
111
134
  srv.on('error', reject);
@@ -1,7 +1,7 @@
1
1
  import { getRequestToken, getRequestTrial, getRequestClientIp, logger } from '../context.js';
2
2
  import { trialToken } from './trial.js';
3
3
 
4
- // 上游错误 envelope 见 openapi 契约 components.schemas.Error:
4
+ // 上游错误 envelope 见 16 号仓主契约 components.schemas.Error:
5
5
  // { code, message, requestId, retryAfter?, resetAt?, quota? }
6
6
  export class UpstreamError extends Error {
7
7
  constructor(payload, httpStatus) {
@@ -65,3 +65,17 @@ export function rollbackLocal(ticket) {
65
65
  logger.warn('trial.local_rollback_error', { err: String(e?.message || e) });
66
66
  }
67
67
  }
68
+
69
+ // 只读:取本实例当个北京日各可试能力已用次数(stdio 游客 get_account 个人视图用)。
70
+ // 返回 { <tool>: { used, limit, remaining } }。
71
+ export function getLocalUsage() {
72
+ const limits = localLimits();
73
+ const db = load();
74
+ const out = {};
75
+ for (const tool of Object.keys(limits)) {
76
+ const used = Number(db[tool] || 0);
77
+ const limit = limits[tool];
78
+ out[tool] = { used, limit, remaining: Math.max(0, limit - used) };
79
+ }
80
+ return out;
81
+ }
@@ -81,6 +81,23 @@ export async function consumeTrial(ip, tool, limits) {
81
81
  }
82
82
  }
83
83
 
84
+ // 只读:取某 IP 当个北京日各可试能力已用次数(不扣减、不建键),供 get_account 展示个人额度视图。
85
+ // 返回 { <tool>: { used, limit, remaining } };存储不可用时按 0 计(fail-open,仅展示用)。
86
+ export async function getTrialUsage(ip, limits) {
87
+ const out = {};
88
+ const day = beijingDayKey();
89
+ const h = ipHash(ip);
90
+ for (const tool of Object.keys(limits)) {
91
+ const limit = Number(limits[tool]) || 0;
92
+ let used = 0;
93
+ if (trialStoreAvailable()) {
94
+ try { const v = await client.get(`trial:use:${h}:${day}:${tool}`); used = v != null ? Number(v) : 0; } catch { /* 展示用,读失败按 0 */ }
95
+ }
96
+ out[tool] = { used, limit, remaining: Math.max(0, limit - used) };
97
+ }
98
+ return out;
99
+ }
100
+
84
101
  // 上游调用失败时回滚本次扣减(额度在后端本就"失败不扣",MCP 试用计数保持同口径)
85
102
  export async function rollbackTrial(token) {
86
103
  if (!trialStoreAvailable() || !token) return;
package/src/server.js CHANGED
@@ -23,7 +23,7 @@ import { fileURLToPath } from 'node:url';
23
23
 
24
24
  // 版本单一事实源:以 package.json.version 为准,避免运行时 Server 版本与包版本漂移
25
25
  // (此前此处写死 '0.2.0',与 package.json/server.json 的 0.1.0 不一致)。
26
- const PKG_VERSION = JSON.parse(
26
+ export const PKG_VERSION = JSON.parse(
27
27
  readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8'),
28
28
  ).version;
29
29
 
@@ -79,6 +79,7 @@ export function buildServer() {
79
79
  title: t.title,
80
80
  description: t.description,
81
81
  inputSchema: t.inputSchema,
82
+ ...(t.outputSchema ? { outputSchema: t.outputSchema } : {}),
82
83
  annotations: TOOL_ANNOTATIONS[t.name],
83
84
  })),
84
85
  }));
@@ -156,14 +157,19 @@ export function buildServer() {
156
157
  try {
157
158
  const result = await tool.handler(parsed.data);
158
159
  logger.info('tool.call', { tool: name, ms: Date.now() - started, ok: true });
159
- let text = JSON.stringify(result, null, 2);
160
- if (trialTicket) {
161
- text += `\n\n${trialRemainingNote(name, trialTicket.remaining, trialTicket.limits)}`;
160
+ // P0-1:content[0].text 只放纯 JSON(保证客户端 json.loads 能过)。
161
+ // 游客剩余次数/注册引导改放「第二个 content block」(audience=assistant),不混入机器可解析的 JSON。
162
+ const content = [{ type: 'text', text: JSON.stringify(result, null, 2) }];
163
+ const notes = [];
164
+ if (trialTicket) notes.push(trialRemainingNote(name, trialTicket.remaining, trialTicket.limits));
165
+ if (localTicket) notes.push(trialRemainingNote(name, localTicket.remaining, localTicket.limits));
166
+ if (notes.length) {
167
+ content.push({ type: 'text', text: notes.join('\n'), annotations: { audience: ['assistant'] } });
162
168
  }
163
- if (localTicket) {
164
- text += `\n\n${trialRemainingNote(name, localTicket.remaining, localTicket.limits)}`;
165
- }
166
- return { content: [{ type: 'text', text }] };
169
+ const out = { content };
170
+ // P1-6:声明了 outputSchema 的工具,额外回结构化结果(与 content[0].text 的纯 JSON 同源)
171
+ if (tool.outputSchema && result && typeof result === 'object') out.structuredContent = result;
172
+ return out;
167
173
  } catch (err) {
168
174
  logger.warn('tool.call', {
169
175
  tool: name,
@@ -1,15 +1,70 @@
1
1
  import { z } from 'zod';
2
2
  import { api } from '../lib/apiClient.js';
3
+ import { getRequestTrial, isGuestMode } from '../context.js';
4
+ import { GUEST_LIMITS, nextBeijingResetAt } from '../lib/guestGate.js';
5
+ import { getTrialUsage } from '../lib/trialStore.js';
6
+ import { getLocalUsage } from '../lib/localCounter.js';
7
+
8
+ function maskIp(ip) {
9
+ const s = String(ip || '');
10
+ if (!s) return null;
11
+ const parts = s.split('.');
12
+ if (parts.length === 4) return `${parts[0]}.${parts[1]}.${parts[2]}.*`;
13
+ return s.replace(/:[^:]+$/, ':*');
14
+ }
15
+
16
+ // P0-2:游客/trial 上下文追加「本 IP / 本实例」的个人额度视图(30/15/15,北京 00:00 重置)。
17
+ // 注册令牌路径不追加(personal=null),行为与旧版一致。
18
+ async function buildPersonalView() {
19
+ const trial = getRequestTrial();
20
+ const guest = !!trial?.active || isGuestMode();
21
+ if (!guest) return null;
22
+ let usage; let scope; let ip = null;
23
+ if (trial?.active) {
24
+ usage = await getTrialUsage(trial.ip, GUEST_LIMITS);
25
+ scope = 'ip'; ip = maskIp(trial.ip);
26
+ } else {
27
+ usage = getLocalUsage();
28
+ scope = 'local-instance';
29
+ }
30
+ const capabilities = {};
31
+ let exhausted = false;
32
+ for (const tool of Object.keys(GUEST_LIMITS)) {
33
+ const u = usage[tool] || { used: 0, limit: GUEST_LIMITS[tool], remaining: GUEST_LIMITS[tool] };
34
+ capabilities[tool] = { used: u.used, limit: u.limit, remaining: u.remaining };
35
+ if (u.remaining <= 0) exhausted = true;
36
+ }
37
+ return {
38
+ scope,
39
+ ...(ip ? { ip } : {}),
40
+ resetAt: nextBeijingResetAt(),
41
+ capabilities,
42
+ exhausted,
43
+ note: `游客个人额度视图(${scope === 'ip' ? '本 IP' : '本实例'},MCP 计数,北京日 00:00 重置);上游 quota 为共享游客池口径(app.limit 实测约 3600–4000),二者不同维,勿混用。`,
44
+ ...(exhausted ? { hint: '本 IP 已用尽,可注册或更换网络:https://www.free-api.aiconvg.xin' } : {}),
45
+ };
46
+ }
3
47
 
4
48
  export const getAccountTool = {
5
49
  name: 'get_account',
6
50
  title: '查询额度与账户状态',
7
51
  description:
8
52
  '查询当前令牌的应用档位(free/paid)、各能力当日额度用量(tts/asr/ocr 的 used/limit/remaining)、' +
9
- '额度重置时间与许可证有效期。只读,不消耗额度。',
53
+ '额度重置时间与许可证有效期。只读,不消耗额度。游客模式下额外返回 personal 字段(本 IP/本实例的个人 30/15/15 用量与北京 00:00 重置)。',
10
54
  inputSchema: { type: 'object', properties: {} },
55
+ outputSchema: {
56
+ type: 'object', additionalProperties: true,
57
+ properties: {
58
+ requestId: { type: 'string' },
59
+ app: { type: 'object', additionalProperties: true },
60
+ quota: { type: 'object', additionalProperties: true },
61
+ personal: { type: 'object', additionalProperties: true, description: '游客个人额度视图(仅 guest/trial 返回)' },
62
+ },
63
+ },
11
64
  zodSchema: z.object({}),
12
65
  async handler() {
13
- return api.getAccount();
66
+ const base = await api.getAccount();
67
+ const personal = await buildPersonalView();
68
+ return personal ? { ...base, personal } : base;
14
69
  },
15
70
  };
package/src/tools/tts.js CHANGED
@@ -20,10 +20,18 @@ export const ttsTool = {
20
20
  engine: { type: 'string', enum: ['standard', 'premium'], description: '引擎:默认 standard(免费);premium 需付费档,按积分计费' },
21
21
  },
22
22
  },
23
+ outputSchema: {
24
+ type: 'object', additionalProperties: true,
25
+ properties: {
26
+ requestId: { type: 'string' },
27
+ audioUrl: { type: 'string' },
28
+ },
29
+ },
23
30
  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(),
31
+ // P1-5:zod 消息不再复述「≤300」数字,避免与 invalidParamHint 重复;具体上限只在 hint 出现一次。
32
+ text: z.string().min(1, '不能为空').max(300, '超过长度上限,请分段多次调用'),
33
+ voice: z.string().min(1, '必填(用 list_voices 查询)'),
34
+ speed: z.number().min(0.5, '不得小于 0.5').max(2.0, '不得大于 2.0').optional(),
27
35
  format: z.enum(['wav']).optional(),
28
36
  engine: z.enum(['standard', 'premium']).optional(),
29
37
  }),
@@ -1,20 +1,44 @@
1
1
  import { z } from 'zod';
2
2
  import { api } from '../lib/apiClient.js';
3
3
 
4
+ function normLang(s) { return String(s || '').trim().toLowerCase().replace(/-/g, '_'); }
5
+
4
6
  export const listVoicesTool = {
5
7
  name: 'list_voices',
6
8
  title: '列出可用音色',
7
9
  description:
8
10
  '获取 TTS 可用音色列表(仅免费开源音色,不计额度)。调用 text_to_speech 前必须先从这里拿 voice 参数,' +
9
- '直接猜测音色名会返回 VOICE_NOT_ALLOWED。',
11
+ '直接猜测音色名会返回 VOICE_NOT_ALLOWED。不传 lang 返回全部;传 lang 按语言前缀过滤(zh→zh_CN、en→en_US…;matcha/fanchen 归 zh_CN)。',
10
12
  inputSchema: {
11
13
  type: 'object',
12
14
  properties: {
13
- lang: { type: 'string', description: '按语言筛选,如 zh / en / ja,默认 zh' },
15
+ lang: { type: 'string', description: '按语言筛选(前缀匹配),如 zh / en / ja;不传则返回全部音色' },
16
+ },
17
+ },
18
+ outputSchema: {
19
+ type: 'object', additionalProperties: true,
20
+ properties: {
21
+ requestId: { type: 'string' },
22
+ count: { type: 'number' },
23
+ voices: { type: 'array', items: { type: 'object', additionalProperties: true } },
14
24
  },
15
25
  },
16
26
  zodSchema: z.object({ lang: z.string().optional() }),
17
27
  async handler(args) {
18
- return api.listVoices(args?.lang);
28
+ const res = await api.listVoices(); // { requestId, voices:[{voice,name,lang,format,engine}], count, note }
29
+ const q = normLang(args?.lang);
30
+ if (!q) return res;
31
+ const all = Array.isArray(res?.voices) ? res.voices : [];
32
+ const voices = all.filter((v) => {
33
+ const l = normLang(v?.lang);
34
+ return l === q || l.split('_')[0] === q || l.startsWith(q + '_');
35
+ });
36
+ return {
37
+ ...res,
38
+ voices,
39
+ count: voices.length,
40
+ lang: args.lang,
41
+ note: `${res?.note ? res.note + ';' : ''}已按 lang=${args.lang} 过滤(前缀匹配)`,
42
+ };
19
43
  },
20
44
  };